
A practical guide to chaos testing RabbitMQ with ToxiProxy, Docker, and Python — no Kubernetes required.
Picture this. It's Friday, 11:47 PM. A network engineer fat-fingers a switch update. The link between two data centers blips for exactly 30 seconds.
RabbitMQ loses connection to its consumers. 10,000 payment documents vanish into the void. Shipments aren't confirmed. The business grinds to a halt until Monday morning.
Why does this happen? Because we test our integrations in a perfect world. We test on localhost where latency is zero and packets never drop. We test the happy path. But production isn't a perfect world. Production is chaos.
By the end of this article, you'll have a working chaos test bench — every file you need is right here in this article — and be able to run your first experiment tonight. No Kubernetes required.
If you don't introduce chaos yourself, production will do it for you. At 3 AM. On a Friday.
Table of Contents
- The Problem with "Green" Tests
- Enter Chaos Engineering
- The Environment
- The Toolchain
- The Architecture
- The Code
- The 5 Experiments
- The Real Bugs We Found (and Fixed)
- How to Start Breaking Your Own Systems
- The Complete Bench
- Final Thoughts
The Problem with "Green" Tests
In a test environment, your network is stable. The broker doesn't restart. Messages arrive instantly. Everything is green.
In production, the network between data centers has 5–50 ms of latency and jitter. Packets get lost. The broker gets restarted during routine updates. A backup job eats 100% of your bandwidth.
We were running a legacy system — specifically, a 1C:Enterprise ERP backend — integrated with RabbitMQ. For those who haven't met it: 1C:Enterprise is an ERP platform widely used in manufacturing and retail across Eastern Europe and Central Asia. Think of it as a monolith that talks to the outside world through a custom integration layer — in our case, RabbitMQ.
We had tests, but they only proved the system worked under ideal conditions. To find out what actually happens when the network dies, we had to break it on purpose.
Legacy systems are especially vulnerable here: their integration layers were often written years ago, before idempotency keys and publisher confirms became standard practice. In our experience, legacy integrations fail not because they're badly written, but because they were written for a world without packet loss and broker restarts.
Enter Chaos Engineering
Chaos Engineering is the practice of running experiments on a system to verify its resilience to real-world failures. It's not about breaking things randomly; it's about forming a hypothesis and testing it.
The loop is simple:
Hypothesis: "If we add 2 seconds of network latency, messages will not be lost."
Experiment: Inject the latency.
Measure: Check throughput, packet loss, and queue depth.
Compare: Did it match the hypothesis? If not, you found a bug. Fix it and repeat.
To do this, we didn't need a massive Kubernetes cluster. We built a lightweight, reproducible stand using Docker.

