Sub topic 3
Sending, receiving, and deleting messages
This chapter assumes you have an AWS account with credentials configured, know basic JSON, and can read Python with boto3. You should also know that an SQS queue stores messages until a consumer processes them.
The three calls
An SQS message moves through three API calls.
SendMessageputs a message in the queue.ReceiveMessagereturns messages to a consumer. It does not remove them.DeleteMessageremoves a message permanently.
Receiving only hides a message for a while (the visibility timeout, covered in the next chapter). The message stays in the queue until you delete it. This is how SQS survives consumer crashes: if a consumer dies before deleting, the message becomes visible again and another consumer can take it.
Sending and receiving in code
This example sends one message, then runs a consumer loop. It assumes the orders queue from the previous chapter exists.
import json
import boto3
sqs = boto3.client("sqs")
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
def process(order):
print("processing", order)
sqs.send_message(QueueUrl=queue_url, MessageBody=json.dumps({"orderId": "1001"}))
while True:
resp = sqs.receive_message(
QueueUrl=queue_url,
MaxNumberOfMessages=10,
WaitTimeSeconds=20,
)
for msg in resp.get("Messages", []):
process(json.loads(msg["Body"]))
# Delete only after successful processing
sqs.delete_message(
QueueUrl=queue_url, ReceiptHandle=msg["ReceiptHandle"]
)Points worth noting:
- The message body is a string. Use JSON when you need structure. A body can be up to 1 MiB (1,048,576 bytes).
MaxNumberOfMessagesaccepts 1 to 10. Batching reduces the number of requests.WaitTimeSeconds=20turns on long polling for this call. The next chapters explain it.resphas noMessageskey when nothing is available, so useresp.get("Messages", []).
The receipt handle
Every receive returns a ReceiptHandle. It identifies that particular receipt of the message, not the message itself. You must pass it to DeleteMessage. If the same message is received twice, each receive produces a different handle. Use the most recent one, because a delete with an old handle can fail or be ignored once the message has been received again.
The response also contains a MessageId, which stays the same across receives. Use it for logging, not for deleting.
Delete after success
The loop deletes after process returns. If process raises an exception, the delete never runs. The message reappears when the visibility timeout expires, and SQS delivers it again.
Deleting before processing reverses this. A crash then loses the message. Delete first only if losing a message is acceptable.
Because a message can be delivered more than once, process must be safe to repeat. A later chapter covers idempotent consumers.
Common errors
| Symptom | Likely cause |
|---|---|
| The same message keeps coming back | The consumer never calls `DeleteMessage`, or fails before it |
| `AWS.SimpleQueueService.NonExistentQueue` | Wrong queue name, region, or account |
| `AccessDenied` | The IAM identity lacks `sqs:SendMessage`, `sqs:ReceiveMessage`, or `sqs:DeleteMessage` |
| Empty responses while the queue holds messages | Short polling can sample only some servers. Use `WaitTimeSeconds` |
Exercise
A consumer receives a message, starts processing, and crashes before calling DeleteMessage. What happens to the message, and why?
Show answer
The message stays in the queue. Receiving only hides it for the visibility timeout. When the timeout expires with no delete, the message becomes visible again and a consumer receives it a second time, which is why consumers should be safe to repeat.