# Exercise 1: Logs Insights and Metric Filters for an API

The `checkout-api` (ECS) writes JSON logs to log group `/ecs/checkout-api`:

```json
{"ts":"2025-06-12T10:15:03.120Z","level":"info","msg":"request completed","requestId":"r-81","route":"/v1/checkout","status":200,"durationMs":184,"userTier":"gold"}
{"ts":"2025-06-12T10:15:03.400Z","level":"error","msg":"payment failed","requestId":"r-82","route":"/v1/checkout","provider":"psp-a","errorCode":"TIMEOUT"}
```

## Deliverables

1. Set the log group **retention** to 30 days (CLI).
2. Write Logs Insights queries for:
   a. requests per route and status class in 5-minute bins over the last 3 hours;
   b. p50/p95/p99 `durationMs` per route, slowest first;
   c. the top 10 `errorCode` values for `payment failed` in the last 24 h, by provider;
   d. all log lines for one `requestId` across the service, in time order.
3. Create a **metric filter** that publishes `Shop/Checkout PaymentFailures` (value 1, dimension `Provider` from the log field) for every `payment failed` line, and an alarm when failures exceed 20 per minute for 3 of 5 minutes.
4. Explain why `durationMs` percentiles should come from logs/EMF or high-resolution raw data rather than from each task publishing its own p99.
5. Estimate monthly log volume if the service handles 400 req/s with ~1.2 log lines of ~300 bytes per request, and the cost impact of 30-day vs never-expire retention (state your per-GB assumptions).

## Requirements Checklist

- [ ] `aws logs put-retention-policy --log-group-name /ecs/checkout-api --retention-in-days 30`.
- [ ] Queries use `filter`, `stats ... by bin(5m)`, `pct(durationMs, 99)`, and `sort`; status class computed (e.g. `floor(status/100)`).
- [ ] Metric filter pattern on JSON fields (`{ $.msg = "payment failed" }`) with a dimension mapped from `$.provider`.
- [ ] Alarm with 3 of 5 datapoints and `notBreaching` for missing data.
- [ ] Percentiles can't be averaged across instances — explanation present.
- [ ] Volume math: 400 × 1.2 × 300 B ≈ 144 KB/s ≈ 12.4 GB/day ≈ 373 GB/month, with a storage comparison over time.
