0% found this document useful (0 votes)
7 views25 pages

Saga Pattern

The document discusses handling payment failures in a microservices architecture involving an OrderService and PaymentService, emphasizing the use of the Saga Pattern to maintain data consistency. It outlines the flow of events from order creation to payment processing, detailing how compensating transactions are triggered in case of payment failures. Additionally, it covers the implementation of reliability mechanisms such as message brokers, idempotency, and the Outbox pattern to ensure eventual consistency and reliable event delivery.

Uploaded by

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

Saga Pattern

The document discusses handling payment failures in a microservices architecture involving an OrderService and PaymentService, emphasizing the use of the Saga Pattern to maintain data consistency. It outlines the flow of events from order creation to payment processing, detailing how compensating transactions are triggered in case of payment failures. Additionally, it covers the implementation of reliability mechanisms such as message brokers, idempotency, and the Outbox pattern to ensure eventual consistency and reliable event delivery.

Uploaded by

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

18/03/2026, 07:16 ChatGPT - System Design Questions

ChatGPT Auto
Act as software engineer,
Goal: Answer design question.
In a microservices architecture, you have an
OrderService and a PaymentService . When a
customer places an order, the order is created and then
payment is processed. How would you handle a scenario
where the payment processing fails after the order has
already been successfully created to ensure data
consistency across the system?

In a microservices architecture, each service owns its own database, so we cannot use
traditional ACID distributed transactions easily.
Instead, we rely on event-driven patterns and compensating transactions to maintain
eventual consistency.
For the OrderService → PaymentService scenario, the standard solution is the Saga
Pattern.

1. Problem Overview
Flow:
1. Customer places order
2. OrderService creates order
3. PaymentService processes payment
4. If payment succeeds → order confirmed
5. If payment fails → order must be cancelled
The challenge:
Order already stored in DB
Payment fails afterwards
Need to keep system state consistent

2. Key Design Principle: Saga Pattern


[Link] 1/25
18/03/2026, 07:16 ChatGPT - System Design Questions

A Saga is a sequence of local transactions.


Each step:
Performs a local DB transaction
Publishes an event
If something fails → trigger compensating transaction
Example compensation:
Step Action Compensation
Create Order Order created Cancel order
Process Payment Charge card Refund

Two implementation styles:


1. Choreography (Event-driven)
2. Orchestration (Central coordinator)

3. Option 1 — Saga with Event Choreography (Most


common)
Services react to events.
Flow
Client
|
v
OrderService
|
|-- OrderCreated Event --> Message Broker
|
v
PaymentService

Step-by-step
Step 1 — Order Created
OrderService:

[Link] 2/25
18/03/2026, 07:16 ChatGPT - System Design Questions

INSERT Order (status = PENDING)


Publish OrderCreated event

Step 2 — Payment Service Processes Payment


PaymentService receives event:
Process payment

Two possibilities:
Success
Publish PaymentSuccess event

Failure
Publish PaymentFailed event

Step 3 — OrderService reacts


If:
PaymentSuccess
UPDATE order
SET status = CONFIRMED

PaymentFailed
UPDATE order
SET status = CANCELLED

Event Flow Diagram


User
|

[Link] 3/25
18/03/2026, 07:16 ChatGPT - System Design Questions

v
OrderService
| Create Order
v
Event: OrderCreated
|
v
Message Broker (Kafka / RabbitMQ)
|
v
PaymentService
| Process Payment
|
+---- Success ----> PaymentSuccess Event
|
+---- Failure ----> PaymentFailed Event
|
v
OrderService
Cancel Order

4. Option 2 — Saga with Orchestrator


A central coordinator service controls the workflow.
Example: OrderWorkflowService .
Flow
OrderWorkflowService
|
+--> OrderService: Create Order
|
+--> PaymentService: Process Payment
|
+--> If fail → Cancel Order

Example
createOrder()
|
v
[Link]()

[Link]()
[Link] 4/25
18/03/2026, 07:16 ChatGPT - System Design Questions

if payment fails:
[Link](orderId)

Advantages
Benefit Explanation
Clear control flow Easier debugging
Central logic Business workflow in one place

5. Handling Data Consistency


We achieve Eventual Consistency.
States:
Order Status Meaning
PENDING Order created, payment pending
CONFIRMED Payment success
CANCELLED Payment failed

