Skip to content

Resources / Messaging

SQS queue

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

TypeScript
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:

TypeScript
const api = new LambdaFunction({  packaging: new JsBundleLambdaPackaging({ entryfilePath: './src/api.ts' }),  connectTo: [taskQueue]});
TypeScript
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 connectTo and 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:

TypeScript
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:

aws sqs send-message --queue-url "<queue-url>" --message-body '{"task":"resize-image","imageId":"123"}'

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.

TypeScript
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:

TypeScript
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

StandardFIFO
OrderBest effortKept within each message group
DuplicatesA message is sometimes delivered twiceDuplicate sends within 5 minutes are dropped
ThroughputPractically unlimited300 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.

TypeScript
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:

TypeScript
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.
  • messageRetentionPeriodSeconds sets how long unprocessed messages stay, from 60 seconds to 14 days. The default is 4 days.
  • maxMessageSizeBytes lowers the size limit below 1 MiB. For larger payloads, upload the data to an S3 bucket and send the object key.
  • policyStatements adds statements to the queue policy, for another account or an AWS service principal. Workloads in the stack use connectTo instead.

Alarms

Two alarm triggers watch a queue:

  • sqs-queue-not-empty goes 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-count goes off when received messages cross thresholdCount (average per period by default), for unexpected traffic.

See Alarms and Alert channels.

Configuration reference

SqsQueueProps13 properties
  • alarmsSqsQueueAlarm[]

    Additional alarms associated with this resource.

  • Automatically deduplicates messages based on their content (SHA-256 hash of the body).

  • delayMessagesSecondnumberDefault 0

    Delay (in seconds) before new messages become visible to consumers. Range: 0–900.

  • Disables globally configured alarms for this resource.

  • eventsSqsQueueEventBusIntegration[]

    A list of event sources that trigger message delivery to this queue.

  • fifoEnabledbooleanDefault false

    Creates a FIFO queue that guarantees message order and exactly-once delivery.

  • Enables high-throughput mode for FIFO queues (up to ~70,000 msg/s per queue).

  • longPollingSecondsnumberDefault 0

    Seconds the queue waits for messages before returning an empty response. Range: 0–20.

  • maxMessageSizeBytesnumberDefault 1048576

    Maximum message size in bytes. Range: 1,024 (1 KiB) to 1,048,576 (1 MiB).

  • messageRetentionPeriodSecondsnumberDefault 345600

    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.

  • visibilityTimeoutSecondsnumberDefault 30

    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