0% found this document useful (0 votes)
3 views42 pages

Enterprise ECommerce Java Backend Guide

The document outlines a comprehensive architecture and implementation guide for an Enterprise E-Commerce Order Management Platform built using Java 21, Spring Boot 3, Oracle, Kafka, and Redis. It details the business requirements, microservices architecture, database design, and user roles, emphasizing the need for scalability, fault isolation, and independent service deployment. The guide is intended for Java backend developers with three years of experience, focusing on microservices engineering and includes sections on security, DevOps, and testing strategies.

Uploaded by

banothsuresh0001
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views42 pages

Enterprise ECommerce Java Backend Guide

The document outlines a comprehensive architecture and implementation guide for an Enterprise E-Commerce Order Management Platform built using Java 21, Spring Boot 3, Oracle, Kafka, and Redis. It details the business requirements, microservices architecture, database design, and user roles, emphasizing the need for scalability, fault isolation, and independent service deployment. The guide is intended for Java backend developers with three years of experience, focusing on microservices engineering and includes sections on security, DevOps, and testing strategies.

Uploaded by

banothsuresh0001
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

ENTERPRISE E-COMMERCE
ORDER MANAGEMENT PLATFORM
Complete Architecture & Implementation Guide

Java 21 | Spring Boot 3 | Oracle DB | Kafka | Redis | Docker


Microservices | Spring Security | JWT | Spring Cloud | GitHub Actions

Designed for Java Backend Developers targeting Enterprise Roles


3 YOE | Senior / Microservices Engineer Level

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

Table of Contents

Section 1 — Business Requirements & System Overview


Section 2 — Complete Microservices Architecture
Section 3 — Project Structure & Organization
Section 4 — Oracle Database Design
Section 5 — API Design & REST Endpoints
Section 6 — Security Design (JWT + OAuth2)
Section 7 — Microservice Communication (Kafka + OpenFeign)
Section 8 — Distributed Transactions & Saga Pattern
Section 9 — Redis Caching Strategy
Section 10 — Resilience & Scalability Patterns
Section 11 — DevOps, Docker & CI/CD
Section 12 — Monitoring, Logging & Observability
Section 13 — Testing Strategy
Section 14 — Step-by-Step Implementation Plan
Section 15 — Interview Preparation Guide
Section 16 — GitHub & Resume Preparation
Section 17 — Advanced Features & Future Roadmap

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 1 | BUSINESS REQUIREMENTS & SYSTEM OVERVIEW

1.1 Business Problem Statement


Modern e-commerce platforms must handle millions of concurrent users, maintain real-time inventory
accuracy, process payments reliably, and ensure that every order follows a consistent lifecycle —
regardless of failures in individual services. Traditional monolithic applications cannot scale to meet
these demands, which is why companies like Amazon, Flipkart, and Swiggy moved to microservices-
based architectures.
This platform simulates a real-world Order Management System (OMS) that mirrors the backend
architecture used at product companies. It solves these core problems:
• Decoupled service ownership — each team owns one service independently
• Independent deployability — deploy Payment Service without touching Order Service
• Fault isolation — a Notification failure does not cascade to Orders
• Horizontal scalability — scale only the services under load
• Audit trails and compliance — every state change is recorded

1.2 User Roles & Permissions


Role Permissions Key Actions
CUSTOMER Browse, cart, order, pay, track Register, login, browse products, add to cart,
place order, view order history, raise returns
SELLER Manage products, view orders, Add/update products, set stock levels, view
manage inventory orders for their products, manage shipping
ADMIN Full system access Manage all users/sellers, view all orders,
configure system, access dashboards,
manage categories

1.3 Complete Order Lifecycle


Order State Machine
CART_CREATED -> ORDER_PLACED -> PAYMENT_PENDING -> PAYMENT_SUCCESS /
PAYMENT_FAILED -> INVENTORY_RESERVED -> ORDER_CONFIRMED -> PROCESSING ->
SHIPPED -> OUT_FOR_DELIVERY -> DELIVERED | CANCELLED | RETURN_REQUESTED ->
RETURN_APPROVED -> REFUND_INITIATED -> REFUNDED

State Trigger Next States


CART_CREATED Customer adds item to cart ORDER_PLACED
ORDER_PLACED Customer clicks 'Place PAYMENT_PENDING
Order'
PAYMENT_PENDIN Order submitted, awaiting PAYMENT_SUCCESS, PAYMENT_FAILED
G payment

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

PAYMENT_SUCCES Payment gateway confirms INVENTORY_RESERVED


S
PAYMENT_FAILED Payment gateway rejects / CANCELLED (auto)
timeout
INVENTORY_RESE Stock deducted from ORDER_CONFIRMED
RVED warehouse
ORDER_CONFIRME All validations passed PROCESSING
D
PROCESSING Warehouse picks and packs SHIPPED
SHIPPED Logistics partner picks up OUT_FOR_DELIVERY
DELIVERED Customer receives package RETURN_REQUESTED (optional)
CANCELLED Customer/system cancels REFUND_INITIATED
REFUNDED Money returned to source Terminal state

1.4 Payment Lifecycle


• Customer initiates checkout -> Order Service calls Payment Service via REST (sync)
• Payment Service creates a PENDING payment record with an idempotency key
• Payment Service calls mock payment gateway (Stripe/Razorpay simulation)
• Gateway webhook fires SUCCESS/FAILURE -> Payment Service updates record
• Payment Service publishes [Link] or [Link] Kafka event
• Order Service consumes the event and transitions order state accordingly
• On failure: Saga compensating transaction triggers inventory rollback

1.5 Inventory Lifecycle


• AVAILABLE_STOCK = total stock added by Seller
• RESERVED_STOCK = stock held for pending orders (not yet delivered)
• SOLD_STOCK = delivered orders
• On order placement: AVAILABLE -> RESERVED (optimistic lock)
• On delivery confirmation: RESERVED -> SOLD
• On cancellation/payment failure: RESERVED -> AVAILABLE (compensating transaction)
• Low stock alert published to Kafka when AVAILABLE < threshold

1.6 Notification Workflow


Event Channel Recipients
Order Placed Email + Push Customer, Seller
Payment Success Email + SMS Customer
Payment Failed Email Customer
Order Shipped Email + SMS + Customer

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

Push
Order Delivered Email + Push Customer, Seller
Low Inventory Email Seller, Admin
Return Approved Email + SMS Customer
Refund Processed Email + SMS Customer

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 2 | COMPLETE MICROSERVICES ARCHITECTURE

2.1 Architecture Overview


Architecture Pattern
Microservices with Event-Driven Architecture. Services communicate via REST (synchronous) for
real-time queries and Kafka (asynchronous) for business events. Each service owns its own Oracle
schema (Database-per-Service pattern). Spring Cloud handles service discovery, config
management, and gateway routing.

2.2 Service Registry


