AWS Builder Center
Building Resilient Event-Driven Architectures with AWS Lambda and Amazon EventBridge

Building Resilient Event-Driven Architectures with AWS Lambda and Amazon EventBridge

Learn how to decouple cloud microservices using Amazon EventBridge and AWS Lambda, featuring patterns for dead-letter queues, idempotent processing, and automated schema discovery.

As modern cloud systems scale, tightly coupled synchronous communication often creates bottlenecks, cascade failures, and deployment dependencies. Adopting an **event-driven architecture (EDA)** using **Amazon EventBridge** and **AWS Lambda** provides a scalable way to decouple microservices while improving resilience and agility.

## Why Event-Driven with EventBridge?

Traditional point-to-point REST integrations require the publisher to know where to send requests and handle timeouts if the consumer is temporarily unavailable. Amazon EventBridge acts as a central event bus that routes events based on declarative filtering rules:

* **Zero consumer awareness:** Publishers simply emit events to an event bus; they have no dependency on downstream consumers.
* **Content-based routing:** Filter rules inspect event payloads, routing only relevant events to specific Lambda functions or Step Functions workflows.
* **Schema registry:** Automatically discover, generate code bindings, and track changes to your JSON payloads.

## Core Architecture Components

1. **Custom Event Bus:** Serves as the central ingestion point for domain-specific business events (e.g., `OrderPlaced`, `PaymentProcessed`).
2. **EventBridge Rules:** Inspect attributes within the JSON event envelope (like `detail-type` or `source`) and trigger downstream targets.
3. **AWS Lambda Targets:** Serverless compute layers executing business logic asynchronously in response to matched events.
4. **Dead-Letter Queues (DLQs):** Amazon SQS queues configured on rules and Lambda functions to capture unprocessed events caused by downstream outages, throttling, or permission issues.

## Step-by-Step Implementation

### 1. Define the Custom Event Bus and DLQ

Using the AWS Cloud Development Kit (CDK) in TypeScript, start by provisioning a dedicated custom event bus alongside an SQS dead-letter queue to catch failed event deliveries:

```typescript
import * as cdk from 'aws-cdk-lib';
import * as events from 'aws-cdk-lib/aws-events';
import * as targets from 'aws-cdk-lib/aws-events-targets';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as sqs from 'aws-cdk-lib/aws-sqs';
import { Construct } from 'constructs';

export class EventDrivenOrdersStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);

// Custom Event Bus for order domain events
const orderBus = new events.EventBus(this, 'OrdersEventBus', {
eventBusName: 'OrdersBus',
});

// Dead-Letter Queue for failed event deliveries
const eventDlq = new sqs.Queue(this, 'OrdersEventDlq', {
retentionPeriod: cdk.Duration.days(14),
});
}
}


2. Create an Idempotent Lambda Consumer

In distributed event-driven systems, EventBridge guarantees at-least-once delivery, meaning duplicate events can occasionally arrive. Lambda handlers should process events asynchronously, validate payloads, and enforce idempotency (for example, by tracking  event.id  or an  orderId  in Amazon DynamoDB):
import { EventBridgeEvent } from 'aws-lambda';
import { DynamoDBClient, PutItemCommand } from '@aws-sdk/client-dynamodb';

interface OrderPlacedDetail {
orderId: string;
customerId: string;
amount: number;
}

const ddb = new DynamoDBClient({});

export const handler = async (
event: EventBridgeEvent<'OrderPlaced', OrderPlacedDetail>
): Promise<void> => {
const { orderId, customerId, amount } = event.detail;

try {
// Conditional write ensures each orderId is processed only once
await ddb.send(
new PutItemCommand({
TableName: process.env.PROCESSED_ORDERS_TABLE,
Item: {
orderId: { S: orderId },
eventId: { S: event.id },
customerId: { S: customerId },
amount: { N: amount.toString() },
processedAt: { S: new Date().toISOString() },
},
ConditionExpression: 'attribute_not_exists(orderId)',
})
);

console.log(`Successfully processed order ${orderId}`);
} catch (error: any) {
if (error.name === 'ConditionalCheckFailedException') {
console.warn(`Duplicate event skipped for order ${orderId}`);
return;
}
console.error(`Failed to process order ${orderId}:`, error);
throw error; // Re-throw to trigger Lambda retry and DLQ routing
}
};


3. Configure Content-Based Routing Rules

Connect the custom event bus to your Lambda consumer using an EventBridge rule. Configure retry policies and attach the SQS DLQ so transient failures do not result in lost business events:
const orderProcessorFn = new lambda.Function(this, 'OrderProcessorFn', {
runtime: lambda.Runtime.NODEJS_20_X,
handler: 'index.handler',
code: lambda.Code.fromAsset('lambda/order-processor'),
});

const orderPlacedRule = new events.Rule(this, 'OrderPlacedRule', {
eventBus: orderBus,
eventPattern: {
source: ['com.example.orders'],
detailType: ['OrderPlaced'],
},
});

orderPlacedRule.addTarget(
new targets.LambdaFunction(orderProcessorFn, {
deadLetterQueue: eventDlq,
maxEventAge: cdk.Duration.hours(2),
retryAttempts: 3,
})
);


4. Enable Automated Schema Discovery

As multiple teams publish events to  OrdersBus , keeping payload contracts aligned becomes critical. Enabling EventBridge Schema Discovery automatically inspects events flowing through the bus and registers OpenAPI or JSON Schema definitions in the EventBridge Schema Registry:
  • Prevent breaking changes: Track schema versions whenever producers add or modify fields.
  • Generate strongly typed bindings: Download code bindings directly into your IDE (TypeScript, Python, Java) so consumer Lambda functions validate event structures at compile time rather than failing at runtime.

Production Best Practices

  • Design concise event envelopes: Keep event payloads focused on key identifiers and state changes rather than embedding massive objects; if payloads exceed 256 KB, store the payload in Amazon S3 and pass a reference URI.
  • Monitor DLQ depth with CloudWatch Alarms: Attach an Amazon CloudWatch alarm to your SQS DLQ ( ApproximateNumberOfMessagesVisible > 0 ) to alert engineering teams immediately when poisoned or failed events accumulate.
  • Use EventBridge Archive and Replay: Enable event archiving on your custom bus so you can safely replay historical events into updated Lambda consumers after bug fixes or feature rollouts.

Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article