Learnings

Senior engineering skills

Debugging Production

Production debugging is a method, not a talent: stop the harm, ask what changed, cut the search space in half, and write down what you saw. The method is shown on a small bank API (Python 3.9 standard library, SQLite, four worker threads) that is broken six different ways and diagnosed from the outside, with every log line, count and timing pasted from a real run.

The method

Part 1 of 6 · how to think before you touch anything

Debugging is a loop

The method

Each pass should rule out about half of what is left. A check whose result would not change your next step is not worth running.

Evidence first, guess second, and one cheap test per guess.
  • Write the hypothesis down before the test, with the result you expect.
  • Change one thing at a time, or you will not know which change worked.

Mitigate before you diagnose

The method

While users are being hurt, the goal is to stop the harm, not to understand it. Pick the fastest reversible action, then investigate with the pressure off.

Four ways to stop the bleeding, cheapest first.
  • Keep the evidence before you restart: copy the logs, dump the thread stacks, note the counts.
  • A restart is a mitigation only if the fault needs time to build up again (leaks). Otherwise it is a coin toss.

What changed?

The method

A system that worked yesterday and fails today was changed by something. Most incidents are found by listing recent changes, not by reading code.

SuspectWhere to look
DeployRelease log, boot lines, version in /health
Config, flags, secretsFlag audit log, environment of the process
DataNew kind of row, a NULL, an empty account, a huge customer
TrafficRequest rate by route and by client, a new caller
DependencyTheir status page, your latency per upstream
TimeCertificate expiry, cron, month end, a counter or disk filling up

Trap: "nothing changed" usually means "nothing I deployed changed". Data, traffic and time change without a commit.

The first five minutes

The method

Four questions size the problem and choose the first tool. Answer them from dashboards and logs, not from memory.

Scope, time and kind, in that order.
  • "Some users" points at data or one host. "Everyone" points at a deploy, a dependency or capacity.
  • "Since when" gives the timestamp to line up against deploys and flags.
  • Wrong data is the worst kind: it keeps growing while you look, and no error rate shows it.

Related: the dashboards these answers come from (rate, errors, duration, SLOs) are in Observability.

Blast radius and severity

The method

Blast radius (who is affected, times what they cannot do) sets the severity, and the severity sets who is woken up. Levels differ by company: this is a typical shape.

LevelMeaningBank exampleTell, and when
SEV1Core function down, or data being damagedTransfers lose moneyPage on-call and a commander now. Customers within about 30 minutes.
SEV2Major feature degraded for manyEvery endpoint hangs at peakPage on-call now. Status page if it lasts.
SEV3One feature broken for someSummary fails for new accountsTeam channel, fix in working hours.
SEV4Cosmetic, or a workaround existsWrong label on a statementTicket.

Rule: when unsure, declare the higher level. Downgrading later costs nothing, upgrading late costs trust.

Narrowing down

Part 2 of 6 · the demo service, and bisecting in space and time

The service under test

Narrowing down

One file of 206 lines: six endpoints, four worker threads, SQLite. Lines 18 to 127 are below, and six faults are already in them: try to spot them before reading Part 3.

  • init_db.py (not shown) makes five accounts with 50,000 rupees each and 60 seed transfers. Account 5, Hemkesh Agrawani, is new and has sent nothing.
  • Not shown: dispatch (line 150 calls the handler, logs start and done with a request id, turns any exception into a logged 500) and a server that hands each connection to a pool of four threads.
  • Two debug hooks are built in: SIGUSR1 dumps every thread's stack (faulthandler), SIGUSR2 logs the biggest allocation (tracemalloc).

Bisect in space: which layer

Narrowing down

A request crosses several hops, and the fault lives in one of them. Test the middle hop first: each check clears everything on one side.

The request path. One hop is lying to the next.
HopCheck
ClientSame request with curl -v from another network
DNS, networkdig, then connect time from curl -w
Proxy, load balancerIts status codes (502, 503, 504) and which backends are in rotation
Appcurl the app port directly, in-flight count, error rate by route
DatabaseActive and waiting connections, slowest running query, locks
DependencyCall it by hand with a timeout, compare with its dashboard

