Master Microservices Architecture

Learn through a complete e-commerce implementation with Spring Boot & Java

8

Microservices

9

Design Patterns

12

Technologies

5

Circuit Breakers

Business Problem & Solution

The Challenge

  • E-commerce business with no digital solutions
  • Manual product catalog management
  • Customer data scattered across systems
  • Payment processing inefficiencies
  • No automated notifications
  • Scalability concerns for growth

The Solution

  • Product Service: Centralized catalog with unique codes
  • Customer Service: Complete customer profiles
  • Order Service: Automated order processing
  • Payment Service: Secure payment handling
  • Notification Service: Automated email confirmations
  • Gateway & Discovery: Scalable infrastructure

Interactive Architecture Diagram

Client Layer

Web Client

Gateway Layer

API Gateway Port: 8222

Core Services

Config Server Port: 8888
Discovery Service Port: 8761

Business Services

Customer Service MongoDB
Product Service PostgreSQL
Order Service PostgreSQL
Payment Service PostgreSQL
Notification Service MongoDB

Infrastructure

PostgreSQL
MongoDB
Kafka
Zipkin

Microservices Deep Dive

Config Server

Port: 8888

Technology: Spring Cloud Config

Database: File System

Purpose & Functionality

The Config Server acts as a centralized configuration management system for all microservices. It eliminates the need to rebuild and redeploy services when configuration changes.

Key Features:
  • Centralized configuration for all services
  • Environment-specific configurations (dev, staging, prod)
  • Dynamic configuration refresh without restart
  • Version control integration with Git
  • Security for sensitive configurations
How it Works:
  1. Stores all service configurations in a central location
  2. Services request their configuration on startup
  3. Provides environment-specific overrides
  4. Enables runtime configuration updates via refresh endpoints

Discovery Service

Port: 8761

Technology: Netflix Eureka

Database: In-Memory Registry

Service Registry & Discovery

The Discovery Service maintains a registry of all available microservice instances, enabling dynamic service-to-service communication without hardcoded URLs.

Key Features:
  • Automatic service registration
  • Health check monitoring
  • Load balancing support
  • Failover and resilience
  • Web dashboard for monitoring
Service Registration Flow:
  1. Services register themselves on startup
  2. Send periodic heartbeats to maintain registration
  3. Other services discover available instances
  4. Automatic deregistration on shutdown

API Gateway

Port: 8222

Technology: Spring Cloud Gateway

Features: Routing, Load Balancing, Tracing

Single Entry Point

The API Gateway serves as the single entry point for all client requests, routing them to appropriate microservices while providing cross-cutting concerns.

Key Responsibilities:
  • Request routing to appropriate services
  • Load balancing across service instances
  • Authentication and authorization
  • Request/response transformation
  • Rate limiting and throttling
  • Distributed tracing integration
