Skip to content

Load Testing NATS JetStream: Acks, Limits, Replicas

Load test NATS JetStream with one copy-paste Locust file: measure publish-ack latency, consume rate and end-to-end latency, and spot the stalls.

Three producers feeding a JetStream stream whose backlog grows behind a pull consumer stuck at max_ack_pending, with an end-to-end latency curve climbing

NATS is fast enough that a quick benchmark almost always looks good. Core NATS publishes in microseconds and a single server moves a very large number of small messages. That is the problem. A test that only publishes in a loop tells you how fast the client can write to a socket, not how your system behaves when a stream stores every message, a consumer has to acknowledge each one and the rest of your pipeline is slower than the broker.

JetStream is the persistence layer of NATS, and it changes the shape of the problem. Messages are stored in a stream, consumers track their own position, and every delivery is acknowledged. Each of those mechanisms has a limit, and each limit fails in its own way when you push on it. This article walks through those failure modes, then gives you one Locust file that exercises them and a way to run it on MaxoPerf.

Core NATS and JetStream are different tests

Core NATS is fire-and-forget. If no subscriber is listening when a message is published, the message is gone, and a slow subscriber is disconnected rather than waited for. Load testing core NATS mostly means measuring server throughput and fan-out, and the interesting failure is a dropped slow consumer.

JetStream adds storage and acknowledgement. A publish to a subject that a stream captures returns an acknowledgement only after the server has stored the message, and with replication, after the replicas agree. That acknowledgement is the number that matters for producers. Consumers then pull or receive messages and acknowledge them, and the broker redelivers anything that is not acknowledged in time. If your application uses JetStream, test JetStream. A core NATS benchmark does not predict it.

How JetStream fails under load

Slow consumers and max_ack_pending

A consumer can only have a limited number of delivered but unacknowledged messages. That limit is max_ack_pending. When a consumer reaches it, the server stops delivering to that consumer until some messages are acknowledged. If your consumers do real work per message, such as a database write, the pending count fills up, delivery pauses and the stream backlog grows even though the server is idle.

From the producer side everything still looks fine: publishes are acknowledged quickly because the stream accepts them. The damage shows up only in end-to-end latency, which climbs for the whole run. This is why a producer-only benchmark is misleading and why the test below measures the time from publish to receipt.

Stream limits silently discarding data

A stream has limits on message count, total bytes and message age. When a limit is reached, the default policy discards the oldest messages to make room. Nothing fails. The publisher keeps getting acknowledgements, and the consumer simply never sees the messages that were discarded before it caught up.

In a load test this appears as an end-to-end count that is lower than the send count even though neither label reports errors. If you rely on a stream to hold a backlog while consumers are down, size the limits for that backlog, and check the message and byte counts after a test, not only the error rate. You can also choose a policy that rejects new publishes when the stream is full, in which case the failure moves to the producer and shows up as failed sends.

Replication adds latency to every publish

A stream with three replicas acknowledges a publish only after a majority has persisted it. That is the durability you pay for, and you pay for it on every message. Publish-acknowledgement latency on a replicated stream is higher than on a single-replica stream, it varies more, and it grows when the replicas sit in different zones or when one of them is slow.

Test with the replica count you run in production. A single-replica stream on a development server is a useful baseline, but it hides the cost that your producers will see. Memory storage and file storage differ too: file storage depends on the disk and on how often the server syncs, which is another reason to test on hardware that resembles production.

Redelivery and the pull loop

When a message is not acknowledged within the acknowledgement wait time, the server delivers it again. Slow processing therefore does two kinds of damage: it holds messages against max_ack_pending, and it creates duplicates that your consumers must tolerate. A load test that only counts sends cannot see either effect.

Pull consumers add a client-side detail. A fetch asks for a batch and waits for the batch to fill or for a timeout. Messages that arrive early wait for the rest of the batch, so a large batch adds latency at low message rates. Keep batches small when you want honest latency numbers.

What to measure

Two numbers describe a JetStream test well:

  • Publish-acknowledgement latency. The time from calling publish to receiving the stream’s acknowledgement. It reflects storage, replication and server load.
  • End-to-end latency and consume rate. The time from a message being created to a consumer receiving it, and how many messages per second consumers handle. It reflects everything in the pipeline, including consumer speed and max_ack_pending.

Read them together. Healthy looks like flat end-to-end latency and an end-to-end count close to the send count. A latency curve that climbs for the whole run means consumers are falling behind. A count that is well below the send count means messages were lost to limits or consumers never caught up.

The test file

The file below is a complete Locust script. Producers publish to a subject captured by a stream and record the acknowledgement time as nats send. Consumers share one durable pull consumer and record the time since each message was created as nats end-to-end. It creates the stream if it is missing, tolerates reruns and skips messages left over from earlier runs.

