Skip to content

Lesson 15 of 30Modern AWS

Queues and Events

Decouple services with SQS, SNS, EventBridge, Kinesis and Step Functions, and pick the right one for each job.

16 min read0/3 questions

When a user places an order, a lot has to happen: charge the card, reserve stock, send an email, update analytics. Doing all of it inside one HTTP request makes the request slow and fragile: if the email provider is down, the order fails. Queues and events let the request do the one essential thing and hand the rest off reliably. On AWS that means five services, and interviewers love asking which one you would use.

SQS: a queue of work

Amazon SQS (Simple Queue Service) is a fully managed message queue. Producers SendMessage; consumers ReceiveMessage, process, then DeleteMessage. Messages wait in the queue (up to 14 days) until someone handles them, so a slow or crashed consumer never loses work.

Two queue types:

StandardFIFO
OrderingBest effortStrict, per message group ID
DeliveryAt least once (rare duplicates)Exactly-once processing within a 5-minute dedup window
ThroughputNearly unlimitedHigh, but limited per group (higher with high-throughput mode)
NameordersMust end in .fifo: orders.fifo

Because standard queues can deliver a message twice, consumers should be idempotent: processing the same message twice has the same effect as once (for example, "insert payment if this order ID has not been charged").

Visibility timeout and dead-letter queues

When a consumer receives a message, SQS does not delete it. It hides it for the visibility timeout (default 30 seconds). If the consumer deletes it in time, done. If the consumer crashes, the timeout expires and the message reappears for another consumer. That is how SQS guarantees work is not lost.

If a message keeps failing (a bug, bad data), it would loop forever. A redrive policy moves it to a dead-letter queue (DLQ) after maxReceiveCount attempts, where you can inspect it, alarm on it, and redrive it once fixed.

Pythonsqs_sim.py
from collections import deque VISIBILITY = 30MAX_RECEIVES = 3 queue = deque([{"id": "order-1", "body": "ok", "receives": 0}, {"id": "order-2", "body": "bad-data", "receives": 0}])dlq, done = [], []invisible = [] # (visible_again_at, message)now = 0 def process(msg): if msg["body"] == "bad-data": raise ValueError("cannot parse") while queue or invisible: for item in [i for i in invisible if i[0] <= now]: invisible.remove(item) queue.append(item[1]) if not queue: now += VISIBILITY continue msg = queue.popleft() msg["receives"] += 1 if msg["receives"] > MAX_RECEIVES: dlq.append(msg["id"]) continue try: process(msg) done.append(msg["id"]) # DeleteMessage except ValueError: invisible.append((now + VISIBILITY, msg)) # not deleted: reappears later print(f"t={now}s {msg['id']} failed (receive {msg['receives']})") print("done:", done)print("dead-letter queue:", dlq)
Output
Press Run (⌘ Enter) to see what happens.

Set the visibility timeout longer than your worst-case processing time (AWS suggests six times the Lambda timeout when Lambda consumes the queue). Too short, and a slow-but-working consumer's message reappears and gets processed twice.

Quick check
Your consumer takes about 90 seconds per message. The queue's visibility timeout is 30 seconds. What happens?
Need a nudge? A hint rules out a wrong answer.

SNS: fan out to many subscribers

Amazon SNS (Simple Notification Service) is pub/sub: a publisher sends one message to a topic, and SNS pushes a copy to every subscriber: SQS queues, Lambda functions, HTTPS endpoints, email, SMS, mobile push.

The classic pattern is SNS to SQS fan-out: one OrderPlaced topic, with a separate queue for each consumer (billing, email, analytics). Each consumer gets its own copy, processes at its own pace, and retries independently. Subscription filter policies let a queue receive only matching messages, like {"country": ["GB"]}.

EventBridge: route events by content

Amazon EventBridge is an event bus with content-based routing. Producers put events onto a bus; rules match events by pattern and send them to targets (Lambda, SQS, Step Functions, another bus, an API destination). AWS services also emit events to the default bus ("EC2 instance stopped", "ECS task failed"), and SaaS partners can send events in.

rule pattern: big orders from the shop
{
  "source": ["com.acme.shop"],
  "detail-type": ["OrderPlaced"],
  "detail": {
    "total": [{ "numeric": [">=", 500] }],
    "country": ["GB", "IE"]
  }
}
publish from your API
import json, boto3
 
