Skip to content
Velloreth
Programming 9 min read

Debugging Strategies That Actually Work

A hypothesis-driven approach to debugging: reproduce reliably, localize with bisection, instrument with intent, fix root causes, and prevent recurrence.

By

Most debugging time is not spent finding the bug. It is spent thrashing — changing something, rerunning, changing something else, rerunning — without a stated theory of what is wrong. The fix is to treat debugging like any other investigation: a loop with explicit steps, where you always know which step you are on.

The loop

StepQuestion you are answeringFailure mode
1. ReproduceCan I trigger this on demand?“Works sometimes” — chasing a ghost
2. LocalizeWhich component/line/input is involved?Reading code at random
3. HypothesizeWhat would have to be true for this to happen?Fixing the first suspicious thing
4. TestDoes an experiment confirm it?Confirming with your eyes, not an experiment
5. FixDoes the fix remove the cause?Patching the symptom
6. PreventHow does this never come back?Skipping — the expensive step

Skipping 1 makes everything after it guesswork. Skipping 3 makes every change a lottery. Skipping 6 guarantees you will debug this again.

1. Reproduce it, completely

A reproducing case is leverage: it turns an outage into a test. Nail down four things — the exact input, the observed output, the expected output, and the environment (version, config, OS, data state).

The move that accelerates everything: shrink it. Take the failing input and start cutting:

500-row CSV import fails      -> 47 rows fail
binary-search the rows        -> rows 12, 31, 44 fail
vary one column at a time     -> only rows with an empty "notes" field fail
vary the pipeline             -> fails after the 2026-03 parser change

That process is bisection applied to inputs, and it generalizes. Halve the search space on whatever axis is largest:

  • Inputs: drop half the data, half the options, half the fields.
  • Code path: comment out or feature-flag half the pipeline — does the bug survive?
  • History: git bisect between last-good and first-bad commit.
  • Environment: one variable at a time between machines (config, dependency version, locale, timezone).
git bisect start
git bisect bad HEAD
git bisect good v2.4.0
# run the repro script at each step; git marks good/bad automatically
# `git bisect run ./repro.sh` automates it fully

Bisection works because bugs usually come from one change. Logarithmic narrowing means twenty candidates take five checks, not twenty.

If the bug will not reproduce: you do not have a reproducing case, you have an observation. Switch from experiments to instrumentation — add the logging described below and wait for it to fire. Do not start “fixing” based on a single sighting.

When it only happens somewhere

“It works on my machine” is not an explanation; it is a list of uncontrolled variables. Diff the environments along the axes that actually change program behavior:

AxisExamples worth checking
VersionRuntime, framework, lockfile vs lockfile-free install
ConfigurationFeature flags, env vars, connection strings, log level
DataSeed data, migrated rows, cache contents, time zone of stored values
Locale/platformDate formats, sorting rules, filesystem case sensitivity
ConcurrencyLoad, worker count, timing under real traffic
BuildDebug vs release, tree-shaking, minified stack traces

The fastest way to shrink this list is to run the reproduction in both places with the same script and compare outputs — not recollections. And if the bug appears only under load or intermittently, suspect time: races, retries, timeouts, and cache expiry all have a schedule, and the schedule is what you are actually debugging.

2. The error is a location, not a cause

Stack traces tell you where the problem was detected. The bad value was usually created somewhere else entirely — an API that returned null an hour ago, a migration that backfilled wrong data, a cache entry written yesterday.

Read a stack trace in this order:

  1. The message itself, read literally. Cannot read properties of undefined (reading 'id') means something was undefined here — your first job is finding who passed it.
  2. The first frame that is your code, not framework frames. Framework internals rarely created the problem.
  3. The chain of callers: how did this value travel here?
  4. The cause chain in languages that nest errors (Caused by: at the bottom usually matters more than the top line).

Then walk the data backwards. Print or break at each point where the value changes hands until you find where it first became wrong. The place it becomes wrong is where the fix belongs; the place it explains wrong is usually just where someone finally complained.

3. State the expectation out loud

The single highest-yield habit, and the one people skip: say exactly what you expected and what you got, in specifics.

“I expected the invoice total to be 1,200 after the discount; I got 1,500. The discount field is present, so either it was not applied or it applied to the wrong base.”

That sentence localizes the bug to two candidates. “The total is wrong” localizes it to the program. Writing the expectation also exposes assumptions — frequently you discover the code is doing what it was written to do, and the bug is in your mental model or the spec.

A related habit: when you form a theory (“I think the cache is stale”), state what you would see if the theory were true and what you would see if it were false, then run the check. If you cannot distinguish the two cases with an experiment, the theory is not a theory yet — it is a guess with a confident tone.

4. Instrument with intent

Logging is not “add prints until something looks odd.” Decide what you need to know, then log exactly that, at the boundary where it becomes knowable:

