Skip to content

Load Testing Redis Streams: Memory, Backlog, Latency

How Redis Streams fails under load and how to measure it: a copy-paste locustfile for send latency, consume rate and end-to-end latency.

A Redis stream drawn as a row of entries: acked ones, ten red entries stuck pending after a consumer died, and new entries arriving at the tail

Redis Streams is easy to adopt and easy to misjudge. The first benchmark on a laptop looks effortless, so the stream gets wired into production, and the trouble shows up weeks later as a memory alarm or a consumer that quietly stopped. A useful Redis load test does not chase a headline number. It reproduces the ways a stream actually degrades and tells you which one you are heading towards.

How Redis Streams fails under load

An untrimmed stream eats memory. Entries in a stream are not removed when a consumer reads them. They stay until you trim the stream, either with MAXLEN on XADD or with an explicit XTRIM. A producer that never trims will, at a steady write rate, fill memory at a steady rate, and Redis then either evicts other keys or refuses writes depending on your maxmemory-policy. A load test that runs for a minute will not show this. The signal to look for is the stream length and memory use growing linearly with the number of messages sent, which tells you how long you have at your real rate.

The pending list grows when consumers die without acking. A consumer group tracks every entry that was delivered but not yet acknowledged with XACK. If a consumer crashes, is killed during a deploy, or throws before it acks, those entries stay in the group’s pending entries list, owned by a consumer that no longer exists. Nothing redelivers them on its own. They sit there until another consumer claims them with XAUTOCLAIM or XCLAIM. Under load this matters twice: the list itself takes memory, and the messages inside it are delayed indefinitely, which shows up as a long tail in end-to-end latency or as work that never completes.

Commands are executed one at a time. Redis runs commands on a single thread. A slow command blocks everything behind it. A large XRANGE or an XREADGROUP with a huge COUNT returns a lot of data in one go, and while it is being built every other client waits. In a load test this looks like send latency that is fine on average but spikes in step with consumer reads. If your send p99 rises when you raise the consumer batch size, that is the cause.

Durability costs write latency. With AOF persistence and appendfsync always, each write waits for the disk. With everysec writes are fast but you can lose a second of data. The setting you choose changes the XADD latency you will see, so run the test against a Redis configured like production, not a default container.

One stream cannot spread across a cluster. A stream is a single key, and a key lives in a single hash slot, so one stream is served by one shard. Adding nodes to a Redis Cluster does not raise the ceiling of a single hot stream. If your design relies on one stream carrying all traffic, a load test is how you find the point where that one shard saturates, before production does.

What to measure

The test below produces two numbers, and the second is the one that matters.

  • redis send is how long the XADD call takes to return. It is the broker-side cost of accepting a message, and it is where persistence settings and big reads show up.
  • redis end-to-end is the time between a producer stamping a message and a consumer group member reading it. It includes queueing: if consumers fall behind, this number climbs over the run while redis send looks perfectly healthy. That divergence is the single most useful thing a message queue test can show you.

The number of redis end-to-end samples per second is your consumer throughput. There is no third label to maintain. In a healthy run the two sample counts are close and the end-to-end line is flat.

Two details keep the numbers honest. Samples are rounded to whole milliseconds, so a local or same-zone Redis reads as 0 to 1 ms; that is rounding, not a bug. And durable streams keep the backlog of the last run, so the script skips any message that was already more than 60 seconds old when the test started. Without that rule a rerun reports the minutes-old messages from the previous run as huge latencies.

The locustfile

Producers call XADD with an approximate MAXLEN, so the stream stays bounded. Consumers share one group, read in batches with XREADGROUP, and acknowledge each batch with a single XACK. The connection comes from a secret, and everything else is a constant you can edit at the top. The file creates the stream and group if they are missing and tolerates them already existing, so you can run it again straight away.

