Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Worked example · 25 min · revision 2

Load leveling, backpressure, claim checks and broker sizing

Work through the messaging design of a photo app step by step: use a queue to level an evening peak and size the workers from a backlog simulation, push back when a producer's buffer fills, pass large files with a claim check, and estimate disk, network and partitions for an event topic from rate, size, retention and replication.

Contentsand lesson path

What you will learn

  • Level load and handle backpressure, consumer lag, retries, dead-letter queues and oversized payloads (claim check), and size a broker from message rate and retention.

01. The problem

A photo-sharing app creates a thumbnail job for every upload. Most of the day it receives about 200 uploads a minute, but every evening there is a 20-minute peak of 900 a minute. Each thumbnail worker finishes about 100 jobs a minute. The product team asks for every thumbnail within 10 minutes of upload. At the same time, the original photos, about 3 MB each, must reach a transcoding service, and the analytics team wants a new topic of photo events with three days of history.

Four questions follow, and this worked example answers them in order:

  • How many workers do we need if a queue absorbs the peak, compared with handling every upload as it arrives?
  • What should the upload API do when it cannot hand jobs to the broker fast enough?
  • How do 3 MB files travel through a broker whose message limit is about 1 MB?
  • How much disk, network and how many partitions does the event topic need?

You can run every step. Steps 1 and 2 need only Python and the confluent-kafka package; steps 3 and 4 use the mq-lab folder and broker from lesson 3. Run the commands from mq-lab.

02. Step 1: Level the load with a queue

Without a queue, the API would have to call a worker for every upload and wait for it, so the system would need enough workers for the peak, 9 of them, sitting mostly idle the rest of the day. Queue-based load leveling puts a queue between the two sides: uploads add jobs at whatever rate they arrive, workers take jobs at the rate they can sustain, and the queue holds the difference. The price is waiting time, so the design question becomes how many workers keep the wait inside the 10-minute target.

The script simulates one hour minute by minute. Each minute it adds the arrivals to the backlog (jobs waiting) and removes what the workers can finish. The wait for a new job is roughly the backlog divided by the workers' rate.

Python · level.py
"""Minute-by-minute backlog of a queue in front of thumbnail workers.
Usage: python level.py WORKERS   (each worker finishes 100 jobs a minute)"""
import sys

workers = int(sys.argv[1])
capacity = workers * 100                         # jobs per minute
arrivals = [200] * 10 + [900] * 20 + [200] * 30  # quiet, a 20-minute peak, quiet
backlog = peak = worst_wait = 0
drained_at = None
for minute, arrived in enumerate(arrivals, start=1):
    backlog = max(0, backlog + arrived - capacity)
    peak = max(peak, backlog)
    worst_wait = max(worst_wait, backlog / capacity)   # minutes a new job waits
    if peak and backlog == 0 and drained_at is None:
        drained_at = minute
    if minute % 10 == 0:
        print(f"minute {minute:2}: {arrived:3} arrived, backlog {backlog:5}")
end = f"empty again at minute {drained_at}" if drained_at else f"{backlog} left at 60"
print(f"{workers} workers: peak backlog {peak}, worst wait {worst_wait:.1f} min, {end}")
Terminal
for w in 9 6 4; do python3 level.py "$w" | tail -n 1; done
python3 level.py 6
Expected output
9 workers: peak backlog 0, worst wait 0.0 min, 0 left at 60
6 workers: peak backlog 6000, worst wait 10.0 min, empty again at minute 45
4 workers: peak backlog 10000, worst wait 25.0 min, 4000 left at 60
minute 10: 200 arrived, backlog     0
minute 20: 900 arrived, backlog  3000
minute 30: 900 arrived, backlog  6000
minute 40: 200 arrived, backlog  2000
minute 50: 200 arrived, backlog     0
minute 60: 200 arrived, backlog     0
6 workers: peak backlog 6000, worst wait 10.0 min, empty again at minute 45

Nine workers match the peak, and no backlog builds up. With six, the backlog grows by 300 jobs a minute during the peak to 6,000, the worst wait reaches exactly the 10-minute target, and the queue is empty 15 minutes after the peak. Four workers are not enough: the wait reaches 25 minutes and 4,000 jobs are still waiting at the end of the hour. The queue lets us run 6 workers instead of 9, with no margin. In practice you would add headroom, or let an autoscaler add workers when the backlog passes a threshold.

03. Step 2: Push back when the buffer fills

A queue absorbs peaks only while it has room. Somewhere, every buffer is finite: the broker's disk, the producer's memory, the consumer's in-memory batch. Backpressure means that a full buffer slows down or refuses the sender, instead of silently dropping data or growing until the process runs out of memory.

A Kafka producer keeps messages in a local buffer until the broker acknowledges them. If the broker cannot be reached, the buffer fills. The script points a producer at a port where nothing listens and gives it a tiny buffer of 5 messages, so you can see what happens when it is full.

Python · buffer.py
"""Fill a producer's local buffer while the broker cannot be reached."""
from confluent_kafka import Producer

