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.
Before you start
Section titled “Before you start”- 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.ymlinstalls theboto3client (1.44.7) when the test starts, with Taurus’s built-inpip-installservice. 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:ReceiveMessageandsqs:DeleteMessage, plussqs:CreateQueueif 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.
The locustfile
Section titled “The locustfile”"""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, uuidimport boto3from botocore.config import Configfrom botocore.exceptions import BotoCoreError, ClientErrorfrom 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 / LocalStackif 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 queuesREGION = "us-east-1"SENDS_PER_USER_PER_SEC = 10 # every send, receive and delete is a billed request on real SQSMESSAGE_BYTES = 512 # payload sizeCONSUMERS = 2 # fixed consumer users (Locust fixed_count)STALE_AFTER_S = 60 # skip messages sent before this run started: a queue keeps old backlogSTARTED = 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 downUpload it together with this taurus.yml. Taurus runs the Locust file and installs the client when the test starts:
execution: - executor: locust scenario: mqscenarios: mq: script: locustfile.pyservices: - module: pip-install packages: - boto3==1.44.7The 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.
Connect it to your broker
Section titled “Connect it to your broker”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 var | Meaning | Example value |
|---|---|---|
SECRET_AWS_ACCESS_KEY_ID | Access key id (required) | <your-access-key-id> |
SECRET_AWS_SECRET_ACCESS_KEY | Secret access key (required) | <your-secret-access-key> |
SECRET_SQS_ENDPOINT_URL | Custom 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.
Run it on MaxoPerf
Section titled “Run it on MaxoPerf”-
Create a new test and upload
taurus.ymlandlocustfile.pytogether.taurus.ymlis 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. -
On the Dependencies tab, bind the secrets from the table above.
-
Set the users and duration. Producers are your users minus
CONSUMERS, so 10 users with the defaultCONSUMERS = 2gives 8 producers at 10 sends per second each. -
Start the run.
Read the results
Section titled “Read the results”The run reports two labels with request type SQS.
sqs sendis the duration of theSendMessagecall, so it includes the network round trip and SQS acknowledging the write. Its samples per second is your send rate.sqs end-to-endis the time from the message’ssent_atto 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.
For the rest of the run page, see read run results.
Tune it for your system
Section titled “Tune it for your system”- Rate and cost.
SENDS_PER_USER_PER_SECtimes 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 usesend_message_batchif you need to cut that cost further. - Consumers. Raise
CONSUMERSif end-to-end latency climbs. Each consumer drains up to 10 messages per receive call. - Long polling.
WaitTimeSeconds=1makesreceive_messagewait 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.
Troubleshooting
Section titled “Troubleshooting”| Symptom | Cause and fix |
|---|---|
Run fails at start with bind SECRET_AWS_ACCESS_KEY_ID and SECRET_AWS_SECRET_ACCESS_KEY | The key secrets are not bound to the test. Bind both, with those exact names. |
sqs send fails with AccessDenied | The IAM principal lacks permission. Grant sqs:SendMessage, sqs:ReceiveMessage, sqs:DeleteMessage and sqs:GetQueueUrl on the queue. |
QueueDoesNotExist or a create error | The 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, EndpointConnectionError | The runners cannot reach the endpoint. Check SECRET_SQS_ENDPOINT_URL, or use a private datacenter outpost. |
sqs end-to-end has no samples | Consumers received nothing, or only messages older than 60 seconds. Check that producers send to the same queue and region. |
| A failed row with no name | An 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.0 | Harmless. pip-install puts boto3 and its urllib3 into the test’s own package path; Taurus keeps its own copy. The run is not affected. |
- Message queue testing: do and don’t
- Load Testing Amazon SQS, the blog post behind this guide
- Connect a private datacenter outpost