AWS X-Ray

Metrics say something is slow. Logs say what one machine was thinking. X-Ray says which hop in the chain ate the 400 ms — it follows a single request across every service it touches and draws the path.

Metric nói có cái gì đó chậm. Log nói một máy đang nghĩ gì. X-Ray nói chặng nào trong chuỗi đã ngốn 400 ms — nó bám theo một request duy nhất qua mọi service nó đi qua rồi vẽ lại đường đi.

Reach for itNên dùng

  • "The API is slow but every service looks healthy" — you need the per-hop breakdown."API chậm mà service nào nhìn cũng khoẻ" — cần bóc tách theo từng chặng.
  • A request crosses several services and you need to know which one to blame.Một request đi qua nhiều service và cần biết đổ lỗi cho ai.
  • API Gateway returns 504 and you need to see where the timeout actually happened.API Gateway trả 504 và cần thấy timeout thật sự xảy ra ở đâu.
  • You want a map of dependencies nobody documented, drawn from real traffic.Muốn có bản đồ phụ thuộc mà không ai viết tài liệu, vẽ từ traffic thật.

Not the right toolKhông phải công cụ này

  • Alarming on a threshold → CloudWatch metric + alarm. X-Ray is for looking, not paging.Cảnh báo theo ngưỡng → CloudWatch metric + alarm. X-Ray để nhìn, không phải để gọi người dậy.
  • Auditing who called what API → CloudTrail. Different question entirely.Kiểm toán ai gọi API nào → CloudTrail. Câu hỏi hoàn toàn khác.
  • Keeping a complete record of every request → sampling means you don't have one. Use logs.Giữ bản ghi đầy đủ mọi request → có sampling nghĩa là bạn không có. Dùng log.
  • Long-term trend analysis → 30-day retention. Push what you need to metrics.Phân tích xu hướng dài hạn → chỉ giữ 30 ngày. Đẩy thứ bạn cần sang metric.

1 · What a trace is made of1 · Một trace gồm những gì

One user request gets a trace ID at the front door and carries it everywhere. Each service that handles it reports a segment (my slice of the work). Inside a segment, each outbound call is a subsegment. Services that can't report for themselves — DynamoDB, an external API — get an inferred segment drawn from the caller's view. Một request của người dùng được gắn trace ID ngay ở cửa vào rồi mang theo đi khắp nơi. Mỗi service xử lý nó báo về một segment (phần việc của tôi). Bên trong segment, mỗi lời gọi ra ngoài là một subsegment. Những service không tự báo được — DynamoDB, một API bên ngoài — sẽ được vẽ ra inferred segment dựa trên góc nhìn của bên gọi.

Timeline of one trace: the API Gateway segment spans the whole request, the orders service segment sits inside it, and subsegments for DynamoDB, SNS and a call to the payments service break down where the time went trace 1-6a8f21b4-… · one request · 412 ms total 0 ms 100 200 300 api-gateway segment orders-svc segment └ DynamoDB subsegment · 22 ms · inferred node └ SNS publish subsegment · 14 ms └ HTTP payments subsegment · 264 ms ← the whole latency lives here payments-svc segment └ RDS query subsegment · 244 ms · the actual culprit gap between a subsegment and the segment below it = time on the wire

Segment = one service's own account of the work. Subsegment = that service's view of a call it made. Both viewpoints are kept, which is how you tell "slow downstream" from "slow network".

