Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

Serverless Observability: X-Ray, Powertools and Structured Logs

When a parcel goes missing, you need the tracking number across every warehouse. Serverless observability is that tracking: structured logs, metrics, and X-Ray traces tied by a correlation id so on-call finds the failing hop in minutes — not by SSH into a server you do not have.

In this chapter

  • Emit structured JSON logs with request ids
  • Use EMF / Powertools metrics
  • Trace with AWS X-Ray across API+Lambda+DDB
  • Design alarms that page humans
  • Link CloudWatch chapter

1. Everyday example: courier tracking number

Fatima in Casablanca (MAD) pastes a tracking id and sees each warehouse scan. Diego in São Paulo (BRL) needs the same for checkout: API Gateway request id → Lambda → DynamoDB. Without one id in every log line, he greps in the dark during a Black Friday incident.

Metrics/alarms depth: CloudWatch. Compute basics: Lambda. Here we wire an observability pattern for serverless apps.

2. Why observability pattern?

No SSH. Short-lived environments. Failures hide in retries and async hops. You need logs, metrics, traces, and alarms designed on day one — not after the first 2 AM page in USD production.

Serverless observability = structured logs + metrics (EMF/Powertools) + distributed traces (X-Ray) + actionable alarms, all correlated by ids (requestId, orderId, trace id).

3. Vertical diagram

Request -> API -> Lambda -> AWS deps -> Logs/Metrics/Traces -> AlarmOne correlation id on every line
Alarm on symptom + runbook link
Client request + correlation id API Gateway access logs Lambda structured logs EMF metrics / Powertools X-Ray service map CloudWatch alarms -> SNS/page Runbook link in alarm description
Telemetry path from edge to page.

4. How: minimum viable observe

  1. JSON log each request with level, msg, orderId, requestId.
  2. Enable X-Ray on API stage + Lambda; use AWS SDK instrumentation.
  3. Emit 3 business metrics: OrdersCreated, PaymentFailed, LagMs.
  4. Alarm: errors, throttles, DLQ depth, iterator age, p99 latency.
  5. Alarm description = runbook URL + owner.
  6. Redact PII — never log full card or national id.

5. Per-concept commands

Tail recent Lambda logs

aws logs tail /aws/lambda/checkout-api --region ap-south-1 --since 10m --format short

Meaning: Fast incident view; prefer JSON fields you can filter.

X-Ray service graph summary

aws xray get-service-graph --region ap-south-1 \
  --start-time $(date -u -d '30 minutes ago' +%s) \
  --end-time $(date -u +%s) \
  --query 'Services[].{N:Name,E:RootSummaryStatistics.ErrorCount}' 

Meaning: Shows which hop is erroring in the last half hour.

Put a safe test metric alarm sketch

aws cloudwatch describe-alarms --region ap-south-1 \
  --alarm-name-prefix checkout --max-records 10 \
  --query 'MetricAlarms[].{N:AlarmName,S:StateValue}' 

Meaning: Lists checkout alarms and state — verify WARNING/ALARM paths in staging first.

Filter logs by orderId

aws logs filter-log-events --region ap-south-1 \
  --log-group-name /aws/lambda/checkout-api \
  --filter-pattern '{ $.orderId = "ord-7841" }' --limit 20 

Meaning: Correlation search — only works if you logged orderId as JSON.

6. Powertools habits

  • Logger: bind correlation keys once per invoke.
  • Tracer: capture outbound SDK calls.
  • Metrics: cold start metric dimension.
  • Idempotency utility where payments matter.

7. Alarm design

SignalPage?Notes
Lambda Errors spikeYes if user pathExclude known probes
ThrottlesYesConcurrency headroom
DLQ depth >0 moneyYesNotify DLQ maybe ticket
IteratorAge highYes for streamsStale projections
p99 latencyIf SLOCold start chapter link

8. Industries

  • Fintech (Aisha, Lagos, NGN): ledger correlation mandatory.
  • Ecommerce (Rohan, Pune, INR): checkout trace + payment metric.
  • Healthcare (Mei, Singapore, SGD): redact PHI in logs.
  • Logistics (Omar, Amman, JOD): scan events metrics per hub.
  • SaaS (Priya, Bengaluru, INR): per-tenant error dashboards.

