Event-driven architecture with EventBridge
# AWS EventBridge Event Routing
Master event-driven architectures with AWS EventBridge using Google Antigravity IDE. This comprehensive guide covers event patterns, rules, and integration strategies for serverless applications.
## Why EventBridge?
EventBridge provides serverless event routing with powerful filtering. Google Antigravity IDE's Gemini 3 engine suggests optimal event patterns and integration architectures.
## Event Bus Configuration
```typescript
// lib/eventbridge.ts
import {
EventBridgeClient,
PutEventsCommand,
PutRuleCommand,
PutTargetsCommand,
} from "@aws-sdk/client-eventbridge";
const client = new EventBridgeClient({ region: process.env.AWS_REGION });
interface CustomEvent<T = unknown> {
source: string;
detailType: string;
detail: T;
eventBusName?: string;
}
export async function publishEvent<T>(event: CustomEvent<T>): Promise<string> {
const command = new PutEventsCommand({
Entries: [
{
Source: event.source,
DetailType: event.detailType,
Detail: JSON.stringify(event.detail),
EventBusName: event.eventBusName || "default",
Time: new Date(),
},
],
});
const response = await client.send(command);
if (response.FailedEntryCount && response.FailedEntryCount > 0) {
throw new Error(`Failed to publish event: ${response.Entries?.[0]?.ErrorMessage}`);
}
return response.Entries?.[0]?.EventId || "";
}
// Usage
await publishEvent({
source: "com.antigravity.orders",
detailType: "OrderCreated",
detail: {
orderId: "order-123",
userId: "user-456",
total: 99.99,
items: [{ productId: "prod-1", quantity: 2 }],
},
});
```
## Event Patterns
```typescript
// infrastructure/eventbridge.ts
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";
export class EventBridgeStack extends cdk.Stack {
constructor(scope: cdk.App, id: string) {
super(scope, id);
// Custom event bus
const orderBus = new events.EventBus(this, "OrderEventBus", {
eventBusName: "order-events",
});
// Order created rule
const orderCreatedRule = new events.Rule(this, "OrderCreatedRule", {
eventBus: orderBus,
ruleName: "order-created",
eventPattern: {
source: ["com.antigravity.orders"],
detailType: ["OrderCreated"],
detail: {
total: [{ numeric: [">=", 100] }],
},
},
});
// Add Lambda target
const processOrderFn = new lambda.Function(this, "ProcessOrderFn", {
runtime: lambda.Runtime.NODEJS_20_X,
handler: "index.handler",
code: lambda.Code.fromAsset("functions/process-order"),
});
orderCreatedRule.addTarget(new targets.LambdaFunction(processOrderFn, {
retryAttempts: 3,
maxEventAge: cdk.Duration.hours(1),
}));
// Pattern with content filtering
const highValueOrderRule = new events.Rule(this, "HighValueOrderRule", {
eventBus: orderBus,
eventPattern: {
source: ["com.antigravity.orders"],
detailType: ["OrderCreated"],
detail: {
total: [{ numeric: [">=", 1000] }],
priority: ["high", "urgent"],
},
},
});
// Add SNS notification target
highValueOrderRule.addTarget(new targets.SnsTopic(alertTopic));
}
}
```
## Lambda Event Handler
```typescript
// functions/process-order/index.ts
import { EventBridgeEvent } from "aws-lambda";
interface OrderCreatedDetail {
orderId: string;
userId: string;
total: number;
items: Array<{ productId: string; quantity: number }>;
}
export async function handler(
event: EventBridgeEvent<"OrderCreated", OrderCreatedDetail>
): Promise<void> {
const { orderId, userId, total, items } = event.detail;
console.log(`Processing order ${orderId} for user ${userId}`);
// Process order logic
await Promise.all([
updateInventory(items),
sendConfirmationEmail(userId, orderId),
updateAnalytics(orderId, total),
]);
// Publish completion event
await publishEvent({
source: "com.antigravity.orders",
detailType: "OrderProcessed",
detail: { orderId, processedAt: new Date().toISOString() },
});
}
async function updateInventory(items: OrderCreatedDetail["items"]) {
// Update inventory for each item
}
async function sendConfirmationEmail(userId: string, orderId: string) {
// Send email notification
}
async function updateAnalytics(orderId: string, total: number) {
// Update analytics
}
```
## Schema Registry
```typescript
// schemas/order-events.ts
import { JSONSchema7 } from "json-schema";
export const orderCreatedSchema: JSONSchema7 = {
$schema: "http://json-schema.org/draft-07/schema#",
title: "OrderCreated",
type: "object",
required: ["orderId", "userId", "total", "items"],
properties: {
orderId: { type: "string", pattern: "^order-[a-z0-9]+$" },
userId: { type: "string" },
total: { type: "number", minimum: 0 },
items: {
type: "array",
items: {
type: "object",
required: ["productId", "quantity"],
properties: {
productId: { type: "string" },
quantity: { type: "integer", minimum: 1 },
},
},
},
},
};
```
## Event Replay
```typescript
// lib/event-replay.ts
import {
EventBridgeClient,
StartReplayCommand,
DescribeReplayCommand,
} from "@aws-sdk/client-eventbridge";
export async function replayEvents(
archiveName: string,
startTime: Date,
endTime: Date,
eventBusArn: string
): Promise<string> {
const client = new EventBridgeClient({});
const command = new StartReplayCommand({
ReplayName: `replay-${Date.now()}`,
EventSourceArn: archiveName,
Destination: { Arn: eventBusArn },
EventStartTime: startTime,
EventEndTime: endTime,
});
const response = await client.send(command);
return response.ReplayArn || "";
}
```
## Best Practices
- Use custom event buses for domain isolation
- Apply content-based filtering in rules
- Implement dead-letter queues for failures
- Use schema registry for event validation
- Enable archive for event replay
- Monitor with CloudWatch metrics
Google Antigravity IDE provides EventBridge patterns and automatically suggests optimal event routing configurations for your serverless applications.This AWS prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their aws implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For AWS projects, consider mentioning your framework version, coding style, and any specific libraries you're using.