Amazon SQS and SNS
Amazon SQS (Simple Queue Service) and SNS (Simple Notification Service) are AWS's two oldest messaging services, and they're usually used together. SQS is a fully managed message queue: producers put messages in, workers take them out, process them and delete them. SNS is a fully managed pub/sub service: a publisher sends one message to a topic and SNS pushes a copy to every subscriber, which can be SQS queues, Lambda functions, HTTP endpoints, email, SMS or mobile push.
The properties that define them:
- Serverless: there are no brokers, partitions or clusters to size. You create a queue or topic with an API call and pay per request. A queue that receives nothing costs nothing; one that receives 50,000 messages per second just works.
- Per-message lifecycle (SQS): each message is received, processed and explicitly deleted. Messages that aren't deleted come back for another try, and messages that keep failing move to a dead-letter queue.
- Push fan-out (SNS): SNS delivers each message to every subscription, with optional filtering so each subscriber only gets what it cares about.
- At-least-once by default: standard queues and topics can deliver a message more than once and don't guarantee order. FIFO variants add ordering and deduplication at lower throughput.
- Durable across zones: messages are stored redundantly across several availability zones before the send call returns.
In interviews, SQS is the go-to answer for "we need a work queue" on AWS: background jobs, image processing, sending emails, webhook delivery, anything where a pool of workers handles independent tasks. SNS plus SQS is the standard way to fan one event out to several services. Interviewers will want to know how failures and retries work, what happens with duplicates, and why you picked a queue over Kafka. This post covers all of that.
SQS: The Core Concepts
Queue: a named, durable buffer of messages, identified by a URL. There are two types, standard and FIFO, covered below.
Message: a body of text (JSON is typical) up to 1 MiB in current limits (256 KB for many years), plus up to 10 message attributes. For bigger payloads, the usual pattern is to put the object in S3 and send a pointer; AWS's extended client libraries do this automatically.
Producer: anything that calls SendMessage (or SendMessageBatch, up to 10 messages per call).
Consumer: a worker that calls ReceiveMessage, processes what it gets, and calls DeleteMessage. Consumers pull from SQS; it never pushes to them (Lambda's SQS integration is AWS polling on your behalf).
The basic worker loop is short:
import boto3, json
sqs = boto3.client("sqs")
URL = "https://sqs.us-east-1.amazonaws.com/123456789012/thumbnails"
while True:
resp = sqs.receive_message(QueueUrl=URL, MaxNumberOfMessages=10,
WaitTimeSeconds=20, # long polling
VisibilityTimeout=120) # time we have to finish
for m in resp.get("Messages", []):
job = json.loads(m["Body"])
make_thumbnail(job["s3_key"]) # must be idempotent
sqs.delete_message(QueueUrl=URL, ReceiptHandle=m["ReceiptHandle"])
The Visibility Timeout
The visibility timeout is the most important idea in SQS, and the one interviewers ask about.
When a consumer receives a message, SQS doesn't delete it. It hides it from other consumers for the visibility timeout (30 seconds by default, up to 12 hours). Then one of two things happens:
- The consumer finishes and calls
DeleteMessagewith the message's receipt handle. The message is gone for good. - The consumer crashes, hangs or is too slow, and the timeout expires. The message becomes visible again and another consumer receives it.
This is how SQS achieves at-least-once processing without the consumer having to do anything clever: a message is only gone once someone explicitly says it's done. It also means a message can be processed twice. If a worker finishes the job but crashes before the delete, or the job takes longer than the timeout, a second worker gets it too.
So you set the visibility timeout comfortably above your normal processing time (a common rule is about six times the typical duration for Lambda consumers), and for long or variable jobs the worker calls ChangeMessageVisibility periodically to extend it, like a heartbeat.
The duplicate cases are the interview point: a worker that finishes but dies before deleting, or a job that outlives its visibility timeout. Both mean the next worker repeats the job. Make processing idempotent (a job ID with a "done" record, a conditional write, or an upsert) and say so before your interviewer asks.
Dead-Letter Queues
A message that fails every time (a malformed payload, a bug for one particular input) would otherwise bounce between workers forever. A redrive policy fixes that: after a message has been received maxReceiveCount times without being deleted, SQS moves it to a designated dead-letter queue (DLQ).
{
"deadLetterTargetArn": "arn:aws:sqs:us-east-1:123456789012:thumbnails-dlq",
"maxReceiveCount": 5
}
The DLQ is just another queue. You alarm on its depth, inspect the failed messages, fix the bug, and use DLQ redrive to move them back to the source queue for another try. Every production queue in your design should have one.
Other Features Worth Knowing
- Long polling:
WaitTimeSecondsup to 20 makesReceiveMessagewait until a message arrives instead of returning empty. It cuts cost and latency, and it's what you should use almost always. - Delay queues and message timers: delay delivery of every message in a queue, or of a single message, by up to 15 minutes. Useful for simple backoff, not for scheduling things days ahead.
- Retention: messages are kept for 4 days by default, configurable from 1 minute to 14 days. A message nobody processes within that window is deleted.
- In-flight limits: a standard queue can have on the order of 120,000 messages received but not yet deleted, and a FIFO queue about 20,000. Very large worker fleets with long timeouts can hit this.
- Batching: send, receive and delete all accept up to 10 messages per call. Batching cuts both cost and API calls by up to 10x.
- No priorities: SQS has no message priority. The usual answer is separate queues (
jobs-high,jobs-low) with workers that poll the high-priority queue first, or separate worker pools sized for each. - No per-tenant fairness: one noisy customer can fill a shared queue and delay everyone behind it. For multi-tenant job systems, shard heavy tenants onto their own queues, or use FIFO message groups per tenant so one tenant's backlog can't monopolise the workers.