Routing Example:
/api/customers/** → Customer Service
/api/products/** → Product Service
/api/orders/** → Order Service
/api/payments/** → Payment Service

Customer Service

Database: MongoDB

Technology: Spring Data MongoDB

Pattern: Document Store

Customer Profile Management

Manages all customer-related data and operations, storing flexible customer profiles in MongoDB for scalability and schema evolution.

Data Model:
  • Personal Info: First name, Last name, Email
  • Address: Street, City, Zipcode
  • Metadata: Creation date, Update history
API Endpoints:
POST /api/customers - Create customer
GET /api/customers/{id} - Get customer details
PUT /api/customers/{id} - Update customer
GET /api/customers/exists/{id} - Check existence

Order Service

Database: PostgreSQL

Technology: Spring Data JPA

Integration: OpenFeign, Kafka

Order Processing Hub

Orchestrates the complete order lifecycle, integrating with multiple services to validate customers, check product availability, process payments, and trigger notifications.

Order Processing Flow:
  1. Validation: Check customer exists via Customer Service
  2. Inventory: Validate products and quantities via Product Service
  3. Order Creation: Create order with PENDING status
  4. Payment: Process payment via Payment Service
  5. Confirmation: Send confirmation via Kafka to Notification Service
  6. Status Update: Update order status based on payment result
Service Dependencies:
  • CustomerClient: Customer validation
  • ProductClient: Product verification
  • PaymentClient: Payment processing
  • Kafka Producer: Event notifications

Notification Service

Database: MongoDB

Technology: Kafka, Thymeleaf

Integration: Java Mail Sender

Event-Driven Notifications

Handles all notification requirements using event-driven architecture. Listens to Kafka events and sends appropriate email notifications to customers.

Notification Types:
  • Order Confirmation: When order is successfully created
  • Payment Success: When payment is processed successfully
  • Payment Failure: When payment processing fails
  • Order Updates: Status changes and updates
Event Processing Flow:
  1. Listen to Kafka topics (order-topic, payment-topic)
  2. Parse incoming event messages
  3. Generate HTML email using Thymeleaf templates
  4. Send email via configured SMTP server
  5. Store notification history in MongoDB
Email Templates:
  • order-confirmation.html
  • payment-confirmation.html
  • payment-failed.html

Microservices Design Patterns

Service Registry & Discovery

Implementation: Netflix Eureka

Services automatically register themselves and discover other services dynamically.

Benefits:
  • Dynamic service location
  • Load balancing
  • Health monitoring
  • Fault tolerance

API Gateway

Implementation: Spring Cloud Gateway

Single entry point for all client requests with routing and cross-cutting concerns.

Benefits:
  • Simplified client interactions
  • Centralized security
  • Request transformation
  • Rate limiting

Database per Service

Implementation: PostgreSQL + MongoDB

Each service owns its data and database, ensuring loose coupling.

Benefits:
  • Data isolation
  • Technology diversity
  • Independent scaling
  • Fault isolation

Event-Driven Architecture

Implementation: Apache Kafka

Services communicate through events for loose coupling and resilience.

Benefits:
  • Loose coupling
  • Asynchronous processing
  • Event sourcing
  • Scalability

Externalized Configuration

Implementation: Spring Cloud Config

Configuration management separated from application code for flexibility.

Benefits:
  • Environment-specific configs
  • Runtime updates
  • Version control
  • Security separation

Distributed Tracing

Implementation: Zipkin

Track requests across multiple services for debugging and monitoring.

Benefits:
  • Performance monitoring
  • Debugging assistance
  • Service dependencies
  • Bottleneck identification

Circuit Breaker

Implementation: Resilience4j

Prevents cascading failures by monitoring service calls and failing fast when downstream services are unavailable.

Benefits:
  • Fault tolerance
  • Automatic recovery
  • Resource protection
  • Cascading failure prevention
Saga-Specific Circuit Breakers:
  • Saga Orchestration: 40% failure threshold
  • Saga Compensation: 25% failure threshold
  • Saga Recovery: 60% failure threshold
  • Customer Validation: 35% failure threshold
  • Inventory Reservation: 45% failure threshold

Saga Pattern

Implementation: Choreography + Orchestration

Manages distributed transactions across multiple services with compensation logic for rollback scenarios.

Benefits:
  • Distributed transaction management
  • Automatic compensation
  • Eventual consistency
  • Resilience to failures
Saga Flow:
  1. Customer Validation: Verify customer exists
  2. Inventory Reservation: Reserve products
  3. Payment Processing: Process payment
  4. Order Completion: Finalize order

Recovery: Automatic timeout handling and retry mechanisms with exponential backoff

Hands-On Learning

Getting Started

Clone the Repository First

Before following the setup steps, clone the complete source code from GitHub:

git clone https://github.com/PramithaMJ/fully-completed-microservices.git cd fully-completed-microservices

Repository: https://github.com/PramithaMJ/fully-completed-microservices

1
Prerequisites
  • Java 17+
  • Maven 3.6+
  • Docker & Docker Compose
  • IDE (IntelliJ IDEA or VS Code)
2
Start Infrastructure
docker-compose up -d

This starts PostgreSQL, MongoDB, Kafka, Zipkin, and admin tools.

3
Start Core Services
1. Config Server (Port 8888)
2. Discovery Service (Port 8761)
3. API Gateway (Port 8222)
4
Start Business Services

Start Customer, Product, Order, Payment, and Notification services in any order.

Testing Scenarios

Create a Customer
API Request:
curl -X POST http://localhost:8222/api/customers \
  -H "Content-Type: application/json" \
  -d '{
    "firstname": "John",
    "lastname": "Doe",
    "email": "john.doe@example.com",
    "address": {
      "street": "123 Main St",
      "houseNumber": "123",
      "zipCode": "12345"
    }
  }'
What Happens:
  1. Request hits API Gateway on port 8222
  2. Gateway routes to Customer Service via Eureka discovery
  3. Customer data stored in MongoDB
  4. Response includes generated customer ID
  5. Trace information sent to Zipkin
Add a Product
API Request:
curl -X POST http://localhost:8222/api/products \
  -H "Content-Type: application/json" \
  -d '{
    "name": "MacBook Pro",
    "description": "Apple MacBook Pro 16-inch",
    "availableQuantity": 10,
    "price": 2499.99
  }'
What Happens:
  1. Request routed through Gateway to Product Service
  2. Product stored in PostgreSQL database
  3. Auto-generated product ID returned
  4. Inventory tracking initialized
Place an Order
API Request:
curl -X POST http://localhost:8222/api/orders \
  -H "Content-Type: application/json" \
  -d '{
    "customerId": "customer_id_here",
    "products": [
      {
        "productId": "product_id_here",
        "quantity": 1
      }
    ],
    "paymentMethod": "PAYPAL"
  }'
Complete Order Flow:
  1. Validation: Order Service validates customer exists
  2. Inventory: Checks product availability
  3. Order Creation: Creates order with PENDING status
  4. Payment: Processes payment via Payment Service
  5. Kafka Event: Publishes order confirmation event
  6. Email: Notification Service sends confirmation email
  7. Status Update: Order status updated to PAID
View Distributed Tracing
Zipkin Dashboard:

Open Zipkin UI

What You'll See:
  • Complete request trace across all services
  • Service call duration and timing
  • Service dependencies visualization
  • Performance bottlenecks identification
  • Error propagation tracking
Trace Components:
Gateway
Order Service
Customer Service
Product Service
Payment Service

Monitoring Dashboards

Eureka Discovery

View all registered services and their health status

Open Dashboard
PostgreSQL Admin

Manage PostgreSQL databases for Order, Payment, and Product services

Open PgAdmin
MongoDB Admin

View MongoDB collections for Customer and Notification services

Open Mongo Express
Email Testing

View sent emails and test notification functionality

Open MailDev

Enterprise Deployment with Kubernetes

Kubernetes Native

Complete Kubernetes deployment manifests with Helm charts for production-ready deployment.

  • Deployment configurations for all services
  • Service discovery and load balancing
  • ConfigMaps and Secrets management
  • Ingress controllers and networking

Blue-Green Deployment

Zero-downtime deployment strategy with automated rollback capabilities for production environments.

  • Automated blue-green switching
  • Health checks and readiness probes
  • Instant rollback on failure
  • Traffic splitting for gradual rollouts

Helm Chart Deployment

Deploy the entire microservices stack:
# Install the complete microservices platform helm install ecommerce-platform ./k8s/helm-charts \ --namespace microservices \ --create-namespace # Verify deployment kubectl get pods -n microservices # Check services kubectl get svc -n microservices
Helm Features:
  • Parameterized deployments
  • Environment-specific values
  • Dependency management
  • Release versioning
  • Easy upgrades & rollbacks

Blue-Green Deployment Process

1
Prepare Green Environment

Deploy new version to green environment while blue serves production traffic

./k8s/blue-green-deploy.sh prepare-green v2.0.0
2
Health Check & Validation

Automated health checks ensure green environment is ready for production

./k8s/blue-green-deploy.sh validate-green
3
Switch Traffic

Instantly switch production traffic from blue to green environment

./k8s/blue-green-deploy.sh switch-to-green
4
Rollback if Needed

Instant rollback to blue environment if issues are detected

./k8s/blue-green-deploy.sh rollback-to-blue

Production-Ready Kubernetes Features

Security
  • Network policies for isolation
  • RBAC (Role-Based Access Control)
  • Secrets management
  • Pod security contexts
Monitoring & Observability
  • Prometheus metrics collection
  • Grafana dashboards
  • Distributed tracing with Jaeger
  • Centralized logging with ELK stack
Scalability
  • Horizontal Pod Autoscaling (HPA)
  • Vertical Pod Autoscaling (VPA)
  • Resource quotas and limits
  • Load balancing with ingress

Quick Start with Kubernetes

Prerequisites:
  • Docker Desktop with Kubernetes enabled
  • kubectl CLI tool
  • Helm 3.x installed
# 1. Build and push Docker images ./k8s/build-images.sh # 2. Deploy with Helm helm install microservices ./k8s/helm-charts \ --namespace microservices \ --create-namespace \ --set global.environment=production # 3. Access the application kubectl port-forward svc/gateway-service 8222:8222 -n microservices # 4. Monitor deployment kubectl get all -n microservices kubectl logs -f deployment/gateway-service -n microservices

Complete Source Code Available

Access the complete, production-ready microservices implementation with detailed documentation, configuration files, and step-by-step commit history.

  • Complete Spring Boot 3.2.5 implementation
  • Docker Compose configuration
  • Detailed README documentation
  • Step-by-step commit history
  • Production-ready configurations
  • Comprehensive testing examples
  • MIT License - Free to use
  • Active community support

Repository

fully-completed-microservices

Spring Boot Microservices Architecture

Java Production Ready Educational