Skip to content

Load Testing Amazon SQS: Latency, Polling and Cost

Load test Amazon SQS with one Locust file: measure send latency and end-to-end latency, and see how visibility timeouts and polling shape the result.

Producers sending into an SQS queue of visible and in-flight messages, two consumers receiving and deleting, and a chart where sqs end-to-end latency climbs while sqs send stays flat

Amazon SQS rarely falls over. It is a managed service with high ceilings, so a load test seldom ends with a red error rate. The problems show up in quieter places: messages that arrive late, messages that arrive twice, consumers that spend your money polling an empty queue. SQS load testing is mostly about measuring those things before your own traffic does.

This post explains how an SQS-backed system slows down under load, what to measure, and gives you a single locustfile.py that measures it on MaxoPerf.

Why “SQS is fast” is not a test result

A send to SQS returns quickly, and that number says nothing about whether your system works. Your system works when a message is sent, received by a consumer and finished before anyone notices. That is a pipeline with three separate behaviours: the producer’s call, the time a message waits, and the consumer’s pace. A test that only hammers SendMessage measures the first one and flatters the other two.

So the test has to run both sides at once, and it has to record two different latencies. Send latency is how long the API call takes. End-to-end latency is the time between the producer stamping a message and a consumer receiving it. When the two diverge, the queue is absorbing a gap between how fast you produce and how fast you consume. That gap is the finding.

How SQS behaves under load

Backlog grows quietly. A queue has no back-pressure for a standard producer. If producers outrun consumers, sends keep succeeding at the same speed while the number of waiting messages climbs. Send latency stays flat and everything looks fine. Only end-to-end latency, rising through the run, shows that consumers are behind. This is why a single error-rate number is a poor verdict on a queue test.

Visibility timeout turns slow consumers into duplicates. When a consumer receives a message, SQS hides it for the visibility timeout. If processing takes longer than that timeout, the message becomes visible again and another consumer receives it. Under light load processing is fast and nobody notices. Under load, processing slows, the timeout is crossed, and the same message is handled twice. Standard queues already deliver at least once, so duplicates are normal, but a load test is where their rate stops being occasional. Test with the visibility timeout you run in production, and make your handlers idempotent.

Short polling burns requests. A receive call with no wait returns immediately, often with nothing. A consumer loop that polls like that sends a stream of empty requests, and you pay for each one. Long polling, where the call waits for messages, cuts the empty responses. A load test that polls the way your code polls shows you the true request count.

FIFO queues have throughput ceilings. FIFO queues give you ordering and deduplication, and in exchange they cap throughput, with limits applied per message group. A burst that a standard queue absorbs can be throttled on a FIFO queue, and the symptom is throttling errors on send rather than a slow queue. If you run FIFO, include your real message group layout in the test, because one hot group serialises everything behind it.

Every request is billed. This is the one that surprises people. Each send, receive and delete is a billed request, and a load test generates them at a rate no normal day does. A 10-minute test at a few hundred messages a second can generate a request count you would not choose to pay for by accident. Know your rate before you press start, and prefer batch calls where your real code uses them.

What to measure

Keep the measurement small and honest. You need two labels:

  • sqs send, the duration of the SendMessage call, including the network and SQS acknowledging the write.
  • sqs end-to-end, the time from the producer’s timestamp to the moment a consumer receives the message, recorded once per message.

From those you read the rest. The samples per second of sqs send is your send rate. The samples per second of sqs end-to-end is your consume rate, because there is one sample per message. If end-to-end samples run well below send samples, consumers are not keeping up. If end-to-end latency climbs through the run, the backlog is growing. If both are steady and close, the system is keeping pace at that rate.

Two details protect the result. First, consumers should ignore messages sent before the test started, since a standard queue keeps the previous run’s backlog and would otherwise report minutes-old latencies. Second, end-to-end latency compares the producer’s clock with the consumer’s, so keep both on one runner, or sync clocks, when the absolute value matters.

The locustfile

The file below runs producers and consumers in one Locust test. It uses boto3, which the taurus.yml below installs when the test starts, creates the queue if it is missing, and reads its connection values from bound secrets. It requires access keys and refuses to use the default AWS credential chain, so a runner never acts with credentials that are not yours.

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

The producers hold a steady send rate per user. The consumers are fixed users that long-poll, record one end-to-end sample for each message, and delete messages in batches of ten. The rate, message size, queue name and consumer count are plain constants at the top, so edit them freely.

Run it on MaxoPerf

  1. Create a test and upload locustfile.py. MaxoPerf detects Locust from the file.
  2. Create workspace secrets SECRET_AWS_ACCESS_KEY_ID and SECRET_AWS_SECRET_ACCESS_KEY, and bind them to the test. Add SECRET_SQS_ENDPOINT_URL only if you target ElasticMQ or LocalStack.
  3. Set the users and duration. Producers are your users minus the consumer count, so 10 users with the default two consumers gives eight producers.
  4. Start the run, then open the results and compare the two labels.

Point it at a queue you are allowed to load, and start with a short run at a low rate so you can see the request volume before you scale up.

What to look for

Read the two labels together. A healthy run has both labels progressing, no failures, end-to-end samples close to send samples and an end-to-end latency that stays flat. That tells you consumers keep up at this rate.

A climbing end-to-end line with a flat send line is the classic backlog: add consumers, speed up processing, or accept the lag. A pile of duplicates points at the visibility timeout. Throttling errors on sqs send point at a FIFO or account limit. A failed row with no name means an exception inside the script, so read the run logs for the traceback.

Then change one thing at a time. Raise the send rate until end-to-end latency starts to climb and you have found the point where your consumers become the limit. Change the consumer count and watch the line flatten. Repeat with your real message size, because payload size changes both labels.

Next steps

The step-by-step Amazon SQS how-to covers secrets, tuning and troubleshooting. The message queue do and don’t page lists the mistakes that make queue tests misleading, from shared production queues to skewed clocks. Run the test on a queue you own, and let the end-to-end line tell you what your consumers can do.