Service Port Responsibility
api-gateway 8080 Single entry point — routing, auth filter, rate limiting
auth-service 8081 JWT issuance, refresh tokens, OAuth2, password management
user-service 8082 Customer/Seller profiles, addresses, preferences
product-service 8083 Product catalog, categories, search, pricing
cart-service 8084 Shopping cart CRUD, price recalculation, coupon validation
order-service 8085 Order lifecycle, state machine, order history
payment-service 8086 Payment processing, refunds, idempotency
inventory-service 8087 Stock management, reservations, low-stock alerts
notification-service 8088 Email/SMS/Push via Kafka events (async only)
admin-service 8089 Admin dashboard APIs, reports, system config
config-server 8888 Centralized config (Spring Cloud Config)
service-registry 8761 Eureka server for service discovery

2.3 Service Communication Strategy


Synchronous Communication (REST via OpenFeign)
• API Gateway -> Any service: Route and forward JWT-authenticated requests
• Order Service -> Payment Service: Initiate payment (user waits for response)
• Order Service -> Inventory Service: Check stock availability before placing order
• Cart Service -> Product Service: Fetch real-time product prices and availability
• Admin Service -> All services: Aggregate data for dashboard reports

Asynchronous Communication (Apache Kafka)


• Order placed -> Inventory Service reserves stock, Notification sends email
• Payment success/failure -> Order Service transitions state

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

• Inventory reserved -> Order Service confirms order


• Order shipped -> Notification Service sends SMS + email
• Low stock -> Notification Service alerts seller and admin

2.4 Database Ownership Per Service


Service Oracle Schema Key Tables
auth-service AUTH_SCHEMA users_auth, refresh_tokens, oauth_accounts
user-service USER_SCHEMA customers, sellers, addresses, profiles
product-service PRODUCT_SCHEMA products, categories, product_images, reviews
cart-service CART_SCHEMA carts, cart_items
order-service ORDER_SCHEMA orders, order_items, order_status_history
payment-service PAYMENT_SCHEMA payments, refunds, payment_outbox
inventory-service INVENTORY_SCHE inventory, inventory_reservations, warehouses
MA
notification-service NOTIF_SCHEMA notification_logs, templates
admin-service ADMIN_SCHEMA admin_users, audit_logs, system_config

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 3 | PROJECT STRUCTURE & ORGANIZATION

3.1 Monorepo Maven Multi-Module Structure


ecommerce-platform/ <- Root Maven POM
[Link] <- Parent POM (dependency management)
[Link] <- All infrastructure + services
.github/workflows/[Link] <- GitHub Actions pipeline
[Link] <- Architecture overview
docs/ <- Architecture diagrams ([Link])
scripts/ <- DB init scripts, local setup
|
+-- common/ <- Shared library module
| +-- common-dto/ <- Shared request/response DTOs
| +-- common-exception/ <- Global exception classes
| +-- common-utils/ <- Utility helpers
| +-- common-security/ <- JWT utilities shared
|
+-- infrastructure/
| +-- config-server/ <- Spring Cloud Config Server
| +-- service-registry/ <- Eureka Discovery Server
| +-- api-gateway/ <- Spring Cloud Gateway
|
+-- services/
+-- auth-service/
+-- user-service/
+-- product-service/
+-- cart-service/
+-- order-service/
+-- payment-service/
+-- inventory-service/
+-- notification-service/
+-- admin-service/

3.2 Standard Package Structure (Per Service)


order-service/
src/main/java/com/ecommerce/order/
|-- [Link]
|-- config/ <- Spring beans, Kafka config, Redis config
|-- controller/ <- REST controllers (@RestController)
|-- service/ <- Business logic interfaces + impl
| +-- impl/
|-- repository/ <- Spring Data JPA repositories
|-- entity/ <- JPA entities (@Entity)
|-- dto/
| +-- request/ <- Inbound request DTOs
| +-- response/ <- Outbound response DTOs
| +-- event/ <- Kafka event DTOs

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis
|-- mapper/ <- MapStruct mappers
|-- exception/ <- Service-specific exceptions
|-- kafka/
| +-- producer/ <- Kafka event publishers
| +-- consumer/ <- Kafka event listeners
|-- feign/ <- OpenFeign client interfaces
|-- validator/ <- Custom validators
|-- util/ <- Constants, helpers
|-- security/ <- Service-level security config
src/main/resources/
|-- [Link]
|-- [Link]
|-- [Link]
|-- db/migration/ <- Flyway SQL migration scripts
src/test/java/com/ecommerce/order/
|-- controller/ <- MockMvc controller tests
|-- service/ <- Unit tests
|-- integration/ <- Testcontainers integration tests
|-- kafka/ <- Kafka consumer/producer tests

3.3 Naming Conventions


Layer Convention
Entity class Order, OrderItem, Payment (singular noun)
Repository OrderRepository extends JpaRepository<Order, Long>
Service interface OrderService (interface)
Service impl OrderServiceImpl implements OrderService
Controller OrderController (@RequestMapping("/api/v1/orders"))
DTO Request CreateOrderRequest, UpdateOrderRequest
DTO Response OrderResponse, OrderSummaryResponse
Kafka Event OrderPlacedEvent, PaymentCompletedEvent
Kafka Topic [Link], [Link], [Link]
Exception OrderNotFoundException, InsufficientStockException
Feign Client PaymentServiceClient, InventoryServiceClient
Mapper OrderMapper (MapStruct interface)

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 4 | ORACLE DATABASE DESIGN

4.1 Oracle-Specific Conventions


Why Oracle?
Oracle is the enterprise standard at banking, telecom, retail giants (Walmart, TCS, Infosys projects).
Oracle sequences replace auto-increment, DATE/TIMESTAMP WITH TIME ZONE for precision,
VARCHAR2 instead of VARCHAR, and NUMBER instead of INT/DECIMAL. Using Oracle on your
project immediately signals enterprise-level experience.

• Use SEQUENCES for primary key generation (not IDENTITY columns for portability)
• Table and column names in UPPER_SNAKE_CASE (Oracle standard)
• All tables include: CREATED_AT, UPDATED_AT, CREATED_BY, IS_DELETED (soft delete)
• Optimistic locking via VERSION column (mapped to @Version in JPA)
• All foreign keys indexed explicitly
• Use CLOB for large text (product descriptions)
• Use BLOB for binary storage references (image URLs stored as VARCHAR2)

4.2 AUTH_SCHEMA
-- AUTH_SCHEMA.USERS_AUTH
CREATE TABLE AUTH_SCHEMA.USERS_AUTH (
ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
EMAIL VARCHAR2(255) NOT NULL UNIQUE,
PASSWORD_HASH VARCHAR2(255) NOT NULL,
ROLE VARCHAR2(20) NOT NULL, -- CUSTOMER, SELLER, ADMIN
IS_ACTIVE NUMBER(1) DEFAULT 1,
IS_EMAIL_VERIFIED NUMBER(1) DEFAULT 0,
FAILED_LOGIN_ATTEMPTS NUMBER DEFAULT 0,
LOCKED_UNTIL TIMESTAMP WITH TIME ZONE,
IS_DELETED NUMBER(1) DEFAULT 0,
VERSION NUMBER DEFAULT 0,
CREATED_AT TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP,
UPDATED_AT TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP
);