locustfile.py
"""NATS JetStream 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 asyncio, json, os, time, uuid
import gevent
import nats
from gevent.lock import Semaphore
from locust import User, task, events, constant_throughput
from locust.exception import StopUser
from nats.errors import TimeoutError as FetchTimeout
# --- connection (bind as a secret; the default works against a local broker) ---
URL = os.environ.get("SECRET_NATS_URL", "nats://localhost:4222")
# --- names + load knobs (edit freely; not secrets: secret values are masked in run output) ---
STREAM = "MAXOPERF_LOAD"
SUBJECT = STREAM.lower() + ".orders"
SENDS_PER_USER_PER_SEC = 10 # producer rate per virtual user
MESSAGE_BYTES = 512 # payload size
CONSUMERS = 2 # fixed consumer users
BATCH = 10 # messages per fetch; a fetch waits for a full batch or 1 s, so keep it small
STALE_AFTER_S = 60 # skip leftovers from earlier runs: no sample, just acked
STARTED = time.time()
# nats-py is asyncio-only: one event loop in a greenlet; gevent's patched selectors keep it cooperative.
LOOP = asyncio.new_event_loop()
gevent.spawn(LOOP.run_forever)
def run(coro, timeout=10):
return asyncio.run_coroutine_threadsafe(coro, LOOP).result(timeout)
NC, JS, LOCK = None, None, Semaphore()
def jetstream(): # connect once per process; create the stream if missing
global NC, JS
with LOCK:
if JS is None:
async def setup():
nc = await nats.connect(URL, max_reconnect_attempts=1) # fail fast if unreachable
js = nc.jetstream()
try:
await js.add_stream(name=STREAM, subjects=[SUBJECT], max_age=600)
except Exception as e:
if "already in use" not in str(e):
raise
return nc, js
NC, JS = run(setup())
return JS
def record(name, start, exc=None, end=None, size=0): # one sample under "nats <name>"
if exc is not None: # the results CSV cannot hold commas or quotes in error text
exc = Exception(str(exc).replace(",", ";").replace('"', "'"))
events.request.fire(request_type="NATS", name=f"nats {name}",
response_time=((end or time.time()) - start) * 1000,
response_length=size, exception=exc, context={})
class Producer(User): # "nats send" = time until JetStream acknowledges the publish
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}).encode()
start = time.time()
try:
run(jetstream().publish(SUBJECT, body))
record("send", start, size=len(body))
except StopUser: # bzt ends the run with it: let it through
raise
except Exception as e:
record("send", start, e)
gevent.sleep(1)
async def fetch(sub):
try:
msgs = await sub.fetch(BATCH, timeout=1)
except FetchTimeout:
return time.time(), []
received_at = time.time() # taken before the acks so they do not inflate latency
for m in msgs:
await m.ack()
return received_at, [m.data for m in msgs]
class Consumer(User): # "nats end-to-end" = receive time - sent_at, per message
fixed_count = CONSUMERS
sub = None
@task
def receive(self):
try:
if self.sub is None: # same durable name: consumers share the work
self.sub = run(jetstream().pull_subscribe(SUBJECT, durable="maxoperf-load"))
received_at, bodies = run(fetch(self.sub), 15)
except StopUser:
raise
except Exception as e:
record("end-to-end", time.time(), e)
gevent.sleep(1)
return
for b in bodies:
sent_at = json.loads(b)["sent_at"]
if sent_at >= STARTED - STALE_AFTER_S:
record("end-to-end", sent_at, end=received_at, size=len(b))
# bzt stops Locust with --stop-timeout=10: close the connection well inside it.
@events.quitting.add_listener
def close(**_):
if NC is not None:
try:
run(NC.close(), 5)
except Exception:
pass

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:
- nats-py==2.17.0

Two details matter for correctness. The nats-py client is asyncio-only, while Locust runs on gevent, so the script runs one event loop inside a greenlet and calls into it from each user. Running asyncio.run inside a task would block every virtual user on the runner. And the consumer takes its receive timestamp before it acknowledges the batch, so acknowledgements do not inflate the latency you read.

Run it on MaxoPerf

  1. Create a test on MaxoPerf and upload locustfile.py as it is. MaxoPerf detects Locust from the file.
  2. Create a secret named SECRET_NATS_URL with your server URL, for example nats://nats.internal:4222, and bind it on the Dependencies tab. For a broker inside your network, run the test on a private datacenter outpost.
  3. Set the virtual users and the duration. With the default two consumers, 10 users means 8 producers and 2 consumers.
  4. Start the run.
  5. Open the results and compare the nats send and nats end-to-end labels.

The taurus.yml below installs nats-py when the test starts, so there is nothing to build. Test only a server you are authorised to load. The script creates its own stream and deletes nothing, so remove the stream afterwards.

What to look for

Start with the shape of end-to-end latency over the run. Flat means consumers keep up. A steady climb is the max_ack_pending stall or consumers that are simply too slow. Add consumers or raise the limit and run again.

Then compare counts. If end-to-end samples fall well short of sends, check the stream’s message and byte counts for discards, and confirm that the consumer’s durable name is bound to the subject you publish to.

Then raise the publish rate and watch nats send. The point where publish-acknowledgement latency bends upward is the capacity of your stream configuration, with the replica count and storage you chose. Repeat with production replicas and storage before you trust the number.

MaxoPerf records latency in whole milliseconds, so a broker that acknowledges in under a millisecond shows 0 or 1 ms. That is expected on a fast network, and the trend under higher load is still readable.

Next steps

Follow the step-by-step how-to for secrets, tuning knobs and troubleshooting, and read Message queue testing: do and don’t before you point a test at a shared broker.