9. Lab

10. Lab - logs + one alarm

Do this in ap-south-1 (Mumbai) unless your org forbids it. Set a budget alert first.

  1. Invoke a lab Lambda; confirm JSON log with a fake orderId.
  2. Enable X-Ray on that function; open service map once.
  3. Create or inspect an alarm on Errors with SNS email in sandbox.
  4. Write a 5-line runbook in a text file for that alarm.

Cleanup (stop billing)

  1. Delete lab alarms and SNS test subscriptions.
  2. Disable X-Ray if not needed to save cost.

11. Same pattern across industries

  • Fintech (Aisha, Lagos): payment webhooks → SQS → Lambda; never block the bank callback thread.
  • Ecommerce (Rohan, Pune): checkout API on API Gateway+Lambda; inventory fan-out on SNS.
  • Healthcare (Mei, Singapore): appointment SMS via SNS; PHI stays in DynamoDB with fine-grained IAM.
  • EdTech (Diego, São Paulo): nightly cleanup EventBridge → Lambda on student drafts.
  • Logistics (Fatima, Casablanca): package scan events on EventBridge bus; Step Functions for customs saga.
  • Media (Kenji, Osaka): S3 upload → Lambda thumbnails; fan-out to moderation + CDN invalidate.
  • SaaS multi-tenant (Priya, Bengaluru): Cognito groups + DynamoDB partition per tenant.
  • Gov portal (Omar, Amman): strangler fig — peel one PDF form route per sprint to Lambda.

12. Troubleshooting checklist

  1. Confirm region (ap-south-1 vs us-east-1 for CloudFront/ACM quirks).
  2. Check CloudWatch Logs for the function name and request id.
  3. Verify IAM execution role allows the API you call.
  4. For async: check DLQ depth and SQS age of oldest message.
  5. For APIs: curl -v and compare status, CORS headers, body.
  6. For workflows: open Step Functions execution event history.
  7. Re-read the linked deep chapter before reinventing a service.
  8. If cost spikes: check concurrency, retries, and provisioned capacity.

13. Common errors and fixes

Each row is a real mistake students and juniors hit. Read the fix before you panic.

Error / symptomFix
Logs are plain text soupSwitch to JSON; one event per line.
X-Ray emptyEnable on API stage + Lambda; IAM xray:PutTraceSegments.
Alarm flappingWiden period; use anomaly or buffered threshold.
PII in logsRedact; structured allow-list fields.
Cannot find order across asyncPropagate orderId in SQS message attributes + logs.
Metrics missingEMF namespace typo; flush on exit.
Cost of traces hugeSampling rules; trace user paths not every ping.
On-call gets email stormsPage only money path; ticket the rest.
Wrong region in consoleAlways set ap-south-1 when debugging Mumbai apps.

14. FAQ

Q. Powertools required?

Strongly recommended; not mandatory if you emit JSON+EMF yourself.

Q. X-Ray vs OpenTelemetry?

X-Ray native; OTel growing — pick one consistent story.

Q. How long to keep logs?

Balance cost vs compliance; often 7-30 days online + archive.

Q. Link CloudWatch chapter?

amazon-cloudwatch-metrics-namespaces-alarms-and-sns-email-alerts.

Q. Async observability?

DLQ depth, age of oldest message, trace across producers.

15. Interview Q&A (Beginner / Mid / Senior + MNC)

Q. Beginner: correlation id?

Same id in every log for one request/order.

Q. Beginner: structured log?

JSON fields, not free text only.

Q. Mid: EMF?

Embedded Metric Format — logs become CloudWatch metrics.

Q. Mid: what to alarm?

Errors, throttles, DLQ, latency vs SLO.

Q. Senior: sampling?

Trace enough to debug; not 100% of health checks.

Q. MNC: evidence?

Trace+log retention meeting audit; runbooks linked.

16. Tips in English, Marathi and Hindi

