Sub topic 2
Amazon SQS queues: what they are and how to create one
This chapter assumes you know the basics of AWS accounts, regions, and IAM, can read JSON, and can read short Python scripts. The examples use Python with boto3, the AWS SDK for Python. You will learn what an SQS queue is, which settings matter at creation time, and how to create a main queue with a dead-letter queue.
What an SQS queue is
Amazon Simple Queue Service (SQS) is a managed message queue. A producer sends messages to the queue, and SQS stores them durably across multiple Availability Zones. A consumer later requests messages, processes them, and deletes them. You do not provision servers, size disks, or patch software.
A queue is a buffer between two parts of a system. The producer does not call the consumer directly. It only needs the queue's address, so the two sides can run at different speeds, fail separately, and scale independently.
SQS uses a pull model. Consumers ask for messages. SQS does not push them to your code. (Lambda can poll for you, as a later chapter shows.)
Each queue is identified by:
- Queue name: unique within an account and region. Names can be up to 80 characters, using letters, digits, hyphens, and underscores.
- Queue URL: the HTTPS address you pass to most API calls, such as
https://sqs.us-east-1.amazonaws.com/123456789012/orders. - Queue ARN: the Amazon Resource Name, used in IAM and queue policies and when you connect other services, such as SNS or a dead-letter queue.
A queue lives in one region. Producers and consumers in other regions can still reach it, but they pay for cross-region latency and data transfer.
Two queue types
SQS offers two types. You choose when you create the queue, and you cannot change it afterward.
| Property | Standard | FIFO |
|---|---|---|
| Throughput | Nearly unlimited | Limited per queue, higher with high-throughput mode |
| Ordering | Best effort | Preserved within a message group |
| Delivery | At least once, duplicates possible | Deduplicated within a 5-minute window |
| Name | Any valid name | Must end in `.fifo` |
This chapter uses standard queues. A later chapter compares the two in detail.
Queue attributes that matter at creation
You can create a queue with only a name, and every other setting takes a default. The attributes below are the ones you will tune most often. Later chapters cover each in depth.
| Attribute | Default | Range | Purpose |
|---|---|---|---|
| `VisibilityTimeout` | 30 s | 0 s to 12 h | How long a received message is hidden from other consumers |
| `ReceiveMessageWaitTimeSeconds` | 0 (short polling) | 0 to 20 s | Default long-polling wait for `ReceiveMessage` |
| `DelaySeconds` | 0 | 0 to 15 min | Delay before new messages become visible |
| `MessageRetentionPeriod` | 4 days | 60 s to 14 days | How long SQS keeps an unprocessed message |
| `MaximumMessageSize` | 256 KiB | 1 KiB to 256 KiB | Largest allowed message body |
| `RedrivePolicy` | none | JSON | Where to send messages that keep failing |
Attribute values are passed as strings, even when they are numbers. That is why the code below writes "60" instead of 60.
Creating a queue with a dead-letter queue
A common starting design has two queues. The main queue holds work. A dead-letter queue (DLQ) holds messages that failed too many times, so that one bad message does not loop forever. The DLQ must exist first, because the main queue's redrive policy refers to the DLQ's ARN.
import json
import boto3
sqs = boto3.client("sqs")
# Dead-letter queue for messages that keep failing
dlq_url = sqs.create_queue(QueueName="orders-dlq")["QueueUrl"]
dlq_arn = sqs.get_queue_attributes(
QueueUrl=dlq_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
# Main queue: 60 s visibility timeout, long polling by default,
# and move a message to the DLQ after 5 failed receives
queue_url = sqs.create_queue(
QueueName="orders",
Attributes={
"VisibilityTimeout": "60",
"ReceiveMessageWaitTimeSeconds": "20",
"RedrivePolicy": json.dumps(
{"deadLetterTargetArn": dlq_arn, "maxReceiveCount": "5"}
),
},
)["QueueUrl"]
print(queue_url)The script does the following:
- Creates
orders-dlqwith default settings and reads its ARN withget_queue_attributes. - Creates
orderswith a 60-second visibility timeout, so a consumer has 60 seconds to finish before the message reappears. - Sets
ReceiveMessageWaitTimeSecondsto 20, soReceiveMessagecalls wait for messages by default instead of returning empty responses. - Sets a redrive policy. After a message has been received five times without being deleted, SQS moves it to
orders-dlq.
The RedrivePolicy value is a JSON document stored as a string, so the code calls json.dumps. The call returns the queue URL, which you will use in every later request.
Idempotent creation
create_queue is idempotent when the name and attributes match an existing queue. It returns the existing URL. If the queue exists with different attributes, SQS returns a QueueNameExists error. This makes the call safe in deployment scripts, but changed settings need set_queue_attributes, shown below.
import boto3
sqs = boto3.client("sqs")
queue_url = sqs.get_queue_url(QueueName="orders")["QueueUrl"]
# Change an attribute on an existing queue
sqs.set_queue_attributes(
QueueUrl=queue_url,
Attributes={"MessageRetentionPeriod": str(7 * 24 * 60 * 60)},
)If you only have the name, get_queue_url looks up the URL. If the queue is in another account, pass QueueOwnerAWSAccountId. The caller still needs permission through the queue policy.
Permissions
Creating a queue needs sqs:CreateQueue. Sending, receiving, and deleting need sqs:SendMessage, sqs:ReceiveMessage, and sqs:DeleteMessage on the queue ARN. Follow least privilege: give producers only send access and consumers only receive and delete access.
Access to a queue is granted by an IAM policy on the caller, a queue (resource) policy on the queue, or both. Within one account, either is enough. For cross-account access or access from another AWS service, the queue policy must allow it. Later chapters use this for SNS.
Common errors
QueueNameExists: the queue exists with different attributes. Useset_queue_attributes, or pick another name.QueueDeletedRecently: you deleted a queue with this name less than 60 seconds ago. Wait and retry.AWS.SimpleQueueService.NonExistentQueue: the name or region is wrong, or the queue was deleted. Check the region of your client.AccessDenied: neither the caller's IAM policy nor the queue policy allows the action.- Invalid attribute value: values must be strings, and each must fall within its allowed range.
- DLQ type mismatch: a standard queue needs a standard DLQ, and a FIFO queue needs a FIFO DLQ. The DLQ must also be in the same account and region.
Cleaning up
Queues with no traffic cost almost nothing, but you should still delete practice queues.
import boto3
sqs = boto3.client("sqs")
for name in ["orders", "orders-dlq"]:
url = sqs.get_queue_url(QueueName=name)["QueueUrl"]
sqs.delete_queue(QueueUrl=url)Deleting a queue removes all its messages. The queue name cannot be reused for 60 seconds.
Exercise
You create a queue named orders with a redrive policy whose deadLetterTargetArn points to a queue that does not exist yet. Why does this fail, and what is the correct order of steps?
Show answer
The redrive policy needs the ARN of an existing dead-letter queue, and SQS validates it when the policy is set. Create the dead-letter queue first, read its ARN with getqueueattributes (AttributeNames=["QueueArn"]), and then create the main queue with a RedrivePolicy that contains that ARN and a maxReceiveCount.
Exercise
A deployment script calls create_queue for "orders" with VisibilityTimeout "120", but the queue already exists with VisibilityTimeout "60". What happens, and how do you apply the new value?
Show answer
SQS returns a QueueNameExists error, because the name matches but the attributes differ. Get the URL with getqueueurl and call setqueueattributes with {"VisibilityTimeout": "120"}.