producer = Producer({
    "bootstrap.servers": "localhost:1",          # nothing listens here
    "queue.buffering.max.messages": 5,           # a tiny buffer, to see it fill
    "message.timeout.ms": 3000,                  # give up on a message after 3 s
    "log_level": 0,                              # hide connection-refused logs
})
errors = []
for n in range(1, 8):
    try:
        producer.produce("thumbnails", value=f"job-{n}",
                         on_delivery=lambda err, msg: errors.append(err.str()))
        print(f"job-{n}: buffered ({len(producer)} waiting)")
    except BufferError as error:
        print(f"job-{n}: refused, {error}")
producer.flush(10)                               # runs the delivery callbacks
print(f"{len(errors)} buffered jobs failed: {sorted(set(errors))}")
Terminal
.venv/bin/python buffer.py
Expected output
job-1: buffered (1 waiting)
job-2: buffered (2 waiting)
job-3: buffered (3 waiting)
job-4: buffered (4 waiting)
job-5: buffered (5 waiting)
job-6: refused, Local: Queue full
job-7: refused, Local: Queue full
5 buffered jobs failed: ['Local: Message timed out']

The first five jobs are accepted into the buffer. Jobs 6 and 7 are refused at once with BufferError ("Local: Queue full"); this is the client pushing back. The five buffered jobs are not safe either: after message.timeout.ms (3 s here) they fail with "Message timed out". The application learns that only through the delivery callback, which is why a producer must always check delivery results.

What should the upload API do on BufferError? Dropping the job loses it silently. Retrying in a tight loop ties up request threads. The usual answer is to pass the pressure upstream: answer the client with HTTP 503 and a Retry-After header, so that it waits and tries again, and alert on the rate of refusals. Consumers apply backpressure too: they fetch a bounded batch, and if their own work queue is full they stop fetching (pause() in Kafka clients, a small prefetch limit in RabbitMQ) until they catch up, while still calling poll so the group does not think they have died.

04. Step 3: Pass large files with a claim check

Brokers are built for many small messages. Kafka's default limit is about 1 MB per message, on the broker (message.max.bytes) and in the client. Large messages make replication, retention and memory use harder to predict, so the usual advice is not to raise the limit far. First, see the limit:

Python · too_big.py
"""Try to publish a 3 MB payload directly."""
import os

from confluent_kafka import KafkaException, Producer

payload = os.urandom(3 * 1024 * 1024)
producer = Producer({"bootstrap.servers": "localhost:19092"})
try:
    producer.produce("media-jobs", key="clip-1", value=payload)
    producer.flush(10)
except KafkaException as error:
    print("refused:", error.args[0].str())
Terminal
./kafka.sh kafka-topics.sh --create --topic media-jobs --partitions 1 > /dev/null
.venv/bin/python too_big.py
Expected output
refused: Unable to produce message: Broker: Message size too large

The claim check pattern stores the payload somewhere built for large objects, such as Amazon S3, Google Cloud Storage or Azure Blob Storage, and publishes only a small message, the "claim", that says where it is. The script uses a local folder as the object store. It writes the object first and publishes second, so a consumer can never receive a claim for an object that does not exist yet. The object key is derived from a SHA-256 hash of the content, so a retried upload writes the same key instead of a second copy, and the consumer can check that it received the right bytes.

Python · claim_check.py
"""Claim check: store the payload, publish a small message that points to it."""
import hashlib
import json
import random
from pathlib import Path

from confluent_kafka import Consumer, Producer

STORE = Path("object-store")                     # stands in for S3, GCS or Azure Blob
STORE.mkdir(exist_ok=True)
payload = random.Random(7).randbytes(3 * 1024 * 1024)   # a fixed 3 MB "video"

digest = hashlib.sha256(payload).hexdigest()
object_key = f"uploads/{digest[:16]}.bin"        # content-addressed: retries reuse it
(STORE / object_key).parent.mkdir(parents=True, exist_ok=True)
(STORE / object_key).write_bytes(payload)        # 1. write the object first
claim = {"object_key": object_key, "size": len(payload), "sha256": digest}
producer = Producer({"bootstrap.servers": "localhost:19092"})
producer.produce("media-jobs", key="clip-1", value=json.dumps(claim))
producer.flush(10)                               # 2. then publish the claim
print(f"published claim: {len(json.dumps(claim))} bytes for a {len(payload)}-byte file")

consumer = Consumer({"bootstrap.servers": "localhost:19092", "group.id": "transcoder",
                     "auto.offset.reset": "earliest"})
consumer.subscribe(["media-jobs"])
msg = consumer.poll(15.0)
claim = json.loads(msg.value())
data = (STORE / claim["object_key"]).read_bytes()   # the consumer fetches the payload
ok = hashlib.sha256(data).hexdigest() == claim["sha256"]
print(f"consumer read {claim['object_key']}: {len(data)} bytes, checksum ok={ok}")
consumer.close()
Terminal
.venv/bin/python claim_check.py
Expected output
published claim: 141 bytes for a 3145728-byte file
consumer read uploads/1f1e5bf7700ec01b.bin: 3145728 bytes, checksum ok=True

