Sub topic 1
Why Asynchronous Messaging Decouples Producers and Consumers
Prerequisites
Assume you know basic AWS accounts, Regions, IAM, JSON, and Python. You should also understand that a distributed application has components that communicate over a network.
Decoupling with asynchronous messaging
Asynchronous messaging lets a producer send work without waiting for a consumer to finish it. A producer is the component that creates a message. A consumer is the component that processes it. A queue stores messages between them.
This separation reduces dependency. The producer can continue when the consumer is slow or temporarily unavailable. The queue absorbs traffic spikes, while consumers process messages at their own pace.
Amazon SQS queues
Amazon Simple Queue Service, or SQS, is a managed queue service. AWS stores the messages and provides APIs for sending and receiving them. You do not manage queue servers.
A standard queue provides high throughput and at-least-once delivery. At-least-once delivery means a message can arrive more than once, so consumers must safely repeat processing.
Sending, receiving, and deleting
The normal lifecycle is send, receive, process, and delete. Receiving does not remove a message. Delete it only after successful processing.
import boto3
sqs = boto3.client("sqs")
queue_url = sqs.create_queue(QueueName="orders")["QueueUrl"]
sqs.send_message(QueueUrl=queue_url, MessageBody='{"orderId":"1001"}')
response = sqs.receive_message(QueueUrl=queue_url, WaitTimeSeconds=20)
for message in response.get("Messages", []):
print(message["Body"])
# Perform successful processing here.
sqs.delete_message(
QueueUrl=queue_url,
ReceiptHandle=message["ReceiptHandle"],
)Visibility timeout
A visibility timeout temporarily hides a received message from other consumers. The default is 30 seconds. Set it longer than the usual processing time. If processing fails or the timeout expires, SQS makes the message visible again. A consumer can extend the timeout for long-running work.
Long polling
Long polling makes SQS wait for messages instead of immediately returning an empty response. Set WaitTimeSeconds up to 20 seconds on receives, or configure the queue’s receive wait time. This reduces empty responses and API cost compared with repeated short polls.
Delay and retention
A queue delay hides newly sent messages for a configured period. A message timer can apply a different delay to one message. Retention controls how long an unprocessed message remains available. Choose retention long enough to handle outages, but remove messages sooner when they are no longer useful.
Exercise
What should a consumer do if processing succeeds but deleting the message fails?
Show answer
Process the same message safely again when it is redelivered, then delete it after successful processing.