On June 4, 1996, the maiden flight of the Ariane 5 rocket lasted 37 seconds before the vehicle self-destructed. The cause: a 64-bit floating point number had been converted to a 16-bit signed integer in the Inertial Reference System software.[3]
Beyond what 16 bits could represent, the value was too large. An exception got raised and the backup system that ran the same software failed in the same way. The primary computer took the error message for flight data and the rocket went off course. Then the on-board self-destruct sequence was triggered.
The Ariane 5 bug cost approximately 370 million US dollars and five years of development. It had been introduced by reusing software from the Ariane 4 mission - software that had been proven correct for Ariane 4's flight envelope, which Ariane 5 exceeded.
No one found it because no one had put the reused module through testing against what Ariane 5 actually performed.
Every piece of software ever built contains bugs and the question is never whether bugs will show up. It is about how fast they are found, how well their root causes are understood and how completely they get fixed.
Developers answer these questions and they decide whether a debugging session takes 20 minutes or two weeks. They also decide whether 370 million dollars worth of hardware makes it through launch.
This article covers the systematic techniques that separate developers who find bugs efficiently from those who waste hours guessing. Debugging is one of the most learnable engineering skills and one of the least formally taught.
What Debugging Actually Is
Debugging. This is the systematic process of finding, isolating and fixing defects in software. The definition holds a word that matters. That word is systematic.
When a developer sees the bug appear, looks at the code and makes a change that seems plausible, checks whether the bug is gone, tries another change, clears the browser cache, restarts the server and then changes something else until the bug disappears, that is non-systematic debugging. The developer does not understand why it happens and cannot explain it.
This is guessing, not debugging. It is slow, unreliable, and teaches nothing.
Like scientific investigation, systematic debugging follows this pattern. Observe the symptom, form a hypothesis about what causes it, design an experiment to test the hypothesis, study the results and refine the hypothesis and go through that cycle again until the root cause appears.
This approach is faster, more reliable and gives understanding that stops similar bugs from appearing again.
Brian Kernighan, co-author of The C Programming Language, wrote: "Debugging is twice as hard as writing the code in the first place.[4]
If you write the code as cleverly as possible, by definition you are not smart enough to debug it. That observation written in 1974 is still accurate. When code is too clever to read clearly, it is also code that is too clever to debug efficiently.
Around half of what software developers spend on programming goes into debugging.[5] By some estimates, the global economic cost of software bugs runs to over one trillion dollars a year.
How striking the relative lack of formal debugging instruction in computer science education becomes clear from these figures.
| Bug Type | When It Appears | Key Diagnostic Tool | Typical Fix Approach |
|---|---|---|---|
| Syntax error | At parse/compile time | Compiler or interpreter message | Read error, correct syntax |
| Runtime error | During execution | Stack trace, error message | Follow stack trace to source |
| Logic error | Incorrect output, no crash | Debugger, print statements, bisect | Trace execution against expected |
| Concurrency bug | Intermittently under load | Thread analysis, reproducing race condition | Synchronization, atomic operations |
| Performance bug | Under specific load/data conditions | Profiler, timing measurements | Algorithm or data structure change |
| Integration bug | When combining components | Network/API monitoring, integration tests | Validate contracts between components |
'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.'
Brian Kernighan, co-author of 'The C Programming Language' (1978)
A Taxonomy of Bugs
Before looking at technique, it helps to know the types of defects that need different approaches.
Syntax Errors
Syntax errors make up the simplest category. The program fails to follow the rules of the language and the compiler or interpreter will not process it. The tool finds the error before execution and most often pinpoints the location exactly.
Today's editors show syntax errors in real time and many underline the problematic code before the file saves.
By far the smallest debugging problem is a syntax error since these get resolved quickly and almost never call for investigation.
Runtime Errors
Runtime errors happen during execution. After parsing and starting to run, the program runs into a condition it cannot manage. That is dividing by zero, dereferencing a null pointer, accessing an array index that does not exist or trying to open a file that is not there.
The program typically crashes with an error message and a stack trace - a list of function calls that led to the failure point. Stack traces are enormously valuable. They show exactly where the program failed and what sequence of calls produced that state.
Common runtime errors include:
- Null pointer dereferences: Calling a method on a variable that holds null rather than an object
- Index out of bounds: Accessing position 10 of a 5-element array
- Stack overflow: Recursive functions that call themselves without a base case
- Type mismatches: Passing a string where a number is expected, in dynamically typed languages
- Unhandled exceptions: Errors thrown by library code that the application does not catch
Logic Errors
Logic errors are the hardest category, and the one requiring the most sophisticated technique. The program runs without crashing but produces incorrect results. No error message. No stack trace. The code does exactly what the developer told it to do - which is not what the developer intended.
Example: A developer at an e-commerce company spent six hours in 2021 debugging a pricing discrepancy. The cart total was occasionally wrong by small amounts. The code ran without errors. The issue was a logic error in floating point arithmetic: the sum 0.1 + 0.2 in JavaScript equals 0.30000000000000004, not 0.3.
Multiple items with decimal prices built up rounding errors that totaled one or two cents off from what customers expected. Support tickets came in because of those errors but the system did not crash.
Both what the code does and what it should do have to be understood to find logic errors. To find them means reasoning about how the program behaves instead of tracing error messages to where they come from.
Concurrency Bugs
Concurrency bugs make up a fourth category that needs separate attention. They bring together the unpredictability of intermittent errors with the difficulty of logic errors.
When two or more processes or threads operate on shared data simultaneously, the order of operations becomes non-deterministic. The same code can produce correct results most of the time and wrong results occasionally, depending on timing that neither the developer nor the test suite controls reliably.
Race conditions occur when the outcome depends on which of two operations executes first. Deadlocks occur when two processes each wait for the other to release a resource. Data races occur when two threads read and write shared memory without synchronization.
Development environments and loaded production systems work with different operation timings and that is why these bugs do not appear during development or testing. It is production use patterns that display the timing dependency that bring them out once the bugs appear in production.
The Debugging Process
Most debugging situations call for the following sequence. Every step is needed and skipping any of them usually adds to the total time taken to debug.[2]
Establish a Reliable Reproduction
When a bug cannot be reliably reproduced, it cannot be studied systematically. Any debugging session begins with the first task of setting up a consistent way to reproduce the bug. That means the exact sequence of steps, inputs and environmental conditions that make the bug appear.
Questions to answer during reproduction:
- What is the exact input that triggers the bug?
- Does the bug appear every time, or intermittently?
- Which environments produce the bug? (Development, staging, production? Which browsers or operating systems?)
- What is the expected behavior?
- What is the actual behavior?
Example. An engineering team at a financial services company worked three days in 2020 on a bug that was described as payments sometimes fail. Debugging got nothing useful from the description.
Once they instrumented the reproduction environment, they found that the failure occurred only when the payment amount went over a particular threshold AND the user had an account fewer than 24 hours old AND the transaction took place between 2 AM and 4 AM UTC.
Each condition alone was insufficient to trigger the bug.
When the reproduction conditions were known precisely, the cause appeared in less than an hour. The cause was a mix of fraud detection heuristics that worked together in an unexpected way.
When a bug does not appear on demand, raise its chances of appearing by running the operation thousands of times in a loop, testing under different timing conditions and adding instrumentation to record what happens when the bug occurs in production.
Narrow the Search Space
A program with 100,000 lines of code contains thousands of potential bug locations. Debugging without narrowing the search space is impractical. The goal of this phase is to reduce the possible locations from thousands to dozens to one.
Binary search. Disable half of the code path by commenting it out. Is the bug still present? If so, the bug is in the part that remains. If not, it is in what was turned off. Each step cuts the code path in half again and a method like this finds a bug in about 17 steps through 100,000 lines of code.
Minimal reproduction. Take out everything that is not needed to trigger the bug. Get rid of unrelated features, simplify what the input data is and get rid of configuration options. When the smallest possible reproduction case is made, the cause most often becomes obvious and noise that hides the root cause gets eliminated.
Layer isolation. With a system that has layers (UI, business logic, data layer), find out which layer gives the bug by testing each one on its own. When the database query brings back the right data but the UI shows wrong data, the bug is in the business logic or rendering layer and not in the database.
Example. When Mozilla got the report that pages with complex CSS sometimes render incorrectly in 2019, that is how it started its debugging of a Firefox rendering bug. It took two weeks to reduce the problem to a minimal reproduction and the result was a seven-line HTML file with particular CSS properties that always brought out the misrender.
The rendering team found the issue (incorrect bounding box calculation for positioned elements inside grid containers) in a single afternoon once the team had the minimal case.
Understand the Root Cause
Fixing the symptom instead of the cause is the most common and costly way that debugging fails. Adding a null check before every function call that might get null is not fixing a bug. It is covering up a defect whose source remains active and will go on to cause more failures.
To stop the bug, the most fundamental underlying condition that must change is the root cause. Asking "why?" recursively until the chain of causation hits something that can be fixed definitively is what it takes to find it.
Five Whys technique (adapted from Toyota manufacturing):
- The application throws a NullPointerException. Why? The user object passed to
processPayment()is null. - The user object is null. Why? The session lookup returned null.
- The session lookup returned null. Why? The session expired before the payment was submitted.
- The session expired during payment. Why? The payment form takes longer than the session timeout to complete.
- The form takes too long. Why? Hand typing a 16-digit card number is what users have to do and that goes beyond the 15-minute session limit set for people with visual impairments who use screen readers.
Fixing it is not about catching the NullPointerException. A fix is to extend session timeout for users in the payment flow or to save session state before it expires during long transactions. Architectural decisions with real effect on user experience, these are decisions that appear only by going after the root cause instead of putting a patch on the symptom.
Fix and Verify
Once the root cause is understood:
- Write a failing test. This test should use the minimal reproduction case to reproduce the bug. It should fail before the fix is applied and pass afterward.
- Implement the smallest fix. That is the one that gets at the root cause. Making minimal changes cuts the risk of adding new bugs.
- Verify the test passes with the fix applied.
- Run the complete test suite to check for regressions introduced by the fix.
- Look for similar bugs, see where else this kind of mistake could show up in the codebase if this logic error could happen here.
- Document the fix. The commit message should record it with an explanation of the root cause and not just the change that was made.
Developers who write a failing test before fixing a bug (sometimes called test-driven bug fixing) adopt one of the highest-value habits available. This practice makes sure the bug does not come back silently and gives future maintainers documentation of what behavior is expected.
The Essential Debugging Toolkit
Interactive Debuggers
An interactive debugger allows the developer to pause program execution at any point and inspect the complete program state: all variables in scope, the call stack, the values returned by recent operations.
Every modern integrated development environment includes a debugger. The capabilities are consistent across languages:
Breakpoints. Execution halts at the line specified and the program stops there waiting for developer input. Developers can look at variable values, work through expressions in the current scope and choose what to do next.
Conditional breakpoints. Pausing execution only when a set condition becomes true, this is what they do. Bugs that appear only under certain conditions require this. Instead of going through thousands of loop iterations by hand, a conditional breakpoint on user.id == 42 or items.length == 0 stops the program only when the relevant condition is met.
Step over / Step into / Step out control how execution proceeds after a pause:
- Step over executes the current line and pauses at the next one
- Step into enters a function call, pausing at the first line of the called function
- Step out completes the current function and pauses at the calling location
Watch expressions show the value of chosen variables or expressions constantly as execution continues. A developer puts a watch on this.cache.size and watches that value get updated at every step without having to check it by hand.
Call stack inspection shows the complete chain of function calls that led to the current execution point - which function called which function all the way up from the initial entry point.
Example. A senior developer at Atlassian said in 2022 that a bug in Jira's search indexing was giving wrong results for certain query combinations and that three days of log analysis had not found what caused it.
With VS Code's debugger attached for two hours during the indexing process showed that a field normalization function was changing what it took in as input. The same object got indexed with different values depending on whether normalization had taken place.
Being able to pause execution mid-normalization and check the object both before and after let the debugger show the mutation right away.
Logging and Print Debugging
Interactive debuggers may be sophisticated but print debugging, which means adding temporary output statements to trace execution, continues to be the most widely used debugging method. Developer surveys from Stack Overflow show it time after time as the most common approach across all experience levels.
Print debugging has genuine advantages:
- No setup required: Works in any environment without configuring a debug adapter
- Temporal view: Shows a sequence of events over time, which interactive debuggers make more difficult to follow
- Remote and production use: Can be used in environments where attaching a debugger is impossible
- Parallel execution: In concurrent code, print output shows the interleaving of operations
Effective print debugging differs from scattering console.log("here") throughout the code:
Include context: console.log('processPayment called', {userId, amount, currency, timestamp}) tells you what the function received. console.log('here') tells you nothing except that execution reached that line.
Use structured logging: Key-value pairs that logging infrastructure can parse, search, and aggregate. logger.info('payment.attempt', {userId: 123, amount: 49.99, status: 'initiated'}) is searchable. Concatenated strings are not.
Log at boundaries: Function entry and exit, API calls, database queries, external service interactions. Knowing what went into and came out of each component is usually sufficient to find where values go wrong.
Include timing. Performance bugs can be found through timestamps or elapsed time and the sequence of events in concurrent systems can be reconstructed as well.
Remove after debugging. Production code should never ship with debug logs sitting in production. That makes the logs noisy, pushes up how much storage the logs cost and carries the risk that sensitive data will get exposed.
Reading Error Messages Thoroughly
Developers routinely glance at the first line of an error and begin guessing, missing the specific location and context information that follows. The most consistently underused debugging tool is the error message itself.
A stack trace contains:
- The error type and message
- The file name and line number where the error occurred
- The chain of function calls that led there
- In some languages, the values of local variables at each frame
TypeError: Cannot read properties of undefined (reading 'email')
at sendWelcomeEmail (notifications.js:47)
at createUserAccount (users.js:89)
at POST /api/users (routes/users.js:23)This trace says: at line 23 of the users route handler, createUserAccount was called.
At line 89 of that function, sendWelcomeEmail was called. At line 47 of the notifications module, something expected to have an email property was undefined. Start at notifications.js:47, look at what is undefined, and trace where it came from.
Reading this trace takes 30 seconds. Ignoring it and guessing can take hours.
Git as a Debugging Tool
Version control history is an often-overlooked debugging resource. When a bug was introduced by a recent code change, git tools can identify the change quickly:
git log --oneline -20 lists the last 20 commits and if the bug appeared recently, the causative commit should appear in that list.
git blame filename.js annotates each line with the last commit that modified it. When a suspicious line appears, git blame shows who wrote it, when, and in what commit - providing the full context of that change.
git bisect performs automated binary search through commit history.[8] The developer marks one commit where the bug is present and one where it is absent; git checks out commits in between, the developer tests each, marks it good or bad, and git narrows the search geometrically.
A bug introduced anywhere in the last 1,000 commits can be found in approximately 10 test cycles.
git diff HEAD~5 shows the changes made in the last five commits - useful for quickly reviewing what changed recently when a bug appears.
How to use version control well, including these debugging workflows, gets full treatment in the context of development workflows and team practices.
Application Performance Monitoring
Without developer intervention, production systems use Application Performance Monitoring (APM) tools such as Datadog, New Relic, Sentry and Honeycomb to automatically capture errors, performance metrics and traces.[6]
These tools attach to the application at runtime and record:
- Every unhandled exception, with full stack traces and the request context that produced it
- Database queries, external API calls, and their durations
- Memory usage, CPU consumption, and thread pool metrics
- Distributed traces showing how a single user request flows through multiple services
Example: Stripe uses extensive internal observability tooling that was publicly described in a 2020 engineering blog post.
Engineers can pull the distributed trace for transactions that were affected when a payment processing anomaly appears in production. They can see which service dealt with each step, spot where latency spiked or where errors occurred and most often they can diagnose production bugs within minutes of the bugs appearing and without having to reproduce them locally.
Debugging Hard Problems
Intermittent Failures
Inconsistently appearing bugs are the most frustrating category of bug. Developers sometimes call them heisenbugs after Heisenberg's uncertainty principle because the bugs seem to disappear when people try to observe them.
Intermittent failures arise from:
- Race conditions: Two concurrent operations interact in an order that produces incorrect results
- Timing dependencies. The bug shows up only when load conditions change the order in which operations run.
- Environment differences: Configuration, data, or resource availability differs between environments
- Memory state corruption: Previous operations leave residual state that affects subsequent ones
Strategies for intermittent bugs:
Increase occurrence rate. Loop the operation thousands of times. A bug that shows up 1% of the time will appear about 100 times in 10,000 runs and that makes it possible to spot and analyze.
Comprehensive instrumentation. Put in place detailed logging around the part of the code where the bug is thought to happen and once the bug appears the logs show what state sequence led to it.
Thread safety analysis. All code running at once should be checked for any access to shared mutable state and tools such as Java's FindBugs or Rust's borrow checker can automatically find potential race conditions as static analyzers.
Chaos engineering. Put in controlled failures such as delayed responses, network partitions and resource exhaustion to show what assumptions hold about how fast things go and how much resource there is. Netflix's Chaos Monkey and equivalents run this process systematically.
Example. A large media streaming company's engineering team published a case study in 2021. It told how an intermittent failure appeared about once per 10,000 requests in their recommendation engine. The failure took seven engineers two weeks to investigate.
There was a subtle race condition in the caching layer as the root cause. Simultaneously deciding that a cache entry needed refreshing were two threads. Both refreshed it from the database and one thread overwrote the other's result with a stale value from a slightly earlier query.
As the fix, distributed locking during cache refresh was what was needed. Before load growth made it common enough to be noticed, the bug had existed for 14 months.
Production-Only Bugs
Some bugs appear only in production environments, where:
- Data volumes are orders of magnitude larger than in development
- Concurrent users create conditions impossible to replicate locally
- Third-party services behave differently than mocked versions suggest
- Configuration differs subtly between environments
Debugging production-only bugs requires production-quality observability:[7]
Correlation IDs: Assign a unique identifier to every request at the entry point and include it in every log message generated by that request. When a bug occurs, the correlation ID lets you trace the complete request flow through all services that handled it.
Feature flags: Roll out changes incrementally to a percentage of traffic. If a bug appears after a deployment, disable the new feature for all traffic instantly without rolling back the deployment.
Canary deployments. Put changes on a small group of servers first and watch error rates and performance metrics for the canary instances before deploying to all servers.[9]
Shadow traffic. Reproduce production-specific conditions in a staging environment by replaying production traffic there without affecting real users.
Debugging Other People's Code
When inheriting or investigating unfamiliar code:
Start from the error and work backward: The stack trace points to where the failure occurred. Trace the call chain upward to understand what sequence of decisions led there.
Read the tests. Tests document what behavior is expected and they show edge cases that the original developer thought about. A test suite is often better documentation than comments.
Look at recent changes, use git log --since="2 weeks ago" and git log --author="username" to narrow the search down to code that was recently changed when the bug is new.
Follow the data: Trace the value of the relevant variable from its creation through every transformation until it reaches the point of failure. Often the bug lies at a transformation step where the value becomes incorrect.
Use the "strangler" approach for legacy code. Add characterization tests to the codebase that document what the code does now even when that behavior is wrong. With these tests catching regressions as you look into and fix the underlying issues, the approach works.
Common Debugging Errors and How to Avoid Them
Changing Multiple Variables Simultaneously
Changing three things and observing that the bug disappears does not tell you which change fixed it. Possibly one of the three changes was the fix; possibly two interact to mask the bug without fixing it; possibly all three are irrelevant and the bug disappeared due to environment changes.
Rule: Change exactly one thing between observations. This is the experimental discipline of debugging.
Debugging by Coincidence
"Restarting the server sometimes fixes it" is not a solution. That is a warning sign. When something accumulates, memory leaks, state does not get reset properly or connections do not get released and once the reason why the restart helps is understood, that points to the actual bug.
Rule: Never accept a fix you do not understand. If clearing the cache fixes the bug, find out what stale data was in the cache and why it was stale.
Assuming the Framework is Wrong
The conclusion that "My code is correct and the bug must be in [React / Django / PostgreSQL]" is sometimes right but most often wrong. Millions of users of widely used frameworks would have run into the same bug.
Check your own code carefully before you think the toolchain is to blame and once you do suspect the toolchain, make a minimal reproduction case to prove it.
Not Writing a Test After Finding the Bug
Without writing a test that would have caught it, the most frequent post-debugging mistake is to fix the bug. A refactor or a well-intended change within a year may bring the same bug back and the debugging session that follows begins from zero.
Rule. Every time a bug gets fixed, write a test that would have caught the bug before it got to production. This has to be a non-negotiable part of fixing the bug.
Debugging While Emotionally Frustrated
When debugging goes on for extended time without success, frustration builds up and that impairs judgment. When debugging gets frustrated, it turns to increasingly random changes, skipped steps and confirmation bias (seeing what you expect to see instead of what is there).
Rules: Take a break after 45 to 60 minutes without progress. Explain the problem to a colleague - the rubber duck effect (articulating a problem to another person, or even to a rubber duck) frequently produces insight. Sleep on difficult problems; the subconscious continues processing.
Prevention: The Economics of Early Bug Detection
The cost to fix a bug increases by roughly an order of magnitude at each stage of the development lifecycle. A bug caught by the developer while writing code might take 5 minutes to fix. The same bug caught in code review might take 30 minutes.
QA testing finds it and that could take an hour including regression testing. In production, it takes an emergency deployment, rollback, customer communication and post-incident review that represents hours or days of multiple people's time and also means potential business impact.
Research going back to Barry Boehm's work in the 1970s has produced these numbers, which have held up in later studies.[10] How the ratios break down varies, yet the core finding holds: fixing bugs earlier costs much less.
This economics argument makes the case for:
Automated testing: Unit tests catch bugs at the moment of writing. Integration tests catch bugs when components are combined. End-to-end tests catch bugs in complete user flows. Each layer catches bugs before they reach the next, more expensive stage.
Type systems. Languages that are statically typed such as TypeScript, Java, Go and Rust get rid of whole classes of bugs at compile time. A type system is not theoretical in its value. It is the particular category of null reference errors, type mismatches and missing field accesses that never make it into production.
A 2017 study of GitHub JavaScript projects found that TypeScript annotations would have stopped 15% of the bugs that were reported.[11]
Linters and static analysis. Without running any code, tools such as ESLint, Pylint and SonarQube look for bug-prone patterns in code. Issues they find in seconds are the kind that could take hours to track down once the software is running.
Code review. Logic errors, missing edge cases and incorrect assumptions that the developer's familiarity with their own code keeps them from seeing get caught by a second pair of eyes. Google's engineering practices document attributes that major quality improvements come from making code review mandatory.
Developers who work with tested, reviewed and typed code find they spend much less time fixing bugs. The connection between code quality practices and how often code gets debugged is direct. Put in place several times over, these practices pay back by saving time spent on debugging.
Details on how quality practices fit into software development workflows can be found in How Software Is Actually Built and in the wider principles covered at developer productivity.
Debugging Across Paradigms
Functional Debugging
Pure functions are much easier to debug in functional programming. These are functions that give the same output for any given input and do not have any side effects. With the inputs known, the output is deterministic. The function can be tested in isolation and no environmental setup is needed.
Debugging functional code primarily means:
- Verifying that functions are actually pure (no hidden global state access)
- Tracing data transformations through function composition pipelines
- Identifying where impure operations (I/O, randomness, time) enter the computation
Object-Oriented Debugging
Through mutable state spread across objects, object-oriented code brings extra debugging complexity by giving each object behavior that depends on the full record of state changes that have happened to it.
Debugging OO code often requires:
- Understanding the complete lifecycle of an object from construction through the point of failure
- Identifying which methods have modified the relevant state
- Tracing message-passing sequences through inheritance hierarchies
Distributed System Debugging
Debugging complexity comes to microservices and distributed architectures that single-process apps do not have. One service failure can show up as a confusing error in another when a user request goes through five or ten different services.
Distributed tracing tools like Jaeger, Zipkin, and AWS X-Ray attach a trace ID to every request and record its passage through each service. When a failure occurs, the trace shows which service failed, what it received, and how long each step took.
The Debugging Mindset Over Time
How systems fail forms the main difference between senior and junior developers in debugging. Junior developers view a bug as a local error in a single line of code.
Senior developers view a bug as evidence of how the system behaves. That evidence can show assumptions that were wrong, edge cases that were overlooked or architectural choices with unforeseen consequences.
This perspective shift brings about different ways of debugging. When a senior developer looks at a bug, she asks first not "which line is wrong?" but "what does this bug show me about how this system works?". The fixes that prove most often to be both stronger and longer lasting come out of where the answer points.
Another consistent difference is documentation. What senior developers find gets documented by them in commit messages, close to complex logic in comments, in incident post-mortems and in test cases that stop regression. Each bug is treated as information to save for future developers, including those who will be their own future selves.
What Research Shows About Debugging
Since the early 2000s, the empirical study of debugging has sped up and it has produced a body of evidence that challenges several common assumptions about how bugs get found and fixed.
Tom Britton, Lisa Jeng, Graham Carver and Paul Cheak did a foundational study at Cambridge Judge Business School in 2013. The study was titled "Reversible Debugging Software" and it found that developers spend 35 to 50 percent of their total programming time on debugging.[5]
Reversible debugging tools that let execution step backward in time cut average debugging time by 26 percent compared to conventional forward-only debuggers and the study found that more strikingly. This points to the directional constraint of traditional debugging tools as being itself a major source of inefficiency.
Andreas Zeller at Saarland University, author of Why Programs Fail (2009), has contributed the most systematic academic framework for debugging methodology.[1]
Zeller's "delta debugging" algorithm, introduced in a 2002 paper in IEEE Transactions on Software Engineering, automates the process of isolating minimal failure conditions.
Given a failing test and a passing test, delta debugging systematically narrows the difference between the two (in input, configuration, or code changes) until the minimal change that causes the failure is identified.
In his empirical studies, Zeller found that delta debugging cut the time to isolate the minimal failure condition by 60 to 80 percent versus manual narrowing mainly by getting rid of the confirmation bias that makes developers miss non-obvious causative factors.
Research by Bettina Berendt and colleagues at KU Leuven, published in 2018 in the Journal of Systems and Software, studied 200 professional developers to understand the cognitive patterns that distinguish effective debuggers from ineffective ones.
Effective debuggers developed explicit hypotheses before testing as the study showed and ineffective debuggers moved instead toward what the researchers named exploration debugging. That means changing something and observing the effect without making a prediction that can be tested.
On average, hypothesis-first debuggers took 18 minutes to solve the bugs assigned to them and exploration debuggers took 47 minutes.
How each group used evidence explained the difference. Hypothesis-first debuggers explicitly updated their mental model with each observation and exploration debuggers collected observations without having a way to interpret them.
The Consortium for Information and Software Quality (CISQ) commissioned a 2020 report that updated and extended the economic cost of debugging. The CISQ estimates that software failures cost the US $1.56 trillion annually.
The report (written by Herb Krasner) says that out of this total, $1.15 trillion gets attributed specifically to operational software failures, bugs that make it to production. It also points to poor debugging practices above all else as what drives repeat failures. That is the failure to find root causes before putting fixes in place.
The report showed that 62% of production incidents came from bugs that had been "fixed" before in the same codebase. That means that organizations use symptom-level fixes without doing root cause analysis as their main way of debugging.
Barry Boehm did the original work on defect detection and repair costs that has been updated by more recent studies at IBM's Systems Sciences Institute and at SEI Carnegie Mellon. The result time after time is a 100 to 1 cost ratio between fixing a defect in production and finding it during requirements specification.
The cost ratio for bugs caught during code review versus bugs in production is about 10 to 1. What that means for debugging practice is clear and direct. Prevention (code review, automated testing and static analysis) is the most economically rational place to invest in debugging rather than diagnosing after deployment.
When companies put 10% more of their debugging time into early detection methods and draw on the cost ratios and detection efficiency data in Boehm's research, they can cut total debugging costs by 50 to 70%.
Real-World Case Studies in Debugging
The Therac-25 radiation therapy machine incidents from 1985 to 1987 are the most thoroughly studied case of production bugs that had catastrophic results.
Six patients received massive radiation overdoses from the Therac-25, a computer-controlled radiation therapy device and three of them died because the control software had a race condition.
In their 1993 paper in IEEE Computer, Nancy Leveson and Clark Turner showed that the race condition happened only when operators entered treatment data faster than a certain speed that had never appeared during tests but was regular in production with operators who knew the interface by heart.
The bug had been present since the Therac-20 predecessor but was masked by hardware interlocks that the Therac-25 eliminated.
Because it shows how concurrency bugs, environment-dependent failures and the removal of redundant safeguards can come together to make bugs in tested code catastrophic in production, the case study is now standard across software engineering courses.
Microsoft's debugging of Windows memory corruption bugs during the development cycles of Windows Vista and Windows 7 is documented by former Microsoft developer Raymond Chen in The Old New Thing blog. That work shows how systematic debugging can be carried out at the scale of a 50-million-line codebase.
Particularly hard to deal with are Windows kernel memory corruption bugs. The symptom of a crash or incorrect behavior most often appears in code that is far removed from where memory was corrupted and that is the cause.
Developing Application Verifier was part of Microsoft's response. This is a dynamic analysis tool that intercepts memory allocations and checks heap integrity on each access and makes corruption show up where it happens instead of showing up much later as a symptom.
Chen showed that Application Verifier cut the average time to find the root cause of heap corruption bugs from 3 to 4 days (without the tool) down to under 4 hours. That represents a gain of 10 to 20 times.
Making implicit constraints explicit and failing immediately once they are broken has become a standard pattern in debugging tool design and that is the approach the tool takes.
Google's production debugging practices, described by engineers in the Google Site Reliability Engineering book (2016) and supplemental blog posts, represent the most systematically documented approach to production debugging at scale.
What Google's SRE team calls structured problem solving is at the heart of its approach. Every production investigation starts with an explicit written hypothesis in a shared document and then comes structured evidence collection followed by a revision of the hypothesis.
After an internal study showed that debugging sessions without written hypotheses took 2.3 times as long on average as structured ones and were 40 percent more likely to end with fixes that got reversed, the practice was put in place.
Google's distributed tracing infrastructure (which became the Dapper research paper, 2010) was developed specifically because the complexity of distributed debugging made unstructured investigation intractable at their scale.
Knight Capital Group's $440 million loss in 45 minutes on August 1, 2012, is the most studied case of a production debugging failure in financial technology. A deployment error activated unused code in Knight's market-making system, causing the system to issue erroneous buy orders for 154 stocks.
Over 45 minutes, Knight's operations team saw losses rise but could not diagnose or stop what was wrong. There was not enough production monitoring in place and no one clearly owned the deployment process.
After its analysis of what happened, the SEC discovered that Knight had no automated circuit breakers to stop trading once losses passed certain thresholds. Order volume anomalies went unalerted in real time and there was no runbook documented for turning off specific parts of the trading system.
The firm lost $440 million, more than its net equity, in a span shorter than a typical debugging session.
Automated circuit breakers, position limits and kill-switches have since been widely adopted across financial trading systems as the case pushed for that adoption. Every one is a direct answer to the particular debugging and monitoring holes the incident revealed.
Sources
- Zeller, Andreas. Why Programs Fail: A Guide to Systematic Debugging. Morgan Kaufmann, 2009.
- Agans, David J. Debugging: The 9 Indispensable Rules for Finding Even the Most Elusive Software and Hardware Problems. AMACOM, 2002.
- Lions, Jacques-Louis. "Ariane 5 Flight 501 Failure: Report by the Inquiry Board." European Space Agency, 1996. View source
- Kernighan, Brian W. and Plauger, P.J. The Elements of Programming Style. McGraw-Hill, 1978.
- Britton, Tom et al. "Reversible Debugging Software." Cambridge Judge Business School, 2013.
- Sentry. "Error Monitoring and Performance." sentry.io.
- Honeycomb. "Observability for Production Systems." honeycomb.io.
- Git. "git-bisect Manual Page." git-scm.com. View source
- Nygard, Michael T. Release It!: Design and Deploy Production-Ready Software. Pragmatic Bookshelf, 2018.
- Boehm, Barry. Software Engineering Economics. Prentice Hall, 1981.
- Gao, Z., Bird, C., & Barr, E. T. (2017). To Type or Not to Type: Quantifying Detectable Bugs in JavaScript. 2017 IEEE/ACM 39th International Conference on Software Engineering (ICSE), 758-769. View source
Further Reading
- Gao, Zheng et al. "An Empirical Study on the Usage of the 'const' Qualifier in C." ACM SIGSOFT International Symposium on Software Testing and Analysis, 2017.








