The checkout that worked for everyone except Mrs O'Brien
It is 4:47 on a Friday afternoon. The deploy went out at noon, the tests passed, and the team is already half out of the door. Then a support ticket lands: checkout is failing for one customer. Just one. QA tries her exact order — same items, same address, same card type — and it goes through without a murmur.
The difference, when someone finally spots it, is her surname. O'Brien. The apostrophe breaks a query built by gluing strings together, and the database chokes on it. The bug was never in the checkout flow, the payment code, or the deploy. It sat in a line that had worked perfectly for every name without a punctuation mark in it — which is to say, for nearly everyone, nearly all the time.
Writing code is making a claim about how the world works; debugging is finding out where that claim was wrong. The developers who are good at it are not the ones who write the fewest bugs — nobody does. They are the ones with a method for narrowing the search.
A moth, a logbook, and a word older than computers
Every discussion of debugging starts with the same story, and the popular version gets it wrong in an instructive way.
On September 9, 1947, engineers working on the Harvard Mark II found a moth stuck in one of the machine's relays. They removed it with tweezers and taped it into the logbook, with the note "First actual case of bug being found." The logbook, moth included, is now in the Smithsonian National Museum of American History. Grace Hopper, who worked on the Mark II team, helped popularise the story and is often credited with coining the term. She did not.
The word "bug" for a small fault was already old: Thomas Edison used it in a letter in 1878, and "debug" was in print by 1945, in an engineering journal, in the context of aircraft engines. Hopper's team already knew the word; that is exactly why the logbook entry is a joke. They had found an actual bug.
The story survives because it captures something true: a bug is usually small, has a definite location, and stays invisible until you know where to look. Most software bugs are like that — one wrong assumption, with consequences somewhere else. The skill is finding which relay the moth is in.
Step one: make it happen again
Before touching a line of code, a good debugger does the most boring thing possible: they make the bug happen on purpose, on their own machine, in a way they can repeat.
A bug you can reproduce is a bug you can beat; one you cannot is a rumour. So the first job is to turn "checkout fails sometimes" into a set of steps with a definite outcome. What exactly did the user click? What data did they enter? Which browser, which version, which account? The O'Brien bug only appears with an apostrophe in the name; one that appears on the first of the month points at date handling; one that hits a single customer points at their data.
Once you can make it fail, shrink it: cut away everything not needed until you have the smallest input that still breaks. Any name with an apostrophe, or only O'Brien? One item in the cart, or only ten? If removing the discount code makes the bug vanish, the discount code is involved, even if it looks innocent.
Reproduction also gives you a test for the fix: run the same steps after changing the code, and if the bug is gone, you are done. Without it, you are guessing — and guessing is how a bug gets "fixed" three times over.
Some bugs refuse to reproduce, and that is information too: one failing once in twenty tries is probably about timing, order, or shared state; one failing on the customer's machine but never on yours is probably about environment. Ask what differs between the two places, and close that gap.
Reading what the machine is actually telling you
When a program fails, it usually leaves a message. Most developers' first instinct is to skim it, catch a familiar word, and start guessing. That instinct wastes more debugging time than any other habit. The message is the cheapest evidence you will get, and it deserves a careful read.
Start with the error itself, not your theory about it. "Cannot read properties of undefined" means something was undefined at that exact moment, so the useful question is why — which means looking one step back, at whatever was supposed to fill it in. Each message points at a specific fact.
Then comes the stack trace, the list of calls in progress when things went wrong. Languages print them in different orders — Python puts the failing line last; Java and JavaScript usually put it first — but the technique is the same: scan for the first frame that belongs to your code rather than a library. Library code is rarely where your bug lives; your code called it with something unexpected, and that frame is the one that matters.
A few traps are worth knowing. Line numbers refer to the code that was running, not the version on your screen now — if someone deployed since the error was logged, you will be reading the wrong code. Minified JavaScript makes traces nearly unreadable without source maps. And some error messages mislead: a framework that swallows the original error and replaces it with a generic one. When message and behaviour disagree, trust the behaviour, and look one layer deeper for a "caused by" chain or the full error object.
Narrowing it down: divide and conquer
Once you can reproduce the bug, the problem becomes a search. Somewhere in the codebase is a wrong line, and the codebase might be a hundred thousand lines long. Staring at all of it is not a strategy. Cutting it in half is.
The technique is binary search applied to code. If a feature works at the start of a function and fails at the end, check the middle: value right, the bug is in the second half; value already wrong, it is in the first. Each check halves the space. The same idea works on systems: if the bug appears when the frontend talks to the API but not when you call the API directly, the frontend is involved.
The blunt version is commenting things out: disable half the code in a suspect function and see whether the bug survives. It is crude but fast. The disciplined version uses better tools — run a single test, or swap a real service for a stub.
When the bug is a regression, Git's bisect command walks the commit history: mark a known-good commit and a known-bad one, and Git checks out the middle commit and asks whether it is good or bad. Answer a dozen times and it hands you the exact commit that introduced the bug — provided your reproduction is reliable enough to answer with.
One rule governs all of this: change one thing at a time. Change three things and the bug disappears, and you cannot tell which change fixed it — or whether the other two broke something else.
The usual suspects: bug families
After a while, you notice bugs come in families. The details differ, but the shapes repeat, and recognising the shape is often faster than tracing the code from scratch.
Off by one
The oldest bug in the book, and still one of the most common. A loop runs one time too many, or one time too few; a page of results shows items 1 to 10, then the next shows items 10 to 19, and item 10 appears twice. The fencepost version: ten posts need nine gaps, not ten, and every programmer has written the ten at least once.
# Adds up the first ten order totals.
# range(1, 10) would quietly drop the last one.
total = 0
for i in range(1, 11):
total += orders[i]
They hide in date arithmetic, in pagination, in anything with a start and an end. The fix is a boundary test: first item, last item, empty list, list of one. Test only the comfortable middle, and the edges will wait for a customer to find them.
State that went stale
Some bugs are not about a wrong line but a value that is right at one moment and wrong later: a cache holding yesterday's price, a form remembering the previous customer's address, a flag set in one branch and never reset, so the second time through it carries the first time's answer.
State bugs are hard because the broken line is fine when you read it; it only fails in the context of everything that ran before. The clue is a bug that depends on order: it works if you do A then B, and fails if you do B then A. When you see that pattern, stop looking at the failing line and look at what is left over from the previous run.
Race conditions
Two things happen at once, and the result depends on which finishes first. Two withdrawals of $50 arrive together against a $100 balance; both read $100, both subtract $50, both write back $50. The balance should be zero; it is $50, because one update overwrote the other. The bug is in the gap between reading and writing, and it only shows up when the timing lines up — which is why races vanish the moment you try to reproduce them.
The honest answer is to remove the race, not make it less likely: a database transaction, a lock, an atomic update — something that makes the read and the write a single step. Adding a small delay and hoping is not a fix. It is a bug with a smaller chance of appearing, which is worse, because now it appears in production on a busy day instead of in testing.
Wrong assumptions about input
Programs are written against an idea of what the input looks like, and the world keeps sending something else: names with apostrophes, empty strings, a phone number pasted with spaces, a date in an unconsidered timezone, so an order placed at 11pm on December 31st is recorded as January 1st.
The defence is to test the edges deliberately: empty, missing, huge, strange, in a different timezone. Input validation is the boundary where your assumptions meet the world, and the bugs that get through it are the ones your tests never imagined.
The copy-paste slip
A block of code is copied, pasted, and edited — and one value is not changed: the discount for returning customers uses the new-customer rate; the error message for payment mentions shipping. The test passes because it was copied too. When a bug smells like "right for the other case, wrong for this one," look for the paste.
Print statements or a debugger?
There are two classic ways to watch a program run, and the trick is knowing which one the situation calls for.
Logging — print statements, done properly — is the older tool, and more powerful than its reputation suggests. You record a value at a moment in time, run the program, and read what happened. It works everywhere, including production, leaves a record you can read after the fact, and shows the sequence of events over time — exactly what you need when the bug is about order or timing. Good logs carry context: a request id, a user id, the values that matter. "Order failed" is nearly useless; "order 48213 failed for user 917 with total -4.00" tells you where to look.
Its weakness is that it changes what it measures: logging slows the program slightly, and for a race condition that is enough to make the bug disappear — the timing changes, the events no longer collide, and you conclude it is fixed when it has only gone quiet.
A debugger does the opposite. Set a breakpoint, run until it stops there, and walk through line by line, inspecting any variable you like. Conditional breakpoints — stop only when the user id is 917, or the total goes negative — make it precise. For a bug you can reproduce locally, a debugger is usually the fastest route to the answer.
Its weakness is that it needs the program running where you can reach it, which rules out most production problems and bugs that appear only under real load or across several services. It also stops the world: while you inspect one request, the others wait — fine on your laptop, unacceptable on a live server. Most experienced developers use both: print a few values to find the neighbourhood, then set a breakpoint once you know the street.
Talk it out: the rubber duck
There is a technique with a silly name and a serious track record. Put a rubber duck on your desk — or open a blank document, or grab a colleague — and explain the code, line by line, out loud, as if to someone who knows nothing about it. Halfway through, you will usually stop mid-sentence: the bug is in the assumption you just said aloud for the first time.
It works because reading code is not the same as explaining it. When you read, your brain fills in what the code is supposed to do; when you explain, you say what it actually does, and the gap between the two is where most bugs live. A colleague works even better than a duck: they ask the question you stopped asking hours ago, and fresh eyes spot the typo you have read past ten times.
The same applies to stepping away. After two hours on one bug, you are no longer reading the code but your memory of it, and your memory is wrong in exactly the place the bug is. A walk, a night's sleep, a different task — anything that breaks the loop — is a legitimate debugging tool.
Fixing it without breaking something else
Finding the bug is half the job. The other half is fixing the cause rather than the symptom, without breaking something else.
The O'Brien bug shows the difference. The quick fix is to strip apostrophes from names: checkout stops failing, but you have just told every O'Brien, D'Angelo, and N'Dour that their name is a problem your system will quietly mangle. The real fix is to stop building queries by gluing strings together and use parameterised queries, so the database treats the name as data, never as code. The symptom was the crash; the cause was the string-building.
The safest order is to write a failing test first, then fix the code, then watch the test pass. The test reproduces the bug in miniature — a checkout with the name O'Brien — and stays in the suite, guarding that case. This is the idea behind unit testing: a small test that proves one thing, run automatically whenever anyone changes the code, so a future change that reintroduces the bug gets caught before a customer sees it.
Keep the fix small. A bug is not an invitation to refactor the whole function while you are in there; every extra change is a new chance to break something. Change the minimum that addresses the cause, check the edges — an empty name, a very long name, a name in another script — and run the full suite, not just your new test. The bug you fixed is the one you know about; the regression you introduced is the one you do not.
When the bug is in production
Everything above assumes you can reproduce the bug on your own machine. Sometimes you cannot: it only happens in production — under real load, with real data, across services you do not control. You cannot attach a debugger to a live server or restart it to see if that helps. You have to work with what the system already tells you.
That is what observability is for: logs, metrics, and traces that let you reconstruct what happened after the fact. A trace shows one request's path through every service it touched; a metric shows the error rate climbing at 2pm, pointing at the 1:45 deploy; a log line with a request id ties the customer's report to the exact request that failed. None of this exists by accident — good teams built the instrumentation before they needed it, because adding it during an incident is too late.
Two other tools matter. Feature flags let you turn off a new code path without deploying anything — if the errors stop when the flag goes off, you have found the neighbourhood and bought time. Gradual rollouts mean a bad change reaches one percent of users before all of them, so the blast radius is small while you are still learning. Some teams go further and deliberately inject failures to practise, an approach covered in chaos engineering — the idea being that the first time you debug a failure should not be the first time it happens for real.
One rule stands above the rest: never debug by editing live code. Reproduce it in staging, with production-like data, and fix it there. A fix typed into a running server is one nobody reviewed, nobody tested, and nobody can reproduce — which is how one bug becomes two.
Questions developers ask about debugging
Is print debugging unprofessional?
No. It is the oldest debugging tool there is, and it works where a debugger cannot reach — production servers, distributed systems, code on someone else's device. The unprofessional move is leaving prints in, or guessing instead of looking.
Why does the bug disappear when I try to reproduce it?
Usually timing or state. A race depends on two things colliding, and anything that changes the timing — a debugger, extra logging, a faster machine — can hide it. A state bug depends on what ran before, and a fresh start clears it. When a bug vanishes on reproduction, the difference between the two runs is itself the clue.
How long should I struggle before asking for help?
Shorter than you think. Thirty focused minutes without progress is a good moment to explain the problem to someone else — the explanation itself often solves it. Asking is not giving up; it is changing the angle of attack.
Should I fix every bug I find while debugging?
No. Fix the one you came for, note the others, and file them. A session that turns into a general cleanup changes ten things at once.
A debugging checklist for your next bug
- Reproduce it, in the smallest form that still fails.
- Read the error message in full, and find the first frame that is your code.
- Halve the search space until the fault has nowhere to hide.
- Check the usual families: off by one, stale state, races, bad input, a bad paste.
- Explain the code out loud before you change anything.
- Fix the cause, not the symptom, and write a test that proves it.
- Run the whole suite, and check the edges of your fix.
- If it only happens in production, lean on logs, traces, and flags — never live edits.
Work through that list and most bugs stop being mysteries: a wrong assumption, sitting in one place, waiting for someone patient enough to find it.
Comments
Post a Comment