Learning SequenceVol. 18 · Part XVIII
0 / 0

Trails / Learning Sequence

LS·204

Phase 8 — Distributed Systems

The eighth phase: queues, Kafka, event-driven architecture, retries, idempotency, the outbox, change data capture, consistency, replication, sagas and resilience, ending with part of the monolith converted into an event-driven subsystem; the order and why, an entry check, step-by-step exit checks mapped to Volumes 5 and 12, the project with milestones and definitions of done, traps, a time budget, and a lab that crashes a service 29 times to compare dual writes with an outbox.

16 topics · ~7 min read · 16-question quiz
Updated Suggest a correction

Start here: Phase 8 in one page

As soon as your application sends a message, calls another service or keeps a copy of data elsewhere, it's a distributed system: parts can fail independently, messages can be lost, duplicated or delayed, and "it worked" can't always be known. Phase 8 teaches the patterns that make such systems correct anyway, and the project applies them by splitting one piece of your monolith into an event-driven subsystem.

The sequence

Text
queues → Kafka → event-driven architecture → retries → idempotency → outbox → CDC → consistency → replication → sagas → resilience

Messaging first (what a queue and a log are), then how to build with events, then the four correctness tools every event-driven system needs (retries, idempotency, the outbox, change data capture), then the theory that explains their limits (consistency and replication), then multi-step business processes (sagas) and keeping it all alive under failure (resilience).

A taste of the project

The lab ran an order service 40 times, writing each order to PostgreSQL and publishing an "order placed" event to a stream, and killed it at random moments (29 crashes):

Design Orders saved Orders with no event Duplicate events
write to the DB, then publish ("dual write") 1,126 29 0
write the order and an outbox row in one transaction; a relay publishes (and crashed 20 times too) 1,126 0 20

The dual write lost an event every time the service died between its two writes: kitchens would never hear about 29 orders. The outbox never lost one, but the relay's own crashes produced duplicates, which is why consumers must be idempotent. "Exactly once" in practice means at least once delivery plus idempotent processing.

How deep to go in Phase 8

Volume 17 defines six mastery levels; Phase 8's exit targets are:

Topic Exit level What that means here
queues and Kafka L3 partitions, consumer groups, offsets, retention, ordering
event-driven architecture L3 events vs commands, schemas and versioning, choreography vs orchestration
retries, idempotency, outbox, CDC L3–L4 implement and debug them
consistency and replication L3 models, CAP/PACELC, replication lag effects
sagas L3 design compensations and failure handling
resilience L3 timeouts, circuit breakers, bulkheads, back-pressure

The sequence, step by step

Step Learn Read Exit check
1 distributed-systems foundations Vol. 5, Start Here, ch. 65 list five ways a remote call can fail
2 messaging and Kafka Vol. 5, ch. 66–67 produce and consume with consumer groups; explain rebalancing
3 delivery semantics and idempotency Vol. 5, ch. 68, 74 an idempotent consumer proven with duplicate deliveries
4 event-driven architecture and the outbox Vol. 12, ch. 128, 131 reproduce the lab's dual-write loss and fix it
5 CDC Vol. 12, ch. 131 publish outbox rows via log-based CDC (e.g. Debezium)
6 consistency, CAP/PACELC, replication Vol. 5, ch. 69–71 explain read-your-writes with a lagging replica
7 consensus, time and ordering Vol. 5, ch. 72, 75 explain why clocks can't order events across machines
8 distributed transactions and sagas Vol. 5, ch. 73 a saga with compensations for an order flow
9 rate limiting, coordination, failure modes, resilience Vol. 5, ch. 76–78; Vol. 12, ch. 130 chaos test: kill a consumer and the broker; nothing lost

Entry check

Phases 3–4 (a transactional backend on PostgreSQL) and Phase 6 (running several services locally).

The phase project: convert part of the monolith into an event-driven subsystem

Goal. Extract one capability (e.g. kitchen notifications, or loyalty credits) into a separate service fed by events from the monolith, without losing or double-applying anything.

Milestones. Choose the boundary and event contracts (versioned schemas) → outbox in the monolith → relay or CDC to Kafka (or another broker) → idempotent consumer service with its own database → retries with back-off and a dead-letter topic → a saga or compensation for one failure path → observability (lag, DLQ size, end-to-end latency) → chaos tests (kill the relay, the consumer, the broker).

