Sub topic 3
Sending, receiving, and deleting messages
This chapter assumes you can create an SQS queue (the previous chapter covered that), have boto3 configured with credentials and a region, and can read basic Python and JSON. Here you will follow one message through its life: send, receive, delete. You will also see the mistakes that cause lost or repeated work.
The three calls that define the lifecycle
An SQS queue stores messages until a consumer removes them. The consumer does not take a message off the queue when it receives it. Three API calls make up the core lifecycle:
| Call | What it does | Who calls it |
|---|---|---|
| `SendMessage` | Adds a message to the queue | Producer |
| `ReceiveMessage` | Returns up to 10 messages and hides them for a time | Consumer |
| `DeleteMessage` | Permanently removes a message | Consumer |
Receiving does not delete. SQS keeps its own copy of every message until you delete it or the retention period ends. This is what lets a crashed consumer's work be picked up again.
Sending a message
A message has a body, which is a string of up to 256 KiB. It can also carry message attributes, which are typed key-value pairs kept outside the body. Most producers put JSON in the body.
import json
import boto3
sqs = boto3.client("sqs")
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
resp = sqs.send_message(
QueueUrl=queue_url,
MessageBody=json.dumps({"orderId": "1001", "total": 25}),
MessageAttributes={
"source": {"DataType": "String", "StringValue": "web"}
},
)
print(resp["MessageId"], resp["MD5OfMessageBody"])The response contains a MessageId and an MD5 hash of the body. A successful response means SQS has stored the message across multiple servers. If the call raises an exception or times out, you do not know whether the message was stored. Retrying is safe for correctness only if your consumers tolerate duplicates, which a later chapter covers.
Some body rules matter in practice:
- The body must be text. Binary data has to be encoded, for example as Base64.
- Only certain Unicode characters are allowed. Control characters such as
\x00are rejected. - For bodies larger than 256 KiB, store the payload elsewhere (for example in Amazon S3) and send a pointer.
Sending in batches
SendMessageBatch sends up to 10 messages in one request. The total payload of a batch is also limited to 256 KiB. Batching reduces request count, and SQS bills per request.
import json
import boto3
sqs = boto3.client("sqs")
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
entries = [
{"Id": str(i), "MessageBody": json.dumps({"orderId": str(2000 + i)})}
for i in range(10)
]
resp = sqs.send_message_batch(QueueUrl=queue_url, Entries=entries)
print("sent:", len(resp.get("Successful", [])))
for failure in resp.get("Failed", []):
print("failed:", failure["Id"], failure["Message"])A batch call can succeed as a whole request while some entries fail. Always check the Failed list. The Id is only a label that is unique within the request and lets you match results to entries.
Receiving messages
ReceiveMessage returns a list under the key Messages. If no message is available, the key is missing, so use resp.get("Messages", []).
import boto3
sqs = boto3.client("sqs")
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
resp = sqs.receive_message(
QueueUrl=queue_url,
MaxNumberOfMessages=10,
WaitTimeSeconds=20,
MessageAttributeNames=["All"],
AttributeNames=["ApproximateReceiveCount"],
)
for msg in resp.get("Messages", []):
print(msg["MessageId"])
print(msg["Body"])
print(msg["ReceiptHandle"][:20], "...")
print(msg["Attributes"]["ApproximateReceiveCount"])Points to know about this call:
MaxNumberOfMessagesis a maximum, between 1 and 10. SQS may return fewer, even when more are waiting, because standard queues spread messages over many servers.- Message attributes are returned only if you ask for them with
MessageAttributeNames. ApproximateReceiveCounttells you how many times the message has been received. It is useful for spotting a message that keeps failing.WaitTimeSecondsturns on long polling. A later chapter covers it. The consumer examples here use 20 seconds, the maximum.
The receipt handle
Each time a message is received, SQS gives you a ReceiptHandle. It identifies that specific receive, not the message itself. The same message received twice has two different handles. You pass the handle to DeleteMessage.
Always use the handle from the most recent receive. A handle from an earlier receive may no longer be valid, and a delete with it can fail or have no effect.
Why a received message comes back
When a consumer receives a message, SQS starts the visibility timeout for it. During that time, other consumers cannot receive the message. If the timeout expires before the message is deleted, the message becomes visible again and can be received again. The next chapter covers tuning this value. For now, remember that deleting is what ends a message's life.
Deleting messages
import json
import boto3
sqs = boto3.client("sqs")
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
def process(order):
print("processing", order)
resp = sqs.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=10, WaitTimeSeconds=20)
for msg in resp.get("Messages", []):
process(json.loads(msg["Body"]))
sqs.delete_message(QueueUrl=queue_url, ReceiptHandle=msg["ReceiptHandle"])Delete after processing succeeds, not before. If you delete first and then crash, the message is gone and the work is never done. If you delete after and then crash between processing and deleting, the message is processed again. SQS chooses the second failure mode: the guarantee is at-least-once delivery, so a duplicate is possible and a loss is not.
DeleteMessageBatch deletes up to 10 messages per request. As with sending, inspect the Failed list in the response.
import boto3
sqs = boto3.client("sqs")
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
resp = sqs.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=10, WaitTimeSeconds=20)
messages = resp.get("Messages", [])
if messages:
result = sqs.delete_message_batch(
QueueUrl=queue_url,
Entries=[
{"Id": m["MessageId"], "ReceiptHandle": m["ReceiptHandle"]}
for m in messages
],
)
for failure in result.get("Failed", []):
print("delete failed:", failure["Id"], failure["Message"])Only batch deletes for messages that were all processed successfully. If processing is per message, delete the successful ones and leave the rest.
A consumer loop with error handling
This loop handles each message separately. A failure in one message does not delete it, and does not block the others.
import json
import boto3
sqs = boto3.client("sqs")
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
def process(order):
if "orderId" not in order:
raise ValueError("missing orderId")
print("processing", order["orderId"])
while True:
resp = sqs.receive_message(
QueueUrl=queue_url,
MaxNumberOfMessages=10,
WaitTimeSeconds=20,
)
for msg in resp.get("Messages", []):
try:
process(json.loads(msg["Body"]))
except Exception as exc:
print("failed, will retry later:", msg["MessageId"], exc)
continue
sqs.delete_message(
QueueUrl=queue_url, ReceiptHandle=msg["ReceiptHandle"]
)When process raises, the loop skips the delete. The message reappears after the visibility timeout and is tried again. Without a limit, a message that can never succeed would loop forever. A dead-letter queue, covered later, solves that.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Messages` key is missing | The queue was empty during the wait | Use `resp.get("Messages", [])` |
| Same message processed twice | Processing took longer than the visibility timeout, or a crash happened before delete | Make consumers idempotent, and set the timeout above worst-case processing time |
| Message never goes away | The consumer never calls `DeleteMessage` | Delete after successful processing |
| `ReceiptHandleIsInvalid` | Handle was truncated, altered, or is from an older receive | Pass the handle exactly as returned from the latest receive |
| Fewer than 10 messages returned | `MaxNumberOfMessages` is an upper bound | Loop and receive again |
| `AccessDenied` | The IAM identity lacks `sqs:SendMessage`, `sqs:ReceiveMessage`, or `sqs:DeleteMessage` | Add the missing action on the queue ARN |
| Attributes missing from a received message | They were not requested | Set `MessageAttributeNames` or `AttributeNames` |
Exercises
Exercise
A consumer calls receive_message, processes the message successfully, and then the process crashes before it calls delete_message. What happens to the message, and why is this considered the safer failure compared with deleting first?
Show answer
The message becomes visible again when its visibility timeout expires, and another receive picks it up, so it is processed a second time. This is safer than deleting first because a crash after a delete would lose the message and its work permanently. A duplicate can be handled by an idempotent consumer, but a lost message cannot be recovered.
Exercise
You call send_message_batch with 10 entries and the call returns without raising an exception. Does that prove all 10 messages were stored? How do you find out?
Show answer
No. A batch request can succeed overall while individual entries fail. Check the Failed list in the response, matching each failed entry to your input by its Id, and resend those entries.