Tuần 7 - Ngày 3: Amazon EventBridge
Mục tiêu học tập
- Hiểu EventBridge: event bus cho event-driven architecture
- Phân biệt Default vs Custom vs Partner Event Bus
- Nắm Rules, Targets, Schema Registry
- Áp dụng cron schedules và cross-account events
1. Tổng quan EventBridge
Amazon EventBridge (formerly CloudWatch Events) = serverless event bus routing events từ AWS services, custom apps, SaaS đến targets.
Đặc điểm
- Schema-based events (JSON structured)
- Filter + route events based on rules
- Multi-source: AWS services, custom apps, SaaS partners
- Multi-target: 25+ AWS services
- Cross-account, cross-region event routing
- Replay events (debugging, reprocessing)
- Schema Registry for event discovery
Use cases
- Event-driven architecture
- Cron-based scheduling (replace cron servers)
- React to AWS service events (EC2 state change, S3 upload)
- SaaS integration (Datadog, Zendesk, Shopify, MongoDB)
- Cross-account event sharing
2. EventBridge Components
Event Bus
- Container for events
- 3 types:
- Default Event Bus: AWS service events go here automatically
- Custom Event Bus: for your custom apps' events
- Partner Event Bus: events from SaaS partners (Zendesk, etc.)
Event
- JSON structured message
- Standard fields:
source,detail-type,detail,time,region,account
Rule
- Filter events based on:
- Event source/detail-type
- Event content (JSON pattern matching)
- Route matched events to targets
Target
- Destination for matched events
- 25+ types: Lambda, SQS, SNS, Step Functions, Kinesis, EC2, Glue, ...
3. Event Structure
{
"version": "0",
"id": "abc123",
"detail-type": "EC2 Instance State-change Notification",
"source": "aws.ec2",
"account": "111111111111",
"time": "2025-01-15T10:00:00Z",
"region": "us-east-1",
"resources": [
"arn:aws:ec2:us-east-1:111111111111:instance/i-12345"
],
"detail": {
"instance-id": "i-12345",
"state": "running"
}
}
Standard AWS Service Events
- EC2: instance state change, terminate, stop
- S3: object created, deleted (must enable)
- CodeCommit: push to repo
- CloudTrail: any API call (subset of API events)
- RDS: snapshot complete
- Auto Scaling: launch, terminate
- ECS: task state change
- Health: AWS health events
- Trusted Advisor: check status change
4. Rules and Patterns
Pattern matching examples
Match EC2 instance running state
{
"source": ["aws.ec2"],
"detail-type": ["EC2 Instance State-change Notification"],
"detail": {
"state": ["running"]
}
}
Match S3 upload to specific bucket
{
"source": ["aws.s3"],
"detail-type": ["Object Created"],
"detail": {
"bucket": {
"name": ["my-bucket"]
}
}
}
Match specific account API call (CloudTrail)
{
"source": ["aws.iam"],
"detail-type": ["AWS API Call via CloudTrail"],
"detail": {
"eventName": ["CreateUser", "DeleteUser"]
}
}
Operators
exists,equals-ignore-case,prefix,suffixnumeric:["=", 5],[">", 100]anything-but: excludecidr: IP range matching
5. Targets (25+ types)
| Target | Use case |
|---|---|
| Lambda | Custom processing |
| SQS | Queue for async processing |
| SNS | Fanout to subscribers |
| Step Functions | Workflow orchestration |
| Kinesis | Stream processing |
| EC2 Run Command | Automation |
| EC2 Action (stop, terminate, reboot) | EC2 management |
| Glue Job | ETL trigger |
| CodePipeline | CI/CD trigger |
| API Destinations (HTTP endpoint) | Webhook to external system |
| Batch Job | Batch compute trigger |
| ECS Task | Container task |
| EventBridge Event Bus (cross-account, cross-region) | Forward events |
Multiple targets
- 1 rule → up to 5 targets
- Each target can have own input transformation
Input Transformation
- Modify event JSON before sending to target
- Use case: target API expects different format
6. Schedule (Cron-based Events)
Replaced traditional cron
- Old way: EC2 cron job
- New way: EventBridge Scheduler (rate or cron expression)
Expressions
rate(5 minutes) → every 5 minutes
rate(2 hours) → every 2 hours
cron(0 12 * * ? *) → daily at 12:00 UTC
cron(0 8 ? * MON-FRI *) → Mon-Fri 8 AM UTC
cron(0/30 * * * ? *) → every 30 min
Use cases
- Periodic Lambda execution
- Daily reports
- Database cleanup
- Health checks
EventBridge Scheduler (newer, 2022+)
- Dedicated scheduler service
- More features: one-time schedule, flexible time windows, dead-letter queue
- Recommended for new schedules
7. Schema Registry
Định nghĩa
Schema Registry = discover and manage event schemas.
Đặc điểm
- Auto-discover schemas từ events on event bus
- Browse + search schemas
- Generate code bindings (Java, Python, TypeScript) for type-safe event handling
- Versioning of schemas
Use case
- Developer productivity (autocomplete in IDE)
- Type safety in code
- Document events for team
8. Cross-Account Events
Setup
- Sender account: Create rule, target = event bus ARN of receiver account
- Receiver account: Custom event bus, resource policy allowing sender account
- Sender publishes → events forwarded to receiver
Use case
- Centralized event hub (security account receives all events)
- Multi-account SaaS
9. Replay Events
Định nghĩa
Archive + Replay = save events to archive, replay later for debugging/reprocessing.
Setup
- Create Archive for event bus
- Archive stores events (configurable retention)
- Replay events to bus → reprocess by rules
Use cases
- Debug after fix (replay events that failed before)
- Add new consumer post-hoc
- Disaster recovery (replay events lost during outage)
10. SaaS Integrations
Partner Event Bus
- AWS partners stream events to your account via Partner Event Source
- Examples:
- Auth0: user events
- Datadog: monitoring events
- MongoDB Atlas: DB events
- Shopify: order events
- PagerDuty: incident events
- Stripe: payment events
- Zendesk: ticket events
Setup
- Subscribe to partner in EventBridge console
- Partner creates Event Source → you create Event Bus from source
- Define rules → route to your targets
11. EventBridge Pipes (2022+)
Định nghĩa
Pipes = point-to-point integration between source và target with optional filtering/enrichment.
Architecture
Difference from Event Bus
- Pipes: 1 source → 1 target (point-to-point)
- Event Bus: N sources → N targets (event hub)
Use case
- Replace simple Lambda triggers
- Built-in batching, filtering, enrichment
- No code for simple integrations
12. EventBridge vs SNS
| EventBridge | SNS | |
|---|---|---|
| Model | Event bus (rule-based) | Pub/Sub topic |
| Sources | AWS services + custom + SaaS | Custom only |
| Filtering | Powerful (JSON pattern) | Basic (attributes) |
| Targets | 25+ types | 10+ types |
| Replay | Yes | No |
| Schema Registry | Yes | No |
| Scheduler | Yes (cron) | No |
| Use case | AWS-native events, complex routing | Notifications, fanout |
Decision
- AWS service events: EventBridge (native)
- Custom app fanout to many subscribers: SNS or EventBridge
- Need filtering, routing logic: EventBridge
- Simple notifications: SNS
13. Pricing
EventBridge
- $1 per million events published to custom/partner bus
- AWS service events to default bus: FREE
- Cross-account: charged at sender
- Archive storage: $0.10/GB-month
- Replay: $1/M events
Schedule
- 14M invocations/month free
- $1 per M after
14. Common Patterns
Pattern 1: Auto-tag EC2 on launch
EC2 instance launch event
→ EventBridge rule (match RunInstances)
→ Lambda: add tags based on launching user
Pattern 2: Replace cron
EventBridge Scheduler (cron 0 2 * * ? *)
→ Lambda: daily database cleanup
Pattern 3: Cross-account audit
Account A, B, C → CloudTrail events → EventBridge
→ Forward to Security Account event bus
→ Lambda: log to S3, alert on suspicious activity
Pattern 4: SaaS integration
Zendesk ticket created
→ Partner Event Bus
→ EventBridge rule
→ Lambda → create Slack notification + update CRM
Câu hỏi ôn tập
-
EventBridge default event bus chứa events gì?
Xem đáp án
Default event bus nhận AWS service events (EC2 state changes, S3 object create, RDS snapshots, CodePipeline state changes, GuardDuty findings...). Không thể delete default event bus. Custom event buses tạo riêng cho application events. Partner event buses nhận events từ SaaS partners (Zendesk, Datadog, PagerDuty...). Rule filter events và route đến targets.
-
Tối đa bao nhiêu targets per rule?
Xem đáp án
5 targets per rule. Mỗi rule có thể fan-out đến 5 services cùng lúc (Lambda, SQS, SNS, Step Functions, API Gateway, Kinesis, ECS, SSM...). Nếu cần fan-out đến nhiều hơn 5 targets, dùng SNS topic làm 1 target rồi fan-out từ SNS. EventBridge supports 300+ AWS services và SaaS partners làm targets.
-
Khi nào dùng EventBridge Pipes thay vì Rules?
Xem đáp án
EventBridge Pipes cho point-to-point integration với transformation: một source (SQS, DynamoDB Streams, Kinesis, Kafka) → optional filtering → optional enrichment (Lambda, Step Functions, API GW) → one target. Phù hợp khi cần transform data trong pipeline. Rules cho broadcast: một event → nhiều targets, complex filtering. Pipes simplify patterns từng cần nhiều Lambda glue code.
-
EventBridge có thể schedule cron jobs không?
Xem đáp án
Có — EventBridge Scheduler (và legacy CloudWatch Events scheduled rules) cho phép schedule theo: cron expression (UTC) hoặc rate expression (ví dụ
rate(5 minutes)). EventBridge Scheduler (2022) là service riêng, cải tiến hơn: flexible time windows, timezone support, retry with DLQ, millions of schedules. Dùng để trigger Lambda, Step Functions, ECS tasks, SQS, API calls theo lịch. -
Schema Registry giúp developer làm gì?
Xem đáp án
Schema Registry document và discover event schemas (structure của JSON events) trong EventBridge. Tự động infer schema từ events hoặc define thủ công. Lợi ích: (1) Code bindings — generate TypeScript/Java/Python classes từ schema, (2) Discovery — team biết events nào available mà không cần liên hệ nhau, (3) Validation — verify events conform to schema trước khi process. Tương tự Swagger/OpenAPI nhưng cho event-driven systems.
Bài tập thực hành
- Tạo rule: EC2 instance state change → SNS notification
- Tạo EventBridge Schedule chạy Lambda mỗi 5 phút
- Setup cross-account event: từ Account A → bus của Account B
- Browse Schema Registry, generate code binding cho 1 event
- Tạo Pipes: SQS → Lambda với filtering
Tài liệu tham khảo chính thức
Tiếp theo: Step Functions