4.2.4 Add Annotations for Tracing

Add Annotations for Tracing Services

Annotations vs Metadata

AnnotationsMetadata
Indexed✅ Searchable❌ Not searchable
Use caseFilter/search tracesDetailed debug data
TypesString, Number, BooleanAny (objects, arrays)

X-Ray Custom Attributes

Scenario thi: Application generates thousands of trace data each hour. Cần filter results based on custom attributes trong X-Ray console.

Giải pháp:

  1. Include custom attributes as new segment fields trong segment document
  2. Add custom attributes as annotations trong segment document

Lưu ý: Annotations là indexed và searchable, segment fields không indexed.

X-Ray SDK

from aws_xray_sdk.core import xray_recorder

subsegment = xray_recorder.begin_subsegment('process_order')

# Annotations — indexed, searchable in X-Ray console
subsegment.put_annotation('order_id', 'order-123')
subsegment.put_annotation('customer_tier', 'premium')
subsegment.put_annotation('is_retry', False)

# Metadata — not indexed, for detailed data
subsegment.put_metadata('order_details', {'items': [...], 'total': 150.00})
subsegment.put_metadata('request_headers', event.get('headers', {}))

xray_recorder.end_subsegment()

Advanced Tracing

  • Drill down traces to individual requests
  • Use filter expressions to find specific traces
  • Segment documents contain trace information
  • Subsegments represent downstream calls

Lambda Powertools — Tracer

from aws_lambda_powertools import Tracer

tracer = Tracer(service="order-service")

@tracer.capture_lambda_handler
def handler(event, context):
    tracer.put_annotation("order_id", event['orderId'])
    tracer.put_metadata("event", event)
    return process_order(event)

Searching by Annotation

X-Ray Console → Traces → Filter:
  annotation.order_id = "order-123"
  annotation.customer_tier = "premium"
  annotation.is_retry = false

X-Ray Segment Documents

X-Ray compiles and processes segment documents to:

  • Generate trace summaries
  • Generate full traces that you can query
  • Create inferred segments for downstream services
  • Build service map

Inferred segments represent:

  • Downstream services
  • Resources in service map
  • Services without X-Ray SDK installed

Exam Tip:

  • Annotations = indexed, searchable (use for filtering)
  • Metadata = not indexed (use for debug details)
  • Use annotations for business-relevant keys (order_id, user_id, tier)
  • X-Ray compiles segment documents to generate queryable traces
  • Inferred segments = downstream services trong service map
  • Filter expressions work on annotations, not metadata