An sqs-queue is an Amazon SQS message queue. One part of your app puts a job on the queue and returns; a consumer
processes it at its own pace, and a burst of jobs waits in the queue instead of overloading the consumer. You pay per
request: the first million each month are free, then $0.40 per million for standard queues in US East.
A queue delivers each message to one consumer. When several services need the same message, publish it to an SNS topic or an event bus and give each consumer its own queue.
Basic example
export default defineConfig(() => { const taskQueue = new SqsQueue({}); return { resources: { taskQueue } };});This creates a standard queue with the AWS defaults: messages up to 1 MiB, kept for 4 days, hidden for 30 seconds after a consumer receives them. The queue alone does nothing; add a producer and a consumer.
Send messages
connectTo gives a workload permission to send, receive and delete messages, and injects the queue's ARN, NAME and
URL as environment variables:
const api = new LambdaFunction({ packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/api.ts' }), connectTo: [taskQueue]});import { SQSClient, SendMessageCommand } from '@aws-sdk/client-sqs';const sqs = new SQSClient({});await sqs.send( new SendMessageCommand({ QueueUrl: process.env.STP_TASK_QUEUE_URL, MessageBody: JSON.stringify({ task: 'resize-image', imageId: '123' }) }));For a queue named taskQueue, the variables are STP_TASK_QUEUE_ARN, STP_TASK_QUEUE_NAME and STP_TASK_QUEUE_URL.
See Connecting resources.
Consume messages
Pick the consumer by how the work runs:
- A Lambda function, for jobs that finish within 15 minutes. Add an SQS event to the function. Lambda polls the queue, passes batches and deletes the messages that succeed. Most queues should start here.
- A container, for long jobs, a steady stream of work or code that needs a long-lived process. Use a
worker service with
connectToand poll the queue in your code.
A container consumer receives a message, processes it, then deletes it. If it crashes before the delete, the message becomes visible again after the visibility timeout and another receive picks it up:
import { SQSClient, ReceiveMessageCommand, DeleteMessageCommand } from '@aws-sdk/client-sqs';const sqs = new SQSClient({});const QueueUrl = process.env.STP_TASK_QUEUE_URL;while (true) { const { Messages = [] } = await sqs.send( new ReceiveMessageCommand({ QueueUrl, MaxNumberOfMessages: 10, WaitTimeSeconds: 20 }) ); for (const message of Messages) { await processTask(JSON.parse(message.Body!)); await sqs.send(new DeleteMessageCommand({ QueueUrl, ReceiptHandle: message.ReceiptHandle })); }}Test either consumer by sending one message after stacktape deploy:
stacktape param get taskQueue url --stage dev --region eu-west-1 prints the queue URL.
Visibility timeout and polling
After a consumer receives a message, the queue hides it for visibilityTimeoutSeconds (30 by default). If the consumer
doesn't delete it in time, the message comes back and runs again. Set it above your longest processing time; for a
Lambda consumer, at least the function's timeout. Stacktape refuses to deploy a Lambda trigger whose function timeout
is longer than the queue's visibility timeout.
longPollingSeconds makes a receive call wait up to that many seconds for messages instead of returning empty at once.
Set it to 20 for container consumers: fewer empty calls, lower cost. Lambda triggers poll on their own and ignore it.
new SqsQueue({ visibilityTimeoutSeconds: 300, longPollingSeconds: 20 })Dead-letter queue
A message that always fails comes back after every visibility timeout until the retention period ends, and each attempt
costs a run of your consumer. A redrivePolicy moves it to a second queue after maxReceiveCount receives:
export default defineConfig(() => { const deadLetterQueue = new SqsQueue({ alarms: [{ trigger: { type: 'sqs-queue-not-empty' } }] }); const taskQueue = new SqsQueue({ redrivePolicy: { targetSqsQueueName: 'deadLetterQueue', maxReceiveCount: 3 } }); return { resources: { taskQueue, deadLetterQueue } };});The sqs-queue-not-empty alarm tells you when a message lands in the dead-letter queue. targetSqsQueueArn points at
a queue outside the stack. A FIFO queue needs a FIFO dead-letter queue.
Standard or FIFO
| Standard | FIFO | |
|---|---|---|
| Order | Best effort | Kept within each message group |
| Duplicates | A message is sometimes delivered twice | Duplicate sends within 5 minutes are dropped |
| Throughput | Practically unlimited | 300 calls per second, 3,000 messages with batching |
| Price in US East | $0.40 per million requests | $0.50 per million requests |
Use a standard queue unless the order of messages matters. FIFO stops duplicate sends, but a consumer can still get a message again when it fails or runs past the visibility timeout. Write consumers to be idempotent with either type.
fifoEnabled: true creates a FIFO queue. Each message then needs a deduplication ID, or set
contentBasedDeduplication: true to use a hash of the body. Every message also needs a MessageGroupId; messages with
the same group ID are processed in order.
new SqsQueue({ fifoEnabled: true, contentBasedDeduplication: true })fifoHighThroughput: true raises the FIFO limit to thousands of calls per second (up to 70,000 in the largest regions).
Order then holds only within each message group, which is already the rule for consumers.
Deliver EventBridge events to the queue
The queue's events property sends matching events from an event bus into the queue, with no producer code. Set one
of eventBusName, eventBusArn or useDefaultBus:
const orderQueue = new SqsQueue({ events: [ { type: 'event-bus', properties: { eventBusName: 'orderBus', eventPattern: { source: ['order-service'], 'detail-type': ['OrderPlaced'] } } } ]});A FIFO queue also needs messageGroupId on the integration. input, inputPath, inputTransformer and
onDeliveryFailure work as on event bus triggers.
Other settings
delayMessagesSecond(0 to 900) keeps new messages hidden for that long before consumers can receive them.messageRetentionPeriodSecondssets how long unprocessed messages stay, from 60 seconds to 14 days. The default is 4 days.maxMessageSizeByteslowers the size limit below 1 MiB. For larger payloads, upload the data to an S3 bucket and send the object key.policyStatementsadds statements to the queue policy, for another account or an AWS service principal. Workloads in the stack useconnectToinstead.
Alarms
Two alarm triggers watch a queue:
sqs-queue-not-emptygoes off when the queue has visible, in-flight, received or sent messages. Use it on a dead-letter queue, or on a queue that should be drained.sqs-queue-received-messages-countgoes off when received messages crossthresholdCount(average per period by default), for unexpected traffic.
See Alarms and Alert channels.
Configuration reference
SqsQueueProps13 properties- alarmsSqsQueueAlarm[]
Additional alarms associated with this resource.
- contentBasedDeduplicationboolean
Automatically deduplicates messages based on their content (SHA-256 hash of the body).
Delay (in seconds) before new messages become visible to consumers. Range: 0–900.
- disabledGlobalAlarmsstring[]
Disables globally configured alarms for this resource.
- eventsSqsQueueEventBusIntegration[]
A list of event sources that trigger message delivery to this queue.
Creates a FIFO queue that guarantees message order and exactly-once delivery.
- fifoHighThroughputboolean
Enables high-throughput mode for FIFO queues (up to ~70,000 msg/s per queue).
Seconds the queue waits for messages before returning an empty response. Range: 0–20.
Maximum message size in bytes. Range: 1,024 (1 KiB) to 1,048,576 (1 MiB).
How long unprocessed messages stay in the queue before being deleted. Range: 60s to 1,209,600s (14 days).
- policyStatementsSqsQueuePolicyStatement[]
Custom access-control statements added to the queue's resource policy.
- redrivePolicySqsQueueRedrivePolicy
Moves messages that fail processing too many times to a dead-letter queue for inspection.
How long (seconds) a message is hidden from other consumers after being received. Range: 0–43,200 (12 hours).
Referenceable parameters
Reference these parameters with the $ResourceParam directive: $ResourceParam('<resource-name>', '<parameter>'). See referenceable parameters.
Next steps
- SQS events: consume the queue with a Lambda function.
- Worker service: consume the queue with a container.
- SNS topic: fan a message out to several queues.