Covers a methodical approach to environment-specific slowness: comparing actual plans, data volume and distribution, statistics, parameter values, compatibility level and configuration, blocking and resource limits between dev and production, and fixing the real cause rather than the symptom.
Same code doesn't mean same plan or same conditions. I compare production's actual plan (from Query Store) with dev's and look at where they diverge, then check the usual differences:
I split plan problems (different or bad plan) from wait problems (same plan, waiting), reproduce with production-sized masked data, and fix the cause, then add a production-sized test.
"'Same code, same indexes' rarely means same conditions. My first split is: is production running a different plan, or the same plan but waiting on something? So I get production's plan from Query Store or
sys.dm_exec_query_plan_statsand compare it with dev's. I also look at Query Store wait categories and duration versus CPU for that query: if duration is 8 seconds but CPU is 40 ms, it's waiting, not computing, and that's blocking, memory grants or IO, not the plan.If the plans differ, it's usually data. Dev has 10,000 orders evenly spread; production has 50 million with one customer owning 2 million. The optimiser rightly picks different plans, and production's might be compiled for the wrong parameter value, which is parameter sniffing. Statistics can be stale in production after big loads, and dev databases restored fresh often have perfect statistics. Then configuration: compatibility level decides the cardinality estimator version, and MAXDOP, cost threshold for parallelism and the Azure SQL service tier all change plan choice and speed.
For example, at [company] a [report] took [40 ms] in test and [8 s] in production. Production's plan was a nested loops join with [1.2 million] key lookups, estimated at [300] rows. The test database had [1%] of the data and no skew. The production statistics were [three weeks old] and the cached plan had been compiled for a small customer. Updating statistics and adding two INCLUDE columns fixed it, and we added a masked, production-sized copy to our performance test stage. The mistake I see is tuning in dev and declaring victory. Dev data doesn't have production's shape, so measure where the problem is."
| Area | Check | Tool |
|---|---|---|
| Plan | Same shape? Where do estimates diverge? | Query Store plans, actual plans |
| Duration vs CPU | Waiting or working? | Query Store runtime and wait stats |
| Data | Row counts, skew for the parameter used | COUNT(*), histograms |
| Statistics | Last updated, sample rate | sys.dm_db_stats_properties |
| Parameters | Compiled vs runtime values | Plan XML ParameterList |
| Configuration | Compat level, MAXDOP, CTFP, tier | sys.databases, sys.database_scoped_configurations |
| Concurrency | Blocking, grants, IO/log limits | sys.dm_exec_requests, sys.dm_db_resource_stats |
| Signal | Likely category |
|---|---|
| CPU ≈ duration, high logical reads | Plan / data volume |
| CPU ≪ duration, LCK_M_* waits | Blocking |
| CPU ≪ duration, RESOURCE_SEMAPHORE | Memory grants |
| CPU ≪ duration, PAGEIOLATCH / log rate waits | IO or tier limits |
After the statistics update and covering index, production went from [8 s] to [60 ms] (reads [3.6 million] to [900]). The new performance stage, using a masked production copy refreshed monthly, caught two similar regressions in the following quarter before release.
Checks whether the candidate investigates environment differences methodically instead of guessing, and separates plan problems from wait problems.
Green flags
Red flags
The optimiser chooses plans from statistics about this database. Dev and test usually have:
dev production
rows: 10,000 50,000,000
skew: none top customer 2M rows
stats: fresh FULLSCAN 3 weeks old, sampled
compat: 160 150 (restored from old server)
load: 1 user 300 req/s, nightly jobs
sys.dm_exec_query_plan_stats with LAST_QUERY_PLAN_STATS for the last actual plan.Query Store stores avg_duration and avg_cpu_time. Their ratio tells you whether to look at the plan or at waits. sys.query_store_wait_stats (2017+) groups waits into categories (Lock, Memory, Buffer IO, Parallelism ...) per plan.
| Setting | Effect |
|---|---|
| Compatibility level | CE version, IQP features (PSP at 160, OPPO at 170) |
MAXDOP (database-scoped) |
Parallel plan shape and speed |
| Cost threshold for parallelism (server) | When parallel plans are considered |
LEGACY_CARDINALITY_ESTIMATION |
Old CE model |
| Azure SQL tier / vCores | CPU, memory (grants), IO and log rate limits |
A database restored from an older server often keeps its old compatibility level.
Use a production-sized copy with personal data masked (important under the Privacy Act 1988 and the APPs; don't copy raw customer data to dev), same compatibility level and settings, statistics in a similar state, and the app's SET options and parameter values via sp_executesql.
avg_duration and avg_cpu_time in Query Store for a query that's blocked vs one that's CPU-bound.sys.database_scoped_configurations on two databases and diff the results.UPDATE with generated names and emails and check plans match production row counts.Compare environments: run the same checks in dev and production and diff the output.
-- 1. Configuration that affects plans
SELECT name, compatibility_level, is_read_committed_snapshot_on, is_auto_update_stats_async_on
FROM sys.databases WHERE name = DB_NAME();
SELECT name, value FROM sys.database_scoped_configurations
WHERE name IN ('MAXDOP', 'LEGACY_CARDINALITY_ESTIMATION', 'PARAMETER_SNIFFING',
'OPTIMIZE_FOR_AD_HOC_WORKLOADS', 'LAST_QUERY_PLAN_STATS');
-- 2. Data volume and skew for the parameter in question
SELECT COUNT(*) AS total_rows FROM dbo.Orders;
SELECT TOP (5) CustomerId, COUNT(*) AS orders
FROM dbo.Orders GROUP BY CustomerId ORDER BY orders DESC;
-- 3. Statistics freshness on the table
SELECT s.name, sp.last_updated, sp.rows, sp.rows_sampled, sp.modification_counter
FROM sys.stats s
CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) sp
WHERE s.object_id = OBJECT_ID('dbo.Orders');
-- 4. In production: is it working or waiting? (Query Store)
SELECT p.plan_id,
AVG(rs.avg_duration) / 1000 AS avg_duration_ms,
AVG(rs.avg_cpu_time) / 1000 AS avg_cpu_ms,
AVG(rs.avg_logical_io_reads) AS avg_reads
FROM sys.query_store_runtime_stats rs
JOIN sys.query_store_plan p ON p.plan_id = rs.plan_id
WHERE p.query_id = 5120
GROUP BY p.plan_id;
SELECT ws.wait_category_desc, SUM(ws.total_query_wait_time_ms) AS wait_ms
FROM sys.query_store_wait_stats ws
JOIN sys.query_store_plan p ON p.plan_id = ws.plan_id
WHERE p.query_id = 5120
GROUP BY ws.wait_category_desc ORDER BY wait_ms DESC;
A small .NET tool to run the same checks against both environments and diff them (read-only login):
namespace DbDiff;
using Dapper;
using Microsoft.Data.SqlClient;
public sealed record DbSettings(string Name, byte CompatibilityLevel, bool RcsiOn);
public static class EnvironmentDiff
{
public static async Task<DbSettings> ReadAsync(string connectionString, CancellationToken ct)
{
await using var conn = new SqlConnection(connectionString);
const string sql = """
SELECT name AS Name, compatibility_level AS CompatibilityLevel,
is_read_committed_snapshot_on AS RcsiOn
FROM sys.databases WHERE name = DB_NAME();
""";
return await conn.QuerySingleAsync<DbSettings>(new CommandDefinition(sql, cancellationToken: ct));
}
}
// Usage: compare ReadAsync(devConn) with ReadAsync(prodConn) and print any differences;
// records give value equality, so `dev == prod` is a quick first check.
sys.databases, scoped configurations and the service objective, and keep them in infrastructure as code.sys.dm_db_resource_stats for resource percentages at 100%.The senior instinct is to stop arguing about whose environment is right and collect evidence from production: plan, duration vs CPU, waits, statistics, configuration. Most 'fast in dev' cases are data shape, and the long-term fix is organisational: a performance stage with production-sized, masked data, and configuration kept identical through infrastructure as code.
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
| Query Store comparison | Any production slowness | None, on by default in Azure SQL | — |
| Masked production copy | Reproducing data-shape problems | Masking pipeline, storage | Data can't be masked safely; use synthetic at scale |
| Synthetic data at scale | Strict privacy, new systems | Must model skew realistically | When real skew is unknown |
| Config as code (Bicep/Terraform, scoped configs in migrations) | Preventing drift | Initial setup | — |
This is almost always parameter sniffing. SQL Server compiled the plan for the first parameter values it saw, maybe a tiny customer, and now reuses it for a customer with 2 million rows. SSMS looks fast because it runs with SET ARITHABORT ON (the app's SqlClient uses OFF), so it gets a separate cache entry and compiles a fresh plan for my values.
I confirm it in Query Store: the regressed query, two plan ids, and in the plan XML ParameterCompiledValue vs ParameterRuntimeValue. Mitigate by forcing the good plan. Then fix properly: OPTION (RECOMPILE) for infrequent queries, OPTIMIZE FOR, a Query Store hint, splitting code paths, or an index that makes one plan good for everyone. SQL Server 2022's PSP optimisation helps some cases.
Statistics describe the distribution of values in one or more columns: a density vector (how many distinct values) and a histogram of up to 200 steps on the leading column. The cardinality estimator combines them with its model assumptions to predict how many rows each operator returns, and every plan choice depends on that number.
Statistics are auto-created on indexes and filtered columns and auto-updated after enough modifications (since compat level 130, roughly SQRT(1000 × rows) for big tables). The CE version follows the database compatibility level.
Stale or sampled statistics show up as big estimated vs actual row gaps, nested loops over huge inputs and spills. The trade-off: fuller, more frequent updates give better plans but cost I/O and trigger recompiles.
First I confirm the database is the bottleneck: sys.dm_db_resource_stats or Azure Monitor shows CPU at 100% while workers and waits climb. Then I find the culprit two ways: live, with sys.dm_exec_requests ordered by CPU, and historically, with Query Store's Top Resource Consuming for the last hour against yesterday.
The key question is whether it's a new or changed query from the release, or the same query with a new plan. A plan regression I mitigate by forcing the last good plan; a code regression by rolling back or turning off the feature flag. Scaling up buys time but isn't a fix.
Then I fix the root cause (non-SARGable LINQ, missing index, N+1), and add release checks and alerts so we catch it before customers do.
How to tell it (STAR)
**S:** Our [billing] statements ran in [40 ms] in test but [8 seconds] in production, and large accounts were timing out at month-end. **T:** I had to work out why the same code behaved so differently. **A:** I pulled production's plan from Query Store rather than tuning in test. CPU matched duration, so it was the plan, not waiting: a nested loops join doing 1.2 million key lookups because the estimate was 300 rows. Statistics were three weeks stale and the cached plan was compiled for a small account. I updated statistics, removed the lookup with INCLUDE columns, scheduled statistics after the nightly load, and pushed for a masked production-sized test stage. **R:** p95 dropped to [60 ms], and the new stage caught [two] similar regressions before release in the next quarter.
Last updated 23 Nov 2026.