Ravindra Bagale's Tip (EN)

No SSH: your tracking number is the correlation id across logs, metrics and traces.

Ravindra Bagale's Tip (MR)

SSH नाही: tracking = correlation id.

Tip (HI)

SSH नहीं: ट्रैकिंग नंबर = correlation id।

Try at home

  1. Add orderId to one log line.
  2. Name 3 alarms for checkout.

In short

  1. Start from a real story, then name the AWS services.
  2. Link existing chapters — do not copy their labs.
  3. Design for failure: retries, DLQ, idempotency, rollback.
  4. Measure before you buy provisioned concurrency or multi-region.

17. Architecture decision checklist

  1. Write the user journey in five bullets with no AWS names.
  2. Mark each step sync (user waits) or async.
  3. Name failure mode: retry, DLQ, compensate, or alert-only.
  4. Name the idempotency key for every write.
  5. Pick data store from access patterns (link DynamoDB modeling).
  6. Estimate monthly cost at 1x and 10x traffic (USD and INR).
  7. Confirm account concurrency and service quotas in ap-south-1.
  8. Decide auth: Cognito, IAM, Lambda authorizer, or none.
  9. Name on-call and which CloudWatch alarm pages them.
  10. Link the deep chapter you will not rewrite.
  11. Only then open console or IaC.

18. Copy-paste quick commands (read-only first)

# Region and identity
aws configure get region
aws sts get-caller-identity

# Lambda landscape
aws lambda list-functions --region ap-south-1 --max-items 20 \
  --query 'Functions[].{N:FunctionName,R:Runtime,T:Timeout,M:MemorySize}' --output table
aws lambda get-account-settings --region ap-south-1

# API Gateway (HTTP APIs)
aws apigatewayv2 get-apis --region ap-south-1 --query 'Items[].{N:Name,Id:ApiId,Ep:ProtocolType}' --output table

# Queues and topics
aws sqs list-queues --region ap-south-1
aws sns list-topics --region ap-south-1 --query 'Topics[].TopicArn'

# Event buses and state machines
aws events list-event-buses --region ap-south-1
aws stepfunctions list-state-machines --region ap-south-1 --query 'stateMachines[].name'

# DynamoDB tables (names only)
aws dynamodb list-tables --region ap-south-1

Run these in a sandbox account. Prefer read-only IAM while learning.

19. More industry and stack stories

  • Fintech (Aisha, Lagos, NGN): bank webhooks must return 200 fast — SQS absorbs spikes; ledger Lambda is idempotent on paymentId.
  • Ecommerce (Rohan, Pune, INR): Black Friday — API Gateway throttle + SQS order intake; SNS fans inventory, email, analytics.
  • Healthcare (Mei, Singapore, SGD): appointment reminders via SNS SMS; PHI only in DynamoDB with condition keys.
  • EdTech (Diego, São Paulo, BRL): EventBridge nightly cleanup of draft quizzes; Lambda timeout 30s, not 15 min.
  • Logistics (Fatima, Casablanca, MAD): package scans on custom EventBridge bus; Step Functions customs saga.
  • Media (Kenji, Osaka, JPY): S3 → Lambda thumbnails; never write thumbs to the watched prefix.
  • SaaS (Priya, Bengaluru, INR): Cognito groups + DynamoDB PK tenantId; one Lambda authorizer for all routes.
  • Gov (Omar, Amman, JOD): strangler — peel one PDF form route per sprint from the monolith.
  • Startup (Sofia, Sofia, EUR): start with Function URL for demos; move to HTTP API when partners need JWT.
  • Retail (Luis, Mexico City, MXN): store POS sync via SQS FIFO when order matters; Standard when it does not.
  • Python: handlers thin; put domain logic in plain modules for unit tests without Lambda.
  • Node: prefer async/await; never block the event loop on sync DNS.
  • Java: SnapStart for cold starts; keep dependencies lean.
  • .NET: AspNetCoreServer for low-traffic tenants; watch package size.
  • Go: single static binary; great for SQS workers.
  • PHP: keep Laravel queues on ECS; Lambda for S3/webhooks glue.

