How to Test Your Code When the Bug Only Happens in Production
Every developer has met this one. The tests pass, the code works on your laptop, and then a user reports a crash you cannot make happen. The bug only happens in production, and the gap between your machine and the live system is where it lives. The fix is not to guess harder. It is to close that gap step by step: gather what production already knows, rebuild the exact conditions, and test the fix in a way that cannot hurt real users.
Why Some Bugs Never Show Up Locally
Your laptop is a kind place. It has one user, a small database, fast disk, and clean data. Production has thousands of users at once, a database that has grown for years, slow networks, and data entered by real people in ways nobody predicted. A bug that needs two requests to arrive in the same millisecond, a record with a missing field from 2019, or a third-party API that answers slowly will simply never fire on your machine.
None of this means your tests are useless. Unit tests catch logic errors. The problem is that a production-only bug lives in the interaction between code, data, timing, and setup. That is why integration testing matters when unit tests are not enough: it checks how parts of the system behave together, which is exactly where these bugs hide.
Start With What Production Actually Tells You
Before you write a single test, collect evidence. Write down the exact time, the user or account involved, the request path, and the error message. Then check whether the bug happens for everyone or only for some users, only at certain times, or only on certain servers. That pattern is often the biggest clue you will get.
Check your error tracker for the same error in the past week. A sudden spike after a release points at new code. A steady trickle that has gone on for months points at bad data or an edge case in old code. Read the stack trace next: it names the exact line where the code failed, and learning how to read a stack trace saves hours of guessing, because the real bug is often two or three frames above the line that threw the error.
Keep a short written record of everything you find: timestamps, request IDs, affected accounts, and the deploys around the time the bug started.
When the Bug Only Happens in Production: Reproduce It Safely
Reproducing the bug is the goal, but copying production data to your laptop is often the wrong way to do it. Real user data contains personal details and payment information. Pulling a full database dump onto a developer machine creates a privacy risk and, in many companies, breaks policy. The safer approach is to reproduce the shape of the data, not the data itself.
Start by finding the smallest input that triggers the failure. If the bug follows one account, look at what makes that account different: an old subscription plan, a name with a special character, an address field left blank years ago. Build a test account with those same traits in staging and run the same steps until it fails the same way.
When you need real production values, sample a small set of records and mask the sensitive fields before they leave production. Careful production bug testing starts with this habit: never move raw user data to a place with weaker security. You can also replay a failing request against staging: record it, strip out auth tokens, and send it again. If it fails there, you have a reproduction you can run again and again. If it passes, the difference is the state around it, not the request. That is the key insight when you try to reproduce production bug reports: match the state, not just the request.
Use Logs, Metrics, and Traces to Narrow It Down
When you cannot reproduce the bug yet, observability is your test bench. Add a log line at each decision point in the failing code path, and include a request ID in every line so you can follow one request from start to finish. Log the inputs that matter: the user ID, the feature flag state, and the result of each external call. Never log passwords, tokens, or full request bodies.
Metrics tell you where to look. A graph of error rate by server can show that only one machine fails, which points at a bad deploy or a full disk on that box. Latency by endpoint can show that the failing request is the slowest one, which points at a timeout or a slow database query. If you are new to this, start with the basics of logs, metrics, and traces and how the three fit together: logs record events, metrics show trends, and traces follow a single request across services.
Traces are the most useful tool for bugs that cross service boundaries. A trace shows each step a request took, how long each step lasted, and where it stopped. If the trace ends at a call to the payment service after 5 seconds, the timeout is the trigger, not your own code. Production debugging techniques like this work because they test a theory against real evidence instead of a guess.
Test in Production Without Breaking It
Sometimes staging cannot reproduce the bug at all. The data is too big, the traffic pattern is too specific, or the bug needs real load. In that case you test in production, but you do it behind guardrails. Feature flags are the simplest guardrail. Wrap the fix or the new logging behind a flag, turn it on for your own account or for 1 percent of users, and watch the results before rolling it out further.
Shadow testing is another option: send a copy of real production traffic to a new version of the service and throw away its responses. Users never see the output, so a crash harms nobody, and you can compare its answers against the live version. Canary deploys work the same way: ship the new code to one server first and roll it out only if its error rate stays clean.
There are rules for testing this way. Never test on all users at once. Always have a way to turn the change off in seconds, not minutes. Write down in advance what result would make you roll back, and watch the dashboards while the test runs. If you cannot watch it, do not ship it.
Make Staging Behave Like Production
Every production-only bug you fix is a sign that staging drifted from production. Close the gap after each incident: same versions of the database, cache, and runtime, same environment variables with different secrets, and seed data shaped like production, with old records, blank fields, and duplicate names.
Load matters too. A bug caused by two requests racing each other will not appear in staging if it handles one request at a time. Add a load test that sends realistic traffic at realistic speed. You do not need to match production volume exactly, just enough concurrency to expose race conditions and connection limits.
Also test the deploy itself. Many production-only bugs are deploy bugs: a migration that ran in the wrong order, a file that was not copied, a service that started before its config arrived. A staging deploy that follows the exact same steps as production catches these before they reach users. If you cannot debug the server directly, these techniques for debugging production without SSH access cover the tools and habits that replace a shell session.
Fix It, Verify It, and Stop It Coming Back
Once you can reproduce the bug, write a failing test first, then fix the code until the test passes. The test is the proof that you understood the bug, and it stays in the suite so the bug cannot return quietly in a later refactor. Keep the test focused on the trigger you found: the blank field, the race, the timeout.
Verify the fix where the bug lived. Deploy behind a flag or to a canary, and watch the error rate for the specific error you chased. If it drops to zero and stays there through a full day of normal traffic, the fix holds. If it drops and returns, you fixed a symptom, not the cause.
Finally, write down what happened. A short incident note with the trigger, the evidence, the fix, and the test is enough. Link it from the code so the next developer who touches that area knows why the odd-looking check exists. That is the last step every time the bug only happens in production: record the pattern. Old data, bad timing, config drift, and untested interactions cause most of them, and each note you write makes the next one faster to find.