logger.info(
    "invoice.priced",
    extra={
        "order_id": order.id,
        "subtotal": order.subtotal,
        "discount_pct": discount.percent,     # the suspicious input
        "currency": order.currency,           # env-dependent values
        "rule_version": pricing.rule_version,
    },
)

Rules that keep instrumentation useful:

  • Log boundaries — where data enters a component, where decisions are made — not every line.
  • Include identifiers and the values in question, in structured form, so you can grep or query them.
  • Log the negative branches: else paths and rejected validations are where silent wrong behavior hides.
  • Use a debugger when you need unplanned inspection — watch expressions, conditional breakpoints, break on throw. Use logging when you need history, concurrency, or something running on a server you cannot attach to.

When the bug vanishes under observation

Classic Heisenbug territory: adding prints or breakpoints makes it disappear. That usually means one of three things:

  • A race. Extra I/O changes the timing. Instrument with timestamps and sequence numbers instead of blocking prints.
  • Stale state. The restart triggered by debugging cleared it. Reproduce without restarting, or dump state before reset.
  • Optimization/debug-mode differences. Debug and release builds genuinely differ — test the build you ship.

The disappearance itself is data. Note exactly what you changed, because “it only happens when X” is a narrowing clue just like a stack trace.

5. Fix the cause, then prove it

The moment of maximum risk is the fix. Two disciplines:

Change one thing. Edits made together cannot be evaluated separately — if the bug leaves, you do not know which of your three changes did it, and one of them may be a new bug.

Explain the whole chain before committing. Not “moving this null check fixed it,” but “the endpoint returns null for archived users, which the handler never considered; I added the check and the handler now handles archived users explicitly.” If you cannot tell that story in three sentences, you have patched a symptom — keep going.

Then verify with the original reproduction, plus:

  • The regression test. Written first if you can discipline yourself — it converts the fix from a claim into a fact, and it stays as a tripwire. The test must fail without the fix: remove the fix locally and watch it go red.
  • Adjacent cases. The same mistake usually lives in sibling code paths (the other endpoint handling archived users, the other import format).
  • A sanity run of the suite. To catch the change-one-thing fallout.

Preventing the sequel

Bugs are cheap to find now and expensive later; the prevention step is small and usually skipped:

PreventionEffortPays off when
Regression test on the reproMinutesAny time this class of bug returns
Clearer error at the true sourceMinutesThe next person hits it
Validation where bad data entersSmallRoot cause was upstream data
Assertion on the invariantMinutesState corruption of this shape
Note in the changelog / issueSecondsSomeone asks “why is this check here”

The error-message upgrade matters more than it sounds. Most long debug sessions start with a confusing message from line 800; making the first message say which record, which field, and which caller can cut the next occurrence from an hour to a minute.

When you are stuck

Everyone stalls. What separates the fast debuggers is the exit ramp:

  1. Re-check the reproduction. Half of “impossible” bugs are reproductions that quietly stopped reproducing.
  2. Re-read the diff. The bug is in something you changed recently, statistically speaking. git diff main...HEAD and read it as a hostile reviewer.
  3. Reproduce from scratch in a minimal harness. Import just the function, feed the value directly. If it does not fail there, the bug is in the environment or wiring, not the algorithm.
  4. Revert to last-known-good and walk forward. Sometimes faster than reading.
  5. Change the medium. Draw the data flow on paper. Explain it to a colleague — or a rubber duck — and listen for the sentence where your explanation stops being true.
  6. Take the walk. Incubation works because debugging is pattern-matching against a mental model, and the model needs a pause to reorganize. Twenty minutes away is a legitimate technique, not a luxury.

What does not work: changing code without a theory and rerunning. If the last three changes did not fix it, the fourth will not either — you are sampling randomly from a large space.

The habit to build

Debugging rewards the same virtues as the rest of engineering: make the problem small, keep a record of what you have ruled out, change one variable at a time, and prefer evidence over plausibility. The bug that took all afternoon was rarely the hard part — the thrashing was.

Keep a note open while you work: reproduction steps, hypotheses tried, results. It forces each attempt to be an experiment instead of a vibe, and when someone else joins, you can hand them the whole investigation instead of a shrug.

Frequently asked questions

What should I do first when a bug appears?
Make it reproduce on demand and capture the exact inputs, output, and environment. A bug you can trigger reliably can be bisected and tested; a bug you cannot reproduce can only be stared at.
Why does my bug disappear when I add logging?
Usually a race or timing issue — extra I/O changes the schedule — or a stale state that a restart cleared. Either way, the disappearance is a clue: switch to timestamps, structure, and non-invasive tracing rather than print statements.
How do I know when I have found the root cause?
You can explain the whole causal chain: the conditions that produce the bad state, where it is created, and where it surfaces. If your explanation starts at the exception line, keep walking backwards until the story is complete.
When should I use a debugger instead of print statements?
When you need to inspect values you did not anticipate needing, or step through branching logic. For simple value tracing, targeted logging is often faster and works over SSH and in CI, where interactive debuggers are awkward.