Amazon Order Processing High Level Flow
Customer
|
v
API Gateway
|
v
Order Service
|
| Local Transaction
| Save Order
| Save Outbox Event
|
v
Kafka
|
+----------------+
| |
v v
Inventory Payment
Service Service
| |
+-------+--------+
|
v
Order Confirm
|
v
Shipping
|
v
Notification1. API Gateway
API Gateway is the single entry point between clients and microservices.
Why do we need API Gateway?
- Without gateway every client needs to know all service URLs
- Central place for authentication
- Central place for rate limiting
- Request routing
- Logging and monitoring
Problem Solved
Prevents clients from directly communicating with internal services and hides microservice complexity.
@RestController
@RequestMapping("/api/orders")
public class GatewayController {
@PostMapping
public ResponseEntity<?> createOrder(){
// validate JWT
// forward request
return ResponseEntity.ok("Request forwarded");
}
}2. Order Service
Order Service owns order creation and order lifecycle.
Why separate Order Service?
- Order logic changes independently
- Own database ownership
- Can scale independently during sales events
Order Creation Code
@Transactional
public void createOrder(OrderRequest request){
Order order=new Order();
order.setStatus("CREATED");
orderRepository.save(order);
OutboxEvent event=new OutboxEvent();
event.setType("ORDER_CREATED");
event.setPayload(convert(order));
outboxRepository.save(event);
}3. Transactional Outbox Pattern
Transactional Outbox stores database changes and events in the same database transaction.
Why do we need Outbox?
Suppose Order is saved successfully but Kafka publishing fails.
Wrong approach
Save Order
|
v
Kafka Publish
|
X Failure
Result:
Order exists but Payment and Inventory never knowProblem Solved
- Avoids lost events
- Makes database and event creation atomic
- Improves reliability
BEGIN;
INSERT INTO orders VALUES(5001,'CREATED');
INSERT INTO outbox VALUES(1,'ORDER_CREATED');
COMMIT;4. Kafka Event Communication
Kafka is used as a communication channel between services.
Why Kafka?
- High throughput
- Durable messages
- Services are loosely coupled
- Supports retry and replay
kafkaTemplate.send(
"order.created",
orderEvent
);5. Inventory Service
Inventory service owns product stock.
Important Interview Scenario: Last Item
Stock = 1
User A buys
User B buys
Both requests arrive togetherSolution
- Optimistic locking
- Pessimistic locking
- Atomic update query
UPDATE inventory
SET stock = stock - 1
WHERE product_id=15
AND stock > 0;Why?
Only one transaction can reduce stock from 1 to 0. The second request gets failure.
6. Payment Service
Payment service communicates with payment gateway and stores payment status.
@KafkaListener(topics="order.created")
public void pay(OrderEvent event){
boolean result = paymentGateway.charge();
if(result){
kafka.send("payment.success",event);
}
else{
kafka.send("payment.failed",event);
}
}7. Saga Pattern
Saga is a pattern used to manage distributed transactions across multiple microservices.
Why Saga?
In microservices we cannot do one database transaction like traditional monolith systems.
Traditional
BEGIN TRANSACTION
Order
Payment
Inventory
COMMIT
Microservices
Order DB Transaction
Payment DB Transaction
Inventory DB TransactionProblem Solved
- Coordinates multiple services
- Handles failures
- Provides compensation
Example Compensation
Order Created
|
Inventory Reserved
|
Payment Failed
|
Saga Compensation
|
Release Inventory
|
Cancel Order8. Idempotency
Kafka usually provides at least once delivery, meaning duplicate events are possible.
Problem
Payment Event received twice
First time:
Charge customer
Second time:
Charge again ❌Solution
if(eventRepository.exists(eventId)){
return;
}
processPayment();
saveEventId();Final Interview Explanation
For Amazon-like order processing, we use API Gateway for entry, Order Service for ownership, Transactional Outbox for reliable event publishing, Kafka for communication, Inventory locking for concurrency control, Payment Service for payment processing, Saga for distributed transaction management, and Idempotency for duplicate message handling.