The design brief#
“Customers buy products online. An order must reserve stock, take payment and book delivery. Customers track their order in real time. Peak is 2,000 orders per second during sales. We must never charge for an order we cannot fulfil, and never ship an unpaid order.”
1. Bounded contexts and data ownership#
| Service | Owns | Database |
|---|---|---|
| Order | Order lifecycle | PostgreSQL |
| Payment | Authorisations, captures, refunds | PostgreSQL (PCI-scoped) |
| Inventory | Stock levels, reservations | PostgreSQL with row locks per SKU |
| Shipping | Shipments, carrier bookings | PostgreSQL |
| Order tracking (read) | Denormalised order view | OpenSearch + Redis |
Each service owns its data, and no service reads another’s database.
2. The orchestrated saga#
The Order Saga runs on Temporal. Steps are ordered so that compensatable steps come first, then the pivot, then retriable steps:
| # | Step | Type | Compensation |
|---|---|---|---|
| 1 | Create order PENDING |
Compensatable | Mark REJECTED |
| 2 | Authorise payment (hold) | Compensatable | Void the authorisation |
| 3 | Reserve stock (with 15-min expiry) | Compensatable | Release the reservation |
| 4 | Capture payment | Pivot | (refund only by a separate business process) |
| 5 | Book shipment | Retriable | none; retry, with ops escalation |
| 6 | Confirm order, notify | Retriable | none |
See the saga sequence and state machine.
3. Messaging and reliability#
- The Temporal worker calls each service’s API with an idempotency key of
sagaId + step. - Services publish domain events (
OrderConfirmed,StockReserved) through outbox + Debezium to Kafka for read models, analytics and notifications. - Consumers are idempotent (inbox table) and keyed by
orderId. - Stock reservations expire automatically, so a stuck saga cannot hold stock forever.
4. CQRS for order tracking#
flowchart LR
OE["Order events"] --> PR["Tracking projector"]
PE["Payment events"] --> PR
SE["Shipping events"] --> PR
PR --> OS["OpenSearch: search orders"]
PR --> RD["Redis: order status by ID"]
UI["Customer app"] --> API["Tracking API"] --> RD
- The customer sees status within about 1 second of each step. The API returns the version so the UI can wait for read-your-writes after placing an order.
- The projector is rebuildable from Kafka history (30-day retention plus the lakehouse for older events).
5. Failure scenarios#
| Scenario | Behaviour |
|---|---|
| Inventory says “out of stock” | Compensate: void the authorisation, reject the order, notify “sorry, no charge” |
| Payment service times out on authorise | Temporal retries with the same idempotency key. After N tries, query the status; if unknown, compensate safely (void is idempotent and handles “no auth found”). |
| Orchestrator worker crashes mid-saga | Temporal replays the workflow history and resumes at the next step |
| Capture succeeds, shipping fails | Past the pivot: retry with backoff; after the SLA, escalate to ops (manual booking) |
Duplicate PlaceOrder click |
API idempotency key returns the original order |
| Kafka consumer replays events | Inbox de-duplication; versioned updates ignore stale events |
| Stock reservation expires before capture | Capture step re-validates the reservation; if lost, compensate the earlier steps |
6. Consistency guarantees (state them explicitly)#
- Strong within each service (ACID); stock per SKU uses row locks or conditional updates (
available >= qty). - Eventual across services. The saga guarantees the business invariants: no capture without a reservation, and no shipment without a capture.
- Eventual for tracking views (about 1 s).
- Daily reconciliation: payments against orders against shipments. Breaks are investigated.
7. Scale#
- 2,000 orders/s × about 6 steps gives about 12,000 activity executions per second. Use a Temporal cluster (or Temporal Cloud) sized with sufficient history shards, and partition task queues by service.
- Hot SKUs (flash sales): pre-split stock into buckets or use a reservation token pool to avoid single-row lock contention.
8. Observability#
- Saga ID = correlation ID across Temporal, HTTP headers and Kafka headers, with OpenTelemetry traces.
- Dashboards: sagas by state, compensation rate, step latency, stuck sagas older than their SLA, DLT counts.
- Alerts: compensation failures (manual review queue), reconciliation breaks.
9. Trade-offs#
| Choice | Why | Cost |
|---|---|---|
| Orchestration (Temporal) | Visible, testable, durable flow | Platform to run, or a managed service |
| Authorise then capture | Avoids refunds for most failures | Authorisations expire; capture must happen within days |
| Reservation expiry | Self-healing | Edge cases when the saga is slower than the expiry |
| CQRS tracking | Fast, scalable reads | Eventual consistency, projector to operate |
Quick check#
Why authorise before reserving stock, and capture only after? Authorisation is compensatable (void), while capture is the pivot. Charging only after stock is secured avoids refunds.
What prevents stock being held forever by a stuck saga? Reservations carry an expiry. Separately, the saga has timeouts that trigger compensation.
How does the customer see their order immediately after placing it? The API returns a version, and the UI waits for the read model to reach it (read-your-writes), or shows an optimistic status.
What invariant does the saga guarantee across services? No capture without a stock reservation, and no shipment without a capture.
Summary#
- Clear data ownership, an orchestrated saga with ordered steps, and expiring reservations.
- Outbox, idempotency and inbox make messaging reliable; CQRS gives real-time tracking.
- State the consistency guarantees explicitly, and back them with reconciliation.
References#
- Chris Richardson, Microservices Patterns (Manning), chapters on sagas and CQRS.
- Temporal, Saga pattern and samples.