-- AUTH_SCHEMA.REFRESH_TOKENS
CREATE TABLE AUTH_SCHEMA.REFRESH_TOKENS (
ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
USER_ID NUMBER NOT NULL REFERENCES AUTH_SCHEMA.USERS_AUTH(ID),
TOKEN_HASH VARCHAR2(500) NOT NULL UNIQUE,
DEVICE_INFO VARCHAR2(500),
IP_ADDRESS VARCHAR2(45),
EXPIRES_AT TIMESTAMP WITH TIME ZONE NOT NULL,
IS_REVOKED NUMBER(1) DEFAULT 0,
CREATED_AT TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP
);

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

CREATE INDEX IDX_REFRESH_TOKEN_USER ON AUTH_SCHEMA.REFRESH_TOKENS(USER_ID);


CREATE INDEX IDX_REFRESH_TOKEN_HASH ON AUTH_SCHEMA.REFRESH_TOKENS(TOKEN_HASH);

4.3 ORDER_SCHEMA
-- ORDER_SCHEMA.ORDERS
CREATE TABLE ORDER_SCHEMA.ORDERS (
ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
ORDER_NUMBER VARCHAR2(50) NOT NULL UNIQUE, -- ORD-20240528-001
CUSTOMER_ID NUMBER NOT NULL,
STATUS VARCHAR2(30) NOT NULL,
SUBTOTAL NUMBER(12,2) NOT NULL,
DISCOUNT_AMOUNT NUMBER(12,2) DEFAULT 0,
TAX_AMOUNT NUMBER(12,2) DEFAULT 0,
DELIVERY_CHARGE NUMBER(12,2) DEFAULT 0,
TOTAL_AMOUNT NUMBER(12,2) NOT NULL,
SHIPPING_ADDRESS_ID NUMBER NOT NULL,
PAYMENT_METHOD VARCHAR2(30),
IDEMPOTENCY_KEY VARCHAR2(100) UNIQUE,
NOTES VARCHAR2(1000),
IS_DELETED NUMBER(1) DEFAULT 0,
VERSION NUMBER DEFAULT 0,
CREATED_AT TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP,
UPDATED_AT TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP,
CREATED_BY VARCHAR2(100)
);

-- ORDER_SCHEMA.ORDER_ITEMS
CREATE TABLE ORDER_SCHEMA.ORDER_ITEMS (
ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
ORDER_ID NUMBER NOT NULL REFERENCES ORDER_SCHEMA.ORDERS(ID),
PRODUCT_ID NUMBER NOT NULL,
PRODUCT_NAME VARCHAR2(500) NOT NULL, -- Snapshot at order time
SKU VARCHAR2(100) NOT NULL,
QUANTITY NUMBER NOT NULL,
UNIT_PRICE NUMBER(10,2) NOT NULL,
TOTAL_PRICE NUMBER(10,2) NOT NULL,
SELLER_ID NUMBER NOT NULL,
VERSION NUMBER DEFAULT 0,
CREATED_AT TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP
);

-- ORDER_SCHEMA.ORDER_STATUS_HISTORY
CREATE TABLE ORDER_SCHEMA.ORDER_STATUS_HISTORY (
ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
ORDER_ID NUMBER NOT NULL REFERENCES ORDER_SCHEMA.ORDERS(ID),
FROM_STATUS VARCHAR2(30),
TO_STATUS VARCHAR2(30) NOT NULL,
REMARKS VARCHAR2(1000),

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis
CHANGED_BY VARCHAR2(100),
CHANGED_AT TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP
);

CREATE INDEX IDX_ORDER_CUSTOMER ON ORDER_SCHEMA.ORDERS(CUSTOMER_ID);


CREATE INDEX IDX_ORDER_STATUS ON ORDER_SCHEMA.ORDERS(STATUS);
CREATE INDEX IDX_ORDER_CREATED ON ORDER_SCHEMA.ORDERS(CREATED_AT);
CREATE INDEX IDX_ITEMS_ORDER ON ORDER_SCHEMA.ORDER_ITEMS(ORDER_ID);
CREATE INDEX IDX_ITEMS_PRODUCT ON ORDER_SCHEMA.ORDER_ITEMS(PRODUCT_ID);

4.4 PAYMENT_SCHEMA
CREATE TABLE PAYMENT_SCHEMA.PAYMENTS (
ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
PAYMENT_REF VARCHAR2(50) NOT NULL UNIQUE, -- PAY-20240528-001
ORDER_ID NUMBER NOT NULL,
CUSTOMER_ID NUMBER NOT NULL,
AMOUNT NUMBER(12,2) NOT NULL,
CURRENCY VARCHAR2(5) DEFAULT 'INR',
STATUS VARCHAR2(20) NOT NULL, -- PENDING, SUCCESS, FAILED, REFUNDED
PAYMENT_METHOD VARCHAR2(30), -- CREDIT_CARD, UPI, NETBANKING
GATEWAY_TXN_ID VARCHAR2(200),
GATEWAY_RESPONSE VARCHAR2(4000),
IDEMPOTENCY_KEY VARCHAR2(100) NOT NULL UNIQUE,
RETRY_COUNT NUMBER DEFAULT 0,
IS_DELETED NUMBER(1) DEFAULT 0,
VERSION NUMBER DEFAULT 0,
CREATED_AT TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP,
UPDATED_AT TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP
);

-- Outbox table for guaranteed event publishing


CREATE TABLE PAYMENT_SCHEMA.PAYMENT_OUTBOX (
ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
AGGREGATE_ID VARCHAR2(100) NOT NULL,
EVENT_TYPE VARCHAR2(100) NOT NULL,
PAYLOAD CLOB NOT NULL,
STATUS VARCHAR2(20) DEFAULT 'PENDING', -- PENDING, PUBLISHED, FAILED
RETRY_COUNT NUMBER DEFAULT 0,
PUBLISHED_AT TIMESTAMP WITH TIME ZONE,
CREATED_AT TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP
);

CREATE INDEX IDX_OUTBOX_STATUS ON PAYMENT_SCHEMA.PAYMENT_OUTBOX(STATUS);

4.5 INVENTORY_SCHEMA
CREATE TABLE INVENTORY_SCHEMA.INVENTORY (
ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
PRODUCT_ID NUMBER NOT NULL UNIQUE,

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis
SKU VARCHAR2(100) NOT NULL UNIQUE,
AVAILABLE_QUANTITY NUMBER NOT NULL DEFAULT 0,
RESERVED_QUANTITY NUMBER NOT NULL DEFAULT 0,
SOLD_QUANTITY NUMBER NOT NULL DEFAULT 0,
LOW_STOCK_THRESHOLD NUMBER DEFAULT 10,
WAREHOUSE_LOCATION VARCHAR2(200),
IS_DELETED NUMBER(1) DEFAULT 0,
VERSION NUMBER DEFAULT 0, -- Optimistic locking
CREATED_AT TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP,
UPDATED_AT TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP
);

