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.
Before you start
Section titled “Before you start”- 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.ymlinstalls theconfluent-kafkaclient (2.16.2) when the test starts, with Taurus’s built-inpip-installservice. 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-loadif it is missing, so use a non-production cluster or give it a separate topic name.
The locustfile
Section titled “The locustfile”Save this as locustfile.py. It sends JSON messages with a send timestamp, and the consumers compute end-to-end latency from that timestamp.
"""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, uuidimport geventfrom locust import User, task, events, constant, constant_throughputfrom confluent_kafka import Consumer, KafkaError, KafkaException, Producerfrom 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 idleSENDS_PER_USER_PER_SEC = 10 # producer rate per virtual userMESSAGE_BYTES = 512 # payload sizeCONSUMERS = 2 # fixed consumer users (Locust fixed_count)STALE_AFTER_S = 60 # skip backlog left over from a previous runSTARTED = 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: raiseexcept 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:
execution: - executor: locust scenario: mqscenarios: mq: script: locustfile.pyservices: - module: pip-install packages: - confluent-kafka==2.16.2Connect it to your broker
Section titled “Connect it to your broker”The script reads three environment variables. Create each as a secret and bind it to the test; only connection values are secrets.
| Secret env var | Meaning | Example value |
|---|---|---|
SECRET_KAFKA_BOOTSTRAP | Bootstrap servers | broker-1.example.com:9092 |
SECRET_KAFKA_USERNAME | SASL username (optional). When set, the script uses SASL_SSL with PLAIN | <your-api-key> |
SECRET_KAFKA_PASSWORD | SASL 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.
Run it on MaxoPerf
Section titled “Run it on MaxoPerf”-
Create a new test.
-
Upload
taurus.ymlandlocustfile.pytogether.taurus.ymlis 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. -
On the Dependencies tab, bind the secrets from the table above.
-
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. -
Start the run.
Read the results
Section titled “Read the results”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.
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.
Tune it for your system
Section titled “Tune it for your system”Edit the constants at the top of the file, then upload it again.
- Load:
SENDS_PER_USER_PER_SEC,MESSAGE_BYTESand the user count set the offered load. Use a message size close to your real traffic. - Producer batching:
linger.msandbatch.sizetrade a little send latency for throughput.compression.typeshrinks batches on the wire.acksdefaults toall; set"acks": 1to see how much of your latency is replication. - Partitions and consumers:
PARTITIONSonly applies when the script creates the topic. Consumers beyond the partition count sit idle, so keepCONSUMERSat or below it. - Fetching:
fetch.min.bytesmakes 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.
Troubleshooting
Section titled “Troubleshooting”| Symptom | Likely cause and fix |
|---|---|
kafka send fails with _TRANSPORT or Broker transport failure | The 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 failed | Wrong 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 use | The user may lack permission to create topics. Create maxoperf-load in advance with the partition count you want. |
kafka end-to-end has no samples | Consumers 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 name | An 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. |
- Message queue testing: do and don’t
- Load Testing Apache Kafka, the longer write-up of how Kafka fails under load
- Connect a private datacenter