Log so you can query
Grepping free-text logs across 200 servers during an incident.
Say it like this
During an incident I need to filter logs by request id, user and service across the whole fleet in seconds, so every service writes JSON lines with a fixed set of fields to a central store instead of free text to local disk.
Basic solution
Emit structured (JSON) logs with request id, user id and service, shipped to a central store.
JSON lines from every instance to one queryable store
Services write JSON to stdout; an agent redacts, batches and ships; the store indexes a few fields and keeps a hot and a cold tier. A query by request id returns the whole story in order.
How it works
- Each service writes one JSON object per event to standard output instead of a free-text line. Every object carries the same base fields: timestamp, level, service, instance, request_id, user_id and message, plus fields specific to the event such as duration_ms or provider.
- A log agent on each host (or a sidecar container next to the service) tails standard output, adds host and deployment labels to each object, groups the objects into batches of a second or so, and ships the batch to the log pipeline. The service itself never talks to the log store.
- The pipeline parses each JSON object, builds an index on the fields that are queried (request_id, user_id, service, level) so searches on them are lookups rather than scans, and stores the remaining fields as compressed text.
- Engineers query by field rather than by substring: every line for request_id X across all services, ordered by time; or every error in the sms-sender for the last 10 minutes, grouped by provider error code.
- Retention is tiered by age. Lines stay hot and indexed for 7 to 14 days, move to cold compressed storage for 90 days, then are deleted or archived to object storage.
- Levels and sampling keep the volume in check. Debug lines are off in production or kept for 1% of requests, info lines mark request boundaries, and warn and error lines are always kept.
What a log line is for
- Logs answer "what exactly happened in this request" after metrics have told you something is wrong. They are the detail you read during an incident, not the alarm that starts it.
Worked example
Notification system log volume
- Each notification produces about 6 log events across the API, router and sender: submit, routed, provider call, provider response, delivery row update, webhook receipt. At 2,900 notifications/s that is ~17K events per second.
- Average event 400 bytes of JSON: 17K × 400 B ≈ 7 MB/s ≈ 600 GB per day raw, about 120 GB per day after 5:1 compression.
- Hot tier 14 days: 1.7 TB compressed on an OpenSearch cluster; cold tier 90 days in object storage: another 9 TB at a few hundred dollars a month.
- Cutting volume: drop the per-event info logs for successful push sends (60% of volume) and keep one summary line per notification with all six timestamps. Volume falls to about 7K events/s, roughly 50 GB per day compressed.
- Incident query: a user reports a missing OTP. Search user_id = 8831 and category = otp in the last hour: 3 lines show submit at 12:01:02, routed at 12:01:02, provider 429 at 12:01:03 with retry scheduled. The query returns in under 2 seconds against 14 days of data because user_id is an indexed field.
- Never logged: the OTP code itself, phone numbers beyond the last 2 digits, and API keys. A redaction step in the agent masks fields matching a deny list before shipping.
Variants and when each wins
Indexed document store (Elasticsearch, OpenSearch)
- Every field of every line is indexed for full-text and field search. It wins when engineers run ad-hoc field searches daily; it loses on cost at volume because indexing everything is expensive.
Label-indexed with brute-force content (Loki)
- Only a few labels (service, level, instance) are indexed, and queries grep the compressed content of the matching streams. It wins on cost, roughly ten times cheaper, and loses on speed for searches over rare fields.
Columnar in a warehouse (ClickHouse, BigQuery)
- Each log line is a row in a column store. It wins for aggregations over long ranges, such as error counts per template version over a month; it is less suited to tailing a service live.
Managed (CloudWatch Logs, Cloud Logging)
- The cloud provider ingests and stores lines and bills per GB ingested and scanned. It wins below a few hundred GB per day with no operations to run.
Recommendation: Loki or a managed store with a strict field schema and sampling for the bulk; keep a short hot window in an indexed store only if ad-hoc field search is a daily need.
Failure modes
Secrets and PII in logs
- An audit finds API tokens and phone numbers in the log store, and therefore in every backup of it. It happens because the code logs whole request bodies. Allow-list the fields you log, redact in the agent before shipping, and treat the log store as sensitive data with its own access controls.
Unbounded volume
- The log bill grows past the compute bill. It happens because debug logging is on in production, a line is written per loop iteration, and retries log the same payload again. Enforce levels in config, sample high-volume paths, and write one summary line per request.
Inconsistent field names
- A query for user_id misses the services that call the same field userId or uid. It happens because each team wrote its own logging code. Ship one logging module per language with a fixed schema, and add a linter that rejects unknown top-level fields.
Local-only logs lost with the instance
- The logs from the instance that crashed are gone with it. It happens because logs were written to local disk and shipped only when the file rotated. Stream to standard output and ship continuously, with the agent buffering a few seconds rather than hours.
No request id
- Lines from ten services about one request cannot be joined into a story. It happens because no correlation id was generated and passed along. Mint one at the edge and include it in every line; the correlation ids block covers how it travels.
Interviewer follow-ups
Answer out loud before you open each one.
What fields belong in every log line?
Timestamp in UTC with milliseconds, level, service, instance or pod, request id, and a short message. Add user id or tenant where the service knows it, and a stable event name so you can count occurrences without parsing the message.
How do you keep log volume under control without losing the lines you need?
Always keep warnings and errors; sample successful info events at a fixed rate; and keep one summary line per request with timings and outcome. During an incident you can raise the sample rate for one service through config.
Logs, metrics or traces: when do you use which?
How would you find every notification affected by a bad template version?
Query the log store for event = rendered and template_version = 12 over the deploy window, group by notification id, and feed the ids to a replay job. That works only because template_version is a structured field; in free text it would be a regex over terabytes.
Connections
- In study paths
- Knowing what broke
- Built on
- Ring buffer
- Pairs with
- Tag every log line with the request · Follow one request across services · Measure what users feel · Protect data and secrets
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 Auto Scaling | Service pods | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon CloudWatch | Hot store (14 days) | Cloud Monitoring, Cloud Logging | Azure Monitor | Prometheus and Grafana, Datadog |
| Amazon S3 | Cold archive (90 days) | Cloud Storage | Blob Storage | Cloudflare R2, MinIO, Ceph |