CREATE TABLE INVENTORY_SCHEMA.INVENTORY_RESERVATIONS (


ID NUMBER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
ORDER_ID NUMBER NOT NULL,
PRODUCT_ID NUMBER NOT NULL,
QUANTITY_RESERVED NUMBER NOT NULL,
STATUS VARCHAR2(20) DEFAULT 'ACTIVE', -- ACTIVE, RELEASED, CONSUMED
EXPIRES_AT TIMESTAMP WITH TIME ZONE, -- Auto-release if payment timeout
CREATED_AT TIMESTAMP WITH TIME ZONE DEFAULT SYSTIMESTAMP
);

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 5 | API DESIGN & REST ENDPOINTS

5.1 API Design Principles


• All APIs versioned: /api/v1/resource
• Consistent response envelope: {success, message, data, errors, timestamp}
• HTTP status codes strictly followed (200, 201, 400, 401, 403, 404, 409, 500)
• Bean Validation (@Valid) on all request bodies
• OpenAPI 3.0 with Swagger UI on every service
• Idempotency-Key header required on payment and order creation

5.2 Standard Response Envelope


// ApiResponse<T> — used by ALL services
{
"success": true,
"message": "Order placed successfully",
"data": { ... },
"errors": null,
"timestamp": "2024-05-28T10:30:00Z",
"traceId": "abc-123-xyz"
}

5.3 Auth Service APIs


Method Endpoint Description
POST /api/v1/auth/register Register new customer/seller
POST /api/v1/auth/login Login -> returns JWT + refresh token
POST /api/v1/auth/refresh Refresh expired access token
POST /api/v1/auth/logout Revoke refresh token
POST /api/v1/auth/forgot-password Send password reset email
PUT /api/v1/auth/reset-password Reset password with token
GET /api/v1/auth/oauth2/google OAuth2 Google login redirect

5.4 Order Service APIs


Method Endpoint Description
POST /api/v1/orders Place new order (requires Idempotency-Key
header)
GET /api/v1/orders/{orderId} Get order details

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

GET /api/v1/orders/my-orders Get current user's order history (paginated)


PUT /api/v1/orders/{orderId}/cancel Cancel an order
POST /api/v1/orders/{orderId}/return Request return
GET /api/v1/orders/{orderId}/tracking Get order tracking status
GET /api/v1/orders/admin/all Admin: get all orders (filtered, paginated)

5.5 Product Service APIs


Method Endpoint Description
GET /api/v1/products List products (filter, sort, paginate)
GET /api/v1/products/{productId} Get product details
POST /api/v1/products Seller: create product
PUT /api/v1/products/{productId} Seller: update product
DELET /api/v1/products/{productId} Seller: soft-delete product
E
GET /api/v1/products/search?q=term Search products by keyword
GET /api/v1/categories List all categories
POST /api/v1/products/{productId}/reviews Customer: post review

5.6 Payment Service APIs


Method Endpoint Description
POST /api/v1/payments/initiate Initiate payment for an order
POST /api/v1/payments/webhook Payment gateway webhook (public)
GET /api/v1/payments/{paymentId} Get payment status
POST /api/v1/payments/{paymentId}/ Initiate refund
refund
GET /api/v1/payments/order/{orderId} Get payment by order ID

5.7 Inventory Service APIs


Method Endpoint Description
GET /api/v1/inventory/{productId} Get stock levels for a product
PUT /api/v1/inventory/{productId}/add- Seller: add stock
stock
POST /api/v1/inventory/reserve Internal: reserve stock for order
POST /api/v1/inventory/release Internal: release reserved stock

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

GET /api/v1/inventory/low-stock Admin: list products below threshold

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 6 | SECURITY DESIGN

6.1 JWT Authentication Flow


Flow Summary
1. Client sends credentials to Auth Service -> 2. Auth Service validates, creates JWT (15min) +
Refresh Token (7 days) -> 3. Client stores tokens -> 4. Every request sends JWT in Authorization:
Bearer <token> header -> 5. API Gateway validates JWT signature and expiry -> 6. Gateway
injects X-User-Id and X-User-Role headers for downstream services -> 7. Downstream services
trust these headers (no DB lookup needed per request)

6.2 JWT Token Structure


// Access Token Claims (15 minutes TTL)
{
"sub": "12345", // userId
"email": "user@[Link]",
"role": "CUSTOMER",
"iat": 1716892800, // issued at
"exp": 1716893700, // expires at (15 min)
"jti": "unique-jwt-id" // prevent replay
}

// Refresh Token — stored as SHA-256 hash in DB


// 7-day TTL, 1 device = 1 refresh token
// On use: rotate refresh token (new one issued, old invalidated)

6.3 Spring Security Config (API Gateway)


@Bean
public SecurityWebFilterChain gatewaySecurityChain(ServerHttpSecurity http) {
return http
.csrf([Link]::disable)
.sessionManagement(s -> [Link](STATELESS))
.authenticationManager(jwtAuthManager)
.securityContextRepository([Link]())
.authorizeExchange(exchanges -> exchanges
.pathMatchers("/api/v1/auth/**").permitAll()
.pathMatchers([Link], "/api/v1/products/**").permitAll()
.pathMatchers("/api/v1/admin/**").hasRole("ADMIN")
.anyExchange().authenticated()
)
.addFilterBefore(jwtAuthFilter, [Link])
.build();
}

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

6.4 Role-Based Access Control (RBAC)


