</>Học Dev
Bài học

Tuần 7 - Ngày 3: Amazon EventBridge

Tuần 7 – Ngày 3

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, suffix
  • numeric: ["=", 5], [">", 100]
  • anything-but: exclude
  • cidr: IP range matching

5. Targets (25+ types)

TargetUse case
LambdaCustom processing
SQSQueue for async processing
SNSFanout to subscribers
Step FunctionsWorkflow orchestration
KinesisStream processing
EC2 Run CommandAutomation
EC2 Action (stop, terminate, reboot)EC2 management
Glue JobETL trigger
CodePipelineCI/CD trigger
API Destinations (HTTP endpoint)Webhook to external system
Batch JobBatch compute trigger
ECS TaskContainer 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

  1. Sender account: Create rule, target = event bus ARN of receiver account
  2. Receiver account: Custom event bus, resource policy allowing sender account
  3. 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

  1. Create Archive for event bus
  2. Archive stores events (configurable retention)
  3. 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

SourcePipe(FilterEnrichTarget)SQS,DynamoDBStreams,Kinesis,Kafka,etc.Lambda,StepFunctions,SQS,SNS,EventBridge,etc.

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

EventBridgeSNS
ModelEvent bus (rule-based)Pub/Sub topic
SourcesAWS services + custom + SaaSCustom only
FilteringPowerful (JSON pattern)Basic (attributes)
Targets25+ types10+ types
ReplayYesNo
Schema RegistryYesNo
SchedulerYes (cron)No
Use caseAWS-native events, complex routingNotifications, 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

  1. 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.

  2. 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.

  3. 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.

  4. EventBridge có thể schedule cron jobs không?

    Xem đáp án

    — 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.

  5. 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