Most engineering time isn't spent writing new code. It's spent figuring out why existing code does something nobody expected, usually at the worst possible moment, with customers affected and a manager asking for an ETA. Debugging is also one of the clearest signals in an interview: give two candidates the same broken service and within ten minutes you can tell who has done this before.
Good debuggers aren't magicians. They follow a method. This article lays it out, with a worked example and the bug patterns that cause most real incidents.
The loop
- Mitigate: stop the bleeding.
- Gather evidence: what exactly is happening, since when, to whom?
- Reproduce: make it happen on demand.
- Isolate: narrow down where it goes wrong.
- Find the root cause: explain why, not just where.
- Fix and verify with a test that fails before and passes after.
- Prevent: make this class of bug harder to repeat.
Beginners jump straight from "something's wrong" to step 6, editing code on a hunch. Sometimes that works. When it doesn't, they've changed the system they were trying to observe and lost the trail.
1. Mitigate first
When users are affected, your first job is to reduce the damage, not to understand the bug. Ask: what changed recently? A deploy, a config change, a feature flag, a traffic spike, a dependency's outage. If a deploy went out 20 minutes before the errors started, roll it back. You can investigate the bad version calmly afterwards.
Other mitigations: turn off a feature flag, shed load, fail over to a replica, temporarily raise a timeout or a pool size. A mitigation that is boring and reversible beats a clever fix written under pressure.
2. Gather evidence
Pin down the symptoms precisely before forming theories:
- What is failing: which endpoint, which job, which error message?
- Since when: the first occurrence, not when someone noticed.
- For whom: all users or some? One region, one app version, one payment method?
- How often: every request, 2% of requests, only under load?
Your tools:
- Metrics show the shape: error rate, latency percentiles, saturation (CPU, memory, connection pools, queue depth). A graph that turns at a specific minute is the most valuable clue you'll get.
- Logs show the details of individual failures. Good logs carry a request or correlation id, so you can follow one request across services.
- Traces show where time goes inside a request across services.
Write down what you know as you go, in the incident channel. It keeps you honest, and it becomes the timeline for the postmortem.
3. Reproduce
A bug you can trigger on demand is half fixed. Try to reproduce it in the smallest environment that still fails: a test, a local run, a staging environment with the same inputs. Use the evidence: the exact request that failed, the same data shape, the same configuration.
If it only happens under load or "sometimes", suspect timing: concurrency, retries, timeouts, caches expiring. Those need a different approach, like adding logging around the suspected window, or writing a test that forces the interleaving.
4. Isolate
Now narrow it down. The most powerful technique is binary search:
- In history:
git bisectmarks a known good and a known bad commit, then checks out the middle until it finds the first bad commit. Fifty commits take about six steps. - In the code path: check the data at the midpoint of the request. Correct there? The bug is downstream. Wrong? Upstream.
- In configuration and data: compare a failing case with a working one and change one difference at a time.
Resist changing several things at once. If the bug disappears, you won't know which change mattered, or whether it really went away.
5. Find the root cause
"The service threw a null pointer exception on line 212" is where. The root cause is why: why was that value null, and why did nothing stop it? A useful habit is asking "why?" until you reach something you can change to prevent the whole class of problem:
- Why did customers get charged twice? Because the payment call was retried after a timeout.
- Why did the retry charge again? Because the request had no idempotency key.
- Why didn't the provider deduplicate? Because it only deduplicates when given a key.
- Why did the timeout happen? Because the provider's p99 latency exceeds our 2-second timeout during peaks.
There are two fixes hiding in there: send an idempotency key (so retries are safe), and set the timeout from the provider's real latency profile (so retries are rarer).
6. Fix and verify
Write a test that reproduces the bug and fails, then make it pass. That test is your proof that the fix addresses the cause, and it stops the bug coming back. Fix the root cause, not the symptom. Catching the null pointer exception and returning an empty response "fixes" the crash and hides the real problem.
Here is the double-charge bug from above, and its fix. The buggy version retries a payment after a timeout without any way for the provider to recognise the duplicate:
def charge_with_retry_buggy(gateway, order_id: str, amount: int) -> str:
for attempt in range(3):
try:
return gateway.charge(amount=amount) # a retry is a brand-new charge
except TimeoutError:
continue # the first charge may have succeeded anyway!
raise RuntimeError("payment failed")
def charge_with_retry(gateway, order_id: str, amount: int) -> str:
key = f"order-{order_id}" # the same key on every attempt for this order
for attempt in range(3):
try:
return gateway.charge(amount=amount, idempotency_key=key)
except TimeoutError:
continue # safe: the gateway returns the original charge for a repeated key
raise RuntimeError("payment failed")The test that proves it: a fake gateway that charges successfully but then times out on the first call. The buggy version records two charges; the fixed one records one. (The full story of keys, deduplication windows and exactly-once is in idempotency and exactly-once.)
7. Prevent
After the fix, ask what would have caught this earlier or limited the damage:
- A test for the edge case (retries, empty input, time zones).
- An alert on the symptom (duplicate charges per hour), not just on errors.
- A safer default in shared code (a payments client that refuses to retry without a key).
- A rollout that would have contained it (canary deploys, feature flags).
Write a short blameless postmortem: timeline, impact, root cause, what went well, what didn't, and owned action items. Blameless doesn't mean nobody is responsible. It means you fix the system that let a reasonable person make the mistake.
The usual suspects
A handful of patterns cause a large share of real incidents. When you're stuck, walk through them:
| Pattern | Typical symptom |
|---|---|
| Retries without idempotency | Duplicate orders, charges, emails |
| Race conditions | Rare, load-dependent wrong values; "works on my machine" (see concurrency) |
| Stale caches | Users see old data after an update; fixed by "clearing the cache" |
| Time zones and clocks | Bugs at midnight, month ends, daylight saving changes, or only for users in one region |
| Off-by-one and boundaries | Failures on empty lists, the last page, exactly-at-limit values |
| Nulls and missing fields | Crashes after a new client version or a partial data migration |
| Resource exhaustion | Slow degradation then collapse: connection pools, file handles, memory leaks |
| N+1 queries | Latency that grows with data size; fine in testing, slow in production |
| Timeouts that are too long or too short | Cascading failures, thread pools filled with waiting requests |
| Configuration drift | Works in staging, fails in production with "the same" code |
Using AI assistants without fooling yourself
AI coding assistants are genuinely useful for debugging, and genuinely good at producing confident, plausible, wrong answers. Use them like a sharp colleague who hasn't seen your system:
- Give context, not just the error. The stack trace, the relevant code, what changed recently, and what you've already ruled out.
- Ask for hypotheses, not fixes. "What could cause this, and how would I tell them apart?" leads to experiments. "Fix this" leads to a patch that may hide the symptom.
- Verify everything. Treat suggestions as theories to test against your evidence. If the assistant says a library behaves a certain way, check the documentation or try it.
- Ask it to explain the root cause in its own words. If the explanation doesn't account for all the symptoms (why only 2% of requests, why only since Tuesday), it isn't the root cause.
- Never paste secrets, credentials or customer data into a tool your organisation hasn't approved.
The skill interviewers are increasingly looking for isn't "can you debug without AI" or "can you prompt an AI". It's whether you stay in charge of the investigation while using one. That's exactly what the CureBugs debugging challenges measure: real bugs, a built-in assistant, and scoring on both your fix and your understanding of the root cause.
In an interview
When you're handed a broken service in a debugging round, narrate the loop out loud: "First I'd check what changed and what the error rate looks like. Let me reproduce it with this failing request… the response is wrong here but the database row is right, so the bug is between the query and the serializer…" Interviewers score the method as much as the fix. A candidate who finds the bug methodically in 15 minutes beats one who guesses it in 5 and can't explain why it happened.