Call five services in a row and every order waits 3,340 ms for all of them, then fails when any one is down. Publish one event to a queue instead and the order returns in 55 ms. A dead email service only makes its own queue longer.
Pick a design, then take the email service down and watch who waits. Then we build, piece by piece, queues, fan-out, partitions, delivery promises, ordering, backpressure and dead letter queues.
You need what an HTTP request is and what a server process is. Service Communication helps. We build the rest from zero.
Illustrative numbers, not measurements: 20 orders a second; order 50 ms, payment 200, inventory 30, email 3,000 (a slow mail server), warehouse 40, analytics 20; a 5 s timeout; 5 ms for the broker to store an event. The clock runs fast. Chapter 0 works these numbers.
Chapter 0
Chain five services and multiply their uptimes, then cut the chain with a queue
A user places an order. The order service must charge the card, update the stock, send an email, tell the warehouse and record analytics. In a synchronous design it calls each service and waits for each answer. The user waits for the sum: 3,340 ms in the hero, most of it the mail server.
Waiting is the small problem. If any one service is down, the order fails. The services are coupled in time: all must be up at the same moment. Call the share of time a service is up its availability a, and the number of services the order calls in a row n.
A equals a-one times a-two, and so on, times a-n.
An order succeeds only if service 1 is up and service 2 is up and so on. If they fail independently, multiply their availabilities. Each extra link lowers A.
With made-up numbers: five services at a = 0.999 each. A = 0.9995 = 0.995, so orders fail 0.5% of the time: about 44 hours a year. With a queue, the order needs only the order service and the broker: 0.999 × 0.999 = 0.998, about 17.5 hours.
Each row is one month for one box; red marks are outages. The bottom rows show when orders fail. Drag the availability and roll a new month.
Simulated in your browser: 30 days, outages at random times with a mean length of 30 minutes, each box down for the chosen share of time, independently. Illustrative. Real outages are often correlated, which makes the chain look better and the shared broker worse.
With a message queue, the order service stores the order, hands one "order created" event to a broker (a server that holds messages), and answers the user. Each downstream service reads the event when it can. If email is down, its messages wait, and it sends them later.
Failure. Symptom: orders fail whenever the analytics service deploys. Measure: the error rate of order requests against each dependency's health. Cause: a non-critical service sits in the synchronous chain. Fix: publish an event and let analytics consume it.
Chapter 1
Hand each message to one consumer, wait for its ack, and count how many messages wait
The simplest pattern is the work queue (point-to-point). Producers put messages in. Consumers take them out, and each message goes to exactly one consumer. Add consumers and they compete for messages, so the queue drains faster.
What if a consumer crashes halfway through a message? The broker must not delete it on hand-out. So the consumer sends an acknowledgement (ack) when it finishes, and only then does the broker delete the message. Amazon SQS hides a received message for a visibility timeout, 30 s by default. If no delete arrives in time, the message becomes visible again for another consumer.
How many messages sit in the system? Call the arrival rate λ and the average time a message spends inside, waiting plus work, W.
L equals lambda times W.
This is Little's law. Messages enter at lambda a second and each stays W seconds, so lambda times W are inside at any moment. Read backwards: a backlog L at rate lambda means the newest message waits L divided by lambda.
With made-up numbers: λ = 900 a second, 10 consumers taking 10 ms each. Erlang C (below) gives W = 16.7 ms, so L = 900 × 0.0167 = 15 messages, 6 of them waiting. A backlog of 50,000 at 2,000 a second is 25 s of lag.
With random arrivals, random work times and c consumers sharing one queue, the chance a message must wait is Erlang C. Call the offered load a = λ / μ, where μ is the messages one consumer finishes per second, and the utilisation ρ = a / c.
λ = 900, μ = 100, c = 10: ρ = 0.9, C = 0.669, Wq = 6.7 ms. With 12 consumers, ρ = 0.75, C = 0.266 and Wq = 0.9 ms. A million-message simulation agreed. One server ten times as fast would give 9 ms, the wrong answer.
Blue messages arrive; pink ones wait in the queue; warm boxes are consumers, each 10 ms a message; teal ticks are acks. Drag the rate and the consumers.
The read-out is Erlang C, exact for random (Poisson) arrivals and random (exponential) work times of mean 10 ms. The animation is a seeded simulation of the same queue, slowed down. Illustrative rates.
At 900 a second, 9 consumers never catch up, 10 wait 6.7 ms and 12 wait under 1 ms. Near full load, each extra consumer cuts the wait sharply.
Failure. Symptom: consumers process some messages twice, each about 30 s after the first try. Measure: processing time against the visibility timeout. Cause: work takes longer than the timeout, so the message reappears while the first consumer still holds it. Fix: a longer timeout, or extend it while working.
Chapter 2
Publish once to a topic, give each service its own copy, and share each copy inside the service
A work queue gives each message to one consumer. But "order created" matters to payment, stock, email and analytics. If the producer sends four messages to four queues, it must know every consumer, and adding one means changing the producer.
Publish/subscribe fixes that. The producer publishes to a topic. Each service subscribes and gets its own copy of every event. A new service subscribes; the producer never changes. On AWS, an SNS topic sends a copy to every SQS queue subscribed to it. This is fan-out.
The email service runs three instances. You want one email per order, not three. So the instances form a consumer group: each group gets every event, and inside a group each event goes to one member. Across groups it is pub/sub; inside a group it is a work queue. Call the events published per second λ and the subscribing groups G.
D equals lambda times G.
Every group gets every event once. So the broker sends lambda copies for each of the G groups. Adding instances to a group spreads its copies; adding a group adds lambda more.
With made-up numbers: λ = 500 orders a second, G = 4 groups. D = 2,000 deliveries a second. At 1 KB an event, 0.5 MB a second comes in and 2 MB a second goes out. A fifth group makes it 2,500.
Each blue event leaves the topic once per group; inside a group one warm instance takes it. Add an instance or a group and watch the deliveries count.
Illustrative: 1 KB events. Inside a group the toy hands events out in turn; Chapter 3 shows how Kafka does it with partitions.
Fan-out is cheap for the producer and costs the broker one copy per group. Ten groups on a 50,000-event-a-second topic is half a million deliveries a second. That is why a slow, rarely used subscriber deserves its own filtered topic.
Failure. Symptom: customers get three identical emails. Measure: emails sent per order against instances of the email service. Cause: each instance subscribed on its own, so each is a group of one. Fix: put the instances in one consumer group (one subscription, one shared queue).
Chapter 3
Keep messages in an append-only log, split it into partitions, and give each partition to one consumer
Kafka, built at LinkedIn and described in a 2011 NetDB paper, does not delete a message when it is read. Each topic is a log: records appended in order, each with a number called its offset. A consumer remembers how far it has read, its position, and saves that number as its committed offset. Records stay until the retention time ends, 7 days by default, so a new group can read from the start.
One log on one disk has a limit. So Kafka splits a topic into partitions, each its own log on some broker, copied to others for safety. Inside a consumer group, each partition is read by exactly one consumer at a time. That rule keeps each partition in order. It also caps the group's parallelism at the partition count.
Call one consumer's speed μ, the partitions P and the consumers in the group c. Kafka spreads partitions as evenly as it can, so the busiest consumer holds ⌈P / c⌉ of them (P divided by c, rounded up).
X-max equals mu times P, divided by the ceiling of P over c.
Each partition gets one P-th of the traffic. The busiest consumer holds the ceiling of P over c partitions and must not exceed mu. So the group keeps up with mu times P divided by that ceiling.
With made-up numbers: μ = 1,000, P = 6. Three consumers hold 2 each: Xmax = 1,000 × 6 / 2 = 3,000. Four consumers hold 2, 2, 1, 1: still 3,000. Six give 6,000. Eight give 6,000 too, and two sit idle.
Purple bars are partitions; lines show their owner. Each warm consumer's bar is its load against a dashed limit of 1,000 a second; pink above the line is lag growing. Drag all three.
Illustrative: 1,000 messages a second per consumer, keys spread evenly so each partition gets 1/P of the traffic. Partitions are dealt to consumers in turn, as Kafka's round-robin assignor does.
At 3,500 a second, four consumers fall behind by 333 messages a second: the two with two partitions each get 1,167. A fifth consumer changes nothing. A sixth fixes it. Pick a partition count with many divisors, such as 12, so more consumer counts split it evenly.
Failure. Symptom: you scale from 6 to 10 consumers and lag does not move. Measure: partitions per consumer. Cause: 6 partitions, so 4 consumers have nothing to read. Fix: create the topic with more partitions than you expect to need.
Chapter 4
Commit before the work and a crash loses messages; commit after and a crash repeats them
A consumer does two things for each batch: it processes the messages and it commits its offset. A crash can land between them. The order of the two is the delivery guarantee.
Most systems choose at-least-once. Kafka's Java consumer commits by default every 5 s, in its poll loop, for records already handed out. How much repeats? Call the messages processed per second λ and the time between commits T.
R equals lambda times T, over 2.
The new owner processes again everything since the last commit. A crash comes at a random moment, so on average half of T has passed. Multiply by lambda.
With made-up numbers: λ = 2,000 a second, T = 5 s. R = 2,000 × 2.5 = 5,000 repeats per crash, up to 10,000. 200,000 simulated crashes averaged 5,005. Commit every 1 s and it is 1,000.
The purple bar is the log. The blue mark is how far the consumer has processed; the teal mark is its last commit; the yellow tick is the commit timer. Pick a mode and crash it.
Illustrative: 2,000 messages a second, batches of 500 (Kafka's default max.poll.records). Each crash lands at a random point of the commit cycle; the counters add up over your crashes.
Exactly-once in the third mode is not a broker feature. The consumer still receives the repeats. It records each message ID with its effect and skips IDs it has seen, so the side effects happen once. Chapter 5 builds that.
Failure. Symptom: after a deploy, some customers pay twice. Measure: payments per order ID around the restart time. Cause: consumers stopped before committing, and the new ones repeated the last seconds. Fix: make the charge idempotent with the order ID, and commit on shutdown.
Chapter 5
Give every message an ID, remember the IDs you have applied, and size how long you remember them
An operation is idempotent if doing it twice has the same effect as once. "Set stock to 10" is idempotent; "subtract 1" is not. An at-least-once consumer needs idempotent effects, or it must recognise repeats.
Brokers help with part of it. Since Kafka 0.11, an idempotent producer tags each write with a producer ID and a sequence number, so a retried send is not written twice. Transactions write to several partitions, and commit offsets, all or nothing. Since Kafka 3.0 the Java producer turns idempotence on by default. Kafka's docs add that exactly-once into another system "generally requires cooperation with such systems", such as your database.
So the consumer keeps a dedup table of message IDs it has applied. The safest table is in the same database as the effect: one transaction writes the effect and the ID, with a unique key. If the ID must live in a separate store, it can hold IDs only for a window. Call the message rate λ, the window W and the bytes per stored ID b.
M equals lambda times W times b.
The table holds every ID seen in the last W seconds. That is lambda times W IDs, each b bytes. A longer window catches older repeats and costs memory in proportion.
With made-up numbers: λ = 2,000, W = 24 h = 86,400 s, b = 40 bytes. M = 2,000 × 86,400 × 40 = 6.9 GB (decimal). A 1-hour window needs 0.29 GB.
Each dot is a repeat, placed by how long after the first copy it arrived (log scale). Inside the yellow window it is caught (green); outside it applies twice (red). Pick a window.
Illustrative mix of repeat delays, simulated: 90% producer retries around 1 s, 9% consumer replays around 2 minutes, 1% replays of a dead letter queue around 6 hours. One million repeats, one fixed seed. 2,000 messages a second, 40 bytes per ID.
A 1-minute window misses 8% of repeats: every replay and redrive. SQS FIFO queues make the same trade on the broker side: they drop a repeated deduplication ID only within 5 minutes.
The reverse problem, a database write and an event that must both happen, is the outbox: write the event into a table in the same transaction, then publish it. Distributed Transactions, the Outbox builds it.
Failure. Symptom: a replay of last night's dead letters charges 40 customers again. Measure: age of the replayed messages against the dedup window. Cause: the IDs had expired from a 1-hour cache. Fix: keep the ID in the payment table with a unique constraint.
Chapter 6
Send every event of one order to one partition, then see what resizing the topic breaks
Order 42 emits "created", "paid", "shipped". If a consumer handles "shipped" before "paid", you ship unpaid goods. One queue with one consumer keeps order, but has one consumer's speed. With several consumers, a fast one can finish message 2 before a slow one finishes message 1.
The fix is to keep order only where it matters: per order. The producer picks a partition from the message's key, here the order ID. Every event of order 42 lands in one partition, and one consumer reads that partition in order. Orders 42 and 43 run in parallel. Call the key k and the partition count P.
p equals hash of k, mod P.
Hash the key k to a number, divide by P and keep the remainder p. The same key always gives the same p, as long as P does not change.
With a toy hash that returns the order number: order 42 goes to 42 mod 4 = 2, order 43 to 3. Grow the topic to 5 partitions and 42 goes to 2, 43 to 3, but over many random hashes 80% of keys move. Doubling 4 to 8 moves 50%.
Rows are partitions, each read by one consumer of a different speed. Blue blocks are events, labelled order and step. Green means handled in order; red means handled before an earlier step of the same order. Pick a routing and press Send.
A deterministic toy: 12 orders starting 0.1 s apart, each order's steps 0.3 s apart, consumers taking 0.40, 0.10, 0.20, 0.55 and 0.12 s an event, toy hash = order number. The resize happens 1.0 s in.
Two more things break order. A rebalance moves a partition to a new consumer, which restarts at the committed offset, so "paid, shipped" can run as "paid, shipped, paid, shipped". And Kafka's producer docs warn that with more than one request in flight and idempotence off, a retried batch can land after a later one.
Failure. Symptom: after adding partitions, a few orders show "shipped" before "paid". Measure: keys whose partition changed, and their events in flight at the change. Cause: the new count sent new events of old orders to new partitions. Fix: create enough partitions up front, or drain before resizing.
Chapter 7
Let a burst fill the queue, then choose to store it, push back on the producer, or drop it
Consumers handle 4,000 messages a second; normal traffic is 3,000. A sale sends 10,000 a second for 10 minutes. The queue grows by 6,000 a second: 3.6 million messages when the burst ends. By Little's law, the newest one waits 3.6 million / 4,000 = 900 s, a 15-minute lag.
The queue absorbed the burst. That is its job. The cost comes after: only the spare capacity drains it. Call the backlog Q, the consumers' total speed cμ and the traffic after the burst λ.
T-drain equals Q divided by, c mu minus lambda.
New messages keep arriving at lambda, so the consumers clear old ones only with what is left over, c mu minus lambda. Divide the backlog Q by that.
Q = 3.6 million, cμ = 4,000, λ = 3,000. Tdrain = 3,600,000 / 1,000 = 3,600 s. A 10-minute burst leaves an hour of lag. Our second-by-second simulation drained at exactly 3,600 s. Double the consumers and it takes 720 s.
The pink area is queue depth over 80 minutes; the dashed line is the limit, if any. Pick a policy, drag the burst, then run it.
Simulated second by second: consumers 4,000 a second, normal traffic 3,000, a 10-minute burst. "Block" holds publishes at the producer once the broker holds 1 million; "shed" drops arrivals above a 60 s lag (240,000). Illustrative numbers.
Backpressure means a full queue slows the producer. RabbitMQ blocks publishing connections when it runs low on memory. Its prefetch setting caps unacked messages per consumer, so one consumer cannot hoard work. SQS stops handing out messages at about 120,000 in flight on a standard queue. Blocking moves the backlog to the producer; it does not remove it. Load shedding drops work on purpose.
Failure. Symptom: a consumer group restarts after a week down and silently skips data. Measure: consumer lag in time against topic retention. Cause: lag passed the 7-day retention, so Kafka deleted records nobody had read. Fix: alert on lag in seconds, well below retention.
Chapter 8
Retry a failing message a few times, then park it, and choose how many tries is enough
Some messages fail every time: bad JSON, a deleted customer, a bug that crashes on one input. This is a poison pill. Retried forever, it wastes a consumer. In an ordered partition it is worse: nothing behind it moves. That is head-of-line blocking.
A dead letter queue (DLQ) catches it. After N failed tries, the message moves to a separate queue, and the main queue continues. SQS calls N maxReceiveCount. RabbitMQ quorum queues default to a limit of 20 deliveries since 4.0. Kafka's consumer has no built-in DLQ; you write to a retry or dead letter topic yourself.
Choosing N is a trade. Too small, and the DLQ parks a healthy message that met a flaky dependency. Too large, and the poison holds a slot for longer. Call the chance one try of a healthy message fails f, and the tries allowed N.
P-D-L-Q equals f to the N.
A healthy message is parked only if every one of its N tries fails. If tries fail independently, multiply f by itself N times. Each extra try cuts the chance by a factor of f.
With made-up numbers: f = 0.3. N = 3 gives 0.33 = 2.7% parked wrongly; N = 5 gives 0.24%. A million simulated messages gave 2.71% and 0.24%. The poison costs about N visibility timeouts: 5 × 30 s = 150 s before it is parked.
Top: the poison pill's tries along a yellow time axis, then the dead letter queue. Bottom: the share of healthy messages parked against N. Switch to an ordered partition to see the pile behind the poison.
Illustrative: 500 messages a second into the partition; tries fail independently; the wait between tries is the visibility timeout or a backoff. Real flaky failures cluster in time, so spread the tries out.
Exponential backoff spreads the tries: 1, 2, 4, 8 and 16 s span 31 s over 5 retries, long enough to outlast a short blip. In an ordered partition, 31 s at 500 messages a second piles 15,500 behind the poison. Many Kafka systems therefore move a failing message to a retry topic at once, which gives up order for that key.
Failure. Symptom: the DLQ fills with good orders every time the tax service blips. Measure: DLQ arrivals against dependency errors. Cause: N = 1 parks every message that met one flaky try. Fix: more tries, spread by backoff, and alert on DLQ depth.
Chapter 9
Feed six partitions, crash and add consumers, inject a poison pill, and read the lag in messages and seconds
Here is a Kafka-like group with every piece of this lesson. Six partitions take your traffic. Consumers own partitions, process them at 1,000 a second each, and commit every 5 s. A crashed consumer is noticed only after a session timeout; then the group rebalances its partitions. In an eager rebalance every consumer stops for it. In a cooperative one (Kafka's KIP-429), only moved partitions stop.
Each row is a partition: the purple log, the teal committed offset, the blue read position and pink lag ahead of it. Warm boxes are consumers. A red dot is a poison pill.
Simulated in your browser, 10 times faster than real time: 4 consumers to start, 1,000 a second each, commits every 5 s, a 10 s session timeout, a 3 s rebalance pause, 5 retries with backoff 1, 2, 4, 8 and 16 s. Kafka's default session timeout is 45 s; the toy uses 10 s to keep the demo short. Illustrative numbers.
Things to try:
The worked number, from the same engine: 2,700 a second, 4 consumers, crash one 12 s in. Under the eager protocol the peak lag was 13,500 messages and the group was back to zero lag after 93 s; cooperative peaked at 6,750 and recovered after 80 s. The peak is the stalled partition (450 a second for 10 s), plus the pause, plus 922 repeats. The slow drain is Chapter 7’s rule: the consumer that took over the stalled partition has only 100 spare a second.
Failure. Symptom: lag spikes every few minutes with no traffic change. Measure: rebalances per hour and consumer poll times. Cause: work per batch exceeds the poll timeout, so the group drops a live consumer and rebalances again and again. Fix: smaller batches, faster work, or a longer max.poll.interval.ms.
Chapter 10
Keep the numbers, the choices and the code for the next time you put a queue between two services
A queue cuts the time coupling between services: the producer needs only the broker. Little's law turns depth into delay, and Erlang C gives the delay for c consumers.
Pub/sub sends one copy per group. A partitioned log gives order per key and caps parallelism at the partition count. When you commit decides whether a crash loses or repeats; idempotent consumers make repeats harmless. A backlog drains only from spare capacity. A dead letter queue keeps one bad message from stopping the rest.
| Term | What it is | This lesson's number |
|---|---|---|
| Chain availability | A = a1 a2 … an | five at 99.9%: 99.5%, 44 h a year down |
| Little's law | L = λW | 50,000 waiting at 2,000 a second: 25 s |
| Erlang C wait | Wq = C / (cμ − λ) | 900 a second, 10 consumers of 10 ms: 6.7 ms |
| Fan-out | D = λG | 500 events, 4 groups: 2,000 deliveries a second |
| Group throughput | Xmax = μP / ⌈P/c⌉ | 6 partitions, 4 consumers: 3,000, same as 3 |
| Repeats per crash | R = λT / 2 | 2,000 a second, 5 s commits: 5,000 |
| Dedup memory | M = λWb | 2,000 a second, 24 h, 40 B: 6.9 GB |
| Partition of a key | p = hash(k) mod P | 4 to 5 partitions moves 80% of keys |
| Drain time | Tdrain = Q / (cμ − λ) | 3.6 million, 1,000 spare: 1 hour |
| Wrongly parked | PDLQ = fN | f 0.3: N 3 gives 2.7%, N 5 gives 0.24% |
| Job | Choice | Why |
|---|---|---|
| Background jobs, one worker each | a work queue: SQS, RabbitMQ | per-message acks, visibility timeout, built-in DLQ |
| One event, many services | SNS to SQS, Google Pub/Sub, a Kafka topic | one subscription per service |
| Ordered events per entity, replay | Kafka keyed by entity ID | partition order, retention, rewind |
| Ordered work on a managed queue | SQS FIFO with message group IDs | one message per group in flight at a time |
| Lossy metrics | at-most-once | a lost sample costs less than a delay |
Appends and scans are sequential, and Kafka's docs say sequential disk access "can in some cases be faster than random memory access". It leans on the operating system's page cache, batches records, and uses sendfile to copy from the page cache to the network without passing through the program. Throughput figures you see quoted depend on hardware and batch size; measure your own.
python# the lesson's numbers in a few lines (sketch) import math def erlang_c_wait(lam, mu, c): # mean queueing delay with c consumers a, rho = lam / mu, lam / (mu * c) top = a**c / math.factorial(c) / (1 - rho) C = top / (sum(a**k / math.factorial(k) for k in range(c)) + top) return C / (c * mu - lam) def group_max(mu, P, c): # busiest consumer holds ceil(P/c) return mu * P / math.ceil(P / min(c, P)) def handle(msg, db): # an idempotent consumer with db.transaction(): if db.seen(msg.id): return # a repeat: skip, then ack db.apply(msg) # the effect ... db.mark_seen(msg.id) # ... and the ID, in one transaction print(round(erlang_c_wait(900, 100, 10) * 1000, 1)) # 6.7 ms print(group_max(1000, 6, 4)) # 3000.0 print(3_600_000 / (4000 - 3000)) # 3600.0 s to drain
Now press Present or Teach and explain four things from memory. Explain why five chained services fail more than one queue. Explain why 4 consumers on 6 partitions do no better than 3. Explain what a crash repeats under at-least-once and how dedup absorbs it. Explain why a 10-minute burst leaves an hour of lag. Then go back to the hero, pick Call in a chain, and take email down.