SQS Events

An SQS event trigger invokes a Lambda function whenever messages arrive in an SQS queue. Messages are delivered in batches — the function fires when the batch size is reached, a time window expires, or the 6 MB payload limit is hit. SQS triggers decouple producers from consumers and absorb traffic spikes between services.

When to use

SQS event triggers fit when you need reliable, at-least-once message processing between services:

  • Work queues — an API enqueues tasks (image processing, email sending, report generation) and a worker Lambda processes them at its own pace.
  • Traffic smoothing — a high-throughput producer writes messages faster than your downstream can handle. The queue buffers the backlog and delivers in controlled batches.
  • Service decoupling — services communicate through queues instead of direct calls, so a failure in one service does not cascade.
  • Delayed processing — SQS queues support configurable delivery delays, useful for retry backoff or scheduled follow-ups.

When NOT to use

  • Fan-out to multiple consumers — a single SQS queue should have only one consumer. If multiple services need the same message, use an SNS topic or EventBridge event bus to fan out into separate queues.
  • Ordered streaming with sub-second latency — for per-shard ordering and continuous stream processing, use Kinesis streams.
  • Request-response patterns — SQS is asynchronous and fire-and-forget. If the caller needs a synchronous response, use an HTTP trigger.

Basic example

This configuration creates an SQS queue and a Lambda function that processes messages from it in batches of 5.

export default defineConfig(() => {
  const orderQueue = new SqsQueue({});

  const orderProcessor = new LambdaFunction({
    packaging: new JsBundleLambdaPackaging({
      entryfilePath: './src/process-orders.ts'
    }),
    events: [
      new SqsIntegration({
        sqsQueueName: 'orderQueue',
        batchSize: 5
      })
    ]
  });

  return {
    resources: { orderQueue, orderProcessor }
  };
});

The sqsQueueName value must match the key you use for the queue in the resources object — here, orderQueue. Use sqsQueueName when the SQS queue is defined in your stack's resources.

batchSize controls how many messages are delivered per invocation (default: 10, maximum: 10,000). With batchSize: 5, the function receives up to 5 messages at a time. For low-volume queues the default is fine; increase it for high-throughput scenarios to amortize invocation overhead.

Batching and throughput

SQS event triggers deliver messages in batches. Your Lambda function is invoked when any of these conditions is met first:

  • The batch reaches batchSize messages
  • The maxBatchWindowSeconds timer expires
  • The batch reaches the 6 MB payload size limit
PropertyDefaultMaximumEffect
batchSize1010,000Maximum messages per invocation
maxBatchWindowSeconds(immediate)300 sWait time to accumulate a larger batch

When maxBatchWindowSeconds is not set, the function is invoked as soon as messages are available. Setting it lets you accumulate larger batches before invoking, which reduces the total number of Lambda invocations. This is the primary lever for cost optimization on high-volume queues — fewer invocations means lower Lambda costs, at the expense of slightly higher message processing latency.

events: [
  new SqsIntegration({
    sqsQueueName: 'eventQueue',
    batchSize: 100,
    maxBatchWindowSeconds: 30
  })
]

This configuration waits up to 30 seconds to fill a batch of 100 messages before invoking the function. If 100 messages arrive in 5 seconds, the function fires immediately without waiting the remaining 25 seconds.

For high-throughput queues, increase batchSize and add a maxBatchWindowSeconds value to amortize Lambda invocation overhead across more messages. Larger batches reduce per-message cost at the expense of higher processing latency. Tune both values based on your throughput and latency requirements.

Limiting concurrency

Set maximumConcurrency (2 to 1000) to cap how many copies of the function the queue runs at once, for example to protect a database or a rate-limited API. Messages wait in the queue while the cap is reached. Without it, Lambda scales the function up to its own concurrency limit.

new SqsIntegration({ sqsQueueName: 'orderQueue', maximumConcurrency: 5 })

Using an external queue

To consume messages from an existing SQS queue not managed by this stack — for example, a queue created by a different deployment tool — use sqsQueueArn instead of sqsQueueName.

events: [
  new SqsIntegration({
    sqsQueueArn: 'arn:aws:sqs:eu-west-1:123456789012:external-queue',
    batchSize: 10
  })
]

You must specify exactly one of sqsQueueName or sqsQueueArn — not both. Use sqsQueueName when the queue is defined in the same Stacktape configuration. Use sqsQueueArn when consuming from a queue managed outside your stack.

Use sqsQueueArn for an existing queue that is not managed by your stack. The source type definition only documents the ARN attachment — verify any required cross-account or resource-policy permissions for your specific AWS setup.

Handling failures

Unlike Kinesis and DynamoDB stream triggers — which expose maximumRetryAttempts and onFailure properties directly on the integration — SqsIntegration does not expose retry, onFailure, or dead-letter properties.

