Debugging
A systematic approach to finding bugs — reproduce, isolate, hypothesise and verify; reading stack traces and error messages; debuggers and breakpoints; logging; binary search with git bisect; debugging production with observability; heisenbugs, concurrency and memory bugs; and rubber-duck debugging.
Debugging is where engineers spend a huge share of their time, yet it's rarely taught. The difference between flailing for hours and finding a bug in minutes is usually method, not genius. Debugging is the scientific method applied to code.
The process
- Reproduce the bug reliably — ideally with an automated test.
- Gather information: error messages, stack traces, logs, inputs, environment, recent changes.
- Isolate: narrow down where the behaviour goes wrong.
- Hypothesise a specific cause.
- Test the hypothesis with an experiment that could prove it wrong.
- Fix the root cause — not just the symptom.
- Verify the fix and add a regression test; look for the same bug elsewhere.
1. Reproduce
A bug you can't reproduce is a bug you can't confidently fix. Pin down:
- Exact inputs, steps and data (which user? which record?).
- Environment: OS, browser, versions, config, feature flags, time zone, locale.
- Frequency: always, sometimes (suspect concurrency, timing, caching, randomness), only in production (suspect data, scale, config).
Then make the smallest reproduction: strip away everything unrelated until removing anything else makes the bug disappear. Often, the bug becomes obvious during this step. Turn it into a failing test — it proves the bug, guides the fix and prevents regressions.
2. Read the error
It sounds obvious, but many people skim past the most valuable clue. Read the whole message and stack trace:
Traceback (most recent call last):
File "app/api.py", line 42, in get_invoice
total = calculate_total(invoice)
File "app/billing.py", line 17, in calculate_total
return sum(line.amount for line in invoice.lines) * (1 + invoice.tax_rate)
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'- Read from the innermost frame (where it failed) outward to your code.
- The message says exactly what's wrong:
tax_rateisNone. The real question becomes why — which invoices have no tax rate, and when did they start appearing? - In chained exceptions ("caused by"), the root cause is usually at the bottom.
- Search the exact message (minus your specific values) — someone has probably seen it.
3. Isolate: divide and conquer
Narrow the search space by halves:
- In code: check the state at the midpoint of the flow. Correct there? The bug is later. Wrong? Earlier.
- In data: does it fail for all inputs or some? Halve the input until a minimal failing case remains.
- In time: when did it start? Use
git bisectto binary-search history for the commit that introduced it (Git):
git bisect start
git bisect bad # current commit is broken
git bisect good v2.3.0 # this release was fine
# Git checks out the midpoint; test it, then mark:
git bisect good # or: git bisect bad
# … repeat ~log2(N) times, or automate:
git bisect run pytest tests/test_invoice.py
git bisect reset1,000 commits take only about 10 steps.
- In environment: works locally but not in staging? Diff everything — versions, config, data, permissions, network.
4–5. Hypothesise and test
Form a specific, falsifiable hypothesis: "invoices created through the bulk importer don't set tax_rate". Then test it: does a manually created invoice work? Does an imported one fail? Change one thing at a time, and predict the outcome before running.
Avoid "shotgun debugging" — randomly changing things until it works. Even if the symptom disappears, you won't know why, and you may have introduced new bugs.
6–7. Fix and verify
- Fix the root cause: the importer should set
tax_rate(and maybe the field should be non-nullable), rather than addingor 0at the crash site. - Ask the "five whys": why did this reach production? Missing validation, missing test, unclear contract?
- Add the regression test, then search for similar bugs (other code paths that create invoices).
Tools
Debuggers
A debugger lets you pause execution and inspect everything:
| Feature | Use |
|---|---|
| Breakpoints | Pause at a line |
| Conditional breakpoints | Pause only when invoice.id == 1043 |
| Logpoints | Print without editing code |
| Step over / into / out | Walk through execution line by line |
| Watch expressions, variable inspection | See state at each step |
| Call stack | How did we get here? |
| Exception breakpoints | Pause when an exception is thrown — even if caught |
Every major IDE (VS Code, IntelliJ, PyCharm) and runtime has one: pdb/breakpoint() in Python, Chrome DevTools and node --inspect for JavaScript, jdb and IDE debuggers for Java, gdb/lldb for native code, and rr for record-and-replay debugging (step backwards in time).
Logging and print statements
Print debugging is legitimate — especially for distributed systems, timing-sensitive code, or when a debugger isn't available. Make it effective: log the values and context you need, with clear labels, and remove temporary prints afterwards. In production code, prefer structured logs with request IDs (Observability).
Other tools
- Profilers for performance bugs: measure, don't guess (py-spy, async-profiler, Chrome Performance panel,
perf, flame graphs). - Network tools: browser DevTools Network tab,
curl -v, Wireshark,tcpdump(Network tools). - System tools:
strace/dtraceto see system calls,lsoffor open files,top/htop(Linux essentials). - Sanitizers for memory and concurrency bugs in native code: AddressSanitizer, ThreadSanitizer, Valgrind.
- Database tools:
EXPLAIN ANALYZEfor slow queries (Query processing).
Debugging production
You usually can't attach a debugger to production. Instead:
- Observability: logs, metrics and distributed traces show which service, endpoint and request failed and how (Observability).
- Correlate with recent changes: deploys, config changes, feature flag flips, dependency updates, traffic shifts. Most incidents are caused by a change — rolling it back is often the fastest mitigation (Monitoring and SRE).
- Use error tracking (Sentry and similar) with stack traces, breadcrumbs and affected-user counts.
- Capture heap dumps, thread dumps and core dumps for memory leaks and deadlocks.
- Reproduce with production-like data (anonymised) in a safe environment.
Tricky categories
| Bug type | Symptoms | Approach |
|---|---|---|
| Heisenbugs | Disappear when observed (adding logs or a debugger changes timing) | Suspect race conditions and uninitialised memory; use record-and-replay, sanitizers, stress tests |
| Concurrency | Intermittent failures, deadlocks, corrupted state | Thread dumps, ThreadSanitizer, reasoning about shared state and lock ordering (Synchronization, Deadlocks) |
| Memory leaks | Memory grows until OOM | Heap snapshots compared over time; look for unbounded caches, listeners never removed, references held by closures |
| Off-by-one / boundaries | Fails only at edges | Test 0, 1, n − 1, n, empty |
| Floating point | 0.1 + 0.2 != 0.3 | Use decimals for money; compare with tolerances (Floating point) |
| Time and dates | Fails at midnight, month end, DST changes, in other time zones | Store UTC; inject clocks in tests |
| Encoding | Garbled characters | Be explicit about UTF-8 at every boundary |
| Caching | Stale data; works after restart | Check every cache layer: browser, CDN, application, database (Caching) |
| "It works on my machine" | Environment differences | Containers, pinned versions, reproducible builds (Docker) |
Mindset
- Question your assumptions — "that can't be the problem" is often where the problem is. Verify what you "know" (is that config actually loaded? is that function actually called?).
- Rubber-duck debugging: explaining the problem line by line to someone (or something) forces you to articulate assumptions, and the answer often appears mid-sentence.
- Take breaks: after an hour of being stuck, a walk often does more than another hour of staring.
- Keep notes of what you've tried and ruled out — especially during incidents.
- Ask for help with a good write-up: what you expected, what happened, how to reproduce, what you've tried.
- Learn from bugs: each one hints at a missing test, a confusing API, or a type that could have prevented it.
- Debug systematically: reproduce, gather information, isolate, hypothesise, test, fix the root cause, add a regression test.
- Read the whole error message and stack trace; find the root cause in chained exceptions.
- Divide and conquer across code, data, environment and history — git bisect finds a bad commit in log₂(n) steps.
- Change one thing at a time; avoid shotgun debugging.
- Use debuggers (conditional breakpoints, exception breakpoints), structured logging, profilers and sanitizers.
- In production rely on observability and recent-change correlation; roll back first, debug after.
- Question assumptions, explain the problem aloud, take breaks, and learn from every bug.