Skip to content

Load test Amazon SQS on MaxoPerf

This guide load tests an Amazon SQS standard queue with producers and consumers in one Locust file. You get three numbers from one run: how long SendMessage takes (sqs send), how many messages per second consumers drain, and how long a message waits between being sent and being received (sqs end-to-end). Copy the file, bind a few secrets and run it.

  • Reachability. The runners must reach your queue. Real SQS has a public endpoint, so managed runners work. For a queue inside a private network, run the test from a private datacenter outpost.
  • Client library. taurus.yml installs the boto3 client (1.44.7) 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.
  • Credentials. An IAM user or role with sqs:GetQueueUrl, sqs:SendMessage, sqs:ReceiveMessage and sqs:DeleteMessage, plus sqs:CreateQueue if the file should create the queue.
  • Authorisation and cost. Test only a queue you are allowed to load. Real SQS bills every send, receive and delete request, so a load test costs real money. Start small and raise the rate on purpose.
locustfile.py
"""Amazon SQS load test for MaxoPerf: producers send, consumers measure end-to-end latency.
Connection values come from MaxoPerf secrets bound to this test (Dependencies tab)."""
import json, os, re, time, uuid
import boto3
from botocore.config import Config
from botocore.exceptions import BotoCoreError, ClientError
from locust import User, task, events, constant, constant_throughput
# --- connection (bind these as secrets) ---
# Keys are required on purpose: a runner's own environment may hold other AWS credentials, so we never use
# boto3's default chain. On your own outpost with an instance role, drop the two key arguments in client().
KEY = os.environ.get("SECRET_AWS_ACCESS_KEY_ID")
SECRET = os.environ.get("SECRET_AWS_SECRET_ACCESS_KEY")
ENDPOINT = os.environ.get("SECRET_SQS_ENDPOINT_URL") or None # only for ElasticMQ / LocalStack
if not KEY or not SECRET:
raise RuntimeError("bind SECRET_AWS_ACCESS_KEY_ID and SECRET_AWS_SECRET_ACCESS_KEY")
# --- names + load knobs (edit freely; not secrets: secret values are masked in run output) ---
QUEUE = "maxoperf-load" # created if missing; pre-create it if your role cannot create queues
REGION = "us-east-1"
SENDS_PER_USER_PER_SEC = 10 # every send, receive and delete is a billed request on real SQS
MESSAGE_BYTES = 512 # payload size
CONSUMERS = 2 # fixed consumer users (Locust fixed_count)
STALE_AFTER_S = 60 # skip messages sent before this run started: a queue keeps old backlog
STARTED = time.time()
ERRORS = (ClientError, BotoCoreError)
def record(name, ms, exc=None, size=0): # one result sample under the label "sqs <name>"
if exc: # Taurus's CSV writer cannot escape quotes or commas, so flatten them out of the message
exc = Exception(re.sub(r'[",\s]+', " ", str(exc)))
events.request.fire(request_type="SQS", name=f"sqs {name}", response_time=ms,
response_length=size, exception=exc, context={})
def client(): # one client per user: botocore sessions are not safe to share between greenlets
return boto3.client("sqs", region_name=REGION, endpoint_url=ENDPOINT, aws_access_key_id=KEY,
aws_secret_access_key=SECRET,
config=Config(retries={"max_attempts": 1}, connect_timeout=5, read_timeout=10))
def queue_url(sqs): # idempotent setup
try:
return sqs.get_queue_url(QueueName=QUEUE)["QueueUrl"]
except sqs.exceptions.QueueDoesNotExist:
return sqs.create_queue(QueueName=QUEUE)["QueueUrl"]
class Producer(User): # label "sqs send" = SendMessage API call duration
wait_time = constant_throughput(SENDS_PER_USER_PER_SEC)
def on_start(self):
self.sqs, self.url = client(), None
@task
def send(self):
body = json.dumps({"id": str(uuid.uuid4()), "sent_at": time.time(), "pad": "x" * MESSAGE_BYTES})
start = time.time()
try:
self.url = self.url or queue_url(self.sqs)
start = time.time()
self.sqs.send_message(QueueUrl=self.url, MessageBody=body)
record("send", (time.time() - start) * 1000, size=len(body))
except ERRORS as e:
record("send", (time.time() - start) * 1000, e)
class Consumer(User): # label "sqs end-to-end" = receive time - sent_at, one sample per message
fixed_count = CONSUMERS
wait_time = constant(0)
def on_start(self):
self.sqs, self.url = client(), None
@task
def receive(self):
try:
self.url = self.url or queue_url(self.sqs)
got = self.sqs.receive_message(QueueUrl=self.url, MaxNumberOfMessages=10, WaitTimeSeconds=1)
now, entries, ms = time.time(), [], {}
for m in got.get("Messages", []):
entries.append({"Id": m["MessageId"], "ReceiptHandle": m["ReceiptHandle"]})
sent_at = json.loads(m["Body"])["sent_at"]
if sent_at >= STARTED - STALE_AFTER_S:
ms[m["MessageId"]] = ((now - sent_at) * 1000, len(m["Body"]))
if not entries:
return
done = self.sqs.delete_message_batch(QueueUrl=self.url, Entries=entries)
failed = {f["Id"] for f in done.get("Failed", [])}
for mid, (latency, size) in ms.items():
record("end-to-end", latency, Exception("delete failed") if mid in failed else None, size)
except ERRORS as e:
record("end-to-end", 0, e)
time.sleep(1) # Locust patches sleep for gevent; avoids a hot loop while the broker is down

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:
- boto3==1.44.7