When your Lambda function throws an error while processing an SQS batch, AWS returns the entire batch of messages to the queue for reprocessing. The queue's visibility timeout controls how long messages stay hidden from consumers after delivery. AWS dead-letter behavior for SQS is configured on the queue through a redrive policy, not on the event source mapping. See the SQS queue resource page for queue-level configuration options.

Because the entire batch is retried on failure, make your handler idempotent — processing the same message twice should produce the same result. AWS SQS records include identifiers like messageId that you can use for deduplication if your processing semantics require it.

Retrying only the failed messages

Set reportBatchItemFailures: true when the handler reports which messages it could not process. The handler returns the IDs of those messages, and only they return to the queue; the rest of the batch is deleted.

events: [new SqsIntegration({ sqsQueueName: 'orderQueue', reportBatchItemFailures: true })]
export default async (event: { Records: Array<{ messageId: string; body: string }> }) => {
  const batchItemFailures: Array<{ itemIdentifier: string }> = [];
  for (const record of event.Records) {
    try {
      await saveOrder(JSON.parse(record.body));
    } catch {
      batchItemFailures.push({ itemIdentifier: record.messageId });
    }
  }
  return { batchItemFailures };
};

Turn it on only for handlers that return this shape. With the setting on, a handler that returns nothing tells Lambda that every message succeeded, so a failure it swallowed is lost.

Processing SQS messages

Your Lambda handler receives the standard AWS Lambda SQS event — an object with a Records array. Each record contains the message body as a string, plus metadata like messageId and attributes.

export default async (event: { Records: Array<{ messageId: string; body: string }> }) => {
  for (const record of event.Records) {
    const order = JSON.parse(record.body);
    console.info(`Processing order ${record.messageId}:`, order);
    await saveOrder(order);
  }
};

If your producer sends JSON, parse record.body in the handler. If it sends plain text, use the string directly. The number of records in event.Records is up to batchSize, and a batch may contain fewer records when the batching window expires or the 6 MB payload limit is reached. For full details on the SQS event structure, see the AWS Lambda with SQS documentation.

API reference

SqsIntegrationProps
Click a property in the tree to see its description, default value, and full type.

SQS Events FAQ

Can I attach multiple Lambda functions to the same SQS queue?

No. Each standard SQS queue should have exactly one consumer. When a message is delivered to a consumer, it becomes invisible to other consumers for the duration of the visibility timeout. If multiple services need the same message, use an SNS topic or EventBridge event bus to fan out to separate queues — one per consumer.

What happens when my Lambda function fails to process a message?

By default, AWS returns the entire batch to the queue; with reportBatchItemFailures, only the messages your handler reports as failed. After the visibility timeout expires, the messages become available for redelivery. SqsIntegration does not expose retry or dead-letter properties. AWS dead-letter behavior is configured on the queue through a redrive policy, not on the event source mapping. See the SQS queue resource page for queue-level configuration options. Because the whole batch is replayed, make your handler idempotent.

How do FIFO queues work with Lambda triggers?

If the referenced queue is FIFO, SqsIntegration still references it through sqsQueueName or sqsQueueArn the same way as a standard queue. FIFO ordering and deduplication are SQS queue-level settings — the SqsIntegration configuration is identical for both queue types. Lambda handlers should still be idempotent because SQS event processing can redeliver messages. See the SQS queue resource page for queue configuration.

How much does SQS cost?

AWS SQS uses a request-based pricing model, with standard queues priced lower than FIFO queues and rates varying by region. AWS includes a free tier for SQS. For current rates and free-tier details, see AWS SQS pricing. For most Lambda-triggered workloads, SQS costs are negligible compared to Lambda execution costs.

When should I use SQS instead of SNS or EventBridge?

Use SQS when you need a durable work queue with one consumer that processes messages at its own pace — order processing, background jobs, traffic buffering. Use SNS when you need pub/sub fan-out: one message delivered to multiple subscribers at once. Use EventBridge when you need content-based routing — filtering events by field values and routing them to different targets without code. A common pattern combines them — SNS or EventBridge fans out to multiple SQS queues, each with its own consumer Lambda.

What is the maximum message size for SQS?

AWS SQS supports messages up to 256 KB. For larger payloads, store the data in an S3 bucket and send the S3 object key as the message body. Your consumer Lambda reads the full payload from S3 using that key. This pattern keeps queue throughput high while supporting arbitrarily large data.

How do I tell whether my queue is falling behind?

Watch the CloudWatch SQS metrics ApproximateNumberOfMessagesVisible (backlog depth) and ApproximateAgeOfOldestMessage (processing lag) — a growing backlog or rising age means your consumer can't keep up, so raise batchSize or increase Lambda concurrency. Configure alarms on these metrics to get alerted, and use stacktape logs to inspect handler errors during message processing.