Tracking Down Intermittent Production Errors Using Only Logs
BehavioralModel answerLast updated
Plan a log-driven investigation of sporadic production failures that never show up in local tests, including team task split, hypothesis tracking, fix verification and a postmortem.
You have just taken ownership of a backend service. Its unit tests all pass on your laptop, yet production logs show errors that appear sporadically and without an obvious pattern. No debugger can be attached to the live system, so logs are your main source of evidence.
Describe how you would handle this from first alert to final retrospective. Your answer should cover:
- Log configuration: how you would adjust verbosity in production, safely and temporarily.
- Better log content: what structured, contextual fields you would add, and how correlation IDs let you follow a single request.
- Finding the signal: how you would cut through a noisy log stream to find the errors that matter.
- Reproduction: how you would build a minimal, repeatable failing case.
- Isolation: how feature flags or canary releases help you narrow down the culprit.
- Team organization: how you would split the investigation among teammates, set up a triage board, and track each hypothesis until it is resolved.
- Closing out: how you would prove the root cause, ship the fix, add regression tests and alerts, and hold a blameless postmortem.
Explain the reasoning behind your choices and the trade-offs involved, not just a checklist.
Hints
Hint 1
Start by measuring impact and finding when the errors began. Compare that timeline with deploys, config changes and traffic patterns, and decide whether a rollback should come before any investigation.
Hint 2
Think about what differs between your laptop and production: concurrency, real data shapes, timeouts, resource limits, configuration and dependency versions. Turn each difference into a hypothesis that makes a testable prediction.
Hint 3
Treat the investigation like a project: give one owner per track, keep a single board listing each hypothesis with its evidence for and against, and only call a cause confirmed when you can both trigger and remove the failure on demand.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overall approach
Work through the incident in order: stabilize, instrument, narrow, reproduce, isolate, confirm, fix, prevent, learn. The guiding idea is that every action should either reduce customer harm or test a specific hypothesis. Guessing and random changes are the main failure mode.
1. Stabilize and scope
- Quantify the problem: error rate (say 0.3% of one endpoint), affected customers, and how fast the error budget is burning.
- Find the start time and overlay it on deploys, config pushes, dependency upgrades, traffic peaks and scheduled jobs.
- If customers are materially hurt, mitigate first by rolling back or disabling a flag. Root cause can wait; harm cannot.
2. Set log levels deliberately
- Production normally runs at
INFO. Raise toDEBUGonly narrowly and temporarily: for one module, one host, or a sampled slice of requests, controlled by runtime config so no redeploy is needed. - Never raise the whole fleet. It increases cost and latency and risks leaking personal data.
- Keep level semantics consistent:
ERRORmeans someone must act,WARNmeans degraded but handled (retries, fallbacks),INFOrecords business events,DEBUGrecords internals. - Attach an expiry to any elevated logging so it does not linger.
3. Structured, contextual logging
Emit JSON rather than free text so lines can be filtered and grouped. Each line should carry:
- A correlation ID (
request_idortrace_id), created at the edge and propagated through HTTP headers and message-queue metadata. - Service name, build version or git SHA, host, region.
- Endpoint, latency, retry count, flag state.
- Downstream dependency name and result.
- A hashed tenant or user identifier (never raw PII).
import contextvars, json, logging, time, uuid
request_id_var = contextvars.ContextVar("request_id", default="-")
class JsonFormatter(logging.Formatter):
def format(self, record):
payload = {
"ts": time.time(),
"level": record.levelname,
"msg": record.getMessage(),
"request_id": request_id_var.get(),
"logger": record.name,
}
payload.update(getattr(record, "ctx", {}))
if record.exc_info:
payload["exc"] = self.formatException(record.exc_info)
return json.dumps(payload)
def handle_request(headers, handler):
rid = headers.get("X-Request-ID") or str(uuid.uuid4())
token = request_id_var.set(rid)
try:
return handler()
finally:
request_id_var.reset(token)
Using contextvars keeps the ID correct under threads and async code, which is exactly where intermittent bugs hide.
4. Separate signal from noise
- Fingerprint errors by exception type, normalized message and top stack frame. Rank groups by volume and first-seen time. A fingerprint that first appeared at a deploy is a strong lead.
- Compare against a healthy baseline across dimensions: version, host, availability zone, endpoint, payload size, tenant, dependency. Errors only on one host point to infrastructure; only on the new version point to code; correlated with a slow dependency point to timeouts or retries.
- Filter known noise (health checks, benign client disconnects) but keep a written list of what you suppressed so nothing is hidden by accident.
- Read full timelines of roughly ten failing requests by correlation ID and look for shared traits.
5. Why do tests pass locally?
List the differences and turn each into a prediction:
- Race conditions and concurrency.
- Real data: nulls, unicode, huge payloads.
- Timeouts and retry storms under load.
- Config or secret drift, dependency version skew.
- Clock skew and time zones.
- Resource limits such as connection pools, memory, file descriptors.
- Cache state.
A good hypothesis is falsifiable: "If pool exhaustion is the cause, errors rise when concurrent requests per pod exceed 20."
6. Minimal reproducible case
- Extract the sanitized inputs, headers and timing of failing requests from the logs.
- Replay them in staging with production-like configuration.
- Add the missing conditions: concurrent load, injected latency or faults, matching dependency versions.
- Shrink the case until removing anything makes the failure vanish.
- Save it as an automated failing test; it becomes the regression test later.
7. Isolate with flags and canaries
- Put the suspect change behind a flag and disable it for, say, half of traffic. Compare error rates between cohorts.
- Run the previous version as a canary beside the current one; if rates differ, bisect the commits between them.
- Change one variable at a time, and log flag state on every request so cohorts can be queried.
Organizing the team
Appoint an incident lead who coordinates and communicates but does not dive into code. Run parallel tracks, each with a single owner:
| Track | Focus |
|---|---|
| Observability | Instrumentation changes, dashboards, fingerprint queries |
| Change analysis | Deploy, config and dependency diffs; bisecting |
| Dependencies and infra | Downstream latency, pools, host or zone skew |
| Reproduction | Replay harness, minimal case, failing test |
| Communication | Stakeholder updates on a fixed cadence |
Triage board
Keep one shared board with columns: Hypothesis, Prediction, Evidence for, Evidence against, Owner, Next experiment, Status (Open, Testing, Refuted, Confirmed). Rules:
- Timebox every hypothesis.
- Keep refuted ones visible with the evidence that killed them, so nobody repeats work.
- Hold short syncs (for example every two hours during an active incident).
- Record decisions on the board, not in private messages.
Confirming root cause
Call it confirmed only when you can:
- Explain the mechanism end to end and match it to the log evidence.
- Trigger the failure on demand in the reproduction.
- Make it disappear by removing the cause (flag off, fix applied) and see production error rates drop in the treated cohort.
Correlation alone is not enough; a cause that explains only some of the errors may mean there are two bugs.
Fix, prevention and learning
- Ship the fix behind a flag, roll out gradually (canary, then wider), and watch the same metrics that exposed the problem.
- Add the failing repro as a permanent regression test, plus a concurrency or fault-injection test if the bug was load-related.
- Add alerts on the symptom (error fingerprint rate, saturation of the relevant resource) with sensible thresholds, and keep the better logging that made diagnosis possible.
- Hold a blameless postmortem: timeline, impact, contributing factors, what detection and response did well or poorly, and owned action items with dates. Focus on system gaps (missing alerts, weak tests, risky rollout), not individuals.
Common mistakes
- Turning on debug logging fleet-wide and drowning in data or leaking PII.
- Investigating before mitigating when impact is high.
- Changing several things at once, so the effect cannot be attributed.
- Declaring victory because errors went down, without proving the mechanism.
- Skipping the regression test and alert, so the same failure returns.
- Letting the lead get absorbed in debugging and losing coordination.