locustfile.py
"""Redis Streams load test for MaxoPerf: producers XADD, consumers measure end-to-end latency.
Connection values come from MaxoPerf secrets bound to this test (Dependencies tab)."""
import json, os, time, uuid
import redis
from locust import User, task, events, constant, constant_throughput
# --- connection (bind as a secret; the default works against a local Redis) ---
URL = os.environ.get("SECRET_REDIS_URL", "redis://localhost:6379/0")
# --- names + load knobs (edit freely; not secrets: secret values are masked in run output) ---
STREAM = "maxoperf-load"
GROUP = "maxoperf-load"
SENDS_PER_USER_PER_SEC = 10 # producer rate per virtual user
MESSAGE_BYTES = 512 # payload size
CONSUMERS = 2 # fixed consumer users (Locust fixed_count)
MAXLEN = 100_000 # approximate trim keeps stream memory bounded
BATCH = 100 # entries per XREADGROUP
STALE_AFTER_S = 60 # skip backlog older than this (left over from a previous run)
STARTED = time.time()
r = redis.Redis.from_url(URL) # one pool per process: each greenlet gets its own connection
def record(name, start, exc=None, size=0): # one result sample under label "redis <name>"
if exc is not None: # bzt's results CSV has no escape char: commas/quotes in errors would crash it
exc = Exception(str(exc).replace(",", ";").replace('"', "'"))
events.request.fire(request_type="REDIS", name=f"redis {name}",
response_time=(time.time() - start) * 1000,
response_length=size, exception=exc, context={})
@events.test_start.add_listener
def create_group(environment, **kw): # idempotent; "$" = only messages sent from now on
try:
r.xgroup_create(STREAM, GROUP, id="$", mkstream=True)
except redis.ResponseError as e:
if "BUSYGROUP" not in str(e):
raise
except redis.RedisError as e:
print(f"setup failed, sends will fail too: {e}")
class Producer(User): # label "redis send" = XADD call duration
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})
start = time.time()
try:
r.xadd(STREAM, {"m": body}, maxlen=MAXLEN, approximate=True)
record("send", start, size=len(body))
except (redis.RedisError, OSError) as e:
record("send", start, exc=e)
class Consumer(User): # label "redis end-to-end" = now - sent_at per entry
fixed_count = CONSUMERS
wait_time = constant(0)
def on_start(self):
self.name = f"c-{uuid.uuid4().hex[:8]}"
@task
def receive(self):
try: # blocking read on a gevent-patched socket yields to other users
res = r.xreadgroup(GROUP, self.name, {STREAM: ">"}, count=BATCH, block=1000)
except (redis.RedisError, OSError) as e:
record("end-to-end", time.time(), exc=e)
time.sleep(1) # don't hot-loop failures
return
for _, entries in res:
for _id, fields in entries:
msg = json.loads(fields[b"m"])
if msg["sent_at"] >= STARTED - STALE_AFTER_S:
record("end-to-end", msg["sent_at"], size=len(fields[b"m"]))
r.xack(STREAM, GROUP, *[i for i, _ in entries])
# teardown: bzt gives Locust 10 s to stop (--stop-timeout), so nothing slow belongs here

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:
- redis==8.1.0

The taurus.yml below installs the redis client when the test starts, so there is nothing to install by hand. The script runs on Locust’s cooperative scheduler; the blocking read in the consumer yields to the producers while it waits, which is why one runner can both send and receive.

Run it on MaxoPerf

  1. Create a test and upload locustfile.py. MaxoPerf detects Locust from the file; you do not need a YAML configuration.
  2. Create a secret holding your Redis URL (rediss://:<password>@host:6379/0 for TLS with a password) and bind it to the test as SECRET_REDIS_URL. The runners must be able to reach Redis, directly or through a private datacenter outpost.
  3. Set ten virtual users for a minute. Two are consumers, so eight are producers at ten messages per second each.
  4. Start the run and open the results.
  5. Raise the users in steps and rerun. The first step where redis end-to-end stops being flat is your consumers’ limit; the first where redis send climbs is Redis itself.

Only point this at a Redis you are authorised to load, and clean up the maxoperf-load stream afterwards.

What to look for

Compare the two labels over the whole run, not just the summary. A healthy stream gives you a send latency that is flat and small, an end-to-end latency that is flat, and almost equal sample counts on both labels. After that, the patterns map onto the failure modes above.

If end-to-end latency climbs while send stays flat, consumers cannot keep up. Raise CONSUMERS or BATCH, and check whether the work your real consumers do per message is the bottleneck, not Redis. If send latency spikes in step with consumer reads, large batches are blocking the single thread; lower BATCH. If you kill a consumer in the middle of a run and the end-to-end sample count falls behind sends permanently, you have found the pending list: entries stuck with a dead consumer, waiting to be claimed. If failed rows appear with no name, the script raised an exception outside the two labelled calls; the run logs have the traceback.

Finally, run it with your production persistence settings and your real message size. Both change the result more than almost any tuning knob.

Next steps

The Redis Streams how-to walks through the same run with screenshots, the tuning knobs and a troubleshooting table. The message queue do and don’t page lists the rules that apply to every broker, such as watching the trend rather than the average and keeping clocks in sync.