๐ŸŽฏ Saga Pattern Interview Prep

Click on any node to expand/collapse details

Concept
Important
Code/Implementation
๐Ÿ” Food Delivery Saga Pattern
๐Ÿง  Core Concepts โ–ถ
What is Saga?
A pattern for managing distributed transactions across microservices using a sequence of local transactions
Why Saga?
โ€ข No 2-phase commit (distributed locks)
โ€ข Better availability & scalability
โ€ข Services stay independent
Two Types:
Orchestration - Central coordinator (used here)
Choreography - Decentralized, event-driven
Key Feature:
Compensating transactions = Rollback in distributed systems
๐Ÿ—๏ธ Architecture โ–ถ
5 Microservices:
Order (8081) - Orchestrator
Payment (8082) - Process payments
Restaurant (8083) - Inventory
Delivery (8084) - Rider assignment
Notification (8085) - Alerts
Communication:
Apache Kafka for async messaging
Topics: requests, responses, compensations
Tech Stack:
Spring Boot 3.2, Java 17, Maven, H2 DB, Spring Cloud Stream
โœ… Happy Path Flow โ–ถ
Step 1: Client creates order โ†’ Order Service (PENDING)
Step 2: Payment request โ†’ Payment Service โ†’ SUCCESS
Step 3: Restaurant request โ†’ Check inventory โ†’ CONFIRMED
Step 4: Delivery request โ†’ Assign rider โ†’ ASSIGNED
Step 5: Notification โ†’ Send confirmation โ†’ COMPLETED โœ…
Order Status:
PENDING โ†’ PAYMENT_PROCESSING โ†’ PAYMENT_COMPLETED โ†’ RESTAURANT_CONFIRMED โ†’ DELIVERY_ASSIGNED โ†’ COMPLETED
โš ๏ธ Compensation Flow โ–ถ
Scenario 1: Payment Fails
Order โ†’ PENDING โ†’ PAYMENT_FAILED โ†’ CANCELLED
No compensation needed (first step)
Scenario 2: Restaurant Fails
Payment โœ… โ†’ Restaurant โŒ
Compensate: Refund payment
Order โ†’ COMPENSATING โ†’ CANCELLED
Scenario 3: Delivery Fails
Payment โœ… โ†’ Restaurant โœ… โ†’ Delivery โŒ
Compensate: Release inventory + Refund
Order โ†’ COMPENSATING โ†’ CANCELLED
Key Point: Each successful step must have a compensating transaction
๐Ÿ’ป Code Implementation โ–ถ
Orchestrator Pattern:
OrderSagaOrchestrator coordinates everything
Uses StreamBridge to send events
Event Listeners:
@Bean Consumer<OrderEvent>
paymentResponses(), restaurantResponses(), deliveryResponses()
Kafka Topics:
payment-requests, payment-responses
payment-compensations (for refunds)
restaurant-requests, restaurant-responses
restaurant-compensations (release inventory)
State Management:
Order entity with @Enumerated OrderStatus
Stored in H2 database
โ“ Interview Questions โ–ถ
Q: Why Saga over 2-phase commit?
A: Avoids distributed locks, better availability, services don't block each other
Q: Orchestration vs Choreography?
A: Orchestration = central coordinator (easier to debug), Choreography = each service reacts to events (more decoupled)
Q: How do you handle failures?
A: Compensating transactions - undo previous steps in reverse order
Q: What if compensation fails?
A: Retry mechanism, dead letter queue, manual intervention, idempotency ensures safe retries
Q: How to ensure idempotency?
A: Check if orderId already processed before executing, store transaction IDs
Q: Eventual consistency?
A: Yes - saga provides eventual consistency, not immediate consistency like ACID
๐ŸŽจ Design Patterns โ–ถ
1. Saga Pattern: Distributed transaction management
2. Event Sourcing: Events drive state changes
3. CQRS: Separate read/write (Order Service tracks state)
4. Idempotency: Safe to process same event multiple times
5. Compensating Transaction: Undo/rollback pattern
6. Observer Pattern: Services listen to events
๐ŸŽฏ Key Interview Points โ–ถ
Say This:
"I implemented orchestration-based saga where Order Service coordinates 4 services via Kafka events"
Highlight:
Each step has a compensating transaction for rollback (refund payment, release inventory)
Mention:
Built with Spring Cloud Stream, ensures idempotency, handles duplicate messages
Trade-offs:
Saga = Eventual consistency (not immediate)
Simpler than 2PC but more complex error handling
๐Ÿงช Testing Strategy โ–ถ
Happy Path Test:
customerId: "customer-123" โ†’ All steps succeed
Payment Failure:
customerId: "FAIL_PAYMENT" โ†’ Order cancelled
Restaurant Failure:
restaurantId: "FAIL_RESTAURANT" โ†’ Compensate payment
Delivery Failure:
deliveryAddress: "FAIL_DELIVERY" โ†’ Compensate all
Integration Tests:
Start Kafka, test end-to-end flow, verify compensations
๐Ÿš€ CI/CD Pipeline โ–ถ
Build Job: Matrix strategy builds all 5 services in parallel
Test Job: Runs unit tests, uploads artifacts
Integration Job: Starts Kafka with Docker Compose, tests connectivity
Docker Job: Builds images for each service (on main branch)
Triggers: Push to main/develop, Pull requests
โš™๏ธ Production Considerations โ–ถ
Monitoring: Track saga execution, failure rates, compensation success
Timeouts: Add timeout handling for each step (if payment takes >30s, compensate)
Dead Letter Queue: For failed compensations that need manual intervention
Observability: Distributed tracing (Spring Cloud Sleuth), Prometheus metrics
Database: Replace H2 with PostgreSQL/MySQL for persistence
Message Broker: Kafka partitioning for scalability, consumer groups
๐ŸŒ Real-world Examples โ–ถ
E-commerce: Order โ†’ Payment โ†’ Inventory โ†’ Shipping
Banking: Transfer money between accounts across services
Travel Booking: Flight + Hotel + Car rental (cancel all if one fails)
Food Delivery: Uber Eats, DoorDash use saga-like patterns
Companies Using: Netflix, Uber, Amazon, Airbnb