Endpoint Pattern Allowed Roles Notes
/api/v1/auth/** PUBLIC Login, register, refresh
GET /api/v1/products/** PUBLIC Anyone can browse
POST /api/v1/products/** SELLER, ADMIN Only sellers create products
/api/v1/orders/** CUSTOMER, ADMIN Customers manage own orders
/api/v1/inventory/** SELLER, ADMIN Inventory management
/api/v1/admin/** ADMIN Full admin access only
Internal service APIs SERVICE_ROLE Machine-to-machine JWT

6.5 Security Best Practices


• Passwords hashed with BCrypt (strength factor 12)
• Account lockout after 5 failed login attempts (locked for 30 minutes)
• JWT signed with RS256 (asymmetric — private key signs, public key verifies)
• Refresh tokens stored as SHA-256 hash in Oracle, not plaintext
• HTTPS enforced in all environments (TLS 1.2+)
• CORS configured to whitelist only frontend domains
• SQL injection protection via JPA parameterized queries (never string concat)
• XSS protection via response headers (X-Content-Type-Options, X-Frame-Options)
• Rate limiting on auth endpoints: 5 attempts/minute per IP
• API Gateway validates JWT on every request — no service trusts incoming JWT directly

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 7 | MICROSERVICE COMMUNICATION

7.1 OpenFeign Configuration


// [Link] in order-service
@FeignClient(
name = "inventory-service",
fallbackFactory = [Link]
)
public interface InventoryServiceClient {
@PostMapping("/api/v1/inventory/reserve")
ApiResponse<ReservationResponse> reserveStock(
@RequestHeader("X-User-Id") String userId,
@RequestBody StockReservationRequest request
);
}

// Fallback factory for Circuit Breaker


@Component
public class InventoryServiceFallbackFactory
implements FallbackFactory<InventoryServiceClient> {
@Override
public InventoryServiceClient create(Throwable cause) {
return request -> {
[Link]("Inventory service unavailable: {}", [Link]());
throw new ServiceUnavailableException("Inventory service is down");
};
}
}

7.2 Kafka Topics & Event Design


Topic Producer Consumer(s)
[Link] order-service inventory-service, notification-service
[Link] order-service inventory-service, notification-service, payment-
service
[Link] payment-service order-service
[Link] payment-service order-service, notification-service
[Link] payment-service order-service, notification-service
[Link] inventory-service order-service
[Link] inventory-service order-service, notification-service
ed
[Link]-stock inventory-service notification-service

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

[Link] order-service notification-service


[Link] order-service notification-service, inventory-service

7.3 Kafka Event Payload Structure


// [Link]
public record OrderPlacedEvent(
String eventId, // UUID for idempotency
String eventType, // "ORDER_PLACED"
Instant eventTimestamp,
Long orderId,
String orderNumber,
Long customerId,
String customerEmail,
List<OrderItemDto> items,
BigDecimal totalAmount,
String shippingAddress
) {}

// Kafka Producer Config


@Bean
public ProducerFactory<String, Object> producerFactory() {
Map<String, Object> config = new HashMap<>();
[Link](ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
[Link](ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, [Link]);
[Link](ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, [Link]);
[Link](ProducerConfig.ACKS_CONFIG, "all"); // Strongest durability
[Link](ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true); // Exactly-once
[Link](ProducerConfig.RETRIES_CONFIG, 3);
return new DefaultKafkaProducerFactory<>(config);
}

7.4 Dead Letter Queue (DLQ) Strategy


// Consumer with DLQ — auto-creates DLQ topic: [Link]
@KafkaListener(topics = "[Link]", groupId = "order-service")
@RetryableTopic(
attempts = "3",
backoff = @Backoff(delay = 1000, multiplier = 2),
dltTopicSuffix = ".DLT"
)
public void handlePaymentCompleted(PaymentCompletedEvent event) {
[Link](event);
}

// DLQ listener — alert ops team


@DltHandler
public void handleDlt(PaymentCompletedEvent event) {
[Link]("DLQ: Failed to process payment event: {}", [Link]());

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis
[Link](event);
}

7.5 Outbox Pattern Implementation


The Outbox Pattern solves the dual-write problem: you need to save to DB AND publish a Kafka event
atomically. Without it, you risk saving the DB record but failing to publish the event (or vice versa).
// Step 1: In @Transactional method, save entity + outbox record together
@Transactional
public PaymentResponse initiatePayment(PaymentRequest request) {
Payment payment = [Link](buildPayment(request));

// Save outbox record IN SAME TRANSACTION


PaymentOutbox outbox = [Link]()
.aggregateId([Link]().toString())
.eventType("PAYMENT_INITIATED")
.payload([Link](buildEvent(payment)))
.status([Link])
.build();
[Link](outbox);

return mapToResponse(payment);
}

// Step 2: Scheduled poller publishes PENDING outbox records to Kafka


@Scheduled(fixedDelay = 1000) // Every 1 second
@Transactional
public void publishPendingEvents() {
List<PaymentOutbox> pending = outboxRepository
.findByStatusOrderByCreatedAtAsc([Link]);
[Link](record -> {
[Link]([Link]().toTopicName(), [Link]());
[Link]([Link]);
});
}

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 8 | DISTRIBUTED TRANSACTIONS & SAGA PATTERN

8.1 Why Distributed Transactions Are Hard


In a microservices architecture, a single business operation (placing an order) spans multiple services
and databases. Traditional ACID transactions do not work across service boundaries. If Order Service
commits but Payment Service fails, you have an inconsistent state.
The Saga Pattern solves this by breaking the distributed transaction into a sequence of local
transactions, each with a compensating action that can undo it if something fails later.

8.2 Choreography-Based Saga — Order Flow


Order Saga Steps
1. Order Service saves ORDER (PENDING) and publishes [Link] -> 2. Inventory Service
consumes, reserves stock, publishes [Link] (or [Link]) -> 3. Order
Service consumes [Link], transitions to INVENTORY_RESERVED, publishes
[Link] -> 4. Payment Service processes payment, publishes [Link] (or
[Link]) -> 5. Order Service consumes [Link] -> transitions to
ORDER_CONFIRMED -> 6. On any failure -> compensating transactions fire in reverse

8.3 Compensating Transactions (Rollback)


Failure Point Compensating Action Events Published
Inventory reservation Release any partial [Link]
fails reservations
Payment fails Release inventory reservation [Link], [Link]
Payment timeout Auto-cancel after 15 min, [Link], [Link]
release inventory
Order confirmed but Initiate return flow [Link]
shipping fails

8.4 Idempotency Implementation


// Idempotency on Order Creation
@PostMapping
public ResponseEntity<ApiResponse<OrderResponse>> createOrder(
@RequestHeader("Idempotency-Key") String idempotencyKey,
@Valid @RequestBody CreateOrderRequest request) {

// Check if same key was processed before


Optional<Order> existing = [Link](idempotencyKey);
if ([Link]()) {
return [Link]([Link](mapToResponse([Link]())));
}

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

[Link](idempotencyKey);
OrderResponse response = [Link](request);
return [Link](201).body([Link](response));
}

8.5 Optimistic Locking for Inventory


// Inventory entity with @Version
@Entity
@Table(name = "INVENTORY", schema = "INVENTORY_SCHEMA")
public class Inventory {
@Id
@GeneratedValue(strategy = [Link])
private Long id;

private Integer availableQuantity;


private Integer reservedQuantity;

@Version // Oracle: maps to VERSION column


private Long version;
}

// On concurrent updates, JPA throws OptimisticLockException


// Handle with retry:
@Retryable(value = [Link], maxAttempts = 3,
backoff = @Backoff(delay = 100))
public void reserveStock(Long productId, Integer quantity) {
Inventory inv = [Link](productId);
if ([Link]() < quantity) {
throw new InsufficientStockException(productId);
}
[Link]([Link]() - quantity);
[Link]([Link]() + quantity);
[Link](inv); // Will fail with version conflict if concurrent
}

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 9 | REDIS CACHING STRATEGY

9.1 What to Cache & Why


Data Redis Key Pattern TTL
Product catalog product:{productId} 30 minutes
Product list (paginated) products:page:{page}:size:{size}:cat: 10 minutes
{cat}
Category tree categories:all 2 hours
Cart cart:{userId} 24 hours (rolling)
User session/profile user:session:{userId} 15 minutes (matches JWT)
Rate limit counter rate_limit:{ip}:{endpoint} 1 minute
Inventory count (read) inventory:{productId}:available 5 minutes
Order status order:{orderId}:status 5 minutes

9.2 Spring Cache Configuration


@Configuration
@EnableCaching
public class RedisCacheConfig {

@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
Map<String, RedisCacheConfiguration> configs = new HashMap<>();

// Per-cache TTL configuration


[Link]("products", defaultConfig().entryTtl([Link](30)));
[Link]("categories", defaultConfig().entryTtl([Link](2)));
[Link]("inventory", defaultConfig().entryTtl([Link](5)));

return [Link](factory)
.cacheDefaults(defaultConfig())
.withInitialCacheConfigurations(configs)
.build();
}

private RedisCacheConfiguration defaultConfig() {


return [Link]()
.entryTtl([Link](10))
.serializeValuesWith(RedisSerializationContext
.[Link](new
GenericJackson2JsonRedisSerializer()));
}
}

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

// Usage on Service method


@Cacheable(value = "products", key = "#productId")
public ProductResponse getProduct(Long productId) { ... }

@CacheEvict(value = "products", key = "#productId")


public void updateProduct(Long productId, ...) { ... }

9.3 Cart Cache (Redis Hash)


// Cart stored as Redis Hash: cart:{userId}
// Field: productId, Value: CartItemDto JSON

@Service
public class CartCacheService {
private final RedisTemplate<String, Object> redisTemplate;
private static final Duration CART_TTL = [Link](24);

public void addItem(Long userId, Long productId, CartItemDto item) {


String key = "cart:" + userId;
[Link]().put(key, [Link](),
[Link](item));
[Link](key, CART_TTL); // Reset TTL on every activity
}

public Map<Object, Object> getCart(Long userId) {


return [Link]().entries("cart:" + userId);
}

public void clearCart(Long userId) {


[Link]("cart:" + userId);
}
}

9.4 Redis Rate Limiting


// Token bucket rate limiting — 100 req/min per user
@Component
public class RateLimiter {
private final RedisTemplate<String, String> redisTemplate;

public boolean isAllowed(String userId, String endpoint, int maxRequests) {


String key = "rate_limit:" + userId + ":" + endpoint;
Long count = [Link]().increment(key);
if (count == 1) {
[Link](key, [Link](1));
}
return count <= maxRequests;
}
}

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 10 | RESILIENCE & SCALABILITY PATTERNS

10.1 Resilience4j Circuit Breaker


# [Link] — Circuit Breaker config for Payment Service calls
resilience4j:
circuitbreaker:
instances:
paymentService:
registerHealthIndicator: true
slidingWindowSize: 10
minimumNumberOfCalls: 5
failureRateThreshold: 50 # Open if >50% fail
waitDurationInOpenState: 30s # Wait 30s before trying again
permittedNumberOfCallsInHalfOpenState: 3
automaticTransitionFromOpenToHalfOpenEnabled: true
retry:
instances:
inventoryService:
maxAttempts: 3
waitDuration: 500ms
retryExceptions:
- [Link]
- [Link]
bulkhead:
instances:
notificationService:
maxConcurrentCalls: 10 # Limit concurrent calls to Notification
maxWaitDuration: 500ms

10.2 Circuit Breaker on Feign Client


@FeignClient(name = "payment-service", fallbackFactory = [Link])
public interface PaymentServiceClient {
@CircuitBreaker(name = "paymentService", fallbackMethod = "paymentFallback")
@Retry(name = "paymentService")
ApiResponse<PaymentResponse> initiatePayment(PaymentRequest request);
}

10.3 Scalability Considerations


Concern Solution
Product service high read Redis cache, read-replica Oracle DB, CDN for images
load
Order service high write load Kafka decoupling, async processing, connection pooling (HikariCP)
Payment service SLA Circuit breaker, idempotency, timeout (5s), async webhook processing

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

Database connection pool HikariCP: max pool = 20, min idle = 5, connection timeout = 30s
Kafka consumer lag Scale consumer instances (same consumer group), increase partitions
API Gateway overload Horizontal scaling, Redis-backed rate limiting, Spring Cloud
LoadBalancer

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 11 | DEVOPS, DOCKER & CI/CD

11.1 Docker Compose — Full Stack


# [Link] (infrastructure only — run this first)
version: '3.8'
services:
oracle-db:
image: gvenzl/oracle-xe:21-slim
environment:
ORACLE_PASSWORD: SecurePass123
ports: ['1521:1521']
volumes: ['oracle_data:/opt/oracle/oradata']

redis:
image: redis:7-alpine
ports: ['6379:6379']
command: redis-server --requirepass redis_password

zookeeper:
image: confluentinc/cp-zookeeper:7.4.0
environment:
ZOOKEEPER_CLIENT_PORT: 2181

kafka:
image: confluentinc/cp-kafka:7.4.0
depends_on: [zookeeper]
ports: ['9092:9092']
environment:
KAFKA_BROKER_ID: 1
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
KAFKA_AUTO_CREATE_TOPICS_ENABLE: 'true'
KAFKA_NUM_PARTITIONS: 3

kafka-ui:
image: provectuslabs/kafka-ui:latest
ports: ['8090:8080']
environment:
KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka:9092

prometheus:
image: prom/prometheus
ports: ['9090:9090']
volumes: ['./[Link]:/etc/prometheus/[Link]']

grafana:
image: grafana/grafana

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis
ports: ['3000:3000']

volumes:
oracle_data:

11.2 Dockerfile (Per Service)


# Multi-stage build — keeps final image small
FROM eclipse-temurin:21-jdk-alpine AS builder
WORKDIR /app
COPY [Link] .
COPY src ./src
RUN mvn clean package -DskipTests

FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
RUN addgroup -S spring && adduser -S spring -G spring # Non-root user
USER spring:spring
COPY --from=builder /app/target/*.jar [Link]
EXPOSE 8085
ENTRYPOINT ["java",
"-XX:+UseContainerSupport",
"-XX:MaxRAMPercentage=75.0",
"-[Link]=file:/dev/./urandom",
"-jar", "[Link]"]

11.3 GitHub Actions CI/CD Pipeline


# .github/workflows/[Link]
name: CI/CD Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main]

jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Java 21
uses: actions/setup-java@v4
with:
java-version: '21'
distribution: 'temurin'
- name: Cache Maven packages
uses: actions/cache@v3
with:
path: ~/.m2

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis
key: ${{ [Link] }}-maven-${{ hashFiles('**/[Link]') }}
- name: Build and Test
run: mvn clean verify
- name: Build Docker image
run: docker build -t [Link]/${{ [Link] }}/order-service:${{ [Link] }} .
- name: Push to GHCR
if: [Link] == 'refs/heads/main'
run: |
echo ${{ secrets.GITHUB_TOKEN }} | docker login [Link] -u $ --password-stdin
docker push [Link]/${{ [Link] }}/order-service:${{ [Link] }}

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 12 | MONITORING, LOGGING & OBSERVABILITY

