📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

A query runs in 50 ms in your dev and test environments but takes 8 seconds in production, with the same code and the same indexes. How do you investigate it methodically, and what are the usual causes?

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.

Mid-Level Debugging Intermediate azure-sql debugging execution-plans query-performance sql-server statistics

🎯 Key points

  • Get the production actual plan (Query Store, sys.dm_exec_query_plan_stats) and compare it with dev, operator by operator
  • Data volume and distribution: 10,000 vs 50 million rows, skewed values that dev doesn't have
  • Statistics: stale or sampled differently in production, and whether maintenance jobs actually run there
  • Parameter values and sniffing: production's cached plan may have been compiled for a different value
  • Configuration: compatibility level (CE version), database-scoped MAXDOP, cost threshold for parallelism, memory available for grants, Azure SQL tier limits (CPU, IO, log rate, workers)
  • Concurrency only production has: blocking from open transactions and jobs, RESOURCE_SEMAPHORE, IO waits; compare duration with CPU and check Query Store waits
  • Reproduce with production-sized, masked data and the app's SET options and parameters
  • Fix the cause, keep environments consistent with configuration as code, and add a production-sized performance test

⏱ 30-second answer

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:

  • Data volume and skew: a scan of 10,000 rows is 50 ms; of 50 million it's seconds.
  • Statistics and parameter sniffing: production's cached plan may be for a different value.
  • Configuration: compatibility level, MAXDOP, service tier.
  • Waits: blocking, memory grants or IO limits only production has.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"'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_stats and 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."


Differences to check, in order

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

Plan problem or wait problem?

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate investigates environment differences methodically instead of guessing, and separates plan problems from wait problems.

Green flags

  • Gets production's plan and compares it with dev's.
  • Checks duration vs CPU and waits.
  • Lists data volume/skew, statistics, parameters and configuration as suspects.
  • Reproduces with production-sized, masked data.

Red flags

  • 'Works on my machine' reasoning.
  • Copies unmasked production data to dev.
  • Only ever looks at indexes.

📚 Learn in depth

1. Why dev lies

The optimiser chooses plans from statistics about this database. Dev and test usually have:

  • Orders of magnitude less data, so scans are cheap and the optimiser may choose them happily.
  • Uniform synthetic data, so no skew and no sniffing surprises.
  • Freshly built indexes and statistics.
  • No concurrent load, so no blocking or grant queues.
           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

2. Getting production evidence safely

  • Query Store: plan(s), duration, CPU, reads, waits per interval for the query. No re-running needed.
  • sys.dm_exec_query_plan_stats with LAST_QUERY_PLAN_STATS for the last actual plan.
  • Application Insights dependency telemetry for timing and which parameters (if logged safely) were slow.
  • Never run unknown heavy queries ad hoc in production during business hours.

3. Duration vs CPU

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.

4. Configuration that changes plans

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.

5. Reproducing faithfully

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.

Try it yourself

  1. Build a table with 10,000 rows and another with 10 million (skewed) and compare plans for the same query.
  2. Compare avg_duration and avg_cpu_time in Query Store for a query that's blocked vs one that's CPU-bound.
  3. Change compat level from 160 to 130 and observe estimate changes on a multi-predicate query.
  4. Query sys.database_scoped_configurations on two databases and diff the results.
  5. Create a masked copy of a table using UPDATE with generated names and emails and check plans match production row counts.

💻 Code

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.

⚠ Common mistakes

  • Mistake: Tuning in dev and declaring it fixed. Why it is wrong: Dev data lacks production's volume and skew. Instead: Measure with production's plan and production-sized data.
  • Mistake: Assuming it's the plan when it might be waiting. Why it is wrong: Blocking or grant waits look like slowness with the same plan. Instead: Compare duration with CPU and check wait categories.
  • Mistake: Ignoring compatibility level and configuration differences. Why it is wrong: The CE version and IQP features follow compatibility level, and MAXDOP, tier limits and memory change plans and speed. Instead: Diff sys.databases, scoped configurations and the service objective, and keep them in infrastructure as code.
  • Mistake: Blaming SQL when the time is spent elsewhere. Why it is wrong: Production may add network latency (cross-region app and database), many round trips from N+1 loops, TLS and connection pool exhaustion that dev on localhost never shows. Instead: Compare Application Insights dependency duration and call counts with the SQL duration in Query Store; if SQL is fast, look at round trips and the network path.
  • Mistake: Copying the production database to dev unmasked. Why it is wrong: Breaches privacy obligations (Privacy Act 1988, APPs) and widens breach exposure. Instead: Use masked or synthetic data at production scale.
  • Mistake: Re-running heavy queries in production to 'see the plan'. Why it is wrong: Adds load during an incident. Instead: Use Query Store and last actual plan DMVs.
  • Mistake: Testing with a different parameter value than the slow one. Why it is wrong: Skewed values have different plans. Instead: Find the compiled and slow runtime values.
  • Mistake: Overlooking Azure SQL tier limits. Why it is wrong: IO or log rate caps make the same plan slower. Instead: Check sys.dm_db_resource_stats for resource percentages at 100%.

🏛 Senior insight: trade-offs

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 —

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions parameter values or cached plans Why: Checks parameter sniffing diagnosis in depth
    How to answer

    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.

  2. When: Candidate mentions statistics differences Why: Checks statistics internals and maintenance
    How to answer

    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.

  3. When: Candidate mentions production monitoring Why: Checks incident handling with Query Store and DMVs
    How to answer

    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.

🛠 Real-world problems: how you handle them

Monthly statement report: 40 ms in test, 8 s in production
Situation
A [billing] service generated customer statements. Test had [500,000] invoice lines with uniform data; production had [60 million] with [a few large accounts] holding [over 1 million] lines each. Production was on [Azure SQL Business Critical].
Signals
Application Insights showed statement generation p95 at [8 s] in production and [40 ms] in test; support tickets from large accounts about timeouts at month-end.
Investigation
Query Store in production showed avg duration close to avg CPU (working, not waiting) and [3.6 million] logical reads per run. The production plan used nested loops with [1.2 million] key lookups, estimated at [300] rows. Statistics on InvoiceLines were [three weeks] old after a migration, and the plan had been compiled for a small account. Test's plan was the same shape but harmless at test's volume.
Resolution
Updated statistics with FULLSCAN, added INCLUDE columns to remove the key lookup, and scheduled a statistics update after the nightly invoice load. Production p95 fell to [60 ms].
Prevention
Added a performance stage using a masked, production-sized copy refreshed monthly; performance tests include the largest accounts; database settings managed in infrastructure as code so environments don't drift.

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.

More in Query Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me