Serverless: event-driven patterns you can ship to production
Production-ready event-driven patterns on AWS: fan-out, load levelling, orchestration vs choreography, sagas, the transactional outbox, idempotency, anti-corruption layers, claim check, event design, and observability.
Part 9 of the Serverless series.
The previous posts covered the services. This one covers how to combine them into systems that survive real traffic, real failures and real change. Each pattern below has a problem, an AWS shape, and the trap to avoid.
Many of these patterns are implemented in The Better Store, my open-source ecommerce demo built with domain-driven design (DDD) and microservices on AWS. Where it helps, I point to where you can see the pattern in a real system.
1. Fan-out
Problem: one thing happened, and several independent parts of the system must react.
Shape: publish one event to EventBridge (or SNS), with a rule (or subscription) per consumer, each delivering to its own SQS queue in front of its Lambda function.
OrderPlaced ──► EventBridge ──┬──► SQS ──► send-confirmation
├──► SQS ──► reserve-stock
└──► SQS ──► update-analytics
Why the queues? Each consumer gets its own buffer, retries and dead-letter queue. A slow analytics consumer can’t hold up confirmations.
2. Queue-based load levelling
Problem: traffic arrives in bursts, but a downstream system (a database, a third-party API with rate limits) can’t take bursts.
Shape: API → SQS → Lambda, with maximum concurrency on the
event source to cap throughput. API Gateway can write to SQS directly and return 202 Accepted
immediately.
Trap: clients now don’t get the result in the response. Give them a status endpoint to poll, or push the result with AppSync Events.
3. Orchestration vs choreography
- Choreography: services react to each other’s events with no central coordinator. Loosely coupled and easy to extend, but the end-to-end flow exists only in your head (and your traces).
- Orchestration: a coordinator, usually Step Functions, calls each step in order. The flow is explicit and visible, but the coordinator knows about every participant.
Rule of thumb: choreography between bounded contexts (Orders, Fulfilment, Billing), orchestration within one bounded context’s multi-step process.
A bounded context is DDD’s term for a part of the system with its own model and language: “order” means something different to Fulfilment than it does to Billing. Bounded contexts make natural service boundaries, and events are how they talk to each other without sharing a database. Finding them is a design exercise, not a technical one; The Better Store, Part 2 walks through it with Event Storming and a context map.
4. Saga: undoing work across services
Problem: a business transaction spans services that can’t share a database transaction. Payment succeeded, but shipping failed.
Shape: a Step Functions workflow where each step has a compensating action, triggered from a
Catch: refund the payment, release the stock, mark the order cancelled.
Trap: compensations can fail too. Give them retries, make them idempotent, and alarm when one ends in a failed state.
In The Better Store: Part 4 applies the saga pattern, with compensating transactions, to the “order purchased” flow across its services.
5. Transactional outbox
Problem: you need to update the database and publish an event. If you write to DynamoDB and
then call PutEvents, a crash in between leaves them inconsistent.
Shape: write only to DynamoDB, and let DynamoDB Streams publish the change. EventBridge Pipes connects the stream to a bus, with filtering and transformation, and no code:
Lambda ──► DynamoDB ──► Streams ──► EventBridge Pipe ──► Event bus
(one write) (filter, reshape)
The event is published if, and only if, the write succeeded.
6. Idempotent consumers
Problem: SQS, SNS, EventBridge and Lambda async invocations are all at-least-once. Your handler will see duplicates.
Shape: give every event a unique ID, and record which IDs you’ve processed, using a DynamoDB conditional write so only the first attempt wins. Powertools for AWS Lambda does this with a decorator:
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer, idempotent_function,
)
persistence = DynamoDBPersistenceLayer(table_name="idempotency")
@idempotent_function(data_keyword_argument="order", persistence_store=persistence)
def charge(order: dict):
...
In The Better Store: idempotent consumers, alongside dead-letter queues, are part of the microservice pattern set applied in Part 4.
7. Anti-corruption layer at the edge
Problem: an external system (a payment provider, a partner, a legacy app) sends you events in its model, with its names, its formats and its quirks. If those leak into your services, every change on their side becomes a change on yours.
Shape: receive external events at the edge and translate them into your own domain events
before anything else sees them. A cheap, robust AWS shape is API Gateway writing the webhook
straight into SQS (no Lambda in the request path, so nothing is lost if processing fails), and a
consumer that validates, translates and publishes your own event, such as PaymentReceived.
Stripe webhook ──► API Gateway ──► SQS ──► translate ──► EventBridge: PaymentReceived
(direct integration) (Lambda)
In The Better Store: Stripe payment webhooks arrive through API Gateway directly into SQS, as described in Part 4.
Trap: verify the webhook’s signature before trusting it, and remember the provider can send the same webhook more than once.
8. Claim check
Problem: the payload is bigger than the service allows: 256 KB for SNS, EventBridge and Step Functions, 1 MiB for SQS.
Shape: store the payload in S3 and send an event containing its key. Consumers fetch it when they need it. Use an S3 lifecycle rule to clean up.
9. Retries, backoff and dead letters
Every failure path needs an end:
- Retries with exponential backoff and jitter for transient errors. The AWS SDKs do this by default; don’t add another retry loop around them.
- Dead-letter queues (or failure destinations) for what still fails.
- An alarm on every DLQ, and a documented redrive process.
A message sitting silently in a DLQ is an outage nobody knows about.
10. Design events as contracts
Once another team consumes your events, they’re a public API. In DDD terms, they’re a Published Language: a documented, shared model that bounded contexts use to integrate, independent of each service’s internal model. So:
- Use clear, past-tense names:
OrderPlaced, notProcessOrder. - Include an event ID, a timestamp and a version.
- Add fields, don’t change or remove them. For breaking changes, publish a new version alongside the old one until consumers move.
- Decide between thin events (IDs, and consumers fetch details) and fat events (the data consumers need). Fat events reduce coupling on reads; thin events avoid leaking data.
- Document them, for example in the EventBridge schema registry.
11. Observability
In an event-driven system, a single request becomes many invocations across many services. You need to be able to follow it:
- Structured JSON logs with a correlation ID passed in every event.
- Distributed tracing with AWS X-Ray or OpenTelemetry, which Powertools wires up.
- Alarms on symptoms: DLQ depth, queue age (
ApproximateAgeOfOldestMessage), Lambda errors and throttles, and failed Step Functions executions.
Good telemetry pays off when things go wrong. In my AWS DevOps Agent demo, I shipped a bug to The Better Store on purpose. Its alarms, logs and traces let an AI agent trace the failure to the exact commit in under four minutes.
A production checklist
- Every async consumer has a DLQ or failure destination, with an alarm
- Every consumer is idempotent
- Concurrency is capped in front of anything that can’t scale
- Events carry an ID, a version and a correlation ID
- Database changes publish events through an outbox, not a second call
- External events are translated into your own domain events at the edge
- Payloads over the size limits use a claim check
- Log retention is set, and you can trace a request end to end
- It’s all deployed as code, with SAM, CDK or Terraform
That’s the Serverless series. Next up: Infrastructure as Code, deploying all of this repeatably with CloudFormation, SAM and the CDK.
← Back to the Serverless overview.
← Series overview