Event-Driven Architecture: SQS, SNS, EventBridge & Kinesis
System Design · Distributed Systems · Advanced · 24 min
Choose between queues, pub/sub, an event bus and streams on AWS, and build consumers that survive retries, poison messages and duplicate delivery.
A restaurant kitchen. The waiter shouts one order (SNS), copies land on the grill, salad and dessert rails (SQS queues), each station works at its own pace, and a ticket that keeps failing goes on a 'problem' spike (DLQ) for the manager.
The idea in everyday words
A queue is a to-do pile: whoever is free grabs the top task, and once it is done it is thrown away. Pub/sub is a group chat: one message, everyone subscribed gets a copy. An event bus is a mail room that reads each envelope and routes it by rules. A stream is a security camera recording: many people can rewind and watch the same footage, in order, at their own speed.
Four shapes: queue, pub/sub, event bus, stream
Event-driven = services announce facts ("OrderPlaced") instead of calling each other directly. The sender doesn't wait for, or even know about, the receivers. That is decoupling: one slow or broken consumer can't take the producer down.
| Shape | AWS service | Delivery | Each message is… | Pick it when |
|---|---|---|---|---|
| Queue | SQS | consumers pull | processed by ONE consumer, then deleted | spreading work over workers, absorbing spikes |
| Pub/sub | SNS | pushed to subscribers | copied to EVERY subscriber | one event, many independent reactions (fan-out) |
| Event bus | EventBridge | pushed by rules | routed by content to matching targets | many event types, routing by fields, SaaS / AWS events, schedules |
| Stream | Kinesis Data Streams (or MSK for Kafka) | consumers read a log | kept for a retention period, readable by many, replayable | ordered high-volume data, replay, analytics |
A classic combo: SNS → SQS fan-out. SNS gives every team a copy; each team's own SQS queue buffers it, retries it and isolates failures. A broken billing consumer only fills the billing queue.
Tiny example: OrderPlaced → SNS topic → queues for email, billing and analytics. Email sends a receipt, billing charges the card, analytics counts revenue. Adding "loyalty points" later = one new subscription, zero changes to the order service.
SQS in depth: visibility timeout, DLQs, FIFO
Lifecycle of one SQS message:
- A consumer calls ReceiveMessage (use long polling so empty polls wait instead of spinning).
- The message becomes invisible for the visibility timeout (say 30 s). Nobody else sees it.
- Success → the consumer calls DeleteMessage. Delete is the "ack".
- Crash or error → no delete. When the timeout expires the message is visible again and its ApproximateReceiveCount goes up.
Visibility timeout too short → a slow but healthy job reappears and runs twice. Too long → a crashed job waits a long time before retry. Set it above your worst normal processing time.
Dead-letter queue (DLQ): a redrive policy with maxReceiveCount. A message gets at most maxReceiveCount receives. If the receive with number maxReceiveCount also fails, the next time it would be delivered its receive count would exceed the limit, so SQS moves it to the DLQ instead. Example: maxReceiveCount = 3 means 3 tries, then the DLQ. This stops a poison message (one that always fails) from looping forever. Alarm on the DLQ's depth, fix the bug, then use DLQ redrive to move messages back.
| Standard queue | FIFO queue | |
|---|---|---|
| Ordering | best effort | strict, per message group id |
| Delivery | at least once (rare duplicates) | duplicate sends are dropped within the 5-minute deduplication window |
| Throughput | very high | lower (see the SQS quotas page) |
The FIFO "exactly-once" fine print. AWS calls FIFO "exactly-once processing", but deduplication works on the send side: the same deduplication id sent twice within the window is stored once. On the receive side nothing changes: if your consumer does the side effect (charges the card) and then times out or crashes before DeleteMessage, the message becomes visible again and is delivered again. FIFO consumers still need idempotency, the same as standard ones.
import boto3, json
sqs = boto3.client("sqs")
resp = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=10, WaitTimeSeconds=20)
for m in resp.get("Messages", []):
handle(json.loads(m["Body"]))
sqs.delete_message(QueueUrl=url, ReceiptHandle=m["ReceiptHandle"])
With Lambda as the consumer, the event source mapping polls for you. Return partial batch failures (ReportBatchItemFailures) so one bad message doesn't make the whole batch retry.
SNS fan-out and EventBridge rules
SNS topics push to SQS, Lambda, HTTP endpoints, email and SMS. A subscription filter policy lets a subscriber receive only some messages (e.g. only "country": ["DE"]).
EventBridge is a smarter router. Producers put events on a bus; rules match on any field with an event pattern and send to targets (Lambda, SQS, Step Functions, another bus, API destinations):
{
"source": ["shop.orders"],
"detail-type": ["OrderPlaced"],
"detail": { "total": [{ "numeric": [">", 100] }] }
}
EventBridge also receives events from many AWS services and SaaS partners, has a schema registry, can archive and replay events, and EventBridge Scheduler runs cron-style jobs. EventBridge Pipes connect a source (SQS, Kinesis, DynamoDB Streams) to a target with optional filtering and enrichment.
SNS or EventBridge? SNS for simple, very high-throughput fan-out to a known set of subscribers. EventBridge when you have many event types, need content-based routing across teams or accounts, or want replay.
Kinesis: shards and ordering
A Kinesis data stream is an append-only log split into shards. Each record has a partition key; its hash picks the shard. Order is guaranteed only within a shard, so all events for one order (same key) stay in order.
- Each shard has a fixed write and read throughput ceiling (see the Kinesis docs). More traffic = more shards, or use on-demand capacity mode.
- Records stay for the retention period, so several consumers can read the same data independently and replay from an earlier point.
- Consumers track their position (a checkpoint). The Kinesis Client Library stores leases and checkpoints in a DynamoDB table.
- A low-cardinality partition key creates a hot shard, the same problem as a hot DynamoDB partition.
Queue vs stream in one line: a queue deletes a message once one worker handles it; a stream keeps records so many readers can process them in order.
At-least-once delivery and idempotency
SQS standard, SNS, EventBridge, Kinesis and Lambda retries all deliver at least once, and even a FIFO queue redelivers after a visibility timeout. Duplicates are rare but normal. So every consumer must be idempotent: processing the same event twice has the same effect as once.
How:
- Give every event a unique idempotency key (event id, order id).
- Before acting, record the key with a conditional write: DynamoDB
put_item(..., ConditionExpression="attribute_not_exists(pk)"). If it fails, you already did this one: skip and delete. - Use natural idempotence when possible: "set status = PAID" is safe to repeat; "balance += 10" is not.
- Careful with "record first, act second": if you crash after recording but before acting, a retry would skip work that never happened. Store a status (IN_PROGRESS with an expiry, then COMPLETED with the result) so a retry after the expiry can try again. Never do "check, then act, then mark" without a condition: two workers can both pass the check.
- Powertools for AWS Lambda has an idempotency utility that does this pattern with DynamoDB.
Publishing reliably: writing to your database and then publishing can fail halfway. The outbox pattern writes the event into the same database transaction, then a separate process (or DynamoDB Streams) publishes it.
Other clouds: GCP Pub/Sub and Eventarc; Azure Service Bus, Event Grid and Event Hubs; open source RabbitMQ, Apache Kafka, NATS.
Go deeper (senior / staff)
Failure modes worth naming.
- Visibility timeout vs Lambda timeout: if the queue's visibility timeout is shorter than the function's run time, healthy messages reappear and run twice. AWS guidance is to set it to several times the function timeout (check the Lambda docs).
- Retry storms: a dependency goes down, every message fails, and consumers hammer it. Cap consumer concurrency (the SQS event source mapping has a maximum concurrency setting), back off, and let the queue absorb the backlog. That is the whole point of the queue.
- Head-of-line blocking: in a FIFO message group, or a Kinesis shard, one poison record stops everything behind it. For Kinesis with Lambda, use bisect-on-error, a maximum retry count and an on-failure destination; alarm on IteratorAge.
Multi-region. SQS, SNS and Kinesis are Regional. For Regional failover of event ingestion, EventBridge global endpoints fail over between a primary and secondary Region using a Route 53 health check, with event replication between the buses; your consumers in both Regions must be idempotent because events can be seen twice around a failover.
Cost reasoning without numbers.
- SQS bills per request: batch up to 10 messages per call and use long polling so empty polls do not cost you.
- Lambda bills per invocation and duration: larger batches and a batching window cut invocations, at the price of latency.
- Kinesis provisioned mode bills per shard-hour whether you use it or not; it wins for steady high volume, while on-demand or SQS fits spiky traffic.
- Large payloads: store the body in S3 and send a pointer (the claim-check pattern) instead of paying to move big messages through every hop.
Trade-off to say out loud: ordering costs throughput. Order only per key that needs it, and stay idempotent anyway.
Step by step
- Publish:
Order 42 → one OrderPlaced message to the SNS topic order-events.
- Fan-out:
SNS copies it into 3 SQS queues: email, analytics, billing. Each queue now has 1 message.
- Happy consumers:
Email and analytics workers receive, process and delete. Their queues are empty.
- Billing fails:
Billing receives (count 1), throws, does not delete. 30 s later the message is visible again. Count 2: fails. Count 3: fails. maxReceiveCount = 3.
- Dead-letter:
The next receive would exceed 3, so SQS moves the message to billing-dlq. A CloudWatch alarm on DLQ depth > 0 pages on-call.
- Fix and redrive:
Deploy the fix, start a DLQ redrive back to the billing queue. Count 1: success, delete. Total receives for this message: 4.
- Duplicate case:
A worker charges the card but dies before delete. The message comes back; the idempotency key evt-42 already exists, so the second worker skips the charge.
Code example
# SNS fan-out to two queues, at-least-once delivery, idempotent consumers.
from collections import deque
queues = {"email": deque(), "billing": deque()}
def publish(event): # SNS: copy to every subscriber
for q in queues.values():
q.append(event)
publish({"id": "evt-1", "order": 41, "amount": 30})
publish({"id": "evt-2", "order": 42, "amount": 25})
queues["billing"].append({"id": "evt-1", "order": 41, "amount": 30}) # duplicate!
processed = set() # stands in for a DynamoDB table
charged = 0
while queues["billing"]:
e = queues["billing"].popleft()
if e["id"] in processed: # conditional put would fail here
print("skip duplicate", e["id"])
continue
processed.add(e["id"])
charged += e["amount"]
print("charged order", e["order"], "amount", e["amount"])
print("total charged:", charged)
print("emails waiting:", len(queues["email"]))Complexity
- Time: O(M · R): each of M messages is received at most R = max_receive_count times
- Space: O(M) for the queue and the receive counters
Interview tips
Name the shape before the service: 'this is fan-out, so SNS to per-team SQS queues' or 'this needs ordered replay, so Kinesis'.
Always say 'at-least-once, so consumers are idempotent, keyed by event id with a conditional write'.
Explain visibility timeout and DLQ together: retries happen by the message reappearing; maxReceiveCount bounds them.
Ordering: SQS FIFO per message group or Kinesis per partition key. Ask what actually needs ordering to avoid a throughput bottleneck.
Mention the outbox pattern for reliably publishing an event together with a database write.
Challenge: SQS Redrive Simulator
Write simulate_queue(messages, max_receive_count).
Each message is {"id": str, "fails": int}: it fails its first fails receives and succeeds on the next one. fails == -1 means it always fails (a poison message).
Simulate one consumer reading a queue in arrival order, starting with the messages in the order given. Failed messages use standard-queue retry behaviour: a failed message goes to the back of the line, like a message reappearing after its visibility timeout. (A real SQS FIFO queue would instead hold back the rest of that message's group until it succeeds or moves to the DLQ.)
- Take the message at the front. Increase its receive count and the total
receives. - If this receive succeeds (
fails != -1and receive count >fails), add its id toprocessed. - Otherwise, if its receive count has reached
max_receive_count, add its id todlq. - Otherwise put it at the back of the queue.
Return {"processed": [...], "dlq": [...], "receives": int} (ids in the order they finished).
Examples:
simulate_queue([{"id": "m1", "fails": 0}, {"id": "m2", "fails": 1}, {"id": "m3", "fails": -1}], 3)→{"processed": ["m1", "m2"], "dlq": ["m3"], "receives": 6}- The same messages with
max_receive_count = 1→{"processed": ["m1"], "dlq": ["m2", "m3"], "receives": 3}. m2 fails its only allowed receive, so it goes to the DLQ. Check both examples: two small off-by-one mistakes can cancel out on the first one.
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Amazon SQS dead-letter queues
- Amazon SQS visibility timeout
- Fanout to SQS queues with SNS
- Amazon EventBridge rules
More in Distributed Systems
- CAP, PACELC & Consistency
- Replication, Failover & Sharding
- Monolith vs Microservices
- Message Queues & Rate Limiting
Previous: Message Queues & Rate Limiting · Next: Reliability: SLOs, Retries & Circuit Breakers