The message on the topic is 141 bytes instead of 3 MB, so the broker stays fast. Two new duties come with the pattern. The objects need a lifecycle rule that keeps them at least as long as a consumer may read the claim, including replays within the topic's retention; delete them too early and replays fail. And the consumer needs permission to read the store, limited to the objects it is meant to read.

05. Step 4: Size the event topic

Sizing starts from the workload, not from the hardware. For the analytics topic the team measured an average of 5,000 events a second, a peak of 15,000, about 600 bytes per event after compression, three days of retention, three replicas, and three consumer groups. One consumer instance handled 1,500 events a second in a load test. Storage depends on the average rate, because retention keeps everything that arrives over days. Network and partitions depend on the peak, because the system must keep up at its busiest minute. Every replica stores a full copy, and every consumer group reads the data once more.

Python · size.py
"""Rough broker sizing for one topic. Change the inputs to match your workload."""
import math

avg_rate, peak_rate = 5_000, 15_000      # messages per second
msg_bytes = 600                          # average size on disk, after compression
retention_days = 3
replication = 3
consumer_groups = 3                      # each group reads every message once
per_consumer_rate = 1_500                # measured: messages/s one consumer handles
headroom = 0.4                           # keep 40% of disk free for growth and repair

stored = avg_rate * msg_bytes * retention_days * 86_400 * replication
disk = stored / (1 - headroom)
write_in = peak_rate * msg_bytes * replication      # leader + follower writes
read_out = peak_rate * msg_bytes * consumer_groups
partitions = math.ceil(peak_rate / per_consumer_rate)

print(f"data kept (all replicas): {stored / 1e12:.2f} TB")
print(f"disk to provision:        {disk / 1e12:.2f} TB")
print(f"peak write into brokers:  {write_in / 1e6:.0f} MB/s")
print(f"peak read by consumers:   {read_out / 1e6:.0f} MB/s")
print(f"partitions for peak:      at least {partitions}")
Terminal
python3 size.py
Expected output
data kept (all replicas): 2.33 TB
disk to provision:        3.89 TB
peak write into brokers:  27 MB/s
peak read by consumers:   27 MB/s
partitions for peak:      at least 10

About 2.3 TB of data is kept across all replicas; with 40% of the disk left free for growth and for recovering a failed broker, provision about 3.9 TB in total, spread over the brokers. At peak the brokers write 27 MB/s, counting every replica, and serve the same again to consumers, plus the traffic between replicas. The partition count must let one group run enough consumers for the peak: 15,000 ÷ 1,500 gives at least 10, and teams usually round up, here to 12, to leave room for growth, because adding partitions later moves keys (lesson 3).

The per-consumer and per-partition rates must come from your own measurement, with your message size and settings. Kafka ships a load generator. Run it against the lab broker to see the method; the numbers depend on the machine and say little about a real cluster.

Terminal
./kafka.sh kafka-topics.sh --create --topic perf-test --partitions 1 > /dev/null
docker exec mq-kafka /opt/kafka/bin/kafka-producer-perf-test.sh --topic perf-test \
  --num-records 200000 --record-size 600 --throughput -1 \
  --producer-props bootstrap.servers=localhost:19092 acks=all |
  tail -n 1 | tr ',' '\n' | sed 's/^ //'
Illustrative output
200000 records sent
42122.999158 records/sec (24.10 MB/sec)
937.44 ms avg latency
1238.00 ms max latency
993 ms 50th
1184 ms 95th
1221 ms 99th
1234 ms 99.9th.

Your result will differ. A single broker in a container shares disk and CPU with everything else and has no replication traffic, so treat the number as a demonstration of the tool, not as a capacity figure. When you are done with the lessons, remove the broker and the lab folder: docker rm -f mq-kafka, then delete mq-lab.

06. Check your understanding

Practice check · 3 questions

Peaks, buffers, claims and sizing

Use the four steps above.

Q1. What peak backlog does `python3 level.py 7` print for the same traffic?
Q2. Why does `claim_check.py` write the object before it publishes the claim?
Q3. During a broker outage, an upload API's producer raises `BufferError` on every new job. What should the API do with new uploads?
Practice only: not graded, not saved, not evidence.

07. Apply it

For the order pipeline in the skill practice, write a one-page capacity note: average and peak events per second, average event size, retention, replication factor and number of consumer groups; the disk and network that follow; the partition count, and how you measured one consumer's rate. Add what the producer does when its buffer fills, and whether any payload is large enough to need a claim check.

08. Review prompt

Without looking back, explain: how a queue lets you run fewer workers than the peak needs and what you pay for it; how to find the minimum worker count from a backlog simulation; what backpressure means on the producer and on the consumer; how a claim check works and the two new duties it brings; which inputs drive disk, network and partition count; and why throughput numbers must be measured.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check