Related: the hop-by-hop "service unreachable" checklist with ss, curl and dig is in Linux Networking.

Bisect in time: which change

Narrowing down

Put every change on one timeline and mark the first bad request. The suspect is the last change before that mark.

Illustrative timeline: the change one minute before the first error goes first.
  • Deploys, flag flips, config pushes, migrations and cron jobs all belong on the same timeline.
  • With many commits between good and bad, git bisect halves them: 1,000 commits need about 10 builds.
  • A slow-building fault (a leak) starts long before the first error. Look for the change before the growth began, not before the crash.

Compare a good and a bad request

Narrowing down

Hold everything the same and vary one thing until the result flips. Here the route, version and time are the same, and only the account differs.

Account 5 is the only one with no row in that count. To reproduce safely:

  • Read-only requests first. For writes, use a test account or a copy of the data.
  • Reproduce on one instance taken out of rotation, or in staging with production's config.

Six worked faults

Part 3 of 6 · symptom, checks, cause, fix, and how to catch it earlier

1. A bad deploy: 500 for one kind of input

Six worked faults

Symptom: after version 1.4.0, a few customers see an error on the summary screen and most do not (the 500 in the comparison above).

Check 1: error rate by route, after 400 mixed requests. One route, and only some of its calls.

Check 2: which inputs, and one stack trace. Join the failing request ids back to their start lines, then read one of them.

Mitigate, then fix: The new field sits behind a flag that is read on every request, so the mitigation is one file write and no deploy.

Caught earlier by: a test with an empty account, an alert on 5xx rate per route (the overall rate here was under 5%), and a canary that takes a slice of real traffic before the full rollout.

2. A slow dependency with no timeout

Six worked faults

Symptom: the rates service starts taking 30 seconds to answer, six clients ask for /rates, and then endpoints that never touch rates stop answering too.

Connect takes 0.2 ms, so network and listener are fine: the app accepts and then says nothing. Check 1: requests started against finished.

Four in flight, four workers, and no start line at all for the health checks. Check 2: sockets.

Four outbound connections to port 8793, one per worker, and two CLOSE_WAIT lines: the health checks, whose clients gave up with nobody free to notice. Check 3: where each thread is.

One slow endpoint holds every worker, so the healthy ones starve.

Root cause and fix: urlopen with no timeout waits for ever. Bound the wait and turn the failure into a fast 503.

  • Health answers again, but it still waited a second for a worker. A timeout bounds the damage, it does not remove it.
  • Next steps: a circuit breaker so calls fail at once while the dependency is down, and a separate small pool for that dependency (a bulkhead).

Caught earlier by: a rule that every network call has a timeout, an in-flight gauge with an alert near the worker count, and a test that runs against a deliberately slow stub.

3. A descriptor leak

Six worked faults

Symptom: the service runs fine for a while, then every database endpoint returns 500 and only /health stays green. The process runs under ulimit -n 64 so that "a while" is seconds.

Check 1: count descriptors over time with lsof -nP -a -p $PID -d 0-999 | tail -n +2 | wc -l. Each round is 20 requests, half of them for account 77, which does not exist.

Ten more per round, exactly the number of 404s, then flat at the limit. Check 2: what the descriptors are.

57 handles on the database file, 57 responses with status 404: one leaked connection per 404.

The happy path gives the connection back. The error path forgot.

Caught earlier by: a gauge of open descriptors (or pool checkouts) with an alert on its slope, a pool with a hard maximum that fails loudly, and acquiring only through with or try/finally.

4. A cache without a bound

Six worked faults

Symptom: no errors, but memory climbs until the process is killed, usually days after the deploy that caused it. The mobile app asks for statements with ?to=<now in milliseconds>.

Check 1: resident memory against requests served (ps -o rss= -p $PID after every 2,000 statements).

About 6 KB per request that never comes back: a leak, not a warm-up. Check 2: ask the process who allocated it, on one instance restarted with PYTHONTRACEMALLOC=3: 2,000 statements, then kill -USR2 $PID.

Root cause and fix: the cache key includes the raw query string and every request sends a new one, so nothing is reused or removed. Give the cache a size.

  • tracemalloc names where memory was allocated (line 43), not who keeps it. Ask for several frames to see the holder (line 83).
  • The bound stops the leak. The cache is still useless until the key drops the timestamp, which is a product decision.