Segment = lời khai của chính service đó về phần việc của mình. Subsegment = góc nhìn của service đó về lời gọi nó phát ra. Giữ cả hai góc nhìn chính là cách phân biệt "phía dưới chậm" với "đường truyền chậm".

  • The service map is the same data drawn as a graph instead of a timeline: a node per service, an edge per call, with latency and error rates on them. Same traces, two views.Service map chính là dữ liệu đó vẽ dạng đồ thị thay vì dạng timeline: mỗi service một node, mỗi lời gọi một cạnh, kèm độ trễ và tỉ lệ lỗi. Cùng một trace, hai cách nhìn.
  • X-Ray splits failures into Error (4xx, the caller's fault), Fault (5xx, yours) and Throttle (429). Reading the map is mostly reading those three colours.X-Ray chia lỗi thành Error (4xx, lỗi bên gọi), Fault (5xx, lỗi của bạn) và Throttle (429). Đọc service map phần lớn là đọc ba màu đó.
  • A segment document is capped at 64 kB — don't dump payloads into it.Một segment document tối đa 64 kB — đừng nhét payload vào đó.
  • Traces and the service map are kept 30 days. If a number matters next quarter, it belongs in a CloudWatch metric, not in X-Ray.Trace và service map giữ 30 ngày. Con số nào còn quan trọng vào quý sau thì phải nằm ở CloudWatch metric, không phải ở X-Ray.

2 · How the data gets in2 · Dữ liệu vào bằng đường nào

Your code never talks to the X-Ray API directly. The SDK (or ADOT, the AWS build of OpenTelemetry) throws small JSON documents at a local daemon over UDP — fire and forget, so a tracing outage can't slow your request. The daemon buffers and ships them in batches. The only thing that changes per platform is who runs that daemon. Code của bạn không bao giờ nói chuyện thẳng với X-Ray API. SDK (hoặc ADOT, bản OpenTelemetry do AWS đóng gói) ném các JSON nhỏ sang một daemon chạy cục bộ qua UDP — bắn xong quên luôn, nên tracing có trục trặc cũng không làm chậm request. Daemon gom đệm rồi đẩy lên theo lô. Thứ duy nhất thay đổi giữa các nền tảng là ai chạy cái daemon đó.

The instrumented application sends segments over UDP to a local daemon, which batches them to the X-Ray API; a table below shows who runs the daemon on EC2, ECS, Lambda, Beanstalk and API Gateway your app + SDK / ADOT instruments incoming requests and every AWS SDK call UDP local, non-blocking X-Ray daemon buffers in a queue, uploads in batches HTTPS needs IAM X-Ray · PutTraceSegments groups segments by trace ID → timeline + service map who runs the daemon EC2 you install and run it yourself instance role needs X-Ray write ECS · EKS a sidecar container next to your app task role needs X-Ray write Lambda AWS runs it — tick Active tracing execution role needs X-Ray write Beanstalk included in the platform — switch it on no install step API Gateway service side — Active tracing per stage also Step Functions, AppSync shaded rows = nothing to install; the pattern follows who owns the runtime

Same shape as every other agent question on AWS: the more of the stack AWS runs, the less you install. Only the top two rows are your problem.

Cùng một dáng với mọi câu hỏi về agent trên AWS: AWS vận hành càng nhiều tầng thì bạn càng ít phải cài. Chỉ hai dòng trên cùng là việc của bạn.

VocabularyTừ vựng Instrumenting — adding the tracing library to your code so it reports what it's doing; usually a few lines of config, not a rewrite. Daemon — a small background process that collects segments locally so your application never waits on the network. ADOT (AWS Distro for OpenTelemetry) — AWS's packaged build of the vendor-neutral OpenTelemetry collector; it can send traces to X-Ray and to other backends at the same time. Instrument — gắn thư viện tracing vào code để nó tự báo cáo đang làm gì; thường chỉ vài dòng cấu hình, không phải viết lại. Daemon — một tiến trình nền nhỏ thu gom segment ngay tại chỗ để ứng dụng không bao giờ phải chờ mạng. ADOT (AWS Distro for OpenTelemetry) — bản OpenTelemetry do AWS đóng gói; nó gửi trace được sang X-Ray và sang backend khác cùng lúc.
  • No traces at all? The answer is almost always IAM — whatever sends the segments (instance role, task role, execution role) needs PutTraceSegments and PutTelemetryRecords.Không thấy trace nào? Câu trả lời gần như luôn là IAM — thứ nào gửi segment (instance role, task role, execution role) đều cần PutTraceSegments và PutTelemetryRecords.
  • Traces stop at the first uninstrumented service. If one hop doesn't propagate X-Amzn-Trace-Id, everything past it becomes a separate trace and the map breaks in half.Trace đứt ngay tại service đầu tiên chưa được instrument. Chỉ cần một chặng không truyền tiếp X-Amzn-Trace-Id là mọi thứ phía sau thành một trace riêng và service map gãy làm đôi.
  • On Lambda, Active tracing gives you the invocation for free; to see calls inside your handler you still add the SDK.Trên Lambda, Active tracing cho bạn phần invocation miễn phí; muốn thấy các lời gọi bên trong handler thì vẫn phải thêm SDK.

3 · Sampling — why your request isn't there3 · Sampling — vì sao không thấy request của bạn

Tracing every request would cost more than running the application. So X-Ray keeps a reservoir — a guaranteed minimum of 1 request per second — plus a rate of 5 % of everything above it. The decision is taken once, by the first instrumented service, and written into the trace header. Everyone downstream obeys it. Trace mọi request thì tốn hơn cả tiền chạy ứng dụng. Nên X-Ray giữ một reservoir — mức tối thiểu đảm bảo 1 request mỗi giây — cộng thêm rate 5 % cho phần vượt lên trên. Quyết định chỉ được đưa ra một lần, bởi service đầu tiên có instrument, rồi ghi vào trace header. Mọi bên phía dưới cứ thế tuân theo.

In one second of twenty requests the first is always recorded by the reservoir and five percent of the remaining nineteen is recorded by rate; the sampling decision is then carried in the trace header to every downstream service one second · 20 requests arrive 1 7 reservoir · the first one each second is always kept rate · 5 % of the other 19 ≈ 1 more the other 18 are served normally and simply never recorded the decision travels with the request — it is not re-taken at each hop api-gateway decides: Sampled=1 orders-svc obeys, does not re-decide payments-svc obeys, does not re-decide X-Amzn-Trace-Id: Root=1-6a8f21b4-…;Parent=53995c3f42cd8ad8;Sampled=1

Sampling is "parent-based": a rule you write for a middle service never fires, because the decision was already made upstream. Put the rule at the entry point.

Sampling theo kiểu "parent-based": rule bạn viết cho một service ở giữa sẽ không bao giờ chạy, vì quyết định đã được đưa ra ở phía trên. Đặt rule ở điểm vào.

  • Rules are evaluated by priority (1–9999, lowest first) and the first match wins. Each rule has its own reservoir and rate, so "trace 100 % of PUT /checkout" is a rule with priority 1 and rate 100.Rule được xét theo priority (1–9999, số nhỏ trước), rule khớp đầu tiên thắng. Mỗi rule có reservoir và rate riêng, nên "trace 100 % của PUT /checkout" là một rule priority 1, rate 100.
  • Define rules in the console, not in a local JSON file. With a local file every instance keeps its own reservoir, so 20 instances quietly become 20 requests per second instead of 1.Định nghĩa rule trong console, đừng để trong file JSON cục bộ. Với file cục bộ, mỗi instance giữ reservoir riêng, nên 20 instance âm thầm thành 20 request mỗi giây thay vì 1.
  • Changing sampling doesn't need a redeploy — that's the point of centralised rules. Turn it up while debugging, turn it back down.Đổi sampling không cần deploy lại — đó chính là ý nghĩa của rule tập trung. Bật cao lúc debug, xong hạ xuống.
  • "The error happened but there's no trace" is normal, not a bug. Sampling is why X-Ray never replaces logs."Lỗi có xảy ra mà không có trace" là bình thường, không phải bug. Chính vì sampling mà X-Ray không bao giờ thay được log.

4 · Finding the one trace you want4 · Tìm đúng cái trace bạn cần

A trace you can't find is worthless. You attach your own fields to a segment two ways, and only one of them is searchable. Một trace không tìm ra được thì vô dụng. Bạn gắn field của riêng mình vào segment theo hai cách, và chỉ một trong hai là tìm kiếm được.

AttachGắn kèm Annotation Metadata
Indexed for searchĐược index để tìm Yes — usable in filter expressionsCó — dùng được trong filter expression No — visible only once you open the traceKhông — chỉ thấy khi đã mở trace ra
Value typesKiểu giá trị Simple key–value (string, number, boolean)Key–value đơn giản (chuỗi, số, boolean) Anything, including objects and listsBất kỳ thứ gì, kể cả object và list
LimitGiới hạn 50 indexed per tracecái được index mỗi trace Only the 64 kB segment sizeChỉ giới hạn 64 kB của segment
Use it forDùng cho customer_id, tenant, cart_size — things you'll search bynhững thứ bạn sẽ tìm theo The request body, a config dump — context you'll read laterBody của request, một bản dump cấu hình — ngữ cảnh để đọc sau
  • Filter expressions are the query language over traces: service("orders-svc") { fault = true }, annotation.customer_id = "c-2291", responsetime > 3.Filter expression là ngôn ngữ truy vấn trên trace: service("orders-svc") { fault = true }, annotation.customer_id = "c-2291", responsetime > 3.
  • A group is a saved filter expression that gets its own service map and its own CloudWatch metrics, published every minute. That is the bridge from tracing to alarming: alarm on the group's fault rate, then open the map.Một group là filter expression được lưu lại, có service map riêng và metric CloudWatch riêng, đẩy lên mỗi phút. Đó là cây cầu từ tracing sang alarm: đặt alarm trên fault rate của group, rồi mở map ra xem.
  • Insights watches a group for anomalies and opens an issue with the impacted requests and the likely root-cause service — useful when nobody was looking at the dashboard.Insights theo dõi bất thường trong một group và mở ra một issue kèm các request bị ảnh hưởng cùng service nhiều khả năng là gốc rễ — hữu ích khi chẳng ai ngồi nhìn dashboard.

5 · Where it sits next to metrics and logs5 · Nó đứng ở đâu so với metric và log

Three columns comparing metrics, logs and traces by the question each one answers, its shape and its cost Metrics "is something wrong?" numbers over time cheap · aggregated this is what alarms on 15 months of history Logs "what happened here?" text lines, one machine complete · verbose every request, if you want retention you choose Traces · X-Ray "where did the time go?" one request, all services sampled · relational the only one that spans hops 30 days

The usual sequence: an alarm on a metric wakes you, a trace tells you which service, its logs tell you why.

Trình tự thường gặp: alarm trên metric đánh thức bạn, trace chỉ ra service nào, log của service đó nói vì sao.

RelatedLiên quan Metrics, alarms and log plumbing: CloudWatch. Why some signals need an agent and others don't — the same ownership logic as the daemon table above: Where metrics come from. Metric, alarm và đường ống log: CloudWatch. Vì sao có tín hiệu cần agent còn tín hiệu khác thì không — cùng logic sở hữu như bảng daemon ở trên: Metric đến từ đâu.

Exam reflexesPhản xạ khi thi

  • "Which microservice is causing the latency?" → X-Ray service map. Not CloudWatch, not CloudTrail."Microservice nào gây ra độ trễ?" → X-Ray service map. Không phải CloudWatch, không phải CloudTrail.
  • "Trace requests on EC2" → install the X-Ray daemon + give the instance role X-Ray permissions. On ECS → run it as a sidecar."Trace request trên EC2" → cài X-Ray daemon + cấp quyền X-Ray cho instance role. Trên ECS → chạy dạng sidecar.
  • "Least effort to trace a Lambda / API Gateway app" → tick Active tracing. Beanstalk → the agent is already in the platform."Ít công nhất để trace app Lambda / API Gateway" → bật Active tracing. Beanstalk → agent đã có sẵn trong platform.
  • "We're only seeing a few requests" → sampling. Raise the rate with a sampling rule at the entry point — a rule on a middle service does nothing."Chỉ thấy vài request" → do sampling. Tăng rate bằng sampling rule ở điểm vào — đặt rule ở service giữa thì vô ích.
  • "Find the traces for one specific customer" → record the ID as an annotation (indexed), then a filter expression. Metadata can't be searched."Tìm trace của một khách hàng cụ thể" → ghi ID dưới dạng annotation (được index), rồi dùng filter expression. Metadata không tìm được.
  • "Alarm when this call path degrades" → an X-Ray group publishes CloudWatch metrics; alarm on those."Cảnh báo khi đường gọi này xuống cấp" → X-Ray group đẩy metric sang CloudWatch; đặt alarm trên đó.
  • "Nothing appears after enabling it" → IAM on the sender, or a hop that doesn't forward the trace header."Bật rồi mà không thấy gì" → IAM ở phía gửi, hoặc một chặng không chuyển tiếp trace header.