How to Debug a Database Query That Fails Only in Production
Published November 22, 2026•Updated November 24, 2026•8 min read
Quick Answer
Reproduce with the exact record that failed, never with a fresh test record.
PostgreSQL prepared statements can switch to a generic plan after about five executions, which is why a query looks fast in psql and slow from the application.
Timeouts that rise with traffic usually mean waiting on a lock or a connection, not slow execution.
Database tools show the SQL that ran. The application values that built that SQL need a log line, a trace attribute or a read-only probe.
The query passed every test, ran in milliseconds on staging, and now returns an error or a timeout for real users. A query that works in staging but fails in production is one of the harder cases of debugging production issues, because the conditions that trigger the failure exist only in production, in its data, its configuration and its traffic. Teams lose hours here by guessing at fixes and redeploying, a pattern covered in where backend teams lose hours in a production incident. The production database query debugging checks below run in a fixed order, from the cheapest evidence to the most invasive, and each one rules out a cause before the next begins.
Why do queries fail only in production?
A query fails only in production when something around it differs from the environment where it was tested. The SQL text is usually identical. What changes is the database configuration, the data the query touches, the execution plan the optimizer picks, or the number of sessions competing for the same rows and connections.
The table below maps each cause to the symptom it tends to produce and the first thing to check.
Cause
Typical symptom
First check
Environment drift
Syntax errors, encoding errors, auth failures
Compare engine version, SQL mode and collation
Production data shape
Errors or wrong results for specific records
Re-run with the exact failing record
Different query plan
Slow for some parameter values, fast for others
Log the plan that ran in production
Locks and connection limits
Timeouts that rise with traffic
Inspect blocked sessions and pool wait time
Checklists from cr0x.net and tier2.dev arrive at the same grouping. Configuration and data differences come first, and scale and concurrency come later.
What evidence should you capture first?
Evidence from the failing request decays quickly, since logs rotate and a successful retry hides the original condition. Collect the four items below before anyone touches the code.
The exact error text and error code, such as the PostgreSQL SQLSTATE or the MySQL error number.
The query fingerprint, so the failing statement can be matched to aggregate statistics.
The bound parameter values that were sent with the statement.
The release or commit SHA, the timestamp and the instance or pod that served the request.
On PostgreSQL, the pg_stat_statements extension records planning and execution statistics for every normalized statement. Sorting by standard deviation surfaces queries whose runtime swings between calls, a common sign of a plan or data problem. Diffing two snapshots taken a minute apart isolates the load happening right now from the totals since the last reset.
SELECT queryid, calls, mean_exec_time, stddev_exec_time, query
FROM pg_stat_statements
WHERE calls >50ORDERBY stddev_exec_time DESC
LIMIT 10;
On MySQL 8, the performance_schema.events_statements_summary_by_digest table gives a comparable per-statement view.
Is production configured differently?
Configuration drift is the cheapest cause to rule out, so it comes before any data or plan analysis. A write-up on local versus live failures lists the usual suspects for MySQL. They include a server version that lacks a feature such as common table expressions, a stricter sql_mode like ONLY_FULL_GROUP_BY, and a character set or collation that changes filtering and sorting. The cr0x.net analysis adds authentication plugin defaults and client library versions, which break connections after an image upgrade.
Run the same settings query in each environment and diff the output.
Driver settings belong in the same comparison. A JDBC prepareThreshold or an ORM option that turns on server-side prepared statements in production changes how the database plans every query, which matters in the plan section below.
Does production data break the query?
Production data holds values that test fixtures never include. Common examples are nulls in columns assumed to be required, rows created before a migration, Unicode in names, and customers with far more records than average. A query can be correct for every row in staging and still fail on one row in production.
Volume changes behavior as well. In one Stack Overflow case, a query with an IN list of hundreds to thousands of IDs ran fast on staging and local and slowly on production, all on the same PostgreSQL version. The answers recommended joining against a VALUES list or derived table and confirming an index on the filtered column.
How do you reproduce it safely?
You reproduce a production-only query failure safely by re-running it with the exact record and the exact parameter values that failed, in an environment that cannot write to production. The tier2.dev checklist gives the most useful rule here: never substitute a fresh record created for the test, because the fresh record lacks the history that caused the failure.
The steps below keep the reproduction close to production without putting customers at risk.
Copy only the failing record and its related rows into a scratch environment, with sensitive fields masked.
Match the production settings captured earlier, including the driver options and plan_cache_mode.
Run read-only checks against a read replica when the data cannot leave production.
Execute the statement as a prepared statement with bound parameters, the same way the application sends it.
A full production dump is rarely needed to reproduce a single failing query, and it creates a copy of customer data that someone then has to secure. Our guide to debugging production without exposing customer PII covers that tradeoff in more detail.
Is the query plan different in production?
The query plan differs in production when table statistics or parameter values lead the optimizer to a different choice. A query can be correct and still time out because production chose a sequential scan where staging used an index.
Why does psql show a fast plan?
Applications send parameterized statements, while engineers testing in psql usually paste literal values. PostgreSQL plans the first several executions of a prepared statement with the real values, then may switch to a generic plan if its estimated average cost is lower. Michal Drozd describes this switch happening after about five executions, with the generic plan running far slower for rare values in skewed columns. A psql session with literals never reaches that state.
PREPARE q(text) ASSELECT*FROM orders WHERE status = $1;
SET plan_cache_mode = force_generic_plan;
EXPLAIN ANALYZE EXECUTE q('failed');
The ExplainSQL guide lists two remedies. Set plan_cache_mode = force_custom_plan for the affected role or session, or disable server-side prepares in the driver with prepareThreshold=0.
How do you log the executed plan?
The auto_explain module writes the plan of any statement slower than a threshold to the server log, including the parameter values. The settings below log statements over three seconds and sample a quarter of them. The PostgreSQL documentation warns that per-node timing adds overhead, so keep the threshold high and the sample rate low on busy systems. MySQL 8.0.18 and later offer EXPLAIN ANALYZE for a similar manual check.
A query is waiting on locks when its timeouts grow with traffic while its execution time stays flat. Compare the two numbers. When wait time exceeds execution time, the bottleneck is the connection pool or a lock. When execution time dominates, return to the plan. Sessions left idle in transaction are a frequent root cause, since each one holds a connection and its locks.
The PostgreSQL function pg_blocking_pids returns the sessions that block a given process, which leads to the root blocker.
SELECT pid, pg_blocking_pids(pid) AS blocked_by,
wait_event_type, state, xact_start, query
FROM pg_stat_activity
WHEREcardinality(pg_blocking_pids(pid)) >0;
The root blocker typically has an old xact_start and an innocent last statement. Set lock_timeout and statement_timeout per role or with SET LOCAL inside migrations, rather than globally, so reports and maintenance jobs keep running.
How do you capture application state too?
You capture application state by recording the variables that built the query at the moment the query failed. Database tooling shows the SQL that ran. It rarely shows why the application built that SQL, for example a user ID that resolved to the wrong tenant or an ID list that grew far past its expected size.
Closing that gap starts with two habits. Log bound parameters next to the error, with sensitive values redacted. Add the query fingerprint and key inputs as attributes on trace spans, so a slow database call links back to the request that issued it. A comparison of distributed tracing tools covers which tools support this well.
Some failures still fall between existing log lines. HyperProbe is an AI on-call agent for live production debugging, built on dynamic instrumentation. It places a read-only probe on the line that builds or executes the query and captures the variable state the next time that line runs on live traffic. Read-only probes do not pause production, change source code or require a redeploy. PII is redacted at the agent before capture, and probes self-clear on a time limit and rate limit.
The tradeoff is scope. A probe captures application state only, not database internals, so it complements auto_explain and pg_stat_activity rather than replacing them. A probe also cannot look back at requests that finished before it was set, which makes it most useful for failures that recur. The guide to production debugging tools compares this approach with other options.
How does this fit your existing stack?
This workflow fits on top of the monitoring a team already runs. Datadog or another APM tool shows which endpoint slowed down, Sentry groups the database exceptions, and PagerDuty routes the alert to the on-call engineer. The database checks above explain what the database did, and a read-only probe explains what the application sent. HyperProbe reads from that stack and goes past it only when the answer is not already in the logs, so nothing has to be migrated or replaced.
A repeatable path for production query failures
The order of the checks matters more than any single command. Capture the evidence, diff the configuration, reproduce with the failing record, log the plan that ran, check for blocked sessions, then capture the application state. Each step is cheap compared with the step after it, and each one removes a cause from the list. When the fix lands, turn the check that found it into a runbook entry or an alert, so debugging production issues of this kind starts from evidence the next time a query fails.
The failures that no runbook check explains are the ones that cost the most hours. Bring one of them to a 30-minute walkthrough, and HyperProbe will work it with you on your own service until it reaches a confirmed root cause. The first incident we work with you is free. To start on your own, HyperProbe is free forever on one service with unlimited probes. Install the SDK from the quickstart on the service that runs the failing query and place your first probe within 15 minutes.
Frequently asked questions
Why does a query work in staging but fail in production?
A query that works in staging but fails in production usually hits a difference in its surroundings, not in its SQL. The four common causes are configuration drift, production data that test fixtures never include, a different execution plan, and lock or connection contention under real traffic. Check them in that order, starting with the cheapest.
Why is a query fast in psql but slow in the application?
Applications usually send prepared statements with bound parameters, while psql tests use literal values. PostgreSQL can switch a prepared statement to a generic plan after about five executions, and that plan can be much slower for rare values in skewed columns. Test with PREPARE and EXECUTE to see the plan the application gets.
How do you reproduce a bug that only happens in production?
Reproduce it with the exact record and parameter values that failed, not with fresh test data. Copy only that record and its related rows into a scratch environment with sensitive fields masked, match the production settings and driver options, and run the statement the way the application sends it. When data cannot leave production, use a read replica.
Should statement_timeout be set globally?
No. Set statement_timeout and lock_timeout per role, or with SET LOCAL inside migrations. A global value can cancel reports, VACUUM and other maintenance work that legitimately runs longer. Scoping the timeout to the application role protects user-facing requests without breaking background jobs that need more time.
Can I debug a production query without redeploying?
Yes. Database-side tools such as pg_stat_statements and auto_explain need no code change. For application state, HyperProbe places a read-only probe on a running service and captures variable state the next time the line executes. Read-only probes do not pause production, change source code or require a redeploy.
How do you debug a production query without exposing customer data?
Mask sensitive fields in any record copied out of production, log bound parameters with sensitive values redacted, and avoid full production dumps. When capturing application state with HyperProbe, PII is redacted at the agent before capture, so the captured evidence does not carry raw customer data into logs or tickets.