What is the benefit of using SQS as an intermediary between SNS and Lambda?
Using an SQS queue as an intermediary between SNS and Lambda has several benefits:
- Batch processing – Lambda can read messages from the SQS queue in batches and invoke a single function to process multiple messages. This reduces the number of Lambda invocations and can optimize costs.
- Rate limiting – The SQS queue acts as a buffer and allows you to control how fast messages are processed by Lambda. This can prevent overloading Lambda if the SNS publish rate is high.
- Retries and reprocessing – If Lambda fails to process a message, that message remains in the SQS queue and can be retried. You can configure the number of retries. With SNS, failed messages are lost after a few retries.
- Persistence – Messages in SQS queues can persist for up to 14 days. This allows Lambda to process messages even if it is temporarily unavailable.
- Scaling – Lambda will automatically scale to match the number of messages in the SQS queue. This provides a self-scaling architecture.
- Latency – SQS introduces some latency as Lambda has to periodically poll the queue for new messages. However, this gives you more control over message processing.
- Ordering – SQS Standard queues provide FIFO message ordering which SNS does not provide. This ensures messages are processed in the order they were received.
In summary, using an SQS queue between SNS and Lambda gives you more control over message batching, rate limiting, retries, scaling and ordering. The trade-off is some additional latency and complexity. But for most use cases, the benefits outweigh the downsides.