6. Reliability Mechanisms
To make the system production-grade:
1. Message Broker
Use:
Apache Kafka
RabbitMQ
Amazon SQS
Purpose:
Reliable async communication
[Link] 5/25
18/03/2026, 07:16 ChatGPT - System Design Questions

Retry support
Decoupling

2. Idempotency
Payment service must avoid double charging.
Example:
paymentId = orderId
if payment already processed:
ignore request

3. Retry Mechanism
Payment failures may be temporary.
Broker retry or DLQ pattern.
Retry 3 times
Then move to Dead Letter Queue

4. Outbox Pattern (Important)


To avoid dual write problem.
Instead of:
Write DB
Publish event

Use:
Write DB
Write event to OUTBOX table
CDC publishes event

This ensures no event loss.

[Link] 6/25
7. Database State Example
18/03/2026, 07:16 ChatGPT - System Design Questions

Order table:
order_id
user_id
status (PENDING | CONFIRMED | CANCELLED)
amount
created_at

8. Handling Edge Cases


Case 1 — Payment timeout
Order stays:
PENDING

Background job:
Cancel order after X minutes

Case 2 — Payment success but event lost


Solution:
Event replay
Payment reconciliation job

Case 3 — Payment processed twice


Solution:
Idempotency key

9. Final Architecture
Client
|

[Link] 7/25
18/03/2026, 07:16 ChatGPT - System Design Questions

v
API Gateway
|
v
OrderService
| (write order)
| publish OrderCreated
v
Message Broker
|
v
PaymentService
| process payment
|
+--> PaymentSuccess
+--> PaymentFailed
|
v
OrderService
update order state

10. What Interviewers Expect (EM/SDM Level)


Key phrases to mention:
Saga Pattern
Eventual Consistency
Compensating Transactions
Message Broker
Idempotency
Outbox Pattern
Retries + Dead Letter Queue

✅ Concise interview answer


In microservices we cannot use distributed ACID transactions, so I would implement
the Saga pattern. When an order is created, OrderService stores it with a PENDING
status and emits an OrderCreated event through a message broker like Kafka.
PaymentService consumes this event and attempts the payment. If payment
succeeds it publishes PaymentSuccess, which OrderService consumes to mark the
order CONFIRMED. If payment fails it emits PaymentFailed, and OrderService
executes a compensating transaction to cancel the order. This ensures eventual

[Link] 8/25
18/03/2026, 07:16 ChatGPT - System Design Questions

consistency. To make the system reliable I would add idempotency keys, retries,
dead-letter queues, and use the Outbox pattern to guarantee event delivery.

If you'd like, I can also show you how FAANG interviewers expect the whiteboard
answer in ~5 minutes, which is slightly different from the detailed explanation.

Can you help me understand this from end user


perspective on amazon site that what would be
happening in backend - while buying stuff there on
webpage.

Let’s walk through the Amazon purchase flow from an end-user perspective and
translate each user action into what likely happens in the backend microservices.
Think of this as a realistic system design mental model (very useful for EM/SDM
interviews).

1. User Clicks “Buy Now” / “Add to Cart”

What user sees


You click Add to Cart or Buy Now.
Backend flow
Client → API Gateway → CartService

[Link] 9/25
18/03/2026, 07:16 ChatGPT - System Design Questions

Steps:
1. Browser sends request
POST /cart/add
productId = X
userId = Y

2. CartService
Validates product
Checks availability
Stores item in cart DB
Database:
Cart
---------
user_id
product_id
quantity

Possible services involved:


ProductService → product info
InventoryService → stock check
CartService → cart state

2. User Clicks Checkout


User perspective
You click Proceed to Checkout.
Backend actions
System prepares the order.
Client → CheckoutService

The checkout service fetches:


Data Service
Cart items CartService

[Link] 10/25
18/03/2026, 07:16 ChatGPT - System Design Questions

Data Service
Product details ProductService
Price PricingService
Discounts PromotionService
Delivery options ShippingService

Response shows:
Total price
Delivery date
Payment options

3. User Clicks Place Order

This is where the distributed transaction problem happens.


User presses Place Order.
Request:
POST /order

4. Order Creation (First Step)


Client

API Gateway

[Link] 11/25
18/03/2026, 07:16 ChatGPT - System Design Questions


OrderService

