Build event-driven systems on AWS with SQS, SNS, EventBridge and Kinesis: fan-out, DLQs, idempotent consumers and queue-based scaling.
A food-delivery marketplace takes 50,000 orders a minute during a big match. Each order triggers seven actions: fraud check, restaurant notification, delivery assignment, payment capture, inventory update, email and analytics. If the Order Service calls all seven directly, one slow dependency stalls every checkout behind it. (This is an illustrative scenario, not any company's real design.)
An event-driven design inverts that. The Order Service records the order, publishes one event and returns. Each downstream service consumes the event at its own pace, scales on its own load and fails without affecting the others.
When Service A calls Service B directly, A inherits B's latency, availability and capacity limits. Chain four calls of 150 to 400 ms and the user waits about a second, and any one failure fails the whole request.
Synchronous: Order -> Fraud (300 ms) -> Restaurant (200 ms) -> Email (150 ms) -> Analytics (400 ms) User waits about 1,050 ms; any failure breaks the chain. Event-driven: Order -> publish event (about 10 ms) -> respond to user Consumers process in parallel, off the critical path.The trade-off is eventual consistency. The user sees "order placed" before every consumer has finished, so design the user experience and the data model for that.
Publish to an SNS topic and subscribe one SQS queue per consumer, each with its own dead letter queue. SNS handles the one-to-many delivery, and SQS provides the buffer, retries and failure isolation.
The CloudFormation below defines the topic, one filtered subscription, the queue, its DLQ and the policy that lets SNS write to the queue. That policy is the step most people forget.
Resources: OrderTopic: Type: AWS::SNS::Topic Properties: TopicName: order-events FraudDlq: Type: AWS::SQS::Queue Properties: MessageRetentionPeriod: 1209600 FraudQueue: Type: AWS::SQS::Queue Properties: VisibilityTimeout: 180 ReceiveMessageWaitTimeSeconds: 20 RedrivePolicy: deadLetterTargetArn: !GetAtt FraudDlq.Arn maxReceiveCount: 5 FraudQueuePolicy: Type: AWS::SQS::QueuePolicy Properties: Queues: [!Ref FraudQueue] PolicyDocument: Statement: - Effect: Allow Principal: {Service: sns.amazonaws.com} Action: sqs:SendMessage Resource: !GetAtt FraudQueue.Arn Condition: ArnEquals: aws:SourceArn: !Ref OrderTopic FraudSubscription: Type: AWS::SNS::Subscription Properties: TopicArn: !Ref OrderTopic Protocol: sqs Endpoint: !GetAtt FraudQueue.Arn RawMessageDelivery: true FilterPolicy: order_value: [{numeric: [">=", 2000]}]The filter policy sends only orders worth 2,000 or more to the fraud queue, so the fraud team's consumer never sees low-value traffic. Filters apply to message attributes by default, so publish order_value as a numeric attribute (or set FilterPolicyScope to MessageBody).
Match the queue's timers to the consumer's runtime, and cap concurrency to protect your database. Three settings do most of the work:
ReceiveMessageWaitTimeSeconds=20 on every queue, which cuts empty receives.Wire up Lambda with partial batch responses so one bad message does not retry the whole batch:
aws lambda create-event-source-mapping \ --function-name fraud-check \ --event-source-arn "$FRAUD_QUEUE_ARN" \ --batch-size 10 \ --function-response-types ReportBatchItemFailures \ --scaling-config MaximumConcurrency=20MaximumConcurrency limits parallel invocations, which stops a queue backlog from overwhelming a database during recovery. Your handler must return the IDs of failed messages in batchItemFailures for partial responses to work.
Use FIFO only when processing order changes correctness, such as applying ledger entries to the same account. FIFO guarantees order within a Message Group ID and offers a five-minute deduplication window.
aws sqs create-queue \ --queue-name ledger-entries.fifo \ --attributes FifoQueue=true,ContentBasedDeduplication=truePick a group ID with many distinct values, such as the account ID. One shared group ID turns the whole queue into a single-lane road.
Record a unique key for each processed event and skip duplicates. Standard SQS is at-least-once, so duplicates are normal operation, not an edge case.
import boto3from botocore.exceptions import ClientError table = boto3.resource("dynamodb").Table("processed-events") def already_done(event_id): try: table.put_item( Item={"pk": event_id, "ttl": 1735689600}, ConditionExpression="attribute_not_exists(pk)", ) return False except ClientError as e: code = e.response["Error"]["Code"] if code == "ConditionalCheckFailedException": return True raiseUse a TTL so the table does not grow forever. In a strict system, write the key and the business change in one transaction, or use the Powertools for AWS Lambda idempotency utility.
Use the transactional outbox pattern. Writing to your database and publishing an event are two separate operations, and a crash between them either loses the event or publishes one for an order that was never saved.
Write the event to an outbox table in the same transaction as the order. A small relay (a DynamoDB Streams trigger or a poller) then publishes outbox rows to SNS or EventBridge and marks them sent. Combined with idempotent consumers, this gives you reliable delivery without distributed transactions.
Use EventBridge for routing events by content to many targets, for reacting to AWS service events and for scheduled work. It supports content-based rules, schema discovery, and archive and replay of past events.
A rule that reacts to EC2 terminations looks like this:
aws events put-rule \ --name detect-ec2-termination \ --event-pattern '{ "source": ["aws.ec2"], "detail-type": ["EC2 Instance State-change Notification"], "detail": {"state": ["terminated"]} }'Auto Scaling scale-in also terminates instances, so filter further in the target or use Auto Scaling events for intentional changes. For application events, publish with put-events from your service using a custom bus and a stable source name.
For scheduled work, prefer EventBridge Scheduler over rule-based cron. It supports time zones, so a 2 AM IST job needs no UTC arithmetic:
aws scheduler create-schedule \ --name nightly-cleanup \ --schedule-expression "cron(0 2 * * ? *)" \ --schedule-expression-timezone "Asia/Kolkata" \ --flexible-time-window Mode=OFF \ --target "Arn=$FN_ARN,RoleArn=$ROLE_ARN"Choose Kinesis Data Streams when you need ordered, high-volume streams that several consumers read independently, with replay. Clickstreams, device telemetry and market ticks are typical.
Each shard accepts up to 1 MB per second or 1,000 records per second for writes and supplies 2 MB per second for reads, so 10 shards ingest up to 10 MB per second. Retention defaults to 24 hours and extends to 365 days. Amazon Data Firehose (formerly Kinesis Data Firehose) can deliver the stream to S3 for archiving with no consumer code. On-demand capacity mode removes shard planning if your traffic is unpredictable.
Scale on backlog per worker, not on raw queue depth. Alarms on a depth threshold react to queue size, which says nothing about how quickly your workers can drain it.
Publish a custom metric of ApproximateNumberOfMessages divided by running instances, then use a target tracking policy. Choose the target as acceptable latency divided by average processing time per message: if each message takes 0.5 seconds and you accept 30 seconds of delay, target a backlog of 60 messages per instance. With Lambda consumers none of this is needed, because the event source mapping scales for you.
| Service | Persistence | Best for |
|---|---|---|
| SQS | Until consumed (up to 14 days) | Work queues, buffering |
| SNS + SQS | Via each queue | Fan-out to many services |
| EventBridge | Archive and replay optional | Routing, AWS events, schedules |
| Kinesis | 1 to 365 days | Ordered streams, replay |
SNS and EventBridge overlap for application fan-out. SNS gives higher throughput and simpler delivery to queues, while EventBridge gives richer filtering, schemas and many more native targets.
maxReceiveCount to 5 or more for Lambda, and alarm when DLQ depth exceeds zero.aws sqs start-message-move-task --source-arn "$DLQ_ARN".References and Further Reading
- Amazon SQS Developer Guide - Visibility timeout, FIFO and DLQ behaviour
- Amazon EventBridge User Guide - Rules, patterns, archive and replay
- Amazon SNS Message Filtering - Filter policy syntax
- Kinesis Data Streams FAQs - Limits and comparison with SQS
SNS retries delivery only for a bounded time and keeps no buffer for a slow or broken subscriber. Giving each consumer its own SQS queue adds durable storage, independent retry and a per-consumer dead letter queue, so one failing service never loses or blocks events for the others.
Set the visibility timeout to at least six times the function timeout, plus any batching window. Set maxReceiveCount to 5 or more on the source queue, because Lambda throttling can consume receives and send healthy messages to the DLQ too early.
When you only need at-least-once delivery and idempotent handlers. FIFO preserves order within a Message Group ID, so one hot group serialises work and limits throughput. Use many distinct group IDs (for example one per account) and standard queues wherever order does not affect correctness.
No. EventBridge routes discrete events to targets by rule and offers archive and replay, but it is not built for sustained high-throughput ordered streams. Kinesis Data Streams gives ordered shards, multiple concurrent consumers and retention of up to 365 days.
Standard queues deliver at least once, and retries or visibility timeouts can process a message twice. Store an idempotency key (for example the event ID) with a conditional write in DynamoDB before applying side effects, or use the Powertools for AWS Lambda idempotency utility.
Discussion0