Building Event-Driven Architectures with Amazon EventBridge, AWS Lambda, and DynamoDB
Learn how to build a scalable, loosely coupled event-driven backend using Amazon EventBridge event buses, AWS Lambda for asynchronous processing, and DynamoDB for persistent storage.
Modern distributed systems require scalable, loosely coupled architectures. Traditional request-response (synchronous) patterns often introduce tight dependencies between microservices, leading to cascading failures and latency bottlenecks.
By shifting to an event-driven architecture (EDA), producers emit events without needing knowledge of downstream consumers. In this guide, we will design and deploy a serverless order-processing pipeline using Amazon EventBridge, AWS Lambda, and Amazon DynamoDB.
Architecture Overview
- Producer: An API endpoint, microservice, or backend client emits a custom
OrderCreatedJSON event.
- Event Router (Amazon EventBridge): Receives the event on a custom event bus, evaluates rules, and routes matching events to targets.
- Consumer (AWS Lambda): Asynchronously triggered by EventBridge rules to validate and process the incoming payload.
- Data Store (Amazon DynamoDB): Lambda persists the processed order and status into a single-table DynamoDB design.
- Dead-Letter Queue (Amazon SQS): Captures failed events for inspection and replay.
Step 1: Create the DynamoDB Table
First, define the persistence layer. We’ll create an
Orders table using on-demand billing.
AWS CLI Commandaws dynamodb create-table \ --table-name Orders \ --attribute-definitions AttributeName=orderId,AttributeType=S \ --key-schema AttributeName=orderId,KeyType=HASH \ --billing-mode PAY_PER_REQUEST
Step 2: Implement the Consumer Lambda Function
This function receives the EventBridge envelope, extracts the order payload, and writes the record to DynamoDB.
Lambda Handler (
index.mjs - Node.js 20.x)import { DynamoDBClient } from "@aws-sdk/client-dynamodb";import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb";
const client = new DynamoDBClient({});const docClient = DynamoDBDocumentClient.from(client);
export const handler = async (event) => { console.log("Received EventBridge Event:", JSON.stringify(event, null, 2));
const order = event.detail;
if (!order || !order.orderId) { throw new Error("Invalid payload: Missing orderId"); }
const item = { orderId: order.orderId, customerId: order.customerId, amount: order.amount, currency: order.currency || "USD", status: "CONFIRMED", createdAt: new Date().toISOString(), };
try { await docClient.send( new PutCommand({ TableName: "Orders", Item: item, }) );
console.log(`Successfully stored order ${order.orderId}`); return { statusCode: 200, body: JSON.stringify({ message: "Order processed successfully" }) }; } catch (error) { console.error("Error writing to DynamoDB:", error); throw error; }};Step 3: Configure the Custom Event Bus and Rules
Using a custom event bus keeps your application domain events separate from standard AWS system events.
1. Create the Custom Bus
aws events create-event-bus --name ecommerce-events2. Create the Routing Rule
Define a pattern that filters strictly for
OrderCreated events originating from com.ecommerce.orders :Event Pattern (
pattern.json ):{ "source": ["com.ecommerce.orders"], "detail-type": ["OrderCreated"]}
aws events put-rule \ --name ProcessOrderRule \ --event-bus-name ecommerce-events \ --event-pattern file://pattern.json- Add the Lambda Target and Permissions
# Add Lambda targetaws events put-targets \ --rule ProcessOrderRule \ --event-bus-name ecommerce-events \ --targets "Id"="OrderProcessorLambda","Arn"="arn:aws:lambda:us-east-1:123456789012:function:OrderProcessor"
# Grant EventBridge permission to invoke the functionaws lambda add-permission \ --function-name OrderProcessor \ --statement-id AllowEventBridgeInvoke \ --action lambda:InvokeFunction \ --principal events.amazonaws.com \ --source-arn arn:aws:events:us-east-1:123456789012:rule/ecommerce-events/ProcessOrderRule
Step 4: Testing the Workflow
To test the flow without writing a producer app, emit a test event directly through the AWS CLI:
Sample Event (
sample-event.json )[ { "EventBusName": "ecommerce-events", "Source": "com.ecommerce.orders", "DetailType": "OrderCreated", "Detail": "{\"orderId\":\"ord-9821\",\"customerId\":\"cust-4410\",\"amount\":129.99,\"currency\":\"USD\"}" }]Publish Event:
aws events put-events --entries file://sample-event.jsonVerify Result:
- Check CloudWatch Logs for the
OrderProcessorLambda function to verify execution.
- Query DynamoDB to verify the record was inserted:
aws dynamodb get-item \ --table-name Orders \ --key '{"orderId": {"S": "ord-9821"}}'
Key Best Practices
- Idempotency: Because EventBridge delivers events with an at-least-once guarantee, ensure your consumer handlers can process duplicate events safely (e.g., using DynamoDB condition expressions).
- Dead-Letter Queues (DLQs): Always attach an Amazon SQS DLQ to your EventBridge targets to capture failed invocations after retries are exhausted.
- Content-Based Filtering: Offload payload inspection to EventBridge rules rather than filtering inside Lambda code, minimizing unnecessary invocations and cost.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article