Messaging & Events

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.

Place orders two ways

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

Five Calls, One Weak Link

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.

Say it aloud

A equals a-one times a-two, and so on, times a-n.

A
A the share of time an order can succeed: every service in the chain is up.
a1, a2
a-one, a-two the availability of each service, from 0 to 1. 0.999 means up 99.9% of the time.
an
a-n the last of the n services. Here n = 5 downstream services.
In plain words

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 numbers

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.

Live through a month of outages

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.

99.9%

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.

  1. Queue: one message, one worker, acks, and how deep the queue gets.
  2. Fan-out: one event to every service that cares.
  3. Log: Kafka's partitioned log and how many consumers help.
  4. Delivery: when you commit decides what a crash loses or repeats.
  5. Once: idempotent consumers and deduplication windows.
  6. Order: order per key, and what resizing and rebalancing break.
  7. Pressure: producers faster than consumers, and the drain time.
  8. Retries: poison pills and dead letter queues.
  9. Showcase: run a consumer group, crash a member, inject a poison pill.
  10. The field guide: numbers, choices, code and links.
The order service calls five services in a row. The email service is down. What happens to new orders?

Chapter 1

One Message, One Worker

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.

Say it aloud

L equals lambda times W.

L
L the average number of messages in the system: in the queue plus in a consumer's hands.
λ
lambda messages arriving per second: 900 here.
W
W the average seconds one message spends inside, from arrival to ack.
In plain words

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 numbers

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.

Where W comes from: Erlang C for c consumers

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.

C = [ac/c! · 1/(1 − ρ)] / [Σk<c ak/k! + ac/c! · 1/(1 − ρ)] Wq = C / (cμ − λ), W = Wq + 1/μ

λ = 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.

Staff the queue

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.

900
10

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.

A queue shows 50,000 messages waiting and receives 2,000 a second. About how old is the newest message when a consumer reaches it?

Chapter 2

One Event, Every Subscriber

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.

Say it aloud

D equals lambda times G.

D
D deliveries per second the broker makes: copies sent out.
λ
lambda events published per second: 500 orders here.
G
G the number of consumer groups (subscriptions). Instances inside a group do not count.
In plain words

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 numbers

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.

Fan out one topic

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.

500

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).

Payment (2 instances), stock (1) and email (3) each form one group on a topic. How many copies of one event are delivered?

Chapter 3

The Log and Its Partitions

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).

Say it aloud

X-max equals mu times P, divided by the ceiling of P over c.

Xmax
X-max the most messages per second the group can keep up with, if keys spread evenly over partitions.
μ
mu messages per second one consumer can process: 1,000 here, illustrative.
P
P partitions in the topic: 6 here.
⌈P / c⌉
the ceiling of P over c partitions held by the busiest of the c consumers: P divided by c, rounded up.
In plain words

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 numbers

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.

Assign partitions to a group

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.

6
4
3,500

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.

A topic has 6 partitions and each consumer handles 1,000 a second. What is the most the group can keep up with using 4 consumers?

Chapter 4

When You Commit Decides What You Lose

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.

  1. At-most-once. Commit, then process. A crash after the commit skips the unprocessed messages. Nothing repeats; some are lost.
  2. At-least-once. Process, then commit. A crash before the commit makes the next owner start from the old offset and repeat the work. Nothing is lost; some repeat.

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.

Say it aloud

R equals lambda times T, over 2.

R
R messages processed a second time after one crash, on average.
λ
lambda messages this consumer processes per second: 2,000 here.
T
T over 2 the commit interval, 5 s here. A crash lands on average halfway through it.
In plain words

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 numbers

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.

Crash between work and commit

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.

5 s

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.

A consumer processes 2,000 messages a second and commits every 5 s. It crashes. About how many messages run twice, on average?

Chapter 5

Exactly Once Is the Consumer's Job

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.

Say it aloud

M equals lambda times W times b.

M
M memory the dedup table needs, in bytes.
λ
lambda messages per second: 2,000 here.
W
W the dedup window: how many seconds the table keeps an ID. A repeat older than W gets through.
b
b bytes per stored ID with its overhead: 40 here, illustrative.
In plain words

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 numbers

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.

Size the dedup window

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.

A consumer dedups with a 1-hour cache of IDs. Which repeat gets through?

Chapter 6

Order per Key, Not per Topic

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.

Say it aloud

p equals hash of k, mod P.

p
p the partition number the message goes to, from 0 to P minus 1.
hash
hash of a function that turns the key into a large number, the same number every time. Kafka's producer hashes the key's bytes.
k
k the message key: the order ID here.
mod
mod the remainder after dividing: 42 mod 4 is 2.
P
P partitions in the topic: 4 here.
In plain words

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 numbers

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%.