The file needs access keys and stops at import time without them. It never falls back to boto3’s default credential chain, because a managed runner’s own environment may hold other AWS credentials. On your own outpost with an instance role, delete the two key arguments in client() and the key check, and boto3 will use the role.

Consumers skip messages sent more than 60 seconds before the test started and delete them without recording a sample. A standard queue keeps the previous run’s backlog, and without this rule a rerun would report minutes-old end-to-end latencies. Standard queues deliver at least once, so an occasional duplicate message is expected.

Only connection values are secrets. The queue name, region and load knobs stay plain constants at the top of the file, because MaxoPerf masks bound secret values in run output and a secret called us-east-1 would garble every error message.

Secret env varMeaningExample value
SECRET_AWS_ACCESS_KEY_IDAccess key id (required)<your-access-key-id>
SECRET_AWS_SECRET_ACCESS_KEYSecret access key (required)<your-secret-access-key>
SECRET_SQS_ENDPOINT_URLCustom endpoint, only for ElasticMQ or LocalStack (optional)http://localhost:9324

Create each as a workspace secret and bind it to the test: see secrets and environments. The name you bind must match the env var exactly, including the SECRET_ prefix. STS session tokens are not covered by this secret set.

Bind the connection values as secrets; the script reads them as environment variables.
  1. Create a new test and 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.
  2. On the Dependencies tab, bind the secrets from the table above.

  3. Set the users and duration. Producers are your users minus CONSUMERS, so 10 users with the default CONSUMERS = 2 gives 8 producers at 10 sends per second each.

  4. Start the run.

The run reports two labels with request type SQS.

  • sqs send is the duration of the SendMessage call, so it includes the network round trip and SQS acknowledging the write. Its samples per second is your send rate.
  • sqs end-to-end is the time from the message’s sent_at to the moment a consumer received it. One sample is recorded per message, so its samples per second is your consume rate. If a delete fails, that message is recorded as a failed sample.

A healthy run has both labels progressing together, no failures, end-to-end samples close to send samples, and an end-to-end latency that stays flat. If end-to-end latency climbs steadily through the run, consumers are falling behind the producers. MaxoPerf rounds every sample to a whole millisecond, so a queue in the same network as the runner can show 0 to 1 ms on sqs send.

Amazon SQS run against an SQS-compatible local queue (ElasticMQ): send latency and end-to-end latency side by side.

For the rest of the run page, see read run results.

  • Rate and cost. SENDS_PER_USER_PER_SEC times the producer count is your send rate. Each message costs a send, a share of a receive and a share of a delete request. The file already batches receive and delete in groups of 10 to keep the request count down; send is one call per message, so use send_message_batch if you need to cut that cost further.
  • Consumers. Raise CONSUMERS if end-to-end latency climbs. Each consumer drains up to 10 messages per receive call.
  • Long polling. WaitTimeSeconds=1 makes receive_message wait for messages instead of returning empty. Short polling burns requests, and you pay for every empty response.
  • Visibility timeout. The file deletes a message right after receiving it. If your real consumers take longer than the queue’s visibility timeout to process a message, SQS hands it out again. That produces duplicates, so test with your real timeout.
  • FIFO queues. The file targets a standard queue. FIFO queues cap throughput per message group and need MessageGroupId, so add it before you load one.
  • Several runners and clock skew. End-to-end latency compares the producer’s clock with the consumer’s. With several runners the clocks can differ by milliseconds or more, and that difference adds straight into the number. Keep both roles on one runner when the absolute value matters.
SymptomCause and fix
Run fails at start with bind SECRET_AWS_ACCESS_KEY_ID and SECRET_AWS_SECRET_ACCESS_KEYThe key secrets are not bound to the test. Bind both, with those exact names.
sqs send fails with AccessDeniedThe IAM principal lacks permission. Grant sqs:SendMessage, sqs:ReceiveMessage, sqs:DeleteMessage and sqs:GetQueueUrl on the queue.
QueueDoesNotExist or a create errorThe queue is missing and the role cannot create it. Create maxoperf-load in the console, or change QUEUE to a queue that exists.
Cannot connect, EndpointConnectionErrorThe runners cannot reach the endpoint. Check SECRET_SQS_ENDPOINT_URL, or use a private datacenter outpost.
sqs end-to-end has no samplesConsumers received nothing, or only messages older than 60 seconds. Check that producers send to the same queue and region.
A failed row with no nameAn exception was raised inside the script rather than by an SQS call. Open the run logs for the traceback.
ModuleNotFoundError: No module named 'boto3'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.
The run log shows ERROR: pip's dependency resolver … bzt … requires urllib3==2.6.3, but you have urllib3 2.8.0Harmless. pip-install puts boto3 and its urllib3 into the test’s own package path; Taurus keeps its own copy. The run is not affected.