Caught earlier by: memory per instance on a dashboard over a week, a cache hit-ratio metric (it was 0%), and a review rule that every in-process cache states its maximum size.

5. Two transfers, one wrong balance

Six worked faults

Symptom: a customer, Subhash Agrawani (account 3), says his balance is lower than his statement adds up to. Every request returned 201 and the log has no errors.

Check 1: reconcile. Recompute each balance from the opening balance and the ledger, and compare.

Check 2: reproduce with two threads. race.py starts two threads that each POST 200 transfers of 10 rupees to account 3, one from account 1 and one from account 2.

440 rupees left accounts 1 and 2 and arrived nowhere. The size of the drift changes from run to run, which is the signature of a race.

Read, compute in the app, write back: the second write erases the first.

Fix. One transaction per transfer, and let the database do the arithmetic.

  • The code fix does not repair the damaged rows. That is a separate, reviewed data correction driven by the reconcile query.

Caught earlier by: the reconcile query as a scheduled job that alerts on any drift, a concurrency test like race.py in CI, and the invariant "total money is constant" checked after every test.

6. Works locally, fails in production

Six worked faults

Symptom: same code, version and schema, yet a transfer works locally (port 8791) and is refused in "production" (a second process on port 8794).

No 5xx and no error log, so an alert on server errors never fires. Check: diff the two environments, here the environment variables of each running process (/health reports version 1.4.0 on both).

A diff gives candidates, not the answer: three differences here. Test the likeliest by changing only that one.

Root cause and fix: the variable was never set in production and the code quietly defaulted to 0. Required config gets no default, so a bad deploy fails at boot and not at the first customer.

  • The same diff habit finds time zone, locale, library version and missing-migration differences: compare pip freeze and the schema the same way.
  • Never print secrets when diffing environments. Compare names, or hashes of values.

Caught earlier by: config validated at startup, effective (non-secret) config logged at boot, an alert on 4xx rate per route, and a smoke test that makes one real transfer after each deploy.

Handling evidence

Part 4 of 6 · reading what the system tells you

Correlation ids

Handling evidence

One id per request, taken from the caller if it sent one, written on every log line and returned in the response. Then one grep gives the whole story of one request.

  • Pass the same id on every outbound call, so the trail continues in the next service.
  • Put it in the error body. A customer can then quote request_id to support.

Read a stack trace bottom-up

Handling evidence

The last line says what went wrong, the frame above it says where, and the frames above that say how the program got there. This is the first error of fault 3.

ReadLineIt tells you
1stsqlite3.OperationalError: ...What failed: an open, not a query
2ndline 31, in acquireWhere: making a new connection, so the pool was empty
3rdline 58, in accountWho asked: the last frame of business code
Lastline 150, in dispatchFramework plumbing, rarely the cause
  • The usual source line under each frame is missing: Python could not open bank_api.py to read it, because the process had no descriptors left. The gap is itself evidence.

Related: pdb, the logging module and log.exception are covered in Debugging and Logging.

The first error, not the loudest

Handling evidence

One cause produces many different errors downstream, and the most frequent one is rarely the cause. Sort by time before you sort by count.

Fault 3: one cause, three kinds of noise, and the cause itself logs nothing.
  • In fault 3 the 404s that leaked were logged as successes. The errors came from innocent requests that arrived later.
  • Search for the first occurrence (grep -m1 ERROR), then read what happened just before it.
  • Error text can mislead: "unable to open database file" was not a missing file.
When sampling logs, keepHow much
Errors, 5xx and slow requestsAll: they are the needle
Successful requests1 in N, chosen by hashing the request id, so every service keeps the same requests
Counts by route and statusAll, as metrics, so rates stay exact

Trap: sampling line by line keeps the start of one request and the end of another. Decide once per request.

Add logging, or attach to the live process?

Handling evidence

Prefer the least invasive tool that answers the question. A hook you built in before the incident is the safest of all.

