The backend follows a microservices architecture pattern with independent, loosely-coupled services that communicate through well-defined APIs.
βββββββββββββββββββββββ
β Angular Frontend β
β (Port 4200) β
ββββββββββββ¬βββββββββββ
β HTTP Requests
βΌ
βββββββββββββββββββββββ
β API Gateway β
β (Port 9090) β
β Spring Cloud GW β
ββββββββββββ¬βββββββββββ
β Route & Load Balance
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Microservices Ecosystem β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββ¬βββββββββββββ¬βββ΄βββββββββββ¬ββββββββββββββ¬βββββββββββ
βΌ βΌ βΌ βΌ βΌ βΌ
βββββββββββ βββββββββββ βββββββββββ βββββββββββββββ βββββββββββ βββββββββββ
β User β βProduct β β Cart β β Order β β Payment β β Eureka β
βService β βCatalog β βService β β Management β β Service β β Server β
β:8089 β β:8082 β β:8085 β β :8084 β β :8765 β β :8761 β
ββββββ¬βββββ ββββββ¬βββββ ββββββ¬βββββ ββββββββ¬βββββββ ββββββ¬βββββ βββββββββββ
β β β β β
βΌ βΌ βΌ βΌ βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β MySQL Database β
β (Port 3306) β
β βββββββββββ βββββββββββ βββββββββββ βββββββββββββββββββ β
β β Users β βProducts β β Cart β β Orders β β
β βDatabase β βDatabase β βDatabase β β Database β β
β βββββββββββ βββββββββββ βββββββββββ βββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Each service owns a specific business domain:
- User Service: User management, authentication, profiles
- Product Catalog: Product information, categories, reviews
- Cart Service: Shopping cart operations, checkout
- Order Management: Order processing, tracking, history
Each microservice has its own database schema:
- Isolation: No direct database access between services
- Independence: Services can evolve their data models independently
- Scalability: Each database can be optimized for its specific use case
Services communicate only through well-defined REST APIs:
- Loose Coupling: Services don't share code or databases
- Technology Agnostic: Services can use different tech stacks
- Versioning: APIs can be versioned independently
spring:
cloud:
gateway:
routes:
- id: user-service
uri: http://localhost:8089
predicates:
- Path=/auth/**, /users/**
- id: product-catalog
uri: http://localhost:8082
predicates:
- Path=/api/products/**
- id: cart-service
uri: http://localhost:8085
predicates:
- Path=/cart/**, /checkout/**
- id: order-service
uri: http://localhost:8084
predicates:
- Path=/api/orders/**- Request Routing: Direct requests to appropriate services
- Load Balancing: Distribute load across service instances
- Cross-Cutting Concerns: CORS, rate limiting, authentication
- API Composition: Aggregate responses from multiple services
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}Each microservice registers with Eureka:
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: trueServices communicate using declarative REST clients:
@FeignClient(name = "product-service")
public interface ProductClient {
@GetMapping("/products/{id}")
ProductDto getProduct(@PathVariable Long id);
@PostMapping("/products/batch")
List<ProductDto> getProducts(@RequestBody List<Long> ids);
@PutMapping("/products/{id}/reduce-stock")
ResponseEntity<String> reduceStock(@PathVariable Long id, @RequestParam Integer quantity);
}- Synchronous: HTTP REST calls via Feign clients
- Request-Response: Direct service-to-service calls
- Circuit Breaker: Fault tolerance (can be added with Hystrix)
- User registration and authentication
- Profile management
- Address and payment method storage
- Wishlist management
@RestController
@RequestMapping("/auth")
public class AuthController {
@PostMapping("/register")
@PostMapping("/login")
@PostMapping("/verify-otp")
}
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{userId}/addresses")
@PostMapping("/{userId}/addresses")
@GetMapping("/{userId}/payments")
@PostMapping("/{userId}/payments")
@GetMapping("/{userId}/wishlist")
}-- Users table
users (id, email, phone, password, name, created_at)
-- Addresses table
addresses (id, user_id, full_name, phone, line1, line2, city, state, postal_code, country, is_default)
-- Payment Methods table
payment_methods (id, user_id, provider, token, is_default, created_at)
-- Wishlist table
wishlist (id, user_id, product_id, created_at)- Product information management
- Category management
- Product search and filtering
- Reviews and ratings
- Inventory management
@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping
@GetMapping("/{id}")
@PostMapping
@PutMapping("/{id}/reduce-stock")
@GetMapping("/{id}/check-stock")
@PostMapping("/{id}/image")
@GetMapping("/image/{imageId}")
}-- Products table
products (id, sku, name, brand, description, price, currency, stock, availability_status, active)
-- Categories table
categories (id, name, description)
-- Product Categories (Many-to-Many)
product_categories (product_id, category_id)
-- Product Specifications
product_specs (product_id, spec_key, spec_value)
-- Product Images
product_images (id, product_id, image_data, image_url, content_type, alt_text, sort_order)
-- Reviews
reviews (id, product_id, user_id, user_name, rating, title, comment, verified_purchase, created_at)- Shopping cart management
- Cart item operations
- Checkout processing
- Price calculations
@RestController
@RequestMapping("/cart")
public class CartController {
@GetMapping("/{userId}")
@PostMapping("/{userId}/items")
@PutMapping("/{userId}/items/{itemId}")
@DeleteMapping("/{userId}/items/{itemId}")
@GetMapping("/{userId}/price")
}
@RestController
@RequestMapping("/checkout")
public class CheckoutController {
@PostMapping
public ResponseEntity<Map<String,Object>> checkout(
@RequestParam Long userId,
@RequestParam Long addressId,
@RequestParam String shipping,
@RequestParam String method
)
}-- Cart table
cart (id, user_id, updated_at)
-- Cart Items table
cart_item (id, cart_id, product_id, quantity, variant)- Order creation and processing
- Order status management
- Order history
- Email notifications
@RestController
@RequestMapping("/api/orders")
public class OrderController {
@PostMapping("/")
@GetMapping("/{orderId}")
@GetMapping("/user/{userId}")
@PutMapping("/{orderId}")
@DeleteMapping("/{orderId}")
@GetMapping("/{orderId}/track")
}-- Orders table
orders (id, order_id, customer_id, customer_email, total_amount, subtotal, shipping, tax, discount,
status, order_date, estimated_delivery, shipping_full_name, shipping_phone,
shipping_address_line1, shipping_address_line2, shipping_city, shipping_state,
shipping_zip_code, shipping_country, payment_type, payment_details, payment_provider)
-- Order Items table
order_item (id, order_id, product_id, product_name, product_image, quantity, price, total)Frontend β API Gateway β User Service β Database
β
OTP Service β Email/SMS
Frontend β API Gateway β Product Catalog β Database
β
Return Products + Images
Frontend β API Gateway β Cart Service β Database
β
Validate with Product Service
Frontend β API Gateway β Cart Service β Order Service β Database
β β
Product Service Email Service
(Reduce Stock) (Confirmation)
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(authz -> authz.anyRequest().permitAll());
return http.build();
}
}- JWT Authentication: Implement token-based authentication
- OAuth2/OpenID Connect: For social login integration
- API Rate Limiting: Prevent abuse and DDoS attacks
- Input Validation: Sanitize all user inputs
- HTTPS: Encrypt all communications
- Service-to-Service Auth: Mutual TLS or service tokens
# Docker Compose scaling
docker-compose up --scale user-service=3 --scale product-catalog=2- API Gateway: Routes requests to available instances
- Database: Read replicas for read-heavy operations
- Caching: Redis for session and frequently accessed data
- Database Indexing: Optimize query performance
- Connection Pooling: Efficient database connections
- Caching Strategy: Application-level and database-level caching
- Async Processing: Non-blocking operations where possible
# Service-specific configuration
server:
port: 8089
spring:
application:
name: user-service
datasource:
url: jdbc:mysql://localhost:3306/Training
username: ${DB_USERNAME:root}
password: ${DB_PASSWORD:password}
jpa:
hibernate:
ddl-auto: update
show-sql: false
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/- Development: Local database, debug logging
- Testing: In-memory database, mock services
- Production: Cloud database, optimized settings
# Start services in dependency order
1. MySQL Database
2. Eureka Server
3. API Gateway
4. User Service
5. Product Catalog
6. Cart Service
7. Order Management
8. Frontend Application# Kubernetes deployment example
apiVersion: apps/v1
kind: Deployment
metadata:
name: user-service
spec:
replicas: 3
selector:
matchLabels:
app: user-service
template:
metadata:
labels:
app: user-service
spec:
containers:
- name: user-service
image: user-service:latest
ports:
- containerPort: 8089
env:
- name: DB_HOST
value: "mysql-service"@RestController
public class HealthController {
@GetMapping("/health")
public ResponseEntity<Map<String, String>> health() {
return ResponseEntity.ok(Map.of("status", "UP"));
}
}- Spring Boot Actuator: Health endpoints and metrics
- Centralized Logging: ELK Stack (Elasticsearch, Logstash, Kibana)
- Distributed Tracing: Zipkin or Jaeger for request tracing
- Monitoring: Prometheus + Grafana for metrics visualization
- Cart to Order: Cart data eventually consistent with order creation
- Inventory Updates: Stock levels updated asynchronously
- User Profile: Profile changes propagated to dependent services
For complex transactions spanning multiple services:
- Order Creation Saga: User β Cart β Inventory β Payment β Order
- Compensation: Rollback operations if any step fails
- Orchestration: Central coordinator manages the saga
This microservices architecture provides a scalable, maintainable, and resilient foundation for the e-commerce platform, following industry best practices and patterns.