Lesson 1: Advanced Patterns
What this lesson covers
- Saga pattern for distributed transactions
- CQRS: Command Query Responsibility Segregation
- Event sourcing for immutable event stores
- Idempotency strategies at scale
Read time: 12 minutes
Simple Explanation
What it is
These are high-level architectural patterns used when systems are too complex for simple request/response flows.
Why we need it
At scale, you need patterns that handle distributed data, long workflows, and retries safely.
Benefits
- Reliable transactions without locking everything.
- Scalable reads and writes with CQRS.
- Auditability through event sourcing.
Tradeoffs
- More moving parts and more data to manage.
- Eventual consistency across services.
Real-world examples (architecture only)
- Order saga -> Payment -> Inventory -> Shipping.
- Event store -> Projections -> Read models.
The Saga Pattern
Distributed transactions without ACID. Break into steps with compensations:
Saga steps:
Pros: Handles long-running transactions, no ACID needed Cons: Complex compensations, eventual consistency
CQRS: Separate Reads and Writes
Command side (writes): Process events, update primary store Query side (reads): Denormalized views optimized for read patterns
Benefit: Independent scaling, optimized views per use case
Event Sourcing
Store events, not final state. Reconstruct state from events:
Pros: Complete audit trail, temporal queries Cons: Complex, large event stores, eventual consistency
Idempotency at Scale
Strategies for idempotent operations:
- Idempotency Keys (client-provided unique ID)
# Example request payload
payload = {"amount": 100, "idempotencyKey": "abc123"}
# System deduplicates on key
# Retry safe
- Database constraints (unique keys)
INSERT INTO transfers (transferId, amount) VALUES (...)
UNIQUE KEY(transferId) -- Duplicate inserts fail gracefully
- State-based (check if already done)
if order.status == "charged":
return # Already processed
charge(order)
order.status = "charged"
What Comes Next
- Lesson 2: Distributed systems (CAP, consensus)
- Lesson 3: Multi-cloud operations
Key Takeaway: Sagas handle distributed transactions. CQRS separates reads and writes. Event sourcing provides audit trails. Idempotency is non-negotiable.