SkillSprout
Chapter 11 · Lesson 2
Intermediate
6 min read

AWS X-Ray and CloudTrail

Overview

When a request crosses many services, a single log file cannot tell you where it slowed down or failed. AWS X-Ray follows each request end to end and draws a service map with latency and error rates per hop. AWS CloudTrail answers a different question: who called which API, when and from where, which is vital for security investigations and compliance.

Think of X-Ray as a parcel tracker showing every depot your package visited and how long it waited at each. CloudTrail is the building's visitor log showing who entered which room and whether they were let in.

The exam asks you to pick the right tool for performance, error and audit scenarios, and to know how to instrument code and Lambda for X-Ray.

Key Concepts

  • An X-Ray trace is the full journey of a request, made of segments (one per service) and subsegments (downstream calls, custom code blocks).
  • Annotations are indexed key-value pairs used to filter and group traces; metadata is non-indexed extra data for debugging.
  • Instrument with the X-Ray SDK or AWS Distro for OpenTelemetry (ADOT); the X-Ray daemon (or agent in Lambda/ECS/Beanstalk) forwards data over UDP 2000 to the service.
  • Lambda active tracing is a function setting; the function role needs xray:PutTraceSegments and xray:PutTelemetryRecords (AWSXRayDaemonWriteAccess).
  • Sampling rules control cost by tracing a subset (default: 1 request/second plus 5% of additional requests); you can customise per URL, method or service.
  • The trace header X-Amzn-Trace-Id propagates the trace ID; API Gateway stages, SQS, SNS and Step Functions can pass it along.
  • CloudTrail records management events (default, 90-day event history), data events (S3 object, Lambda invoke, DynamoDB item - extra cost, opt-in) and Insights events for unusual activity.
  • Create a trail to deliver logs to S3 (and CloudWatch Logs), enable log file validation, and use multi-Region or organisation trails; CloudTrail Lake queries events with SQL.

Detailed Notes

X-Ray vs CloudTrail vs CloudWatch

QuestionTool
Which downstream call is slow?X-Ray
Which service returns most errors, with a service map?X-Ray
Who deleted this DynamoDB table?CloudTrail
Is CPU or error rate above a threshold?CloudWatch
What did this function print?CloudWatch Logs
Was this configuration changed?AWS Config (and CloudTrail)

Enabling X-Ray on Lambda (SAM)

yaml
Globals:
  Function:
    Tracing: Active
  Api:
    TracingEnabled: true

Active tracing on the function creates a segment automatically. To trace AWS SDK calls and add detail, patch the SDK in code.

Instrumenting Python

python
from aws_xray_sdk.core import xray_recorder, patch_all
import boto3

patch_all()    # trace boto3, requests, etc.

@xray_recorder.capture("calculate_discount")
def calculate_discount(order):
    seg = xray_recorder.current_subsegment()
    seg.put_annotation("customerTier", order["tier"])     # indexed, filterable
    seg.put_metadata("cart", order["items"])              # not indexed
    return 0.1 if order["tier"] == "gold" else 0.0

def handler(event, context):
    return {"discount": calculate_discount(event)}

Filter expressions in the console: annotation.customerTier = "gold" AND responsetime > 2.

Instrumenting Node.js

javascript
import AWSXRay from "aws-xray-sdk-core";
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";

const ddb = AWSXRay.captureAWSv3Client(new DynamoDBClient({}));

Running the daemon

On EC2 install and run the X-Ray daemon with an instance profile that allows xray:PutTraceSegments. In ECS add the daemon (or ADOT collector) as a sidecar container and expose UDP port 2000. Elastic Beanstalk can enable it with an option setting (XRayEnabled: true).

Troubleshooting X-Ray

SymptomLikely cause
No traces from LambdaActive tracing off or role lacks X-Ray permissions
Downstream calls missingSDK not patched/captured
No traces from EC2/ECSDaemon not running, UDP 2000 blocked, missing IAM permissions
Too many traces / costSampling rules too generous

CloudTrail essentials

bash
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=DeleteTable \
  --max-results 5

aws cloudtrail create-trail --name org-trail --s3-bucket-name audit-logs-111122223333 \
  --is-multi-region-trail --enable-log-file-validation
aws cloudtrail start-logging --name org-trail