OptionUse whenRisk
Built-in hook (stack dump on a signal, debug endpoint)Stuck or slow process, right nowLow. Sending the signal to a process with no handler kills it.
Raise log level at runtimeYou need more detail on one pathLog volume and cost, secrets in debug lines
Add logging and redeployThe fault is repeatable and can wait minutesA restart destroys the state of a leak or a hang
Sampling profiler attached from outsideCPU is busy and you do not know whereNeeds privileges, small pause per sample
Interactive debugger on a live processAlmost never in productionA breakpoint stops every request on that thread

Related: profilers and finding the bottleneck under load are in Performance and Load Testing.

Safe actions in production

Part 5 of 6 · do not make the incident bigger

Read-only and risky commands

Safe actions in production

Looking is free, changing is not. Know which side of the line a command is on before pressing Enter.

Read-only: just run itRisky: say it first, get a second pair of eyes
curl a GET, /healthAny POST, PUT or DELETE against real data
grep, tail, awk on logsTruncating or deleting logs to free disk
ps, lsof, netstat or ss, dfkill, restart, kill -9 (no cleanup, no evidence)
SELECT with a LIMIT, on a replicaUPDATE, DELETE, DDL, a full-table SELECT on the primary
EXPLAINEXPLAIN ANALYZE: it runs the query
Reading config and flagsChanging config, flushing a cache, scaling down

Trap: "read-only" can still hurt. A heavy query on a struggling primary, or packet capture with full bodies (customer data), are both changes.

Flags and kill switches

Safe actions in production

A feature flag separates deploying code from turning it on. A kill switch is a flag whose only job is to turn something off quickly.

PropertyWhy it matters at 3 a.m.
Read at request time, not at bootOff in seconds with no restart (fault 1)
Safe default when the flag store is downThe flag system must not be a new outage
Every flip is logged with who and whenFlips belong on the timeline

Trap: the demo reads flags.json on every request, which is why fault 3 broke it. Real flag clients cache the value and refresh in the background.

Roll back or roll forward

Safe actions in production

Rolling back returns to a version that is known to work. Rolling forward ships a new, less tested change under pressure, so it needs a reason.

Roll back by default. Roll forward only when going back is the riskier move.
  • Rollback stays possible only if migrations are backward compatible: add first, remove in a later release.
  • A rollback does not undo bad data written by the bad version (fault 5).

Database changes and the two-person rule

Safe actions in production

A wrong manual write during an incident turns one incident into two. Slow down exactly here.

RuleIn practice
Two peopleOne types, one reads the statement aloud and confirms host and database
Count before you changeRun the WHERE as a SELECT COUNT(*) first
Inside a transactionBEGIN, change, check the row count, then COMMIT or ROLLBACK
Keep a way backCopy the affected rows to a side table first

Interview point: the two-person rule is not about distrust. Under stress people run the right command on the wrong host.

The incident, and after

Part 6 of 6 · roles, updates, the post-mortem and a cheat sheet

Roles and the status update

The incident, and after

The person debugging cannot also coordinate and write updates. Split the work as soon as more than two people are involved.

The commander decides and does not type commands. Operations is the only role that changes production.
  • Impact in the customer's words, a fixed next-update time, and no guesses stated as facts.
  • Handoff: the outgoing person states the current hypothesis, what was ruled out and what is in progress, and the incoming person says "I have it" in the channel.

The timeline: MTTD and MTTR

The incident, and after

Every incident has the same five timestamps. The gaps between them show whether to invest in detection, response or repair.

Users stop hurting at "mitigated". The root cause is gone at "resolved".
MetricMeasuresImprove it with
MTTD, mean time to detectFault starts to detectedAlerts on symptoms, reconciliation jobs
MTTA, mean time to acknowledgeDetected to acknowledgedPaging policy, fewer noisy alerts
MTTR, mean time to recoverFault starts to mitigated (definitions vary, say which)Rollback speed, flags, runbooks

Trap: "MTTR" is used for repair, recovery, respond and resolve. State the start and end points whenever you quote it.

The blameless post-mortem

The incident, and after

Blameless means asking why the action made sense to the person at the time, so people report what really happened. The output is a document with a fixed shape.