Keep each order in order

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.

Events are keyed by order ID into 4 partitions. Can "shipped" for order 42 be handled before "paid" for order 42?

Chapter 7

When Producers Outrun Consumers

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 λ.

Say it aloud

T-drain equals Q divided by, c mu minus lambda.

Tdrain
T-drain seconds until the backlog is gone.
Q
Q the backlog: messages waiting when the burst ends.
cμ
c mu what all c consumers process per second together: 4,000 here.
λ
lambda messages still arriving per second: 3,000 here. c mu minus lambda is the spare capacity.
In plain words

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.

With numbers

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.

Ride out a burst

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.

10,000

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.

A burst leaves 3.6 million messages. Consumers do 4,000 a second and 3,000 still arrive. How long to drain?

Chapter 8

Poison Pills and Dead Letters

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.

Say it aloud

P-D-L-Q equals f to the N.

PDLQ
P-D-L-Q the chance that a healthy message ends up in the dead letter queue.
f
f the chance one try fails for a passing reason, such as a flaky dependency: 0.3 here, illustrative.
N
to the N the tries allowed before parking. All N must fail.
In plain words

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 numbers

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.

Choose the tries

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.

5
30%
30 s

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.

A dependency fails 30% of tries for passing reasons. What share of healthy messages does N = 3 park in the DLQ?

Chapter 9

Run a Consumer Group

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.

Run the group

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.

2,700

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:

  1. At 2,700 a second with 4 consumers, lag stays near zero. Drag to 3,500: two consumers own two partitions each, and lag grows by 333 a second (Chapter 3).
  2. Back to 2,700, then crash a consumer. Its partition stalls for the 10 s timeout, the group pauses, and the new owner repeats work since the last commit (Chapter 4).
  3. Do the same with cooperative rebalancing: the other partitions keep moving.
  4. Inject a poison pill. With the DLQ on, partition 0 stops for 31 s, then moves on. Turn the DLQ off and partition 0 stops for good (Chapter 8).

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.

In an eager rebalance, what happens to partitions whose owner did not change?

Chapter 10

The Field Guide

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.

Terms and numbers

TermWhat it isThis lesson's number
Chain availabilityA = a1 a2 … anfive at 99.9%: 99.5%, 44 h a year down
Little's lawL = λW50,000 waiting at 2,000 a second: 25 s
Erlang C waitWq = C / (cμ − λ)900 a second, 10 consumers of 10 ms: 6.7 ms
Fan-outD = λG500 events, 4 groups: 2,000 deliveries a second
Group throughputXmax = μP / ⌈P/c⌉6 partitions, 4 consumers: 3,000, same as 3
Repeats per crashR = λT / 22,000 a second, 5 s commits: 5,000
Dedup memoryM = λWb2,000 a second, 24 h, 40 B: 6.9 GB
Partition of a keyp = hash(k) mod P4 to 5 partitions moves 80% of keys
Drain timeTdrain = Q / (cμ − λ)3.6 million, 1,000 spare: 1 hour
Wrongly parkedPDLQ = fNf 0.3: N 3 gives 2.7%, N 5 gives 0.24%

Which broker for which job

JobChoiceWhy
Background jobs, one worker eacha work queue: SQS, RabbitMQper-message acks, visibility timeout, built-in DLQ
One event, many servicesSNS to SQS, Google Pub/Sub, a Kafka topicone subscription per service
Ordered events per entity, replayKafka keyed by entity IDpartition order, retention, rewind
Ordered work on a managed queueSQS FIFO with message group IDsone message per group in flight at a time
Lossy metricsat-most-oncea lost sample costs less than a delay

Why Kafka is fast

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.

Corrections to common figures

Checklist

  1. Keep only what the user must wait for in the synchronous path; publish the rest.
  2. Make every consumer idempotent, keyed by a message or business ID.
  3. Key events by the entity whose order matters; choose the partition count up front.
  4. Run consumers below about 75% busy, and alert on lag in seconds.
  5. Set the visibility timeout above the slowest processing time.
  6. Give every queue a DLQ with backoff between tries, and watch its depth.
  7. Use the outbox when a database write and an event must both happen.

The core as code

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

Keep going

The takeaway. A queue trades waiting for lag. Size consumers with Erlang C, partition by the key whose order matters, commit after the work and make the work idempotent, alert on lag in seconds, and park poison pills after a few spaced tries.

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.

Messaging & Events
Kafka design · SQS DLQs · RabbitMQ quorum queues · Back to Gleams