Docker containers as building blocks
The Environment
One important note before the details — the numbers below mean nothing without context:
- RabbitMQ: 3.12.x, classic queues (single node in the test bench)
- ToxiProxy: 2.x; faults injected via latency toxics (with jitter) and connection cuts
- Python: 3.11, pika 1.3
- Docker Compose: 4 services under test, one machine
- Load: 200 messages/sec, ~2 KB per document
- Duration per experiment: 10 minutes, 3 runs each
All percentages you'll see are measured against ~120,000 messages per run. Measurements were collected via Prometheus counters — and you can reproduce every number with the complete bench at the end of this article.
One caveat: this bench runs on a single machine, so network conditions are emulated, not real. Real-world latency profiles will differ — but the bugs we found (idempotency, confirms, heartbeat) are logic bugs, and those show up regardless of how faithful the emulation is.
And yes — if you're on modern RabbitMQ, quorum queues would soften the message-loss results we found with classic queues. That's a separate migration story; the bugs we exposed are real in both setups.
The Toolchain
We kept the stack simple and accessible for any developer:
ToxiProxy: a TCP proxy that lets you inject latency, drop packets, and sever connections. It sits directly between our producer/consumer and RabbitMQ.
Docker API: used by our Python chaos controller to restart the RabbitMQ container on demand.
Prometheus + Grafana: to actually see what was happening in real time.
Python: for the producer, the consumer, and the chaos controller itself.
The Architecture
We built a sandbox that mimics the production flow: a producer publishes through ToxiProxy to RabbitMQ, a consumer reads from the broker, and the Chaos Controller sits on top — it talks to ToxiProxy's API to inject network faults and to the Docker daemon to kill the broker on demand.
Architecture: producer publishes through ToxiProxy to RabbitMQ, consumer reads, chaos controller injects faults
The Code
Here is the core of the chaos controller. It really is this simple:
python import requests import time TOXIPROXY_URL = "http://toxiproxy:8474" PROXY_NAME = "rabbitmq_main" def apply_toxic(name, toxic_type, attributes): url = f"{TOXIPROXY_URL}/proxies/{PROXY_NAME}/toxics" payload = { "name": name, "type": toxic_type, "stream": "downstream", "toxicity": 1.0, "attributes": attributes, } requests.post(url, json=payload).raise_for_status() def remove_toxic(name): url = f"{TOXIPROXY_URL}/proxies/{PROXY_NAME}/toxics/{name}" requests.delete(url) def experiment_delay(duration, delay_ms=2000): apply_toxic("latency_delay", "latency", {"latency": delay_ms, "jitter": 100}) time.sleep(duration) remove_toxic("latency_delay") The producer side — publishing with a persistent message and a mandatory flag:
python import pika, json, uuid def publish(channel, payload: dict): msg_id = str(uuid.uuid4()) body = json.dumps({"id": msg_id, **payload}) channel.basic_publish( exchange="payments", routing_key="payment.doc", body=body, properties=pika.BasicProperties( delivery_mode=2, # persistent message_id=msg_id, # idempotency key ), mandatory=True, # fail fast if unroutable ) The connection setup with the heartbeat fix (the one that killed the 5-minute reconnect) — note the traffic goes through ToxiProxy, exactly as in the architecture:
python params = pika.ConnectionParameters( host="rabbitmq-toxiproxy", # all traffic goes through ToxiProxy, not the broker directly port=5672, # the proxied port heartbeat=10, # dead connection detected in ~10 s, not 5 min blocked_connection_timeout=30, # don't hang forever when the broker blocks us ) connection = pika.BlockingConnection(params) channel = connection.channel() channel.confirm_delivery() # publisher confirms: broker And the consumer — idempotency check before doing the expensive work. Note the except branch: it releases the idempotency key on failure, so a processing crash can never silently lose a message on redelivery:
python def handle(ch, method, properties, body): msg_id = properties.message_id if not redis.set(f"processed:{msg_id}", 1, nx=True, ex=86400): ch.basic_ack(delivery_tag=method.delivery_tag) return # duplicate — already processed try: process_document(body) # business logic ch.basic_ack(delivery_tag=method.delivery_tag) except Exception: # release the idempotency key so a redelivered copy can be processed redis.delete(f"processed:{msg_id}") ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True) (The retry and backoff logic around these snippets is standard exponential backoff — nothing hidden.)
The 5 Experiments
We ran five escalating experiments against the system, measuring lost messages, duplicates, and recovery time.
What we tracked: throughput (messages/sec), queue depth, consumer lag, lost messages, duplicates, and time-to-recovery — all on a pre-built Grafana dashboard.
Grafana dashboard with real-time metrics
Experiment Lost messages Duplicates Recovery Broken?
1 Latency 2000 ms 0% 0% Auto None
2 Packet loss 10% < 0.1% ~3% Auto Idempotency
3 Connection break 30 s 0% 0% ~5 min Heartbeat
4 Broker restart 2.1% 0% ~2 min Publisher confirms
5 Total chaos 5.3% 12% 45 s Everything
1. Network latency (2000 ms). Added 2 seconds of latency with 100 ms jitter to all packets. Throughput dropped significantly, queue depth grew — but zero messages were lost. Once the latency was removed, the system recovered automatically.
2. Packet loss (10%). Dropped 10% of all packets. AMQP handled retransmissions; message loss stayed under 0.1%. But we saw a spike in duplicates (~3%): the broker didn't get the acknowledgment and redelivered the message. Our consumer processed it twice.
3. Connection break (30 seconds). Severed the TCP connection entirely. The producer started throwing connection errors, the consumer lost its stream, messages accumulated in the queue. Both reconnected — but the producer hung for a full 5 minutes waiting for a TCP timeout (more on that below). The backlog was processed, zero messages lost.
4. Broker restart. Executed docker restart rabbitmq mid-traffic. 2.1% of messages were lost. The producer thought the messages were sent — but they died in memory. We hadn't configured publisher confirms.
5. Total chaos. 500 ms latency + 20% packet loss + a broker restart, all at once. 45 seconds to recover, 5.3% lost messages, 12% duplicates. A brutal but necessary wake-up call.
Note: experiments ran sequentially — the 5-minute reconnect bug from experiment #3 was already fixed (heartbeat = 10) by the time we ran Total Chaos. Otherwise the recovery numbers would have been much worse.

Server room cables — the environment our experiments imitate
The Real Bugs We Found (and Fixed)
This wasn't just an academic exercise. The chaos tests exposed four bugs that happy-path tests would never have caught:
1. Double processing. The packet-loss test revealed our consumer wasn't idempotent — a redelivered message was processed twice.
Fix: an idempotency key in the message payload, checked against Redis before processing (see the consumer code above). One caveat worth a paragraph: if Redis itself goes down, the check fails closed — we chose to treat "unknown" as "not processed" and rely on the downstream document being re-processed rather than under-processed. Know which failure mode your business tolerates before copying this.
2. Unbounded queue growth. When the consumer died, the queue grew to 10 million messages and crashed RabbitMQ with memory exhaustion.
Fix: TTL on the queue and a Dead Letter Queue for expired messages.
3. Five-minute reconnect. When the network broke, the producer hung for 5 minutes waiting for a TCP timeout.
Fix: we set the AMQP heartbeat to 10 seconds on the client connection (pika: heartbeat=10 in ConnectionParameters). Now the client knows the connection is dead within 10 seconds. If you're tuning this, also look at consumer_timeout on the broker side — a slow consumer trips it before heartbeats even matter.
4. Silent message loss on restart. Unconfirmed messages vanished when the broker restarted.
Fix: enabled publisher confirms and set the mandatory flag on the channel.
How to Start Breaking Your Own Systems
You don't need a dedicated SRE team to start. Here is the playbook we used:
1. Identify the critical path. What is the one integration you absolutely cannot afford to lose? For us — payment documents.
2. Build a realistic sandbox. Don't test on localhost. Use Docker Compose to spin up the broker, a producer, and a consumer. Put ToxiProxy in the middle.
3. Start simple. Don't start with total chaos. Start with 500 ms of latency. Look at the metrics. Write down what happens.
4. Fix and repeat. When you find a bug, fix it. Then run the exact same experiment again. Prove that your system is now stronger.
The Complete Bench
Everything you need is in this article — no external repository required. Copy these three files, and you have the full stand from the architecture section.
docker-compose.yml — the four services under test, plus Redis for idempotency and the observability stack:
yaml version: "3.8" services: rabbitmq: image: rabbitmq:3.12-management environment: RABBITMQ_DEFAULT_USER: bench RABBITMQ_DEFAULT_PASS: bench toxiproxy: image: ghcr.io/shopify/toxiproxy:2.5.0 command: ["-host=0.0.0.0"] ports: - "8474:8474" # ToxiProxy API — the chaos controller talks to this port depends_on: - rabbitmq redis: image: redis:7-alpine producer: build: ./producer environment: RABBIT_HOST: toxiproxy # traffic goes through ToxiProxy, never directly to the broker RABBIT_PORT: 5672 depends_on: - toxiproxy consumer: build: ./consumer environment: RABBIT_HOST: toxiproxy REDIS_HOST: redis depends_on: - toxiproxy - redis prometheus: image: prom/prometheus volumes: - ./prometheus.yml:/etc/prometheus/prometheus.yml grafana: image: grafana/grafana ports: - "3000:3000" ToxiProxy bootstrap config — the proxy that everything connects through. Save it as config.json and ToxiProxy will pick it up on start:
json { "proxies": [ { "name": "rabbitmq_main", "listen": "0.0.0.0:5672", "upstream": "rabbitmq:5672", "enabled": true } ] } prometheus.yml — RabbitMQ ships a built-in Prometheus plugin; just enable it and point Prometheus at port 15692:
yaml scrape_configs: - job_name: rabbitmq static_configs: - targets: ["rabbitmq:15692"] For Grafana: open localhost:3000, import any RabbitMQ overview dashboard (community dashboard ID 10991 is a solid starting point) — you'll get throughput, queue depth, and consumer lag in real time, exactly the panels you need for the experiments above.
To run an experiment: docker compose up -d, wait for the broker to come up, then call one of the chaos controller functions from the code section (experiment_delay for experiment #1, and so on). Each run: clean slate via docker compose down && docker compose up -d, 10 minutes of traffic, three repetitions.
Final Thoughts
If you are relying on integration tests that only cover the happy path, you are gambling with your production environment. Chaos testing isn't about being pessimistic; it's about being prepared.
Don't wait for a network engineer to fat-finger a switch on a Friday night. Break your integrations yourself, in a controlled environment, while you still have time to fix them.
Spin up the bench and run experiment #1 tonight — it takes 15 minutes.