SectionContains
SummaryThree sentences: what broke, for whom, for how long
ImpactNumbers: users, requests, money, minutes
TimelineTimestamps of events, decisions and what each was based on
Root causeThe change in the system that, if absent, means no incident
Contributing factorsWhat made it likelier, larger or longer
What went well, what was luckyKeep the first, do not rely on the second
Action itemsOwner, due date, and the kind (see below)

Root cause vs contributing factor: in fault 2 the missing timeout is the root cause. Four workers, no in-flight alert and no slow-stub test are contributing factors: each one fixed would have made it smaller, none would have prevented it.

Five whys

The incident, and after

Keep asking "why" until the answer is a process or a design, not a person or a line of code. Fault 2, worked through:

The last box is where the action item goes: one HTTP client with a default timeout.
  • Stopping at "the call had no timeout" fixes one call. The next engineer writes the same bug.

Action items that prevent recurrence

The incident, and after

"Be more careful" is not an action item. Each one changes the system and falls into one of three kinds.

KindQuestionFrom the six faults
DetectionHow do we know in one minute next time?5xx and 4xx alerts per route, in-flight gauge, descriptor and memory slope, hourly reconcile job
PreventionHow does this class of bug not ship?Default timeout in one HTTP client, connections only via with, bounded caches, transactions for money, config checked at boot
MitigationHow do we make it smaller and shorter?Flag on every new path, one-command rollback, bulkhead per dependency, canary release

Rule: every item has one owner and a date, and at least one item is detection. A fix with no new alert means the next variant is found by customers again.

Symptom to first check

The incident, and after

SymptomFirst checkLikely cause
500s on one route, some inputsError rate by route, one stack traceBad deploy, unexpected data
Everything hangs, connect is fastStarted vs finished, sockets, thread dumpWorkers held by a dependency
Fine for hours, then errors on all routesDescriptor or connection count over timeLeak on an error path
Memory climbs, restarts "fix" itRSS against requests, then tracemallocUnbounded cache or list
Wrong numbers, no errorsReconcile against the ledgerRace, missing transaction
Works on one machine onlyDiff version, environment, schemaConfig or environment
Connect itself fails or is slowDNS, port, proxy status codesNetwork or proxy hop
Fails at the same time every dayCron, batch jobs, backupsTime

On-call checklist

The incident, and after

WhenDo
Before the shiftLaptop, access and pager tested. Recent deploys and open risks read. Runbooks and rollback command known.
Minute 0 to 5Acknowledge. Scope: who, which endpoints, since when, what kind. Declare a severity. Open one channel.
Minute 5 to 15List what changed. Mitigate: roll back, flag off, scale or shed. Save evidence before any restart.
While it lastsOne hypothesis at a time, written in the channel. Updates at fixed times. Ask for help early.
Before closingVerify with the check that showed the fault. Watch for one full cycle. Say "resolved" and at what time.
AfterTimeline while memory is fresh. Post-mortem within days. Action items with owners.

Interview questions

The incident, and after

QuestionShape of a good answer
Tell me about a production incident you debugged.Impact in numbers, how it was detected, how you mitigated first, the two or three checks that narrowed it, root cause, the fix, and what you changed so it cannot recur. Say "I" for your actions and include one thing you got wrong.
An alert fires at 3 a.m. What do you do first?Acknowledge, scope it, check what changed, mitigate. Diagnosis comes after users are safe.
Every endpoint is slow, CPU is idle. Where do you look?Idle CPU means waiting. In-flight count, thread dump, connections to dependencies and the database (fault 2).
How do you find a memory leak in a running service?Confirm growth per request, not per time. Then allocation tracking on one instance, and look for unbounded containers (fault 4).
A customer reports a wrong balance. No errors anywhere.Treat as SEV1. Reconcile to size it, stop the writer if it grows, reproduce concurrently, fix code and data separately.
Rollback or hotfix?Roll back by default. Roll forward only if the old version cannot run against the current schema or data.
What makes a post-mortem useful?Blameless, a timeline with the reasons for each decision, root cause separated from contributing factors, and owned actions that include detection.
How do you debug something you cannot reproduce?Narrow with evidence from production: correlation ids, a good request against a bad one, then add targeted logging behind a flag and wait for the next occurrence.

Back to Senior Skills.