Skip to content

Load test Apache Kafka on MaxoPerf

This test measures three things against your Apache Kafka topic: how fast producers get an acknowledgement from the broker (kafka send), how many messages consumers read per second, and how long a message takes to travel from producer to consumer (kafka end-to-end). One locustfile.py does all of it. You change only the connection values, which you bind as secrets.

  • The broker must be reachable from the runners. Use a public endpoint with authentication, or run the test through a private datacenter outpost inside your network.
  • taurus.yml installs the confluent-kafka client (2.16.2) when the test starts, with Taurus’s built-in pip-install service. Nothing is preinstalled on the runner, so runners need outbound HTTPS to PyPI. On a private datacenter without internet access, allow PyPI or your package mirror.
  • Only load a cluster and a topic you are authorised to test. The script creates the topic maxoperf-load if it is missing, so use a non-production cluster or give it a separate topic name.

Save this as locustfile.py. It sends JSON messages with a send timestamp, and the consumers compute end-to-end latency from that timestamp.

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. Taurus runs the Locust file and installs the client when the test starts:

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

The script reads three environment variables. Create each as a secret and bind it to the test; only connection values are secrets.

Secret env varMeaningExample value
SECRET_KAFKA_BOOTSTRAPBootstrap serversbroker-1.example.com:9092
SECRET_KAFKA_USERNAMESASL username (optional). When set, the script uses SASL_SSL with PLAIN<your-api-key>
SECRET_KAFKA_PASSWORDSASL password (optional)<your-api-secret>

Bound secret values are masked in run output. That is why the topic name, partition count and other settings are plain constants at the top of the file: a masked topic name would garble every error message.

Bind the connection values as secrets; the script reads them as environment variables.
  1. Create a new test.

  2. Upload taurus.yml and locustfile.py together. taurus.yml is the entry point: it runs the Locust file and installs the client when the test starts.

    Upload taurus.yml and locustfile.py together: Taurus runs the Locust file and installs the client when the test starts.
  3. On the Dependencies tab, bind the secrets from the table above.

  4. Set the virtual users and duration. Two of the users are consumers (CONSUMERS), so producers = users minus 2. Ten users for a few minutes is a good first run.

  5. Start the run.

Open the finished run and look at the two labels. kafka send is the time from producing a message to the broker’s acknowledgement. kafka end-to-end is the time from producing to a consumer reading it, and its samples per second are your consume rate.

A healthy run shows both labels with no failures once the consumers have joined the group, and a flat end-to-end line. A few failed end-to-end samples in the first seconds of the run are warm-up, not a problem. If end-to-end latency climbs for the whole run, consumers are falling behind even when send looks fine.

Apache Kafka run: send latency and end-to-end latency side by side.

Taurus rounds every sample to a whole millisecond, so on a local or same-zone cluster, fast acknowledgements show as 0 or 1 ms. Read the trend, not the last digit. See read run results for the general layout.

Edit the constants at the top of the file, then upload it again.

  • Load: SENDS_PER_USER_PER_SEC, MESSAGE_BYTES and the user count set the offered load. Use a message size close to your real traffic.
  • Producer batching: linger.ms and batch.size trade a little send latency for throughput. compression.type shrinks batches on the wire. acks defaults to all; set "acks": 1 to see how much of your latency is replication.
  • Partitions and consumers: PARTITIONS only applies when the script creates the topic. Consumers beyond the partition count sit idle, so keep CONSUMERS at or below it.
  • Fetching: fetch.min.bytes makes the broker wait for more data per fetch, which lowers request count and raises latency.
  • Rebalances: consumers that join mid-run trigger a group rebalance and a pause in end-to-end samples. Start all consumers together, then judge the steady part of the run.
  • Several runners: each runner has its own clock. End-to-end latency adds any clock skew between runners, so keep clocks in sync with NTP or compare against a single-runner run.
SymptomLikely cause and fix
kafka send fails with _TRANSPORT or Broker transport failureThe runner cannot reach the address the broker advertises. Check the bootstrap address, the broker’s advertised listeners and the network path, or use an outpost.
SASL authentication failedWrong API key or secret, or the cluster uses a different mechanism. Re-check the secrets; for SCRAM change sasl.mechanisms in the file.
Topic error on first useThe user may lack permission to create topics. Create maxoperf-load in advance with the partition count you want.
kafka end-to-end has no samplesConsumers got no messages: more consumers than partitions, or the group is still rebalancing. Wait for warm-up, or lower CONSUMERS.
A failed row with no nameAn unhandled exception inside the script. Open the run logs for the traceback.
ModuleNotFoundError: No module named 'confluent_kafka'The pip-install step could not install the client, usually because the runner has no route to PyPI (common on a private datacenter). Allow outbound HTTPS to PyPI or your mirror, and check the run logs for the pip error.