OrderService does:
INSERT order
status = PENDING

Example:
Order
-----------
orderId
userId
items
status = PENDING
amount

Why PENDING?
Because payment is not yet confirmed.

5. Event is Published
After order creation:
OrderCreated Event

Published to message broker.


Example brokers:
Apache Kafka
RabbitMQ
AWS SQS
OrderService

Event Bus

PaymentService
InventoryService
NotificationService

[Link] 12/25
6. Payment Processing
18/03/2026, 07:16 ChatGPT - System Design Questions

PaymentService receives:
OrderCreated

Now it:
1. Calls payment gateway
Example:
Stripe
Visa
Bank network
[Link]()

Possible outcomes:
Payment Success
PaymentSuccess Event

Payment Failure
PaymentFailed Event

7. What Happens If Payment Fails


Example:
Card declined
Bank timeout
Fraud detection
Flow:
PaymentFailed Event

OrderService

OrderService updates order:


[Link] 13/25
18/03/2026, 07:16 ChatGPT - System Design Questions

status = CANCELLED

User sees:
Payment failed. Please retry.

8. What Happens If Payment Succeeds


PaymentSuccess Event

Now several services react.


PaymentService

Event Bus

Multiple Consumers

Consumers:
Service Action
OrderService Mark order CONFIRMED
InventoryService Reserve stock
ShippingService Start fulfillment
NotificationService Send email
AnalyticsService Record event

9. Inventory Reservation
InventoryService:
reserve(productId, quantity)

Example:
[Link] 14/25
18/03/2026, 07:16 ChatGPT - System Design Questions

Inventory
-------------
product_id
available_stock
reserved_stock

Flow:
available_stock -= 1
reserved_stock += 1

This prevents overselling.

10. Shipping / Fulfillment


Fulfillment service:
createShipment(orderId)

Tasks:
Select warehouse
Pick item
Pack item
Assign delivery partner
This may integrate with:
Amazon warehouse system
Logistics APIs

11. Notification to User


NotificationService sends:
Email
SMS
Push notification
Example:
"Your order has been placed successfully."

[Link] 15/25
18/03/2026, 07:16 ChatGPT - System Design Questions

12. Final Order State


Order table:
Order
-------------
order_id
user_id
status
amount
payment_status
shipping_status

States:
PENDING
CONFIRMED
SHIPPED
DELIVERED
CANCELLED

13. Full Backend Flow


User
|
v
Frontend (Amazon Web)
|
v
API Gateway
|
+---- CartService
|
+---- CheckoutService
|
+---- OrderService
|
v
OrderCreated Event
|
v
Message Broker
|
+-------+--------+
| |

[Link] 16/25
18/03/2026, 07:16 ChatGPT - System Design Questions

PaymentService InventoryService
| |
v v
PaymentSuccess Reserve Stock
|
v
OrderService
|
v
ShippingService
|
v
NotificationService

14. Why This Architecture Is Used


Amazon uses asynchronous microservices because:
Problem Solution
Millions of orders Async events
Failures Retry queues
Service independence Event-driven
Scalability Horizontal scaling

This pattern is called:


Saga Pattern
Instead of one transaction, we use:
Local transactions + events + compensating actions

15. Realistic Timing (What user feels)


User experience timeline:
Click "Place Order"

1–2 seconds

[Link] 17/25
18/03/2026, 07:16 ChatGPT - System Design Questions

Order confirmation page



Email confirmation

Inventory + shipment happens async

16. Interview Insight (Important)


A strong system design answer mentions:
Saga Pattern
Event-driven architecture
Eventual consistency
Message queues
Compensating transactions

✅ Simple mental model


Create Order → Process Payment → Reserve Inventory → Ship Order

Cancel order if payment fails

If you want, I can also explain the complete Amazon order system architecture (15+
microservices) that FAANG interviewers expect in “Design Amazon / E-commerce
system” interviews.

Say i hold on payment page for 2-3 minutes, by then


order created event in backend where it will stay, i mean
consumption of event is depedent on user action? how
this works ?

Good question — this is exactly where real-world systems differ from the simplified
interview flow.
[Link] 18/25
18/03/2026, 07:16 ChatGPT - System Design Questions

In most large e-commerce systems (including Amazon-like designs), the order is NOT
created until you actually press “Place Order”.
So if you stay on the payment page for 2–3 minutes, usually no order event exists yet.
Let’s break down what really happens.