Done when. Under chaos tests, every committed business change produces exactly one effect downstream (verified by reconciliation queries); consumer lag and DLQ alerts exist; schema changes are backward-compatible; a README explains the guarantees in one paragraph.

Stretch. Replay the full topic into a new consumer to rebuild its state from scratch.

Common traps

  • Dual writes (database + broker) without an outbox.
  • Assuming exactly-once and skipping idempotency.
  • Events as remote procedure calls ("please do X") instead of facts ("X happened").
  • Unversioned event schemas.
  • Distributed monolith: services that must all be up together.

Exit criteria

  • [ ] The project meets its "done when" list.
  • [ ] I can explain delivery semantics and how to get effectively-once processing.
  • [ ] I can design an outbox with relay or CDC and an idempotent consumer.
  • [ ] I can explain consistency models and replication lag effects to a product owner.
  • [ ] I scored at least 80% on 40 questions from Volume 5's quizzes, twice.

Time budget

Volume 5 (about 88,000 words) plus Volume 12's messaging and event-driven chapters is about 7 hours of reading; with practice, about 29 hours, plus 3–4 weeks for the project: about 7 weeks at 8 hours a week.

Lab: dual writes vs the outbox, under crashes

Setup. PostgreSQL 16 and Redis Streams (standing in for a message broker) on the lab machine. An order service writes 50 orders per run, 40 runs, each as a separate process; before publishing each event it dies with os._exit(9) with 2% probability (a crash, a deploy, an OOM kill). Two designs:

  • dual write: INSERT the order and commit, then XADD the event.
  • outbox: INSERT the order and an outbox row in one transaction; a separate relay process reads unsent outbox rows, publishes each, then marks it sent. The relay also crashes with 2% probability, after publishing and before marking sent, and is restarted until the outbox is empty.

Afterwards, every order in the database is compared with the events in the stream.

Results

Design Producer crashes Relay crashes Orders Events Distinct Orders with no event Duplicate events
dual write 29 — 1,126 1,097 1,097 29 0
outbox 29 20 1,126 1,146 1,126 0 20

What it shows

  • Every producer crash in the dual-write design lost an event: the order was committed, the event never sent. Downstream services (kitchens, loyalty, analytics) silently diverged from the source of truth. Reversing the order (publish, then commit) just swaps the failure: events for orders that don't exist.
  • The outbox lost nothing: an order and its outbox row commit together or not at all, and the relay keeps publishing committed rows until it succeeds.
  • The outbox duplicated exactly as many events as the relay crashed (20): publish succeeded, the "mark sent" didn't, so the event went out again on restart. That's at-least-once delivery, and it's the right trade-off: duplicates are cheap to handle (consumers record processed event IDs, or make effects idempotent with keys and upserts), lost events are expensive to find.
  • With CDC, the relay is replaced by a connector reading PostgreSQL's WAL; duplicates are still possible after connector restarts, so consumer idempotency is still required.

Try it yourself

  1. Add a consumer that applies "add loyalty points" from the stream and make it idempotent with a processed_events table; prove the total is correct despite the 20 duplicates.
  2. Swap the dual write's order (publish, then commit) and measure the opposite failure.
  3. Replace the polling relay with Debezium reading the outbox table, and crash the connector.
  4. Add ordering requirements (events per customer in order) and partition the stream by customer ID.

Revision sheet: Phase 8, distributed systems

Key ideas

  • Sequence: queues → Kafka → EDA → retries → idempotency → outbox → CDC → consistency → replication → sagas → resilience.
  • No atomic write across a database and a broker: use an outbox (with a relay or CDC).
  • At-least-once delivery + idempotent consumers = effectively once.
  • Events are versioned facts; sagas compensate; resilience patterns contain failures.

Numbers to remember

  • Lab: 29 crashes → dual write lost 29 events; outbox lost 0 and duplicated 20 (one per relay crash).
  • Budget: ~29 study hours + 3–4 project weeks ≈ 7 weeks at 8 h/week.

Pitfalls

  • Dual writes; publish-then-commit.
  • Non-idempotent consumers.
  • Commands disguised as events; unversioned schemas.
  • A distributed monolith.

Glossary

  • Outbox: a table of events written in the business transaction and published later.
  • CDC: change data capture from the database log.
  • Idempotent consumer: processing a message twice has the same effect as once.
  • Dead-letter queue: where messages go after repeated failures.
  • Saga: a sequence of local transactions with compensations.