events = boto3.client("events")
events.put_events(Entries=[{
    "EventBusName": "shop",
    "Source": "com.acme.shop",
    "DetailType": "OrderPlaced",
    "Detail": json.dumps({"orderId": "A17", "total": 640, "country": "GB"}),
}])

EventBridge Scheduler is the modern way to run things on a schedule (cron(0 3 * * ? *) or one-off at a time), with time zones and retries, replacing cron boxes.

The difference from SNS: SNS is "send this to everyone subscribed to this topic"; EventBridge is "look at what this event says and route it to whoever cares", with many AWS integrations, archives and replay.

Kinesis: ordered streams

Amazon Kinesis Data Streams is for streams: a high-volume, ordered log of records that many consumers can read and re-read (retention from 24 hours up to a year). Records with the same partition key go to the same shard and stay in order. Think clickstreams, IoT telemetry, app logs feeding analytics. Amazon Data Firehose (formerly Kinesis Data Firehose) loads streaming data into S3, Redshift or OpenSearch with no consumer code. Amazon MSK is the managed Kafka alternative.

A queue message is work that disappears once done. A stream record is history that stays for every reader.

Step Functions: workflows with steps

AWS Step Functions runs state machines: a workflow of steps with branching, retries, timeouts, parallel branches and waits, defined in JSON (Amazon States Language) or drawn in Workflow Studio. Use it when a process has several steps that must happen in order with error handling, like "charge card, then reserve stock, and if reserving fails, refund".

order workflow (trimmed)
{
  "StartAt": "ChargeCard",
  "States": {
    "ChargeCard": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": { "FunctionName": "charge-card", "Payload.$": "$" },
      "Retry": [{ "ErrorEquals": ["States.TaskFailed"], "MaxAttempts": 3, "BackoffRate": 2 }],
      "Next": "ReserveStock"
    },
    "ReserveStock": {
      "Type": "Task",
      "Resource": "arn:aws:states:::lambda:invoke",
      "Parameters": { "FunctionName": "reserve-stock", "Payload.$": "$" },
      "Catch": [{ "ErrorEquals": ["States.ALL"], "Next": "Refund" }],
      "End": true
    },
    "Refund": { "Type": "Task", "Resource": "arn:aws:states:::lambda:invoke", "Parameters": { "FunctionName": "refund", "Payload.$": "$" }, "End": true }
  }
}

An order pipeline, end to end

Order processing with events and queues
ShopperShopperOrders API: ECSOrders APIECSOrders DBOrders DBEventBridge: shop busEventBridgeshop busStep Functions: payment flowStep Functionspayment flowSQS emails: + DLQSQS emails+ DLQData Firehose: to S3Data Firehoseto S3PaymentsPaymentsEmail worker: LambdaEmail workerLambdaS3 data lakeS3 data lakePOST /ordersINSERTOrderPlacedrulerulerulepoll

The API saves the order and returns 202 Accepted quickly. That is the only synchronous work.

1/5

Choosing between them

SQSSNSEventBridgeKinesis Data Streams
ModelQueue (pull)Pub/sub topic (push)Event bus with rules (push)Ordered stream (pull, replayable)
Consumers per messageOneEvery subscriberEvery matching ruleEvery reader, independently
OrderingFIFO queues onlyFIFO topics onlyNoPer shard
Keeps messagesUp to 14 days, until deletedNo (delivers and forgets)Optional archive and replay24 hours to 1 year
Best forBuffering work, smoothing loadSimple fan-out, notificationsRouting by content, AWS/SaaS events, schedulesHigh-volume telemetry, analytics
Match the pairs0/5 matched

Match the need to the service.

Choose an item, then its match on the other side.
Quick check
Bank account events (deposit, withdraw) must be applied in order for each account, but different accounts can be processed in parallel. What do you use?
Need a nudge? A hint rules out a wrong answer.
Key terms
visibility timeout
How long a received SQS message stays hidden. If not deleted in time, it reappears.
dead-letter queue
Where messages go after failing maxReceiveCount times, for inspection and redrive.
idempotent consumer
Processing the same message twice has the same effect as once. Needed for at-least-once delivery.
fan-out
One published message delivered to many subscribers, like SNS to several SQS queues.
event bus
EventBridge's router: rules match events by content and send them to targets.
shard
A Kinesis partition. Records with the same partition key land on one shard, in order.