Skip to content

Load Testing Apache Kafka: Lag Hides Behind Fast Sends

How Apache Kafka fails under load, why healthy producers can hide growing consumer lag, and a copy-paste locustfile.py that measures both.

A Kafka topic drawn as six partition lanes: one hot partition is packed with red messages while a consumer on it falls behind and a third consumer sits idle

Most Kafka load tests answer the wrong question. They push messages at a topic as fast as a producer can go, read the producer’s throughput, and call the cluster healthy. Producers are the easy half. Kafka acknowledges a write once the leader, and by default the in-sync replicas, have it, and a broker that accepts writes happily can still be serving them to consumers far too late. The number that matters to your users is how long a message takes to arrive, and that is not the number a producer-only test reports.

This post covers how Apache Kafka tends to fail under load, what to measure so those failures show up, and a single locustfile.py you can run on MaxoPerf to measure it. The file is the same one in the step-by-step how-to.

How Kafka fails under load

Consumer lag hides behind healthy producers

A producer and a consumer are separate workloads. Producers append to a log; consumers read from it at their own pace. When consumers are slower than producers, nothing breaks. The log just grows, and every new message waits behind a longer backlog. Send latency stays flat, broker CPU looks fine, and error rates are zero. The only symptom is that the time between a message being written and being read keeps rising.

This is why a Kafka test has to carry a timestamp inside each message and compute latency at the consumer. Anything that watches only the producing side is blind to lag by construction.

Partition skew and hot keys

Kafka parallelism is partitions. A topic with six partitions can keep at most six consumers in one group busy. Messages with the same key always land on the same partition, so a skewed key distribution, such as one large tenant or one popular product, loads one partition far more than the rest. The consumer that owns it falls behind while its neighbours idle.

Two lessons follow. First, test with a key distribution that looks like production, not a uniform random key. Second, adding consumers beyond the partition count does nothing: the extras join the group and receive no partitions. If you scale consumers and the consume rate does not move, count partitions before you blame the code.

Rebalance storms

When a consumer joins or leaves a group, the group rebalances and partitions are reassigned. During a rebalance, consumption pauses. Autoscaling consumers under load, or consumers that fail health checks and restart, can trigger rebalances repeatedly, and each one produces a gap in throughput and a spike in end-to-end latency. A test that starts all its consumers once, waits for warm-up, and then measures will miss this. A test that adds or removes consumers during the run will show it.

acks=all and replication latency

With acks=all, a write is acknowledged only after every in-sync replica has it. That is the setting that protects you from losing data, and it is also where cross-zone network latency and slow follower disks enter your send latency. A cluster can look fast with acks=1 and noticeably slower with acks=all. Test with the setting you run in production, and consider running it both ways once to see how much of your latency is replication.

Disk and page cache pressure

Kafka leans on the operating system’s page cache. Consumers that read recent data are served from memory, so a healthy, caught-up consumer is cheap. A consumer that falls far behind reads old segments from disk, which is slower and also evicts the data caught-up consumers need. Lag therefore feeds on itself: the further behind a consumer is, the more it costs the cluster to serve it. This is one reason a test that lets lag build can produce a sudden cliff rather than a gentle slope.

What to measure

Two numbers carry most of the signal, and the script reports them as separate labels:

  • kafka send: the time from producing a message to the broker’s acknowledgement. This is the producer’s view and shows replication and broker health.
  • kafka end-to-end: the time from producing a message to a consumer reading it. This is the user’s view and shows lag, skew and rebalances. Its samples per second are your consume rate.

Read them together. Healthy looks like both labels free of failures and an end-to-end line that stays flat. Trouble looks like end-to-end latency that climbs across the run while send stays calm. That gap is lag, and a producer-only test never sees it.

The locustfile

The script uses Locust and the confluent-kafka client; the taurus.yml next to it installs that client when the test starts. A few choices in it are deliberate:

  • One producer is shared by all producer users, because the client batches internally and a producer per user would start a pile of background threads.
  • Send latency comes from the client’s own delivery report, not from a clock read in the callback. Callbacks only run on the next poll, so a clock read there would measure the producer’s own waiting time.
  • Consumers poll with a zero timeout and sleep briefly when idle. A blocking poll would freeze every virtual user on the runner, because Locust runs on a cooperative event loop.
  • Messages older than 60 seconds before the test started are skipped, so a backlog from the previous run does not pollute this one.