20. Glossary (short)

TermMeaning
Cold startFirst invoke pays init; later invokes reuse the env
IdempotencySame request twice → same effect
DLQDead-letter queue for failed messages
ChoreographyServices react to events; no central conductor
OrchestrationCentral workflow (Step Functions) directs steps
Fan-outOne event → many consumers
Fan-inMany branches join before next step
Strangler figPeel routes from monolith gradually
SagaDistributed tx via steps + compensations
Provisioned concurrencyKeep N envs warm; you pay for ready capacity

21. Practice: explain out loud

  1. 60 seconds: everyday story for serverless observability.
  2. 60 seconds: sync vs async with a checkout example.
  3. 60 seconds: when you refuse Lambda.
  4. 60 seconds: DLQ + idempotency in one breath.
  5. Record once; cut fillers; record again.

22. Safe lab hygiene

  • Tag every lab resource with owner and expiry date.
  • Set a monthly AWS Budget alarm in INR or USD before experiments.
  • Prefer read-only commands first; mutate in a sandbox account.
  • Delete queues, APIs, tables you created — DynamoDB and APIGW leave footprints.
  • Never put production secrets in env vars or screenshots.
  • Do not enable provisioned concurrency for a hello-world.

24. Myths to drop

MythReality
Serverless means zero serversServers exist; you do not manage them
Always cheaper than EC2Steady high load can favor EC2/Savings Plans
No Ops neededYou own IAM, data, alarms, cost, incidents
One Lambda per app is fineBounded contexts scale better
Queues are optional decorationQueues are the load leveler and blast-radius wall

25. Error budget thinking for serverless

If your monthly error budget is 0.1% on checkout, a fan-out that retries aggressively can burn the budget with duplicate emails while money stays correct. Separate business correctness SLOs from notification SLOs.

  1. Write two SLOs: money-correct and notify-delivered.
  2. Retries on money path: bounded + idempotent.
  3. Retries on notify path: best-effort + DLQ.
  4. Page humans on money DLQ; ticket on notify DLQ.

26. Regional notes (ap-south-1)

  • Build labs in Mumbai (ap-south-1) unless your org mandates elsewhere.
  • Some services launch first in us-east-1 — check feature availability.
  • Data residency for INR fintech may require in-region only.
  • Latency to end users in India usually favors ap-south-1.

27. Naming conventions that save incidents

# Suggested prefixes
# Lambda:  pay-intake-prod, pay-worker-prod
# SQS:     pay-orders.fifo / pay-orders-dlq
# SNS:     pay-order-events
# EB bus:  pay.domain
# SFN:     pay-refund-saga
# DDB:     pay-orders-prod

Include env (dev/stage/prod) and domain. Future you grepping CloudWatch will thank present you.

28. Pre-mortems (ten minutes)

  1. Imagine tomorrow headline: double charge in AED. What broke?
  2. Imagine DLQ depth 50,000 after a bad deploy. How do you drain?
  3. Imagine Cognito outage. Do APIs fail closed or serve read-only?
  4. Write answers in the runbook before go-live.

29. Currency and locale in examples

Rotate currencies in designs: INR, USD, EUR, AED, NGN, BRL, JPY, SGD. Rotate names: Aisha, Rohan, Mei, Diego, Fatima, Kenji, Priya, Omar, Sofia, Luis. This keeps mental models global — not one-country samples.

30. Worked story: Aisha ledger page (NGN)

  1. PaymentFailed metric spikes; alarm pages.
  2. X-Ray shows DynamoDB throttle on ledger table.
  3. Logs filter paymentId show retries exhausted to DLQ.
  4. Fix capacity; redrive; postmortem updates runbook.

31. Anti-patterns

  • console.log without request id.
  • Alarm with no owner or runbook.
  • Tracing 100% including synthetic freeloaders.

