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
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.
- 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
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.
- 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?
A system that worked yesterday and fails today was changed by something. Most incidents are found by listing recent changes, not by reading code.
| Suspect | Where to look |
|---|---|
| Deploy | Release log, boot lines, version in /health |
| Config, flags, secrets | Flag audit log, environment of the process |
| Data | New kind of row, a NULL, an empty account, a huge customer |
| Traffic | Request rate by route and by client, a new caller |
| Dependency | Their status page, your latency per upstream |
| Time | Certificate 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
Four questions size the problem and choose the first tool. Answer them from dashboards and logs, not from memory.
- "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
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.
| Level | Meaning | Bank example | Tell, and when |
|---|---|---|---|
| SEV1 | Core function down, or data being damaged | Transfers lose money | Page on-call and a commander now. Customers within about 30 minutes. |
| SEV2 | Major feature degraded for many | Every endpoint hangs at peak | Page on-call now. Status page if it lasts. |
| SEV3 | One feature broken for some | Summary fails for new accounts | Team channel, fix in working hours. |
| SEV4 | Cosmetic, or a workaround exists | Wrong label on a statement | Ticket. |
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
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, logsstartanddonewith 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:
SIGUSR1dumps every thread's stack (faulthandler),SIGUSR2logs the biggest allocation (tracemalloc).
Bisect in space: which layer
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.
| Hop | Check |
|---|---|
| Client | Same request with curl -v from another network |
| DNS, network | dig, then connect time from curl -w |
| Proxy, load balancer | Its status codes (502, 503, 504) and which backends are in rotation |
| App | curl the app port directly, in-flight count, error rate by route |
| Database | Active and waiting connections, slowest running query, locks |
| Dependency | Call 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
Put every change on one timeline and mark the first bad request. The suspect is the last change before that mark.
- Deploys, flag flips, config pushes, migrations and cron jobs all belong on the same timeline.
- With many commits between good and bad,
git bisecthalves 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
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
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
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.
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
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.
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
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
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.
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
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 freezeand 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
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_idto support.
Read a stack trace bottom-up
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.
| Read | Line | It tells you |
|---|---|---|
| 1st | sqlite3.OperationalError: ... | What failed: an open, not a query |
| 2nd | line 31, in acquire | Where: making a new connection, so the pool was empty |
| 3rd | line 58, in account | Who asked: the last frame of business code |
| Last | line 150, in dispatch | Framework plumbing, rarely the cause |
- The usual source line under each frame is missing: Python could not open
bank_api.pyto 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
One cause produces many different errors downstream, and the most frequent one is rarely the cause. Sort by time before you sort by count.
- 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, keep | How much |
|---|---|
| Errors, 5xx and slow requests | All: they are the needle |
| Successful requests | 1 in N, chosen by hashing the request id, so every service keeps the same requests |
| Counts by route and status | All, 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?
Prefer the least invasive tool that answers the question. A hook you built in before the incident is the safest of all.
| Option | Use when | Risk |
|---|---|---|
| Built-in hook (stack dump on a signal, debug endpoint) | Stuck or slow process, right now | Low. Sending the signal to a process with no handler kills it. |
| Raise log level at runtime | You need more detail on one path | Log volume and cost, secrets in debug lines |
| Add logging and redeploy | The fault is repeatable and can wait minutes | A restart destroys the state of a leak or a hang |
| Sampling profiler attached from outside | CPU is busy and you do not know where | Needs privileges, small pause per sample |
| Interactive debugger on a live process | Almost never in production | A 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
Looking is free, changing is not. Know which side of the line a command is on before pressing Enter.
| Read-only: just run it | Risky: say it first, get a second pair of eyes |
|---|---|
curl a GET, /health | Any POST, PUT or DELETE against real data |
grep, tail, awk on logs | Truncating or deleting logs to free disk |
ps, lsof, netstat or ss, df | kill, restart, kill -9 (no cleanup, no evidence) |
SELECT with a LIMIT, on a replica | UPDATE, DELETE, DDL, a full-table SELECT on the primary |
EXPLAIN | EXPLAIN ANALYZE: it runs the query |
| Reading config and flags | Changing 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
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.
| Property | Why it matters at 3 a.m. |
|---|---|
| Read at request time, not at boot | Off in seconds with no restart (fault 1) |
| Safe default when the flag store is down | The flag system must not be a new outage |
| Every flip is logged with who and when | Flips 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
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.
- 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
A wrong manual write during an incident turns one incident into two. Slow down exactly here.
| Rule | In practice |
|---|---|
| Two people | One types, one reads the statement aloud and confirms host and database |
| Count before you change | Run the WHERE as a SELECT COUNT(*) first |
| Inside a transaction | BEGIN, change, check the row count, then COMMIT or ROLLBACK |
| Keep a way back | Copy 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 person debugging cannot also coordinate and write updates. Split the work as soon as more than two people are involved.
- 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
Every incident has the same five timestamps. The gaps between them show whether to invest in detection, response or repair.
| Metric | Measures | Improve it with |
|---|---|---|
| MTTD, mean time to detect | Fault starts to detected | Alerts on symptoms, reconciliation jobs |
| MTTA, mean time to acknowledge | Detected to acknowledged | Paging policy, fewer noisy alerts |
| MTTR, mean time to recover | Fault 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
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.
| Section | Contains |
|---|---|
| Summary | Three sentences: what broke, for whom, for how long |
| Impact | Numbers: users, requests, money, minutes |
| Timeline | Timestamps of events, decisions and what each was based on |
| Root cause | The change in the system that, if absent, means no incident |
| Contributing factors | What made it likelier, larger or longer |
| What went well, what was lucky | Keep the first, do not rely on the second |
| Action items | Owner, 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
Keep asking "why" until the answer is a process or a design, not a person or a line of code. Fault 2, worked through:
- Stopping at "the call had no timeout" fixes one call. The next engineer writes the same bug.
Action items that prevent recurrence
"Be more careful" is not an action item. Each one changes the system and falls into one of three kinds.
| Kind | Question | From the six faults |
|---|---|---|
| Detection | How do we know in one minute next time? | 5xx and 4xx alerts per route, in-flight gauge, descriptor and memory slope, hourly reconcile job |
| Prevention | How 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 |
| Mitigation | How 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
| Symptom | First check | Likely cause |
|---|---|---|
| 500s on one route, some inputs | Error rate by route, one stack trace | Bad deploy, unexpected data |
| Everything hangs, connect is fast | Started vs finished, sockets, thread dump | Workers held by a dependency |
| Fine for hours, then errors on all routes | Descriptor or connection count over time | Leak on an error path |
| Memory climbs, restarts "fix" it | RSS against requests, then tracemalloc | Unbounded cache or list |
| Wrong numbers, no errors | Reconcile against the ledger | Race, missing transaction |
| Works on one machine only | Diff version, environment, schema | Config or environment |
| Connect itself fails or is slow | DNS, port, proxy status codes | Network or proxy hop |
| Fails at the same time every day | Cron, batch jobs, backups | Time |
On-call checklist
| When | Do |
|---|---|
| Before the shift | Laptop, access and pager tested. Recent deploys and open risks read. Runbooks and rollback command known. |
| Minute 0 to 5 | Acknowledge. Scope: who, which endpoints, since when, what kind. Declare a severity. Open one channel. |
| Minute 5 to 15 | List what changed. Mitigate: roll back, flag off, scale or shed. Save evidence before any restart. |
| While it lasts | One hypothesis at a time, written in the channel. Updates at fixed times. Ask for help early. |
| Before closing | Verify with the check that showed the fault. Watch for one full cycle. Say "resolved" and at what time. |
| After | Timeline while memory is fresh. Post-mortem within days. Action items with owners. |
Interview questions
| Question | Shape 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.