1. When You Are On the Payment Page (Nothing Final


Yet)
User flow:
Cart → Checkout → Payment Page

Backend state:
CartService
CheckoutService

At this stage:
Your cart is stored
Checkout details are calculated
No order created yet
So there is no OrderCreated event in the system.
Instead, systems often create a Checkout Session.
Example:
CheckoutSession
---------------
session_id
user_id
cart_snapshot
shipping_address
status = ACTIVE
expires_at = now + 10 min

Purpose:
Lock prices
Store checkout context
[Link] 19/25
18/03/2026, 07:16 ChatGPT - System Design Questions

Allow you to stay on the payment page

2. What Happens While You Wait 2–3 Minutes


Your browser simply holds the checkout session.
Backend:
CheckoutService
|
+-- session stored in Redis / DB

Nothing triggers payment yet.


Possible background things happening:
Task Purpose
Session TTL expire abandoned checkout
Inventory soft hold temporarily reserve stock
Price validation re-check price later

Example:
Redis
checkout_session:12345
TTL = 10 minutes

3. When You Click Place Order


Now the actual transaction starts.
Client

OrderService

Steps:
1. Validate checkout session
2. Validate cart items
[Link] 20/25
18/03/2026, 07:16 ChatGPT - System Design Questions

3. Validate stock
4. Create order
INSERT order
status = PENDING_PAYMENT

Now the event is published.


OrderCreated Event

4. Where the Event Stays


The event is written to a message broker.
Examples:
Apache Kafka
RabbitMQ
AWS SQS
Example architecture:
OrderService
|
v
Message Broker
|
v
PaymentService

If PaymentService is slow, the event simply waits in the queue.


Example Kafka topic:
[Link]

The message sits there until consumed.

5. Is Consumption Dependent on User Action?


No.
[Link] 21/25
18/03/2026, 07:16 ChatGPT - System Design Questions

Once the event is published:


System handles everything asynchronously

User action is finished.


Flow:
User clicks Place Order

OrderCreated event

PaymentService consumes event

PaymentSuccess / PaymentFailed

Even if the user:


closes browser
loses internet
closes app
The backend flow continues.

6. Real Systems Often Use a Slightly Different Flow


Many e-commerce systems actually do:
Authorize Payment → Create Order

Instead of:
Create Order → Charge Payment

Why?
Because they want to avoid creating useless orders.
More realistic flow:
Place Order

Payment Authorization

[Link] 22/25
18/03/2026, 07:16 ChatGPT - System Design Questions


Order Created

But for complex systems with multiple services they may still use Saga workflow.

7. Handling Long Wait on Payment Page


Suppose you wait 10 minutes.
Possible outcomes:
Case 1 — Checkout Session Expired
Session expired
Please refresh checkout

Case 2 — Inventory Changed


Example:
Item out of stock

Case 3 — Price Updated


Example:
Price changed, please review order

8. Timeline Example
If you wait 3 minutes on payment page:
T=0 checkout session created
T=3m user clicks place order
T=3.1s order created
T=3.2s event published
T=3.5s payment processed

So the event exists only after your action.

[Link] 23/25
9. Key Insight
18/03/2026, 07:16 ChatGPT - System Design Questions

Events represent completed actions, not user intentions.


So:
User browsing → no events
User reviewing checkout → no events
User clicks place order → event created

10. Exception: Inventory Reservation Systems


Some systems temporarily reserve inventory when checkout starts.
Example:
[Link](productId, TTL=10min)

Then:
User pays → reservation confirmed
User abandons → reservation released

This prevents overselling.

✅ Simple answer (interview level)


While the user is on the payment page, no order is typically created yet. Instead, the
system maintains a checkout session containing cart and pricing details, often stored
in Redis with a TTL. The actual order creation and event publishing usually happens
only when the user clicks “Place Order.” At that point the OrderService creates the
order with a pending status and publishes an OrderCreated event to a message
broker like Kafka. The PaymentService then consumes the event asynchronously and
processes the payment.

If you'd like, I can also show you how Amazon prevents overselling when millions of
users are checking out simultaneously, which is a very common FAANG system
design follow-up question.
[Link] 24/25
18/03/2026, 07:16 ChatGPT - System Design Questions

[Link] 25/25

You might also like