Skip to content

Load test NATS JetStream on MaxoPerf

This test measures three things on a NATS JetStream stream: how long a publish takes until JetStream acknowledges it, how many messages per second the consumers keep up with, and how long each message takes to get from producer to consumer. It uses one Locust file with a producer user and a consumer user, so the same run shows both sides of the stream. Copy the file, bind your server URL as a secret and start the run.

  • The server must be reachable from the runners. For a public endpoint, use a URL with authentication or TLS (tls://). For a broker inside your network, run the test on a private datacenter outpost.
  • taurus.yml installs the nats-py client (2.17.0) when the test starts, with Taurus’s built-in pip-install service. 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.
  • JetStream must be enabled on the server. The script creates its own stream, MAXOPERF_LOAD, so use a server you are authorised to load.
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. Taurus runs the Locust file and installs the client when the test starts:

taurus.yml
execution:
- executor: locust
scenario: mq
scenarios:
mq:
script: locustfile.py
services:
- module: pip-install
packages:
- nats-py==2.17.0

Producers publish and wait for the JetStream acknowledgement (nats send). Consumers share one durable pull consumer, fetch up to BATCH messages, acknowledge them and record the time since each message was sent (nats end-to-end). The script skips and acknowledges messages that were sent more than 60 seconds before the test started, so a backlog left by an earlier run does not skew the numbers.

Only the connection value is a secret. Bound secret values are masked in run output, which is why the stream name and the load knobs stay plain constants at the top of the file: a masked stream name would garble every error message.

Secret (bound as env var)MeaningExample value
SECRET_NATS_URLServer URL. Use tls:// for TLS, or nats://user:pass@host:4222 for credentials.nats://nats.internal:4222

Create the secret in your workspace and bind it to the test as described in Secrets and environments.

Bind the connection values as secrets; the script reads them as environment variables.
  1. Create a new test.

  2. Upload taurus.yml and locustfile.py together. taurus.yml is 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.
  3. On the Dependencies tab, bind SECRET_NATS_URL.

  4. Set the virtual users and the duration. Producers are the users minus CONSUMERS: 10 users with the default CONSUMERS = 2 gives 8 producers and 2 consumers.

  5. Start the run.

The run has two labels. nats send is the publish-to-acknowledgement time. nats end-to-end is the time from the producer’s timestamp to the moment a consumer received the message. Its sample count per second is the consume rate.

A healthy run shows both labels with samples and no failures. The end-to-end sample count is close to the send count and its latency stays flat. An unhealthy run shows end-to-end latency climbing for the whole run or an end-to-end count well below the send count. The consumers are falling behind. Read how to read run results for the general layout.

NATS JetStream run: send latency and end-to-end latency side by side (whole milliseconds; local acks round to 0–1 ms).
  • Stream storage and replicas. The script uses the server default (file storage, one replica). Add storage=nats.js.api.StorageType.MEMORY or num_replicas=3 to add_stream to match production. Replication raises the publish-ack latency, and that is the number to watch.
  • max_ack_pending. A pull consumer stops receiving once it has that many unacknowledged messages. The script acknowledges every message straight after the fetch. If you add slow processing, raise the limit on the consumer or add consumers.
  • BATCH. Messages in one fetch arrive together, so early messages in a batch wait for the rest. Keep it small (the default is 10) for honest end-to-end numbers: a fetch waits for a full batch or one second.
  • Publish rate. SENDS_PER_USER_PER_SEC times the producer count is the offered rate. Raise it until nats send latency bends upward.
  • Subjects. The script uses one subject. If your system fans out across many subjects, change SUBJECT and the stream’s subjects to a wildcard such as maxoperf_load.>.
  • Several runners. Producers and consumers on different runners compare timestamps from different clocks. Clock skew adds straight into end-to-end latency, so keep clocks synchronised with NTP.
  • Stream limits. The stream keeps messages for 10 minutes (max_age=600) so test data does not pile up. Delete the stream when you are done: nats stream rm MAXOPERF_LOAD.
SymptomCause and fix
nats: no servers availableThe runners cannot reach the URL. Check the address, the firewall and the TLS scheme, or use an outpost inside your network.
nats: authorization violationThe credentials in SECRET_NATS_URL are wrong or lack permission to publish and subscribe on maxoperf_load.orders and the JetStream API.
stream name already in use with a different configurationA stream named MAXOPERF_LOAD exists with other settings. Change STREAM or delete the old stream.
nats end-to-end is emptyConsumers received nothing. A durable named maxoperf-load may be bound to another subject. Delete it or change the durable name.
A failed row with no nameAn unhandled exception inside the script. Open the run logs for the traceback.
ModuleNotFoundError: No module named 'nats'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.