12.1 Structured Logging with Correlation IDs


// Add Correlation ID to every log line via MDC
@Component
public class CorrelationIdFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res, FilterChain chain) throws ... {
String correlationId = [Link]("X-Correlation-Id");
if (correlationId == null) {
correlationId = [Link]().toString();
}
[Link]("correlationId", correlationId);
[Link]("userId", [Link]("X-User-Id"));
[Link]("X-Correlation-Id", correlationId);
try {
[Link](req, res);
} finally {
[Link]();
}
}
}

# [Link] — JSON structured logs


# Every log line contains: timestamp, level, correlationId, userId, service, message
# Makes logs searchable in ELK/Loki

12.2 Prometheus Metrics with Micrometer


# [Link]
management:
endpoints:
web:
exposure:
include: health,info,metrics,prometheus
metrics:
tags:
service: order-service
environment: ${SPRING_PROFILES_ACTIVE:dev}

// Custom business metric


@Service
public class OrderService {
private final Counter ordersPlacedCounter;
private final Timer orderProcessingTimer;

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis
public OrderService(MeterRegistry registry) {
ordersPlacedCounter = [Link]("[Link]",
"status", "success");
orderProcessingTimer = [Link]("[Link]");
}

public OrderResponse createOrder(CreateOrderRequest request) {


return [Link](() -> {
// ... business logic
[Link]();
});
}
}

