SkillSprout
Chapter 5 · Lesson 3
Advanced
6 min read

X-Ray Tracing and EventBridge Event Routing

Overview

When a request crosses ten microservices, metrics tell you something is slow but not where. AWS X-Ray adds distributed tracing: each request gets a trace ID, every service adds a segment, and X-Ray builds a service map showing latency and errors per hop.

Amazon EventBridge is the serverless event bus. AWS services, your applications and SaaS partners publish events; rules match patterns and route them to targets such as Lambda, Step Functions, SQS, SNS, CodePipeline, SSM Automation and API destinations. It is the glue of event-driven operations.

Imagine a package tracking system: X-Ray is the tracking number that follows one parcel through every depot, while EventBridge is the sorting centre that sends each parcel to the right belt based on its label. Together they turn raw telemetry into answers and automated reactions.

Key Concepts

  • X-Ray trace = one request; segments = work by one service; subsegments = downstream calls; annotations (indexed, filterable) and metadata (not indexed).
  • Instrument with the X-Ray SDK or AWS Distro for OpenTelemetry (ADOT); enable active tracing on Lambda/API Gateway; run the X-Ray daemon or ADOT collector on EC2/ECS/EKS.
  • Sampling rules (default: first request each second plus 5%) control cost; you can customise by service, URL and method.
  • Groups and filter expressions (e.g. responsetime > 3 AND http.status = 500) give focused views and can drive CloudWatch alarms.
  • EventBridge rules match event patterns or run on schedules; each rule has up to 5 targets, with input transformers and DLQs per target.
  • The default event bus receives AWS service events; custom buses and partner buses isolate application and SaaS events; cross-account / cross-Region targets are other buses.
  • Archive and replay store events and re-send them; schema registry discovers event structure.
  • EventBridge Pipes connect a source (SQS, DynamoDB streams, Kinesis) to a target with filtering and enrichment; Scheduler runs one-off or recurring invocations at scale.

Detailed Notes

X-Ray instrumentation

ComputeHow to enable
LambdaTracingConfig: Active (SAM: Tracing: Active) and the SDK for downstream calls
API GatewayStage setting Enable X-Ray tracing
Elastic BeanstalkOption setting XRayEnabled: true
EC2 / on-premisesInstall the X-Ray daemon (UDP 2000) or ADOT collector; instance role needs AWSXRayDaemonWriteAccess
ECS / EKSSidecar daemon or ADOT collector; task role permissions
python
from aws_xray_sdk.core import xray_recorder, patch_all
patch_all()  # auto-instrument boto3, requests, etc.

@xray_recorder.capture("calculate_price")
def calculate_price(order):
    seg = xray_recorder.current_subsegment()
    seg.put_annotation("customerTier", order["tier"])
    seg.put_metadata("items", order["items"])

Annotations are indexed key-value pairs used in filter expressions; metadata holds any object but is not searchable. For propagation across services, the X-Amzn-Trace-Id header carries Root, Parent and Sampled.

Sampling rule

json
{
  "SamplingRule": {
    "RuleName": "checkout-high",
    "Priority": 10, "FixedRate": 0.2, "ReservoirSize": 5,
    "ServiceName": "checkout", "ServiceType": "*", "Host": "*",
    "HTTPMethod": "POST", "URLPath": "/checkout/*", "ResourceARN": "*", "Version": 1
  }
}

Reservoir = guaranteed traces per second; FixedRate = percentage of additional requests. The service map highlights nodes with errors (4xx yellow, 5xx red, throttles purple). X-Ray Insights detect anomalies automatically, and trace-linked logs connect traces to CloudWatch Logs.

EventBridge rules and targets

json
{
  "source": ["aws.ec2"],
  "detail-type": ["EC2 Instance State-change Notification"],
  "detail": { "state": ["terminated", "stopped"], "instance-id": [{ "prefix": "i-" }] }
}

Pattern operators include exact match, prefix, suffix, anything-but, numeric, exists and $or. Create a rule via CLI:

bash
aws events put-rule --name codepipeline-failed --event-pattern file://pattern.json
aws events put-targets --rule codepipeline-failed --targets \
  Id=1,Arn=$TOPIC_ARN,InputTransformer='{"InputPathsMap":{"p":"$.detail.pipeline"},"InputTemplate":"\"Pipeline <p> failed\""}'