Revision, interview and comparison cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Revision card: Structured JSON logs. Free-text logs make incidents a grep lottery. Emit JSON with level, correlation id, and key fields every line. Adopt Powertools Logger → add correlation id → query in Logs Insights. Mei Chen redacts PII before any log line ships.
Revision card: Structured JSON logs · Download PNG · Open card page
Revision card: X-Ray across services. Logs alone cannot show which hop ate the latency. Active tracing + Powertools Tracer links Lambda to downstream calls. Enable active tracing → sample wisely → open the service map on incidents. Ravi Sir opens the service map before guessing the slow API.
Revision card: X-Ray across services · Download PNG · Open card page
Comparison: Free-text logs vs Structured JSON. Free-text logs: Human sentences hard to aggregate. Structured JSON: JSON fields queryable in Logs Insights.
Comparison: Free-text logs vs Structured JSON · Download PNG · Open card page
Comparison: Logs only vs Logs + X-Ray. Logs only: Each service logs locally; hop latency hidden. Logs + X-Ray: Traces show the cross-service path and slow segment.
Comparison: Logs only vs Logs + X-Ray · Download PNG · Open card page
Interview card: Correlation id. Support cannot stitch API→Lambda→Dynamo without a shared id. Propagate one correlation id on logs, traces, and outbound events. MNC: where do you generate the id if the client did not send one?
Interview card: Correlation id · Download PNG · Open card page
Interview card: EMF custom metrics. PutMetricData per request can cost and throttle under load. Embedded Metric Format emits metrics from structured log lines cheaply. MNC: name one business metric you would EMF from an order Lambda.
Interview card: EMF custom metrics · Download PNG · Open card page
Interview card: Alarm Errors + Throttles. Watching only duration misses outages that return errors fast. Alarm on Errors, Throttles, and saturation signals for critical functions. MNC: what page goes with the alarm — runbook first line?
Interview card: Alarm Errors + Throttles · Download PNG · Open card page
Interview card: Sample traces for cost. 100% tracing on a hot path can dwarf the compute bill. Sample high-volume traces; keep errors and slow traces preferentially. MNC: propose a sampling rate for a 5k RPS public API.
Interview card: Sample traces for cost · Download PNG · Open card page

More cards: Ravi Sir's Cards.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Milan Furniture is a furniture business in Milan. Giulia Rossi looks after its IT and cloud work. They count money in EUR and run their AWS resources in the eu-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 16

Easy Trace an AWS request path

Which AWS tracing service can show parts of a request across instrumented services and help locate a slow dependency?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Easy Make logs queryable by field

A team wants logs with named fields such as service and eventId. Which common structured format can it emit?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Easy Join logs without a secret

Three functions write separate logs. What common identifier should they carry so a team can trace one business request across the logs?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Easy Identify Lambda helper libraries

Name the AWS open-source toolkit taught here for structured logging, tracing and metrics in Lambda code.

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Easy List log groups

CLI.

List CloudWatch log groups

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Obs stack YAML

Map.

YAML: traces: xray, logs: json, lib: powertools.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Easy Select incoming request instrumentation

Which tracing mode on a supported Lambda function causes it to sample and trace requests rather than only using the upstream setting?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Turn selected log fields into metrics

Which CloudWatch log format expresses custom metric data alongside log fields?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Calculate observed failure percentage

A test period records 240 invocations and 12 errors. Enter the error percentage as a number without a percent sign.

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Calculate an expected trace count

An exercise samples 10 percent of 4,000 uniformly eligible requests. How many traces does that represent on average?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Protect sensitive log fields

An email address and login token are included in an incoming request. What operation hides these values before writing a diagnostic log?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Ops YAML

Alarm.

YAML: alarm_on: errors, link: correlation_id.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Hard Read an initialization field

Which field in Lambda REPORT log entries measures initialization for executions where this duration is reported?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Hard Name a latency percentile

The team wants the value that 95 percent of request latencies fall at or below. Which percentile is this?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Hard Choose a less verbose production level

Assume levels DEBUG, INFO, WARN and ERROR. Which standard level keeps routine service events while excluding DEBUG detail?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Hard Clean up persistent log data

After deleting the disposable Lambda function, which CloudWatch resource might still retain its generated logs and need a separate cleanup step?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.