12.3 Key Grafana Dashboards to Build


Dashboard Metrics to Monitor
Service Health HTTP request rate, error rate (5xx), p99 latency per service
Order Funnel Orders placed/hour, payment success rate, order confirmation rate
Kafka Lag Consumer group lag per topic, messages produced/consumed per second
JVM Health Heap usage, GC pause time, thread count, DB connection pool
Redis Hit rate, miss rate, memory usage, eviction count
Business KPIs Revenue/hour, failed payments/hour, inventory alerts

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 13 | TESTING STRATEGY

13.1 Testing Pyramid


Layer Tool What to Test
Unit Tests (60%) JUnit 5 + Mockito Service layer, mappers, validators, utility methods
Integration Tests Testcontainers + Full HTTP request -> DB flow, Kafka
(30%) MockMvc consumer/producer
Contract Tests Spring Cloud Contract API contracts between services (consumer-driven)
(10%)

13.2 Unit Test Example


@ExtendWith([Link])
class OrderServiceTest {
@Mock private OrderRepository orderRepository;
@Mock private InventoryServiceClient inventoryClient;
@Mock private KafkaEventPublisher eventPublisher;
@InjectMocks private OrderServiceImpl orderService;

@Test
void createOrder_whenStockAvailable_shouldReturnOrderResponse() {
// Arrange
when([Link](any())).thenReturn(stockAvailableResponse());
when([Link](any())).thenReturn(sampleOrder());

// Act
OrderResponse result = [Link](sampleRequest());

// Assert
assertThat([Link]()).isEqualTo(OrderStatus.ORDER_PLACED);
verify(eventPublisher, times(1)).publish(any([Link]));
}
}

13.3 Integration Test with Testcontainers


@SpringBootTest(webEnvironment = RANDOM_PORT)
@Testcontainers
class OrderControllerIntegrationTest {
@Container
static OracleContainer oracle = new OracleContainer("gvenzl/oracle-xe:21-slim")
.withDatabaseName("testdb")
.withUsername("test")
.withPassword("test");

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis
@Container
static KafkaContainer kafka = new KafkaContainer(
[Link]("confluentinc/cp-kafka:7.4.0"));

@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
[Link]("[Link]", oracle::getJdbcUrl);
[Link]("[Link]-servers", kafka::getBootstrapServers);
}

@Test
void placeOrder_withValidRequest_returns201() {
[Link]().uri("/api/v1/orders")
.header("Authorization", "Bearer " + getTestJwt())
.header("Idempotency-Key", [Link]().toString())
.bodyValue(validOrderRequest())
.exchange()
.expectStatus().isCreated()
.expectBody([Link])
.value(r -> assertThat([Link]()).isEqualTo("ORDER_PLACED"));
}
}

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 14 | STEP-BY-STEP IMPLEMENTATION PLAN

Week-by-Week Roadmap (10 Weeks)

Week Focus Deliverable


Week Foundation Setup Docker Compose with Oracle+Kafka+Redis running, parent POM,
1 config-server, eureka, API gateway shell
Week Auth Service Full JWT auth: register, login, refresh token, Spring Security config,
2 Oracle schema, unit tests
Week User + Product User profiles, product CRUD, Redis caching for products, category
3 Service management, Swagger docs
Week Cart + Inventory Redis-backed cart, inventory management, optimistic locking, stock
4 Service reservation API
Week Order Service Order placement, state machine, OpenFeign calls to inventory,
5 order history, Outbox pattern
Week Payment Service Payment initiation, mock gateway, webhook simulation,
6 idempotency, Outbox, DLQ
Week Saga + Kafka Wiring Full choreography Saga: [Link] -> [Link] ->
7 [Link] -> [Link]
Week Notification + Admin Async Kafka-driven notifications, admin dashboard APIs, reporting
8 endpoints
Week Resilience + Security Circuit Breaker, rate limiting, API Gateway auth filter, security
9 hardening, error handling
Week DevOps + Polish Full Dockerization, GitHub Actions CI/CD, Prometheus/Grafana,
10 integration tests, README + diagrams

Common Beginner Mistakes to Avoid


• DO NOT call other service DBs directly — always go through the service's API
• DO NOT skip idempotency on order and payment creation
• DO NOT put business logic in controllers — controllers only handle HTTP concerns
• DO NOT use String for money — always use BigDecimal
• DO NOT forget to handle Kafka consumer failures with DLQ
• DO NOT store JWTs in Oracle — they are stateless; only refresh token hashes go in DB
• DO NOT use EAGER loading for JPA relations — always use LAZY and fetch explicitly
• DO NOT use SELECT * queries — always project needed fields with DTOs

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 15 | INTERVIEW PREPARATION GUIDE

15.1 How to Explain Your Architecture (2-Minute Pitch)


Script Template
"I built a production-style microservices e-commerce platform with 9 services using Java 21, Spring
Boot 3, and Oracle DB. Services communicate synchronously via OpenFeign for real-time queries
and asynchronously via Kafka for business events. I implemented the Saga choreography pattern for
distributed order-payment-inventory transactions, with the Outbox pattern guaranteeing exactly-once
event delivery. The API Gateway handles JWT authentication and Redis-backed rate limiting. I
containerized everything with Docker and set up a GitHub Actions CI/CD pipeline with Prometheus
and Grafana monitoring."