Event sources worth knowing

SourceExample events
AWS servicesEC2 state change, CodePipeline/CodeBuild/CodeDeploy state change, ECS task state, GuardDuty/Security Hub findings, Config compliance change, Health events
CloudTrailAny API call (via the AWS API Call via CloudTrail detail type); management events are delivered to the default bus
SchedulesCron or rate expressions (use EventBridge Scheduler for flexible time zones and scale)
SaaS partnersDatadog, Zendesk, Auth0 and others
Custom appsPutEvents API

Cross-account and cross-Region routing

Aggregate events centrally: in each source account a rule targets the central account's event bus (the bus resource policy allows the organisation via aws:PrincipalOrgID). The central account then runs remediation or forwards to SIEM. Cross-Region routing sends to a bus in another Region for DR or aggregation.

Reliability features

Targets have retry policy (up to 24 hours, 185 attempts) and a dead-letter queue. Archive events and replay them after fixing a bug. For ordered or high-throughput data use Kinesis; EventBridge targets are at-least-once with no ordering guarantee.

Pipes and Scheduler

Pipes reduce glue code: SQS -> filter -> enrichment (Lambda / API Gateway) -> Step Functions. Scheduler supports millions of schedules, flexible time windows, one-time schedules and retries.

Observability combos

Use X-Ray to find the slow downstream call, CloudWatch Logs to read the error and EventBridge to automatically open an incident (Systems Manager Incident Manager) or rollback deployment. CloudWatch ServiceLens and Application Signals present traces, metrics and logs together.

Instrumentation and sampling

ChoiceDetail
X-Ray SDK vs OpenTelemetryAWS recommends ADOT / OpenTelemetry for new work; the X-Ray daemon or collector ships segments
SamplingDefault rule: first request each second plus 5% of the rest; custom rules per service, URL or method
Annotations vs metadataAnnotations are indexed and filterable; metadata is not indexed
Groups and insightsFilter expressions create groups; Insights detect anomalies
PropagationThe X-Amzn-Trace-Id header carries the trace; SQS and Lambda propagate via AWSTraceHeader

For Lambda enable active tracing (TracingConfig: Mode: Active), for ECS run the collector as a sidecar, and grant xray:PutTraceSegments and xray:PutTelemetryRecords. CloudWatch Application Signals adds SLOs and service-level dashboards on top of traces.

Real World Example

Scenario: checkout latency spikes randomly. The team enables active tracing on API Gateway and Lambda and uses the ADOT collector on ECS. The service map shows the Inventory service calling a DynamoDB table with throttles; annotations (customerTier) reveal only bulk customers are affected.

Separately, an EventBridge rule on CodeDeploy Deployment State-change Notification with state FAILURE posts to chat and starts an SSM Automation to capture diagnostics. Both signals reach engineers within a minute.

Architecture Diagram

Tracing a request and routing events
Architecture
AWS Cloud
API Gatewaytrace id
Lambdasegments
DynamoDBsubsegment
X-Ray service map
EventBridge rule
Automation target

X-Ray follows the request; EventBridge routes operational events to actions.

  1. 1API Gateway assigns a trace ID and samples the request.
  2. 2Each downstream call adds segments and subsegments.
  3. 3X-Ray builds a service map showing errors and latency per node.
  4. 4AWS service events (deployments, state changes) enter EventBridge.
  5. 5Rules route events to notification or remediation targets.

Best Practices

  • ✓Use ADOT/OpenTelemetry for portability, and add annotations for business keys you will filter on.
  • ✓Tune sampling rules: high rate for critical paths, low for noisy ones.
  • ✓Centralise events with cross-account buses restricted by organisation ID.
  • ✓Configure DLQs and retry policies on important EventBridge targets.
  • ✓Use archive and replay for recovery from consumer bugs.

Common Interview Questions

Exam Tips

DOP-C02 focus

  • "Find which downstream service causes latency" = X-Ray service map.
  • "React to AWS service state changes" = EventBridge rule; "on a schedule" = rule or Scheduler.
  • X-Ray on EC2/ECS needs the daemon (UDP 2000) or ADOT collector and an IAM role.
  • EventBridge cross-account = target the other account's event bus with a resource policy.

Finished this lesson?

0 of 44 lessons done · 0% of the course