An enterprise-grade Spring Boot e-commerce backend system with advanced distributed features including flash sales (seckill), distributed locking, message queue processing, and comprehensive testing infrastructure.
This is a production-ready e-commerce backend API built with modern Java technologies and enterprise patterns, featuring:
- RESTful API Design with complete CRUD operations
- JWT Authentication & Authorization with role-based access control and token blacklist
- High-Concurrency Flash Sale System (Seckill) with Redis + RabbitMQ
- Distributed Locking with Redisson for race condition prevention
- Distributed Rate Limiting with Bucket4j and Redis for API protection
- Reliable Message Queue with idempotency guarantees
- Advanced Order Management with state machine workflow and facade pattern
- Atomic Stock Management using Redis Lua scripts
- Comprehensive Test Suite with 19+ passing JUnit tests
- Docker Compose for local development environment
- CI/CD Pipeline with GitHub Actions
- Professional Architecture following Spring Boot best practices
| Category | Technologies |
|---|---|
| Backend Framework | Spring Boot 3.5.4, Spring Security, Spring Data JPA |
| Database | MySQL 8.0+ with JPA/Hibernate ORM |
| Caching & Locking | Redis with Spring Data Redis, Redisson 3.32.0 for distributed locks, Bucket4j for rate limiting |
| Message Queue | RabbitMQ with Spring AMQP for async processing |
| Authentication | JWT (java-jwt 3.8.1) with BCrypt encryption, Token Blacklist |
| Payment Gateway | Stripe 24.3.0 (configured, ready for integration) |
| API Documentation | Swagger/OpenAPI 2.2.0 |
| Build Tool | Maven |
| Java Version | Java 17+ |
| DevOps | Docker Compose, GitHub Actions CI/CD |
- User Registration & Authentication with email validation
- JWT Token-based Security with 24-hour token expiration
- Token Blacklist Service - Logout support with Redis-backed revoked token storage
- Role-based Authorization (Customer, Admin, Super Admin)
- Password Encryption using BCrypt
- Profile Management with user data validation
- Hierarchical Category Structure with parent-child relationships
- Dynamic Category Tree with unlimited nesting levels
- Category Validation preventing deletion of categories with products
- Bulk Category Operations for administrative tasks
- Advanced Product Management with detailed attributes
- Multi-parameter Filtering (category, price range, status)
- Product Search with fuzzy matching
- Inventory Tracking with real-time stock updates
- Pagination & Sorting for large datasets
- Persistent Cart Management across user sessions
- Real-time Price Calculations with tax and shipping
- Item Selection/Deselection for flexible checkout
- Stock Validation preventing overselling
- Cart Synchronization across multiple devices
- Multiple Shipping Addresses per user
- Default Address Management with automatic selection
- Address Validation ensuring delivery accuracy
- Geographic Integration ready for shipping calculations
- Complete Order Lifecycle management
- State Machine Implementation (Pending β Paid β Shipped β Completed)
- OrderFacade Pattern - Orchestrates complex multi-service operations
- Distributed Locking - Redisson multi-lock prevents race conditions (10s wait, 30s lease)
- Transaction Management ensuring data consistency across multiple tables
- Payment Integration ready (Stripe configured)
- Order Tracking with status updates
- Inventory Reservation during order processing with automatic rollback
- Redis Stock Preloading - StockWarmer preloads inventory at startup for sub-millisecond reads
- Atomic Stock Deduction - Lua scripts ensure atomic Redis operations (no race conditions)
- One Participation Per User - 24-hour Redis-based deduplication per product
- Async Order Processing - RabbitMQ decouples stock deduction from order creation
- Reliable Message Queue - SeckillMessage entity tracks pending/failed messages
- Idempotency Guarantees - ReliableMessage table prevents duplicate processing
- Scheduled Retry Mechanism - Failed messages retried every 5 seconds with exponential backoff
- Smart Failure Handling - Distinguishes transient failures (requeue) from permanent (discard)
- Message Consumer - RabbitMQ listener with manual ACK/NACK for reliable processing
Seckill Flow:
1. User clicks "Buy Now" β SeckillService.doSeckill()
2. Check user eligibility (Redis: seckill:user:{productId}:{userId})
3. Deduct Redis stock atomically (Lua script)
4. Create SeckillMessage (PENDING status) in database
5. SeckillMessageTask (scheduled @5s) sends PENDING messages to RabbitMQ
6. SeckillOrderConsumer receives message
7. Check ReliableMessage for idempotency (messageId + consumerName)
8. Create order, deduct database stock, mark message SUCCESS
9. ACK message to RabbitMQ
- Redisson Multi-Lock - Prevents concurrent modification of shared resources
- Deadlock Prevention - Products locked in sorted order (by ID) to avoid circular waits
- Lock Parameters - 10-second wait timeout, 30-second lease time
- Automatic Unlock - Always releases locks in finally block, checks
isHeldByCurrentThread() - Use Cases - Order creation with multiple products, stock reservation
- Token Bucket Algorithm - Bucket4j implementation with greedy refill strategy
- Redis-Backed Distributed Rate Limiting - Consistent rate limiting across multiple instances using Lettuce client
- Two-Level Protection:
- IP-based Rate Limiting: 100 requests/second per IP address
- User-based Rate Limiting: 50 requests/second per authenticated user
- Proxy-Aware IP Detection - Correctly identifies client IP behind proxies (X-Forwarded-For, X-Real-IP)
- HTTP 429 Response - Returns "Too Many Requests" when limits exceeded
- Automatic Token Refill - Buckets refill every second for continuous service
- 5-Minute Expiration - Inactive buckets automatically expire to conserve Redis memory
- JWT Integration - Extracts user ID from JWT tokens for user-level rate limiting
- Protection Against - DDoS attacks, API abuse, resource exhaustion
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Client Layer β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Controllers (REST API Layer) β
β UserController β ProductController β OrderController β SeckillController
β βββ Rate Limit Filter (Bucket4j + Redis) β
β βββ JWT Authentication Filter β
β βββ Global Exception Handler β
β βββ Response Wrapper (ResponseResult) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Service Layer β
β UserService β ProductService β OrderFacade β SeckillService β
β CartService β AddressService β StockService β TokenBlacklistService β
β βββ Business Logic & Validation β
β βββ Transaction Management (@Transactional) β
β βββ Distributed Lock Orchestration (Redisson) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Repository Layer (JPA) β
β UserRepository β ProductRepository β OrderRepository β CartRepository
β βββ Custom Queries (JPQL, Native SQL) β
β βββ Pagination & Sorting β
β βββ Entity Relationship Management β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββ
β β β β
β MySQL β Redis β RabbitMQ β
β (Primary DB) β βββββββββββββββββββββββ β ββββββββββββββββββββ
β β β Stock Cache β β β Seckill Queue ββ
β β β Token Blacklist β β β Payment Timeout ββ
β β β User Participation β β β Message Retry ββ
β β β Distributed Locks β β ββββββββββββββββββββ
β β β Rate Limit Buckets β β β
β β βββββββββββββββββββββββ β β
βββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Background Workers β
β SeckillMessageTask (Scheduled @5s) β Retry failed messages β
β SeckillOrderConsumer (RabbitMQ Listener) β Process async orders β
β StockWarmer (@PostConstruct) β Preload Redis stock at startup β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- Facade Pattern -
OrderFacadeorchestrates complex multi-service transactions - Message Queue Pattern - Async processing with RabbitMQ for high-concurrency scenarios
- Distributed Lock Pattern - Redisson multi-lock prevents race conditions
- Rate Limiting Pattern - Token bucket algorithm with Redis for distributed API protection
- Idempotency Pattern -
ReliableMessageentity prevents duplicate processing - Custom Exception Hierarchy - 17 custom exceptions with proper HTTP status codes
- Entity-First Design - Services return entities, controllers convert to DTOs
- Multi-table Transactions - ACID compliance with Spring's
@Transactional - Advanced JPA Queries - Custom repository methods with JPQL and native SQL
- Lua Script Atomicity - Redis operations use Lua for atomic multi-command execution
- Scheduled Task Retry - Exponential backoff for failed message processing
POST /api/users/register # User registration
POST /api/users/login # User authentication
GET /api/users/{username} # Get user profileGET /api/products # List products with filtering & pagination
GET /api/products/{id} # Get product details
POST /api/products # Create product (Admin)
PUT /api/products/{id} # Update product (Admin)
GET /api/products/search # Search productsGET /api/cart # Get user cart
POST /api/cart/add # Add item to cart
PUT /api/cart/update/{id} # Update cart item quantity
DELETE /api/cart/remove/{id} # Remove item from cart
DELETE /api/cart/clear # Clear entire cartPOST /api/orders # Create order from cart
GET /api/orders # Get user orders
GET /api/orders/{id} # Get order details
POST /api/orders/{id}/pay # Process payment
POST /api/orders/{id}/ship # Ship order (Admin)
POST /api/orders/{id}/cancel # Cancel orderPOST /api/seckill/{productId} # Participate in flash sale
POST /api/seckill/enable/{productId} # Enable product for flash sale (Admin)GET /api/addresses # Get user addresses
POST /api/addresses # Create new address
PUT /api/addresses/{id} # Update address
DELETE /api/addresses/{id} # Delete address
POST /api/addresses/{id}/default # Set default addressGET /api/categories # List all categories
GET /api/categories/{id} # Get category details
POST /api/categories # Create category (Admin)
PUT /api/categories/{id} # Update category (Admin)
DELETE /api/categories/{id} # Delete category (Admin)- Java 17+
- Maven 3.6+
- MySQL 8.0+ (required)
- Redis Server (required for distributed locks, caching, and seckill)
- RabbitMQ (required for async message processing)
The easiest way to set up the development environment with all required infrastructure services:
# Clone the repository
git clone https://github.com/yourusername/ecommerce-backend.git
cd ecommerce-backend
# Create .env file with your credentials (or use the provided template)
cp .env.example .env # Edit this file with your settings
# Start infrastructure services (MySQL, Redis, RabbitMQ)
docker-compose up -d
# Check service health
docker-compose ps
# Run the Spring Boot application (in a separate terminal)
mvn spring-boot:run
# Or run from your IDE (IntelliJ IDEA, Eclipse, VS Code)Included Infrastructure Services:
- MySQL 8.0 (port 3306) - Primary database with custom configuration
- Pre-configured with
ecommerce_dbdatabase - Custom my.cnf for optimized performance
- Credentials from
.envfile
- Pre-configured with
- Redis 7.0 (port 6379) - Caching, distributed locks, rate limiting
- AOF persistence enabled
- 256MB memory limit with noeviction policy (prevents lock eviction)
- Resource limits: 512MB max memory
- RabbitMQ 3.12 with Management UI (ports 5672, 15672)
- AMQP messaging for seckill system
- Management UI at http://localhost:15672 (guest/guest)
- Resource limits: 512MB max memory
All services configured with:
- Health checks and automatic restart policies
- Resource limits to prevent system overload
- Persistent volumes for data retention
- Isolated Docker network for inter-service communication
Environment Configuration:
Create a .env file in the project root (already in .gitignore):
# MySQL Configuration
MYSQL_ROOT_PASSWORD=rootpassword
MYSQL_DATABASE=ecommerce_db
MYSQL_USER=abel
MYSQL_PASSWORD=1234
# Redis Configuration
REDIS_PASSWORD=
# RabbitMQ Configuration
RABBITMQ_USER=guest
RABBITMQ_PASSWORD=guest
RABBITMQ_VHOST=/Useful Commands:
# View logs for all services
docker-compose logs -f
# View logs for specific service
docker-compose logs -f mysql
# Stop services (keeps data)
docker-compose stop
# Stop and remove containers (keeps volumes/data)
docker-compose down
# Stop and remove everything including data
docker-compose down -v
# Restart a specific service
docker-compose restart redis
# Access MySQL shell
docker exec -it ecommerce-mysql mysql -uabel -p1234 ecommerce_dbWhy run app separately from Docker Compose?
- Faster development iteration (no Docker rebuild on code changes)
- IDE debugging works normally
- Spring DevTools hot reload enabled
- See logs directly in IDE console
- Clone the repository
git clone https://github.com/yourusername/ecommerce-backend.git
cd ecommerce-backend- Install Required Services
- MySQL 8.0+
- Redis Server
- RabbitMQ
- Configure Database
mysql -u root -p
CREATE DATABASE ecommerce_db;- Update Application Properties
# src/main/resources/application-local.properties
spring.datasource.url=jdbc:mysql://localhost:3306/ecommerce_db
spring.datasource.username=your_username
spring.datasource.password=your_password
# Redis configuration
spring.data.redis.host=localhost
spring.data.redis.port=6379
# RabbitMQ configuration
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest- Build and Run
mvn clean install
mvn spring-boot:runThe API will be available at http://localhost:8080
Once the application is running, access the Swagger UI documentation at:
http://localhost:8080/swagger-ui/index.html
This provides interactive API testing with request/response examples.
The project includes extensive unit and integration tests covering all layers:
Run All Tests:
mvn testRun Specific Test Class:
mvn test -Dtest=ProductServiceImplTestRun Tests with Coverage:
mvn verifyTest Structure:
-
Service Layer Tests (19+ tests):
ProductServiceImplTest- Product CRUD, filtering, paginationCategoryServiceImplTest- Hierarchical category operationsCartServiceImplTest- Cart operations with stock validationAddressServiceImplTest- Address management, default addressUserServiceImplTest- Registration, authentication, role management
-
Repository Tests:
ProductRepositoryTest- Custom queries, filteringCategoryRepositoryTest- Hierarchy queriesCartItemRepositoryTest- User-specific queriesUserRepositoryTest- User lookupsAddressRepositoryTest- Address queries
-
Controller Tests (MockMvc):
ProductControllerTest- REST endpoint testingCategoryControllerTest- Category API testingCartControllerTest- Cart API testingUserControllerTest- Authentication endpointsAddressControllerTest- Address API testing
Testing Patterns:
@Transactionalfor automatic rollback- Mockito for service mocking
@WebMvcTestfor controller tests@DataJpaTestfor repository tests- Integration tests require MySQL and Redis
GitHub Actions CI/CD:
- Automated test execution on every push
- Test reports generated with dorny/test-reporter
- PR checks for test failures
- Token Expiration: 24 hours (configurable)
- Secret Key: Stored in application properties (use environment variables in production)
- Algorithm: HMAC256
- Connection Pooling: HikariCP (default)
- JPA/Hibernate: Auto DDL generation (disable in production)
- Transaction Management: Spring's @Transactional
Automated workflow configured in .github/workflows/ci.yml:
- Trigger: Push to
mainbranch - Steps:
- Checkout code
- Set up Java 17
- Build with Maven (
mvn clean install) - Run JUnit tests (
mvn test) - Generate test reports with dorny/test-reporter
- Fail PR if tests fail
View Build Status: Check the Actions tab on GitHub for build and test results.
This project is configured for deployment on Railway:
Deployment Steps:
- Connect GitHub repository to Railway
- Configure environment variables:
SPRING_DATASOURCE_URLSPRING_DATASOURCE_USERNAMESPRING_DATASOURCE_PASSWORDJWT_SECRETREDIS_HOSTandREDIS_PORTRABBITMQ_HOST,RABBITMQ_PORT,RABBITMQ_USERNAME,RABBITMQ_PASSWORD
- Railway auto-deploys on git push to main
- Access application at Railway-provided URL
Services Required on Railway:
- MySQL (Railway MySQL plugin)
- Redis (Railway Redis plugin)
- RabbitMQ (CloudAMQP add-on or custom deployment)
See RAILWAY_DEPLOYMENT.md for detailed deployment guide.
Local Development with Docker Compose:
# Start infrastructure services only
docker-compose up -d
# Run Spring Boot app separately (see Quick Start section)
mvn spring-boot:runProduction Dockerfile:
The project includes a multi-stage production Dockerfile optimized for cloud deployment:
Features:
- Multi-stage build (Maven build stage + JRE runtime stage)
- Non-root user for security
- G1GC garbage collector for better performance
- Container-aware JVM memory settings
- Health check with 90s startup grace period (for StockWarmer initialization)
- Optimized for Railway/AWS/Cloud deployment
Build and Deploy:
# Build the Docker image
docker build -t ecommerce-backend .
# Run locally (requires external MySQL, Redis, RabbitMQ)
docker run -p 8080:8080 \
-e DATABASE_URL=jdbc:mysql://host:3306/ecommerce_db \
-e REDIS_URL=redis://host:6379 \
-e CLOUDAMQP_URL=amqp://user:pass@host:5672 \
ecommerce-backend
# For Railway deployment, push to GitHub and Railway will auto-buildDockerfile Highlights:
- Stage 1: Maven build with dependency caching
- Stage 2: Minimal JRE runtime (Alpine Linux)
- JVM Options:
-Xmx512m -Xms256m -XX:+UseG1GC -XX:+UseContainerSupport - Health Check:
/actuator/healthendpoint with proper startup time - Security: Runs as non-root
springuser
- Docker Compose for local development
- GitHub Actions CI/CD pipeline
- Comprehensive test suite
- Environment-specific properties (dev, local, prod)
- Logging configuration (logs/ecommerce.log)
- Configure production database (MySQL on Railway)
- Set up Redis in production
- Set up RabbitMQ in production
- Configure JWT secret from environment variables
- Set up monitoring and health checks
- Configure SSL/TLS certificates
- Set up backup and disaster recovery
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- User Management - JWT authentication, token blacklist, role-based authorization
- Product Catalog - Full CRUD with advanced filtering, pagination, search
- Category Management - Hierarchical categories with unlimited nesting
- Shopping Cart - Real-time cart management with stock validation
- Order System - Complete order lifecycle with OrderFacade pattern and distributed locking
- Address Management - Multiple shipping addresses with default address support
- Seckill/Flash Sale System - High-concurrency flash sales with Redis + RabbitMQ
- Distributed Locking - Redisson multi-lock for race condition prevention
- Rate Limiting - Bucket4j with Redis-backed distributed rate limiting (IP and user-based)
- Message Queue - Reliable async processing with idempotency guarantees
- Testing Infrastructure - 19+ JUnit tests with GitHub Actions CI/CD
- Docker Compose - Local development environment with all services
- API Documentation - Comprehensive Swagger/OpenAPI documentation
- Deployment Pipeline - GitHub Actions CI/CD with automated testing
- Frontend Integration - React frontend with Vercel deployment
- Payment Gateway Integration - Stripe configured, integration in progress
- Metrics & Monitoring - Prometheus/Grafana integration
- Email Notifications - Order confirmation, shipping updates
- Advanced Search - Elasticsearch integration for full-text search
- Image Upload - AWS S3 integration for product images
- Caching Optimization - Multi-level caching strategy
Abel - Full Stack Developer
This project is licensed under the MIT License - see the LICENSE file for details.
This project demonstrates enterprise-grade Spring Boot development with advanced distributed systems patterns:
- High-Concurrency Handling - Flash sale system handling thousands of concurrent requests
- Distributed Systems - Redis-based distributed locking and caching
- Async Processing - RabbitMQ message queue with retry mechanisms
- Idempotency Guarantees - Duplicate request prevention in distributed environment
- Comprehensive Testing - 19+ unit/integration tests with CI/CD pipeline
- Production-Ready - Docker Compose, environment configs, health checks, logging
- Clean Architecture - Facade pattern, entity-first design, custom exception hierarchy
Perfect for:
- Learning advanced Spring Boot concepts
- Understanding distributed systems patterns
- Interview preparation (demonstrates real-world scenarios)
- Portfolio project showcasing enterprise-level development skills