15.2 Must-Know Interview Questions & Answers


Question Key Points to Mention
How do you handle distributed Saga pattern (choreography), compensating transactions, Outbox
transactions? pattern, idempotency keys, no 2PC
Why Kafka over REST for some Decoupling, async processing, guaranteed delivery, retry, DLQ,
communication? consumer group scaling
How do you prevent duplicate Idempotency-Key header, check DB before processing, UNIQUE
orders? constraint on idempotency_key
How do you handle payment [Link] Kafka event, Order Service transitions to
failure? CANCELLED, Inventory Service releases stock
Why Oracle over PostgreSQL? Enterprise standard, SEQUENCES, VARCHAR2, robust
partitioning, used at Walmart/TCS/banks
How does your JWT auth work? RS256 signed, API Gateway validates, injects X-User-Id header,
services trust gateway headers
How do you handle Kafka RetryableTopic with exponential backoff (3 retries), then DLT, DLQ
message failure? listener alerts ops
How do you cache product data? Redis @Cacheable with 30min TTL, @CacheEvict on update,
cache key includes productId
What is the Outbox Pattern? Save event to DB in same transaction as entity, scheduled poller
publishes to Kafka, prevents dual-write problem
How do you scale this system? Horizontal scaling per service, Kafka partition scaling, Redis
cluster, Oracle read replicas, K8s HPA

15.3 Trade-off Discussions


Decision Trade-off Explanation
Choreography vs Orchestration Chose choreography: no single point of failure, services
Saga decoupled. Downside: harder to visualize flow. For complex flows,

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

Orchestration (Temporal/Camunda) is better.


Sync vs Async for Order- Used sync check (Feign) for stock availability BEFORE placing,
Inventory async (Kafka) for reservation AFTER placing. Sync = user gets
immediate feedback; Async = scalable processing.
Redis cache TTL choice 30 min for products balances freshness vs load. Lower TTL =
more DB hits. Higher TTL = stale data risk. Critical data (inventory)
uses 5 min.
Oracle vs PostgreSQL Oracle for enterprise/banking-grade projects, better SEQUENCE
support, row-level locking. PostgreSQL would be fine for startups.

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 16 | GITHUB & RESUME PREPARATION

16.1 GitHub README Structure


# E-Commerce Order Management Platform

## Architecture Overview
[Insert [Link] architecture diagram as PNG]

## Tech Stack
| Layer | Technology |
|-------|-----------|
| Backend | Java 21, Spring Boot 3, Spring Cloud |
| Database | Oracle DB (schema-per-service) |
| Cache | Redis 7 |
| Messaging | Apache Kafka |
| Security | Spring Security, JWT (RS256), OAuth2 |
| DevOps | Docker, GitHub Actions |
| Monitoring | Prometheus + Grafana |

## Services
| Service | Port | Description |
| api-gateway | 8080 | Single entry point |
...

## Key Design Patterns


- Saga Pattern (Choreography) for distributed transactions
- Outbox Pattern for guaranteed event publishing
- CQRS-lite: separate read/write models in Product Service
- Circuit Breaker with Resilience4j
- Idempotency on critical write operations

## Quick Start
docker-compose up -d
mvn clean install
# Services auto-register with Eureka

## API Documentation
Swagger UI: [Link] (per service)

16.2 Resume Bullet Points


Strong Resume Bullets
Use this format: [Action verb] + [Technology/Pattern] + [Business impact/scale metric]

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

• Designed and implemented a microservices-based e-commerce backend with 9 Spring Boot 3


services using Oracle DB (schema-per-service), achieving full domain isolation and independent
deployability
• Implemented Saga choreography pattern with Kafka event-driven communication for distributed
order-payment-inventory transactions, with compensating transactions for guaranteed data
consistency on failure
• Built Outbox Pattern-based event publishing ensuring exactly-once Kafka event delivery,
eliminating dual-write inconsistency across service boundaries
• Engineered API Gateway with JWT (RS256) authentication, Redis-backed rate limiting (token
bucket), and Spring Cloud Circuit Breaker, improving system resilience under load
• Designed Redis caching strategy for product catalog, cart, and session data with TTL-based
eviction, reducing Oracle read load by simulating 70% cache hit rate
• Implemented optimistic locking on inventory reservations preventing overselling under
concurrent order placement scenarios
• Configured GitHub Actions CI/CD pipeline with multi-stage Docker builds, automated testing,
and GHCR image registry, reducing manual deployment to zero

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

SECTION 17 | ADVANCED FEATURES & FUTURE ROADMAP

17.1 Phase 2 Enhancements


Feature Technology Why It Matters
Full-text product Elasticsearch 8 Oracle LIKE queries don't scale for search. ES
search gives faceted filtering, typo tolerance, and sub-
10ms search.
Distributed tracing Micrometer Tracing + See the full journey of a request across 9
Zipkin services. Essential for debugging in production.
Kubernetes K8s + Helm charts HPA (auto-scaling), rolling deployments, health
deployment probes, resource limits. K8s is the production
standard.
Service mesh Istio Mutual TLS between services, traffic shaping,
canary deployments, observability without code
changes.
Real payment Razorpay / Stripe SDK Replace mock gateway with real webhook
gateway handling, signature validation, and idempotent
retries.
Recommendation Apache Spark or ML "Customers also bought" via collaborative filtering
engine Service on Oracle order history data.
Event sourcing Kafka + Event Store Store order state changes as events, not current
state. Full audit trail, time-travel queries.
Multi-region Oracle Data Guard + Active-passive Oracle replication, Kafka topic
Kafka MirrorMaker mirroring for cross-region durability.

17.2 Performance Optimization Roadmap


• Database connection pooling: HikariCP tuning (maxPoolSize, connectionTimeout,
validationTimeout)
• Oracle partitioning on ORDERS table by CREATED_AT (range partitioning) for faster time-
range queries
• Oracle materialized views for admin reporting dashboards (avoid expensive JOINs at query
time)
• Kafka consumer parallelism: increase topic partitions to match consumer instances for
horizontal scaling
• Redis Cluster mode for high availability and horizontal cache scaling
• Spring WebFlux for Notification Service (inherently async, no benefit to blocking threads)
• Oracle AWR (Automatic Workload Repository) reports for query performance analysis in
production

Final Tip for Interviews


When asked 'What would you improve?', say: 'I would add distributed tracing with Zipkin to trace
requests across all 9 services, implement Kubernetes with HPA for auto-scaling under load, and

Confidential — For Interview Preparation Only Page


Enterprise E-Commerce Order Management Platform | Java 21 + Spring Boot 3 + Oracle + Kafka + Redis

replace the mock payment gateway with a real Razorpay integration with proper signature validation
and webhook idempotency.' This shows you think in production terms.

— END OF DOCUMENT —
Built for Java Backend Engineers targeting Enterprise & Product Companies

Confidential — For Interview Preparation Only Page

You might also like