Load test RabbitMQ on MaxoPerf
This test publishes persistent messages to one RabbitMQ queue while consumers read and acknowledge them. It measures three things: how long a publisher waits for the broker to confirm a message, how many messages per second the consumers keep up with, and how long each message takes from publish to receipt. If end-to-end latency climbs during the run, the consumers are falling behind the producers.
Before you start
Section titled “Before you start”- The broker must be reachable from the runners. For managed runners that means a public AMQP endpoint with credentials. For a broker inside your network, run the test on a private datacenter outpost.
taurus.ymlinstalls thepikaclient (1.5.0) 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-test a broker, vhost and queue you are authorised to test. Read Message queue testing: do and don’t first.
The locustfile
Section titled “The locustfile”Save this as locustfile.py. It declares a durable queue called maxoperf-load if it does not exist, so a rerun is safe.
"""RabbitMQ load test for MaxoPerf: producers publish, consumers measure end-to-end latency.Connection values come from MaxoPerf secrets bound to this test (Dependencies tab)."""import json, os, time, uuidimport pikafrom gevent import sleepfrom locust import User, task, events, constant, constant_throughput
# --- connection (bind as a secret; the default works against a local broker) ---URL = os.environ.get("SECRET_RABBITMQ_URL", "amqp://guest:guest@localhost:5672/%2F")# --- names + load knobs (edit freely; not secrets: secret values are masked in run output) ---QUEUE = "maxoperf-load"SENDS_PER_USER_PER_SEC = 10 # producer rate per virtual userMESSAGE_BYTES = 512 # payload sizeCONSUMERS = 2 # fixed consumer users (Locust fixed_count)PREFETCH = 100 # unacked messages a consumer may holdSTALE_AFTER_S = 60 # skip leftovers from earlier runs (durable queue keeps them)STARTED = time.time()
def record(name, start, exc=None, size=0): # one result sample under "rabbitmq <name>" if exc is not None: # bzt's results CSV cannot escape commas or quotes in error text exc = Exception(str(exc).replace(",", ";").replace('"', "'")) events.request.fire(request_type="RABBITMQ", name=f"rabbitmq {name}", response_time=(time.time() - start) * 1000, response_length=size, exception=exc, context={})
class Rabbit(User): abstract = True conn = None
def channel(self): # lazy connect: an unreachable broker becomes failed samples, not a crash if self.conn is None: params = pika.URLParameters(URL) params.heartbeat = 600 # pika only services heartbeats inside its own calls self.conn = pika.BlockingConnection(params) ch = self.conn.channel() ch.queue_declare(QUEUE, durable=True) # idempotent while arguments match self.setup(ch) self.ch = ch return self.ch
def drop(self): try: self.conn.close() except Exception: pass self.conn = None
def on_stop(self): # bzt gives teardown --stop-timeout=10 s if self.conn is not None: self.drop()
class Producer(Rabbit): # "rabbitmq send" = publish call until the broker confirms wait_time = constant_throughput(SENDS_PER_USER_PER_SEC)
def setup(self, ch): ch.confirm_delivery()
@task def send(self): start = time.time() try: ch = self.channel() start = time.time() # exclude connect time body = json.dumps({"id": str(uuid.uuid4()), "sent_at": time.time(), "pad": "x" * MESSAGE_BYTES}).encode() ch.basic_publish("", QUEUE, body, pika.BasicProperties(delivery_mode=2)) record("send", start, size=len(body)) except (pika.exceptions.AMQPError, OSError) as e: # incl. UnroutableError / NackError self.drop() record("send", start, e)
class Consumer(Rabbit): # "rabbitmq end-to-end" = now - sent_at for every message read fixed_count = CONSUMERS wait_time = constant(0) messages = None
def setup(self, ch): ch.basic_qos(prefetch_count=PREFETCH) self.messages = ch.consume(QUEUE, inactivity_timeout=0.5)
@task def receive(self): start = time.time() try: self.channel() method, _, body = next(self.messages) if method is None: # idle: nothing arrived within 0.5 s return sent_at = json.loads(body)["sent_at"] self.ch.basic_ack(method.delivery_tag) if sent_at >= STARTED - STALE_AFTER_S: record("end-to-end", sent_at, size=len(body)) except (pika.exceptions.AMQPError, OSError) as e: # StopUser (run over) must pass through self.drop() record("end-to-end", start, e) sleep(1) # do not spin while the broker is downUpload 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: - pika==1.5.0Connect it to your broker
Section titled “Connect it to your broker”Only the connection value is a secret. The queue name and the load knobs stay constants at the top of the file, because MaxoPerf masks bound secret values in run output and a secret queue name would garble every error message.
| Secret env var | Meaning | Example value |
|---|---|---|
SECRET_RABBITMQ_URL | AMQP URL with credentials and vhost. Use amqps:// for TLS. | amqps://loadtest:<password>@mq.example.com:5671/%2F |
The default vhost / is written %2F in the URL. Create the secret and bind it to the test as described in Secrets and environments.
Run it on MaxoPerf
Section titled “Run it on MaxoPerf”-
Create a new test and 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. -
Open the Dependencies tab and bind
SECRET_RABBITMQ_URL. -
Set the number of users and the duration. Two of the users are always consumers (
CONSUMERS); the rest are producers. With 10 users and the default rate, that is 8 producers at 10 messages per second each. -
Start the run.
Read the results
Section titled “Read the results”The run reports two labels.
rabbitmq sendis the time from the publish call until the broker confirms the message. It is the latency a real producer waits.rabbitmq end-to-endis the time from the moment a message was built to the moment a consumer received it. Its sample count per second is your consume rate.
A healthy run has end-to-end samples close to the send samples (consumers keep up), no failures, and an end-to-end latency that stays flat. An unhealthy run shows end-to-end latency climbing for the whole run, or far fewer end-to-end samples than send samples. That means messages are piling up in the queue.
Two details to know:
- MaxoPerf records every sample in whole milliseconds. A broker on the same network often confirms in under a millisecond, so
rabbitmq sendcan read 0 or 1 ms. - Messages published more than 60 seconds before the test started are acknowledged and skipped without a sample. A durable queue keeps the backlog of an earlier run, and counting it would report minutes-old latencies.
See Read run results for the rest of the results page.
Tune it for your system
Section titled “Tune it for your system”| Knob | What it changes |
|---|---|
SENDS_PER_USER_PER_SEC, MESSAGE_BYTES | Offered load and payload size. Raise the rate until send latency or the end-to-end curve bends. |
CONSUMERS | Consumer count. Add consumers if end-to-end latency climbs while the broker is healthy. |
PREFETCH | How many unacknowledged messages one consumer may hold. A low value caps consumer throughput; a very high one lets one consumer hoard messages. |
| Publisher confirms | The file calls confirm_delivery() so rabbitmq send measures the broker’s confirmation. Removing it makes publishing faster but the send label then only measures a socket write. |
delivery_mode=2 | Persistent messages, which are written to disk. Use 1 (transient) only if your production publishers do. |
| Queue type | The file declares a classic durable queue. To test a quorum queue, add arguments={"x-queue-type": "quorum"} to queue_declare and use a new queue name. Quorum queues replicate every publish, so expect higher send latency. |
| Connections | Each virtual user opens its own connection and channel, because a pika connection cannot be shared between users. Many users means many connections; that is realistic for many clients, but watch the broker’s connection limit. |
When you run on several runners, each runner has its own clock. End-to-end latency compares the publisher’s clock with the consumer’s, so a clock that is a few hundred milliseconds off shifts every end-to-end sample. Keep runner clocks in sync (NTP) or read the trend, not the absolute value.
Troubleshooting
Section titled “Troubleshooting”| Symptom | Cause and fix |
|---|---|
rabbitmq send fails with AMQPConnectionError | The runner cannot reach the broker. Check the host, port (5672, or 5671 for TLS), amqp:// versus amqps://, and the vhost in the URL. For a private broker use an outpost. |
ACCESS_REFUSED | Wrong credentials, or the user has no permissions on that vhost. Grant configure, write and read on the vhost. |
PRECONDITION_FAILED when declaring the queue | The queue maxoperf-load already exists with different arguments (for example a different queue type). Change QUEUE to a new name or match the existing arguments. |
No rabbitmq end-to-end samples | The consumers never received a message. Check that the test has more than CONSUMERS users, and that the queue is not being drained by another consumer. |
| A failed row with no name | An unhandled exception inside the script. Open the run logs for the traceback. |
ModuleNotFoundError: No module named 'pika' | 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 RabbitMQ: where the queue breaks explains how RabbitMQ fails under load.
- Connect a private datacenter