A sample event includes eventName, userIdentity (ARN, session issuer), sourceIPAddress, requestParameters, errorCode such as AccessDenied and eventTime.

Event typeDefaultExamples
ManagementOn (history 90 days)CreateBucket, RunInstances, AttachRolePolicy
DataOffS3 GetObject, Lambda Invoke, DynamoDB GetItem
InsightsOffUnusual API call rate or error rate

Reacting to events

  • Match CloudTrail API calls in EventBridge (for example DeleteTrail, root login) to trigger remediation.
  • Query logs in Athena or CloudTrail Lake.
  • Use log file validation (digest files) to prove logs were not tampered with.

Troubleshooting with both

  1. Alarm shows rising latency (CloudWatch).
  2. Open the service map (X-Ray) and see DynamoDB subsegments throttled.
  3. Use CloudTrail to find the recent change that lowered the table's provisioned capacity.

Instrumenting with the X-Ray SDK

python
from aws_xray_sdk.core import xray_recorder, patch_all
patch_all()                      # traces boto3, requests, etc.

@xray_recorder.capture("price_lookup")
def price(item):
    seg = xray_recorder.current_subsegment()
    seg.put_annotation("itemId", item)          # indexed, filterable
    seg.put_metadata("raw", {"detail": "..."})  # not indexed
    return lookup(item)
yaml
Globals:
  Function: { Tracing: Active }
  Api: { TracingEnabled: true }
X-Ray termMeaning
TraceEnd-to-end request, identified by the X-Amzn-Trace-Id header
Segment / subsegmentWork done by a service / by a downstream call within it
AnnotationsKey-value pairs indexed for filter expressions
MetadataExtra data, not searchable
Sampling rulesDefault is the first request each second plus 5 percent; customise per route
Service mapGraph with latency and error rates per node

On EC2 and on-premises, the X-Ray daemon (or the CloudWatch agent / ADOT collector) forwards segments over UDP port 2000; Lambda, Beanstalk and ECS integrate with the daemon or sidecar, and the role needs xray:PutTraceSegments and xray:PutTelemetryRecords. X-Ray can use OpenTelemetry through AWS Distro for OpenTelemetry.

CloudTrail queries

Management events are recorded by default for 90 days in Event history; create a trail to deliver to S3 for long retention, add data events (S3 objects, Lambda invokes) at extra cost, and use CloudTrail Lake for SQL queries. Enable log file validation to detect tampering.

bash
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=UpdateTable --max-results 5

Pair a metric filter or an EventBridge rule on CloudTrail events with an alarm to react to sensitive API calls such as policy changes or console logins without MFA.

Real World Example

A travel-booking platform noticed random 3-second checkout delays. The X-Ray service map showed a third-party fraud API subsegment taking most of the time for a subset of requests, which they identified by filtering on a custom annotation paymentProvider. Separately, after a configuration incident, CloudTrail revealed that a CI role had removed an S3 bucket policy at 02:14 UTC from a known IP. They added an EventBridge rule on DeleteBucketPolicy to alert instantly.

Architecture Diagram

Tracing and auditing
Architecture
AWS Cloud
Client
API Gateway
Lambdaactive tracing
DynamoDB
X-Ray service map
CloudTrail

X-Ray traces the request path; CloudTrail records API calls.

  1. 1The request enters API Gateway, which starts or continues a trace.
  2. 2Each downstream service adds segments and subsegments to the trace.
  3. 3X-Ray assembles the service map with latency and error rates.
  4. 4Independently, CloudTrail records every control-plane API call for audit.

Best Practices

  • ✓Enable active tracing and add annotations for business keys.
  • ✓Tune sampling rules for production cost.
  • ✓Use ADOT if you want OpenTelemetry portability.
  • ✓Enable a multi-Region organisation trail with log file validation and S3 object-lock protection.
  • ✓Alert on sensitive API calls via EventBridge.

Common Interview Questions

Exam Tips

DVA-C02 focus

  • Latency across microservices / service map -> X-Ray; who did what -> CloudTrail.
  • Filter traces by custom field -> annotations.
  • Lambda tracing: enable active tracing and X-Ray permissions on the role.
  • S3 object-level or Lambda invoke auditing -> CloudTrail data events.

Finished this lesson?

0 of 46 lessons done · 0% of the course