locustfile.py
"""Apache Kafka load test for MaxoPerf: producers send, consumers measure end-to-end latency.
Connection values come from MaxoPerf secrets bound to this test (Dependencies tab)."""
import json, os, time, uuid
import gevent
from locust import User, task, events, constant, constant_throughput
from confluent_kafka import Consumer, KafkaError, KafkaException, Producer
from confluent_kafka.admin import AdminClient, NewTopic
# --- connection (bind these as secrets; defaults work against a local broker) ---
BOOTSTRAP = os.environ.get("SECRET_KAFKA_BOOTSTRAP", "localhost:9092")
USERNAME = os.environ.get("SECRET_KAFKA_USERNAME") # optional: set for SASL_SSL (e.g. Confluent Cloud)
PASSWORD = os.environ.get("SECRET_KAFKA_PASSWORD")
# --- names + load knobs (edit freely; not secrets: secret values are masked in run output) ---
TOPIC = "maxoperf-load"
PARTITIONS = 6 # consumers beyond the partition count sit idle
SENDS_PER_USER_PER_SEC = 10 # producer rate per virtual user
MESSAGE_BYTES = 512 # payload size
CONSUMERS = 2 # fixed consumer users (Locust fixed_count)
STALE_AFTER_S = 60 # skip backlog left over from a previous run
STARTED = time.time()
CONF = {"bootstrap.servers": BOOTSTRAP}
if USERNAME: # SCRAM is one word change: sasl.mechanisms = SCRAM-SHA-512
CONF.update({"security.protocol": "SASL_SSL", "sasl.mechanisms": "PLAIN",
"sasl.username": USERNAME, "sasl.password": PASSWORD})
def record(name, start, exc=None, size=0): # one result sample under label "kafka <name>"
if exc: # the results CSV cannot hold commas or quotes: flatten the error text
exc = Exception(" ".join(str(exc).replace(",", ";").replace('"', "'").split()))
events.request.fire(request_type="KAFKA", name=f"kafka {name}",
response_time=(time.time() - start) * 1000,
response_length=size, exception=exc, context={})
try: # idempotent setup: create the topic once per process, tolerate "already exists"
for f in AdminClient(CONF).create_topics([NewTopic(TOPIC, PARTITIONS, 1)]).values():
try:
f.result(10)
except KafkaException as e:
if e.args[0].code() != KafkaError.TOPIC_ALREADY_EXISTS:
raise
except Exception as e:
print(f"topic setup skipped: {e}")
# One producer per process: librdkafka is thread-safe and batches internally.
PRODUCER = Producer({**CONF, "linger.ms": 5, "message.timeout.ms": 10000})
events.quitting.add_listener(lambda **kw: PRODUCER.flush(5)) # bzt allows ~10 s for teardown
def delivered(err, msg): # runs inside poll(); latency() is librdkafka's own produce-to-ack time
start = time.time() - (msg.latency() or 0)
record("send", start, Exception(str(err)) if err else None, len(msg.value() or b""))
class SendUser(User):
wait_time = constant_throughput(SENDS_PER_USER_PER_SEC)
@task
def send(self):
body = json.dumps({"id": str(uuid.uuid4()), "sent_at": time.time(), "pad": "x" * MESSAGE_BYTES})
PRODUCER.produce(TOPIC, body.encode(), on_delivery=delivered)
PRODUCER.poll(0) # serve delivery callbacks without blocking the gevent loop
while len(PRODUCER) > 10_000: # back-pressure: let the queue drain
PRODUCER.poll(0)
gevent.sleep(0.005)
class ReceiveUser(User):
fixed_count = CONSUMERS
wait_time = constant(0)
def on_start(self):
# earliest: sends made while the group is still joining are not lost
self.c = Consumer({**CONF, "group.id": "maxoperf-load", "auto.offset.reset": "earliest"})
self.c.subscribe([TOPIC])
def on_stop(self):
self.c.close()
@task
def receive(self):
msg = self.c.poll(0) # never a blocking timeout: it blocks in C and freezes every user
if msg is None:
gevent.sleep(0.01)
return
if msg.error():
record("end-to-end", time.time(), Exception(str(msg.error())))
return
sent_at = json.loads(msg.value())["sent_at"]
if sent_at >= STARTED - STALE_AFTER_S: # older messages are a previous run's backlog
record("end-to-end", sent_at, size=len(msg.value()))

Upload it together with this taurus.yml, which runs the Locust file and installs the client at test start:

taurus.yml
execution:
- executor: locust
scenario: mq
scenarios:
mq:
script: locustfile.py
services:
- module: pip-install
packages:
- confluent-kafka==2.16.2

Run it on MaxoPerf

  1. Create a new test and upload locustfile.py unchanged. MaxoPerf detects Locust from the file.
  2. Create secrets for SECRET_KAFKA_BOOTSTRAP and, if your cluster needs SASL, SECRET_KAFKA_USERNAME and SECRET_KAFKA_PASSWORD, then bind them on the Dependencies tab.
  3. Set ten virtual users and a few minutes of duration. Two of the users are consumers, so the rest are producers.
  4. Start the run and watch both labels.
  5. Change one knob at a time, such as partitions, acks or linger.ms, and run again.

Use a cluster and topic you are allowed to load. The script creates the topic maxoperf-load if it is missing, so point it at a non-production cluster.

What to look for

Start with failures. Any failed row, including one with no name, means something is wrong before latency even matters. A failed row with no name is an exception inside the script, and the run logs hold the traceback.

Then compare the labels. If kafka send is high and kafka end-to-end is close to it, the cost is on the write path: replication, batching, network. If kafka send is low and kafka end-to-end is high or climbing, the cost is on the read path: not enough consumers, too few partitions, a hot key or a rebalance.

Finally, change the shape of the test. Raise the producer rate until end-to-end latency stops being flat; that is the throughput your consumers can sustain. Add consumers up to the partition count and confirm the consume rate follows. Add a hot key to see how your system behaves when one partition carries most of the load.

Taurus rounds samples to whole milliseconds, so a fast local cluster shows 0 or 1 ms for sends. That is a limit of the measurement, not a sign of a bug.

Where to go next

Follow the step-by-step Apache Kafka how-to for screenshots, tuning options and a troubleshooting table, and read Message queue testing: do and don’t for rules that apply to every broker. When you are ready to run your own test, start on MaxoPerf and bring your own cluster.