troubleshooting
27 TopicsAzure SQL Query Editor Won't Connect? Start Here
The Azure portal loads fine, you open Query Editor, and then you get "failed to fetch" or a vague connection error. It's tempting to assume the database is down, or to look for "the Query Editor IP" to add to your firewall. Usually, it's neither. Query Editor runs in your browser, so the problem can start on your laptop, your corporate proxy, the SQL firewall, your sign-in, or the database itself. The quickest fix is to work out which of those layers is failing before you change any server rules. How Query Editor actually connects There's no single Microsoft source IP to allowlist. For public connections to the query editor, you need to add your outbound IP address to the server's allowed firewall rules to access your databases. The IP that matters are the one your network presents to the internet, not an Azure address. Private Link changes this. You don't need to add your IP address to the SQL server firewall rules if you have a Private Link connection set up on the server, and you connect to the server from within the private virtual network. In that case, focus on DNS and whether you're really inside the right network. Check port 443 first Starting in March 2026, the Azure SQL query editor uses only TCP port 443. If something on your network blocks that traffic, you'll see messages about local network settings or proxy configuration. A quick test from PowerShell: Test-NetConnection <server-name>.database.windows.net -Port 443 If TcpTestSucceeded is False, the problem is on the client or network side. Keep in mind that opening 443 locally doesn't replace the SQL server firewall or Private Link setup. You still need both. Proxies and TLS inspection Corporate proxies cause more of these failures than people expect. If you see an error about the X-CSRF-Signature header, verify that your computer's clock is set to the right time and time zone, and if you're behind a proxy, make sure that the request header X-CSRF-Signature isn't being modified or dropped. A simple check: try Query Editor from a clean network, such as a phone hotspot. If it works there but not on the corporate network, talk to your network team, not the database team. Authentication and database users Being signed in to the portal doesn't give you access to the database. For Microsoft Entra sign-in, your database must be configured with Microsoft Entra authentication, and you must have a Microsoft Entra user created in the database. If you see "The server is not currently configured to accept this token," the fix is usually a contained user: CREATE USER [user@contoso.com] FROM EXTERNAL PROVIDER; Serverless databases that are paused On serverless databases, the "not currently available" message often just means your serverless database is currently paused. Selecting Continue starts the resume. Wait approximately one minute, refresh the page, and try again. Know the tool's limits Query Editor is built for quick queries, not everything. The query editor has a five-minute timeout for query execution. Also, the query editor doesn't support connecting to the logical server's master database. For either of those cases, use SSMS or VS Code with the MSSQL extension. Trying SSMS from the same machine is also a good diagnostic, because it shows whether the issue is with the browser path or with general connectivity. Symptom to layer: a quick reference What you see Likely layer First thing to try "Failed to fetch" / local network settings message Browser or client network Test-NetConnection on port 443 Works on hotspot, fails on corporate network Proxy / TLS inspection Ask network team to check header handling X-CSRF-Signature error Clock or proxy Fix system time, check proxy Firewall / client IP not allowed error SQL server firewall Add your current outbound IP only Fails from outside VNet with Private Link Private networking Check DNS resolves to the private endpoint "Not configured to accept this token" Authentication Create the contained Entra user "Database not currently available" Serverless pause Wait about a minute and retry One last word on firewall rules Please don't open wide IP ranges just to get Query Editor working. Add the specific outbound IP you need, remove it when you're done, and use Private Link for anything that needs ongoing access. Most Query Editor failures turn out to be network or identity issues, not database problems. Find the layer first and the fix is usually small. Reference: Azure Portal Query Editor - Azure SQL Database | Microsoft Learn128Views0likes0CommentsA Practical RCA Method for Azure SQL: Separating Evidence, Correlation and Root Cause
CPU hit 100%. You scaled the database. The problem went away. You still haven't proved that CPU was the root cause. We see RCAs written this way all the time, and it's easy to understand why. There's pressure to explain what happened, and a clear story feels better than an open question. But an RCA built on correlation can send a team in the wrong direction. You end up paying for capacity you don't need while the real cause waits for the next incident. Here's the method we use to keep evidence, correlation and conclusions apart. What an RCA should answer A useful RCA answers four questions: What happened? Symptoms and impact, with exact times. Why did it happen? The cause, backed by evidence. What stopped it? The mitigation. What are we still unsure about? The limits of the evidence. Most weak RCAs answer the first and third questions well and then treat the third as if it were the second. The framework Observation → Correlation → Hypothesis → Validation → Conclusion Step What it means Example Observation Something you measured directly "CPU reached 95% at 09:00 UTC" Correlation Two observations happened close together "Login failures started two minutes later" Hypothesis A possible explanation you can test "High CPU caused the failover" Validation Evidence that supports or rules out the hypothesis "Comparable CPU peaks last week caused no failover" Conclusion What the validated evidence allows you to say "CPU is not established as the cause" The step that gets skipped most often is validation, and it's the one that matters most. A worked example (synthetic) Here's an invented incident on a fictional database, SalesDB: 09:00 UTC CPU rises to 95% 09:02 UTC Login failures begin (error 40613) 09:04 UTC Database fails over to another replica 09:05 UTC Connections recover The first draft of the RCA practically writes itself: "High CPU caused the failover." Before you accept that, ask: Did CPU actually reach the limit? 95% is high, but it isn't exhaustion. Were worker or session limits reached? Check max_worker_percent and max_session_percent in sys.dm_db_resource_stats. Was memory under pressure? Was the failover triggered independently? For example, by planned maintenance. Check Resource Health and Service Health. What happened during earlier high-CPU periods? If CPU reached 95% three times last week with no failover, CPU alone doesn't explain this one. Did other databases on similar workloads see the same thing? Now classify every statement: Statement Classification CPU reached 95% Confirmed Login failures occurred Confirmed The events overlapped in time Confirmed CPU caused the failover Unconfirmed hypothesis The failover restored connectivity Confirmed The failover proves the old replica was faulty Not established That table is more honest than the first draft, and more useful too. It shows the reader exactly what's known and what still needs work. Habits that make RCAs better Use UTC everywhere. Mixed time zones are the most common reason two sets of logs "don't line up." Convert everything before you compare anything. Define the impact first. Who was affected, how badly, and for how long? "Some logins failed between 09:02 and 09:05" is far more useful than "the database was down." Keep observations and interpretation apart. "Error 40613 was returned" is an observation. "The database was unavailable because of load" is an interpretation. Write them in separate places. Consider more than one explanation. If you only have one hypothesis, you'll find evidence for it. Write down at least two, then look for evidence that would rule each one out. Compare against healthy periods. A metric only means something next to its baseline. High CPU during an incident matters less if CPU is just as high every Monday morning. Compare against unaffected resources. If two databases had the same load and only one failed, load probably isn't the whole story. Don't assume the fix explains the cause. Restarts, failovers and scale operations change many things at once: the compute node, connections, caches and sometimes the physical host. When the problem stops after one of them, you know something in that bundle mattered. You don't know which part. When "root cause unknown" is the right answer Sometimes the evidence doesn't support a definite cause. Saying so isn't failure. It's accuracy. A good RCA with an open cause still gives the reader something to act on: What was ruled out, and how. Which hypotheses remain, ranked by likelihood. What evidence would settle it next time, such as finer-grained monitoring, connection-level logging or a synthetic probe. What resilience work reduces the impact whatever the cause turns out to be, such as retry logic or alerting. A simple RCA template 1. Summary – One paragraph: what happened, the impact, the current status 2. Impact – Who/what was affected, start and end times in UTC 3. Timeline – Observations only, in UTC 4. Analysis – Hypotheses considered, evidence for and against each 5. Root cause – What the evidence supports (or "not established") 6. Mitigation – What restored service 7. Limitations – What the evidence could not show 8. Next actions – Prevention, detection, and evidence gaps to close Summary A good RCA tells you what the evidence shows, and also what it doesn't let you claim. "We restarted it and the problem went away" describes a mitigation, not automatically a root cause. Keep those two apart, and your RCAs become something people can trust and act on.132Views0likes0CommentsWhen SQL Performance Changes Without a Code Change: Read the Actual Execution Plan Before Tuning
Your query returns 800 rows, but the engine processed 108,000 to get there. That gap may be the whole performance problem. "This query used to be fast, and nobody changed it" is one of the most common things we hear in performance cases. Often the first reaction is to update statistics, add an index or scale up. Those can help, but they're guesses. A better first question is: Which operator produced far more rows than expected, and why? The actual execution plan answers that question. Why the same SQL can slow down Leaving the code untouched doesn't keep everything else the same. Common reasons a query slows down on its own: Data growth: a history table that doubles in size makes every join against it more expensive. A different plan: new statistics, a recompile or a parameter value can lead the optimizer to choose a different shape. Changes in data distribution: for example, more versions per key than before. The query text is the same, but what the engine actually does may not be. Estimated vs. actual plans An estimated plan is what the optimizer expects to happen. An actual plan shows what did happen, including the real row count at every operator. To capture one: In SSMS: select Include Actual Execution Plan (Ctrl+M) before you run the query. In T-SQL: run SET STATISTICS XML ON before the query. For the last actual plan of a cached query: turn on LAST_QUERY_PLAN_STATS and query sys.dm_exec_query_plan_stats. Both are supported in Azure SQL. Once you have the plan, read it from right to left. On each operator, compare Estimated Number of Rows with Actual Number of Rows. The first place where the two numbers diverge sharply is usually where to start. A small example that gets expensive Here's a common pattern: a table with one current row per entity, joined to two history tables before any filtering. CREATE TABLE dbo.Entity (EntityId int PRIMARY KEY, Status varchar(10)); CREATE TABLE dbo.PriceHistory (EntityId int, ValidFrom date, Price decimal(10,2)); CREATE TABLE dbo.RegionHistory (EntityId int, ValidFrom date, Region varchar(10)); -- 1,000 entities, 800 of them Active INSERT dbo.Entity SELECT value, CASE WHEN value % 5 = 0 THEN 'Closed' ELSE 'Active' END FROM GENERATE_SERIES(1, 1000); -- 18 price versions per entity INSERT dbo.PriceHistory SELECT e.EntityId, DATEADD(MONTH, v.value, '2024-01-01'), 100 + v.value FROM dbo.Entity AS e CROSS JOIN GENERATE_SERIES(1, 18) AS v; -- 6 region versions per entity INSERT dbo.RegionHistory SELECT e.EntityId, DATEADD(MONTH, v.value * 3, '2024-01-01'), CONCAT('R', v.value) FROM dbo.Entity AS e CROSS JOIN GENERATE_SERIES(1, 6) AS v; This query looks harmless: WITH joined AS ( SELECT e.EntityId, e.Status, p.ValidFrom AS PriceFrom, p.Price, r.ValidFrom AS RegionFrom, r.Region FROM dbo.Entity AS e JOIN dbo.PriceHistory AS p ON p.EntityId = e.EntityId JOIN dbo.RegionHistory AS r ON r.EntityId = e.EntityId ), windowed AS ( SELECT *, LAG(Price) OVER (PARTITION BY EntityId ORDER BY PriceFrom) AS PrevPrice, ROW_NUMBER() OVER (PARTITION BY EntityId ORDER BY PriceFrom DESC, RegionFrom DESC) AS rn FROM joined ) SELECT EntityId, Price, PrevPrice, Region FROM windowed WHERE Status = 'Active' AND rn = 1; It returns 800 rows. Here's what happens along the way: 1,000 entities ↓ join price history (18 versions each) 18,000 rows ↓ join region history (6 versions each) 108,000 rows ↓ LAG + ROW_NUMBER → sort 108,000 rows sorted ↓ filter: Status = 'Active' AND rn = 1 800 rows The engine builds and sorts 135 rows for every row you get back. Because Status isn't a partitioning column of the window functions, the filter on it can't be applied before them. The engine has to compute every window first and filter afterwards. Count at every stage The quickest way to see where rows multiply is to count them stage by stage: SELECT COUNT(*) AS rows_, COUNT(DISTINCT e.EntityId) AS entities FROM dbo.Entity AS e; -- 1,000 | 1,000 SELECT COUNT(*), COUNT(DISTINCT e.EntityId) FROM dbo.Entity AS e JOIN dbo.PriceHistory AS p ON p.EntityId = e.EntityId; -- 18,000 | 1,000 SELECT COUNT(*), COUNT(DISTINCT e.EntityId) FROM dbo.Entity AS e JOIN dbo.PriceHistory AS p ON p.EntityId = e.EntityId JOIN dbo.RegionHistory AS r ON r.EntityId = e.EntityId; -- 108,000 | 1,000 When COUNT(*) grows but COUNT(DISTINCT key) stays the same, the join is multiplying rows rather than adding new information. That's a many-to-many join between history tables. Check correctness before you tune That join multiplication can also change the results, not just the cost. After the second join, every price version appears 6 times. LAG(Price) is meant to return the previous price, but it can now return a duplicate of the same price. The query runs, returns the expected number of rows, and some of the values may be wrong. In a real case we worked on, duplicate history rows were identified as something that could affect previous-value logic like this. It was a hypothesis to test against the business rules, not a confirmed defect. Treat it the same way in your environment: confirm what the result should be before you make it faster. A better shape Reduce each history table to only what you need, then join: WITH p AS ( SELECT EntityId, Price, LAG(Price) OVER (PARTITION BY EntityId ORDER BY ValidFrom) AS PrevPrice, ROW_NUMBER() OVER (PARTITION BY EntityId ORDER BY ValidFrom DESC) AS rn FROM dbo.PriceHistory ), r AS ( SELECT EntityId, Region, ROW_NUMBER() OVER (PARTITION BY EntityId ORDER BY ValidFrom DESC) AS rn FROM dbo.RegionHistory ) SELECT e.EntityId, p.Price, p.PrevPrice, r.Region FROM dbo.Entity AS e JOIN p ON p.EntityId = e.EntityId AND p.rn = 1 JOIN r ON r.EntityId = e.EntityId AND r.rn = 1 WHERE e.Status = 'Active'; The window functions now each run over a single history table, so LAG sees each price version once. The joins then combine one row per entity instead of multiplying versions. Compare the actual plans of the two queries side by side, and check that the results match what the business expects. Other things to look for in the actual plan Sort and hash warnings. A yellow warning icon on an operator can mean it spilled to tempdb because its memory grant was too small for the real row count. Memory grant. Check the root operator's properties. A grant sized for 1,000 rows can't handle 108,000. Late filters. A filter near the left of the plan (close to the end of processing) that removes most rows means the work to its right was mostly wasted. Statistics. Use them as evidence. If estimated and actual row counts are far apart on a table scan or seek, outdated statistics may be the cause. If the estimates are accurate there but wrong after a join, updating statistics again usually won't help. Checklist Capture the actual plan, not only the estimated one. Find the first operator where estimated and actual rows diverge sharply. Count rows and distinct keys at each join. Look for many-to-many joins between history tables. Check whether filters run before or after expensive sorts and window functions. Look for spills and undersized memory grants. Confirm the results are correct before you optimize. Test changes on a smaller copy of the data, then confirm the improvement at full size. Summary The most expensive rows in a query are often the ones your application never receives. Before you update statistics again or add another index, find out how many rows each step actually produced. The actual execution plan already shows that.133Views0likes0CommentsAzure SQL Hyperscale Looks Healthy, but Logins Are Failing: Troubleshooting Partial Availability
Can an Azure SQL database look healthy while your users can't log in? Yes. It happens when the health signals and your application are measuring different things. We see this question in support cases fairly often: "Availability looked fine, so why couldn't my application connect?" This post explains why the two can disagree, especially on Hyperscale, and how to collect the evidence that shows what really happened. A quick look at Hyperscale Hyperscale separates compute from storage. At a high level: Compute replicas run your queries. These are the primary, plus any high-availability (HA) and named replicas. Each one keeps a local cache of hot data. Page servers store the data and serve pages the compute replica doesn't have cached. The log service receives the transaction log and passes changes on to the other components. This design is what makes Hyperscale scale so well. It also means "the database" is several components working together, and they don't all fail together. The Hyperscale architecture overview covers this in more detail. "Available" isn't one thing These are four questions that sound similar but aren't: Signal What it really tells you Service or resource availability The database is online at the platform level Primary replica health The compute node serving your writes is working normally Login success rate New connections are actually completing Query latency Work is finishing in a reasonable time once connected Storage can be healthy while the compute replica is struggling. The database can be online while some logins fail. And a health check can succeed between two failed attempts. Healthy storage + degraded compute ≠ healthy application experience. A real-world pattern In a recent Hyperscale case, the customer saw intermittent login failures and slow reads from remote storage on the primary replica. The storage components themselves looked healthy. The database was never fully down, and some health checks kept succeeding while the application had trouble connecting. Customer impact ended after a failover moved the workload to a different, healthy replica. However, the exact underlying cause on the original replica wasn't confirmed. The failover fixed the symptoms, and that tells you the problem was tied to that specific replica. It doesn't tell you why. Recovering service and finding the root cause are separate results, and an RCA should make clear which of the two it reached. Why averages hide the problem Most dashboards show data averaged over 1 minute, 5 minutes or 1 hour. A short burst of failures disappears in those averages. Suppose a probe connects every 5 seconds, and 6 attempts fail in a 30-second burst: View Probes Failures Success rate The 5-minute window containing the burst 60 6 90.0% The full hour 720 6 99.2% Your users felt a real outage. The hourly chart looks almost perfect. Measure what your users experience Platform metrics are useful but run your own lightweight probe from where your application runs. Here's a simple Python example: import time, csv, datetime, pyodbc CONN = ("Driver={ODBC Driver 18 for SQL Server};" "Server=tcp:<server>.database.windows.net,1433;" "Database=<db>;Encrypt=yes;Authentication=ActiveDirectoryMsi;") REGION = "<app-region>" with open("sql_probe.csv", "a", newline="") as f: w = csv.writer(f) while True: ts = datetime.datetime.now(datetime.timezone.utc).isoformat() login_ms = query_ms = None ok, err = False, "" try: t0 = time.perf_counter() conn = pyodbc.connect(CONN, timeout=15) login_ms = round((time.perf_counter() - t0) * 1000) t1 = time.perf_counter() conn.cursor().execute("SELECT 1").fetchone() query_ms = round((time.perf_counter() - t1) * 1000) conn.close() ok = True except pyodbc.Error as e: err = str(e)[:200] w.writerow([ts, ok, login_ms, query_ms, err, REGION]) f.flush() time.sleep(5) Each row records: The UTC timestamp Whether the connection succeeded Login time Time for a simple query The SQL error, if any The region the probe ran from Keep the raw rows rather than only averages. If login time rises before failures begin, that's often the earliest warning you'll get. Lining up the evidence When something goes wrong, put these side by side in UTC: Application errors, with error numbers and connection IDs Your probe results Resource Health and Service Health events Database performance data, such as sys.dm_db_resource_stats and Query Store wait statistics. See Hyperscale performance diagnostics for Hyperscale-specific waits. Any failover, scale or deployment events If you open a support case, include: The exact UTC time windows Sample error messages, with error numbers Connection IDs Your probe data Which application hosts or regions were affected With that information, we can start investigating straight away instead of spending the first day collecting it. Build for partial failure Retry transient errors with a retry limit, exponential backoff and jitter. (See our previous post on maintenance and failover.) Set sensible connection and command timeouts, so a slow login doesn't hold up a thread indefinitely. Alert on probe failures and login time, not just on platform availability. Know how to recover. For example, knowing when a failover is appropriate, and who can request it, saves time during an incident. Summary "Is the database online?" is often too simple a question. Ask instead: Can my application connect, how long does that take, and how fast are queries once connected? Measure those directly, at a fine enough granularity, and short partial outages stop being invisible.108Views0likes0CommentsHigh Latency, Normal CPU: Diagnosing PAGELATCH and Buffer Latch Contention in Azure SQL
A database can have spare CPU and still spend most of its time waiting. Your application is crawling. You open the Azure portal and CPU is moderate, storage I/O looks fine, worker usage is normal and there's plenty of space. Nothing on the Overview page looks wrong. So, what is the database actually waiting for? We recently worked through a case like this with an Azure SQL elastic pool. Latency was severe, but there was no sign of CPU, memory, worker, storage I/O, disk space or tempdb exhaustion. The evidence pointed somewhere less obvious: contention on in-memory pages under very high concurrency. This post explains how to recognize that pattern and what to do about it. Normal CPU doesn't mean a healthy database CPU shows how much work the database is doing. It doesn't show how long requests spend waiting to do that work. A request's elapsed time is roughly its CPU time plus its wait time. When wait time dominates, response times can get much worse while CPU stays flat or even drops. That's why wait statistics are the missing piece. They tell you what requests were waiting for, not just how busy the server was. PAGELATCH vs. PAGEIOLATCH These two wait types look alike but point to very different problems: Wait type What it means Typical cause PAGEIOLATCH_* Waiting for a page to be read from storage into memory I/O pressure, large scans, not enough memory PAGELATCH_* Waiting to access a page that is already in memory Many sessions competing for the same small set of pages A latch is a short, lightweight lock that protects a page while it's being read or changed. Usually, it's held for microseconds. When hundreds of sessions want the same page at the same moment, they line up, and those microseconds add up to seconds. In Query Store these waits are grouped under the Buffer Latch wait category, separate from Buffer IO (PAGEIOLATCH) and Latch (non-page latches such as LATCH_EX). Why concurrency multiplies the problem Latch contention doesn't grow in a straight line. Adding sessions that all compete for the same hot page doesn't add throughput. It adds queueing. Past a certain point, total throughput falls as concurrency rises, while CPU stays well below its limit. Common hot spots include: Last-page inserts: many sessions inserting into a table keyed on an ever-increasing value (IDENTITY, sequence, timestamp). Small, frequently updated tables: counters, status tables or queue tables. Metadata-heavy patterns at scale: for example, many application instances starting at once and each running schema or metadata discovery queries against the same system catalog pages. tempdb allocation or metadata pages under heavy temporary-object churn. A troubleshooting workflow Latency is high → CPU is normal → check waits → latch waits dominate → find the statements and pages → understand the workload pattern → reduce contention Step 1: Rule out resource exhaustion sys.dm_db_resource_stats keeps about the last hour of usage in 15-second intervals: SELECT TOP (40) end_time, avg_cpu_percent, avg_data_io_percent, avg_log_write_percent, avg_memory_usage_percent, max_worker_percent, max_session_percent FROM sys.dm_db_resource_stats ORDER BY end_time DESC; For elastic pools, also check sys.elastic_pool_resource_stats in the master database of the logical server. A healthy pool can still contain one database that is struggling. Step 2: Find out which waits dominate right now sys.dm_db_wait_stats is cumulative, so take two snapshots and compare them: SELECT wait_type, waiting_tasks_count, wait_time_ms INTO #w1 FROM sys.dm_db_wait_stats; WAITFOR DELAY '00:01:00'; -- sample during the slow period SELECT TOP (10) w2.wait_type, w2.waiting_tasks_count - w1.waiting_tasks_count AS waits, w2.wait_time_ms - w1.wait_time_ms AS wait_ms FROM sys.dm_db_wait_stats AS w2 JOIN #w1 AS w1 ON w1.wait_type = w2.wait_type WHERE w2.wait_time_ms - w1.wait_time_ms > 0 AND w2.wait_type NOT LIKE '%SLEEP%' AND w2.wait_type NOT LIKE 'XE%' AND w2.wait_type NOT IN ('WAITFOR', 'BROKER_TASK_STOP', 'SOS_WORK_DISPATCHER') ORDER BY wait_ms DESC; If PAGELATCH_EX or PAGELATCH_SH is at or near the top, keep going. Step 3: See who is waiting, and on which page SELECT r.session_id, r.wait_type, r.wait_time, r.wait_resource, s.program_name, s.host_name, pi.page_type_desc, OBJECT_NAME(pi.object_id, pi.database_id) AS object_name, pi.index_id, t.text AS sql_text FROM sys.dm_exec_requests AS r JOIN sys.dm_exec_sessions AS s ON s.session_id = r.session_id OUTER APPLY sys.dm_exec_sql_text(r.sql_handle) AS t OUTER APPLY sys.fn_PageResCracker(r.page_resource) AS pc OUTER APPLY sys.dm_db_page_info(pc.db_id, pc.file_id, pc.page_id, 'DETAILED') AS pi WHERE r.wait_type LIKE 'PAGELATCH%'; Look for patterns: Many sessions on the same object and page: a classic hot page. The same statement repeated many times: a high-frequency pattern. Database ID 2: the contention is in tempdb. A system object: metadata contention. Step 4: Find the statements that accumulate the most waiting When elapsed time is far higher than CPU time, a statement is mostly waiting: SELECT TOP (10) qs.execution_count, qs.total_elapsed_time / 1000 AS total_elapsed_ms, qs.total_worker_time / 1000 AS total_cpu_ms, (qs.total_elapsed_time - qs.total_worker_time) / 1000 AS approx_wait_ms, SUBSTRING(st.text, qs.statement_start_offset / 2 + 1, (CASE qs.statement_end_offset WHEN -1 THEN DATALENGTH(st.text) ELSE qs.statement_end_offset END - qs.statement_start_offset) / 2 + 1) AS statement_text FROM sys.dm_exec_query_stats AS qs CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st ORDER BY approx_wait_ms DESC; To investigate after the fact, Query Store keeps waits for each query: SELECT TOP (10) q.query_id, qt.query_sql_text, SUM(ws.total_query_wait_time_ms) AS buffer_latch_wait_ms FROM sys.query_store_wait_stats AS ws JOIN sys.query_store_plan AS p ON p.plan_id = ws.plan_id JOIN sys.query_store_query AS q ON q.query_id = p.query_id JOIN sys.query_store_query_text AS qt ON qt.query_text_id = q.query_text_id WHERE ws.wait_category_desc = 'Buffer Latch' GROUP BY q.query_id, qt.query_sql_text ORDER BY buffer_latch_wait_ms DESC; Step 5: Build a timeline Put the following side by side by minute: Request rate and connection count Latch wait time CPU Application events such as deployments, restarts, scale-outs and batch jobs Contention that starts exactly when connections surge, and not when CPU climbs, tells you a lot. Why scaling can look like the fix In our case, latency recovered around the time the pool was scaled up. It's tempting to conclude that more vCores fixed it. That conclusion isn't proven. Scaling an Azure SQL database or pool does much more than add CPU: The workload usually moves to new compute. All connections are dropped and re-established. Memory and caches start fresh. Time passes, and the peak may simply end. Any of these can break a contention pattern, whatever the vCore count. To tell correlation from causation, compare latch waits at similar load before and after the change. If the same waits come back at the next peak on the larger size, capacity wasn't the root cause. Reducing contention Database side Last-page insert hot spots: consider OPTIMIZE_FOR_SEQUENTIAL_KEY = ON on the index, or a less sequential key design where appropriate. Small hot tables: spread or partition them, or reduce how often they're updated (batching, caching). tempdb churn: reduce heavy temporary-table creation in high-frequency code paths. Application side Limit concurrency. Size connection pools and worker counts on purpose. More parallel sessions isn't always faster. Cache metadata. Run schema or metadata discovery once, not on every connection or request. Avoid startup storms. Stagger instance startup, and use retry with exponential backoff and jitter. Batch small operations instead of sending thousands of tiny concurrent ones. Try it yourself: a concurrency lab CREATE TABLE dbo.HotInsert ( Id bigint IDENTITY(1,1) NOT NULL, Payload char(200) NOT NULL DEFAULT 'x', CreatedAt datetime2 NOT NULL DEFAULT SYSUTCDATETIME(), CONSTRAINT PK_HotInsert PRIMARY KEY CLUSTERED (Id) ); Run the same insert at three concurrency levels, for example with the RML Utilities ostress tool: ostress -S"<server>.database.windows.net" -U"<user>" -P"<password>" -d"<labdb>" ^ -Q"INSERT dbo.HotInsert DEFAULT VALUES;" -n1 -r20000 -q Repeat with -n16 and then -n200, adjusting -r so the total number of rows stays similar. For each run, record: Rows per second CPU from sys.dm_db_resource_stats The PAGELATCH_EX delta from the Step 2 query Then enable OPTIMIZE_FOR_SEQUENTIAL_KEY and run the test again: ALTER INDEX PK_HotInsert ON dbo.HotInsert SET (OPTIMIZE_FOR_SEQUENTIAL_KEY = ON); Watch how throughput levels off, or drops, as concurrency rises while CPU stays well below its limit. That's latch contention. Quick decision tree Is latency high but CPU, I/O, workers and memory normal? → Check waits. Is PAGEIOLATCH dominant? → Storage or memory pressure. Look at scans and indexing. Is PAGELATCH dominant? → In-memory contention. Find the hot pages and objects (Step 3). Is the hot page in a user table? → Insert pattern, key design or hot rows. Is it in tempdb or a system object? → Temporary-object churn or metadata-heavy patterns. Did it start with a connection surge? → Fix concurrency on the application side. Did scaling help? → Confirm at the next comparable peak before treating it as the fix. Key takeaway Not every Azure SQL performance problem needs more vCores. When latency is high and CPU is normal, look at what the database is waiting for, not just how busy it is. Latch contention is a concurrency problem, and it's usually solved by changing the workload pattern rather than buying more compute.107Views0likes0CommentsLessons Learned #561: It is Fast on the Other Server —What Should We Compare First?
While working on a support case, our customer told us that a stored procedure was taking longer than expected. “It’s fast on the other server,” they explained. Our customer was executing the same stored procedure with the same parameter value in both environments. They had already compared the data and indexes and had not found an obvious explanation for the difference. At that point, we had a symptom, but we still needed evidence to explain it. My first question was simple: was the slower execution doing more work, or taking longer to do comparable work? To answer that question, we needed to look beyond the query text. We would compare the actual execution plans, logical reads, CPU time, and elapsed time, using each observation to guide the next step. In this article, I would like to share how I investigated the problem, step by step. For the demonstration, I will use two tables with identical data and equivalent indexes in the same Azure SQL Database. You can also run this example on two different servers, using one copy of the table on each server. Step 1: Collect evidence from both executions The customer had already compared the data and indexes. Before making any changes, I asked them to collect the same information from both environments: The actual execution plan. The output from SET STATISTICS IO ON. The output from SET STATISTICS TIME ON. We also needed to confirm that both tests used the same parameter value and returned the same results. The execution time told us that there was a difference. These additional details would help us understand why. Logical reads show how many page accesses an execution performs. CPU time shows how much processor time it uses, while elapsed time shows how long it takes. The actual execution plans help us connect those measurements to the operations performed. I wanted to compare this evidence before updating statistics, changing indexes, or recompiling the procedure. Those changes could alter the behavior we were trying to understand. Step 2: The slower execution was doing more work Once we had collected the execution plans and measurements, I started by comparing logical reads, CPU time, and elapsed time. The measurements showed a clear difference: Metric Execution A Execution B Logical reads 30,418 1,532,129 CPU time 219 ms 954 ms Elapsed time 216 ms 1,284 ms Physical reads 0 0 In this sample, execution B took almost six times as long and performed approximately 50 times as many logical reads. We now had an important clue: the slower execution was doing considerably more work. Both executions reported zero physical reads. However, that did not mean that accessing the data was free. Logical reads still represent page accesses through the buffer pool, and repeatedly accessing those pages consumes resources. The higher CPU time in B supported the same observation. Waiting could also contribute to its elapsed time, but waiting alone would not explain the additional logical reads. My next step was to inspect the actual execution plans: which operations were responsible for that extra work? Step 3: An Index Seek does not always mean less work The difference in logical reads gave us a direction. I opened both actual execution plans to see how each execution accessed the data. Execution A used a Clustered Index Scan. It read one million rows, selected the 500,000 that matched the customer, and calculated the total. Execution B used an Index Seek, followed by Nested Loops and a Key Lookup. At first glance, the seek might look like the better choice. It located the customer's orders through the nonclustered index. However, that index did not contain Amount, which the query needed to calculate the total. For each matching order, the plan retrieved the missing value from the clustered index. The Key Lookup executed 500,000 times. That helped explain the additional logical reads: execution B repeatedly accessed the clustered index to retrieve individual rows. Observation Execution A Execution B Access pattern Clustered Index Scan Index Seek followed by Key Lookups Estimated matching rows 500,000 100 Actual matching rows 500,000 500,000 Key Lookup executions None 500,000 The estimates provided our next clue. Execution A expected 500,000 matching rows and received 500,000. Execution B expected only 100, but received 500,000—5,000 times its estimate. A seek followed by a small number of lookups can be efficient. However, repeating those lookups half a million times can become expensive. The plans also used different execution modes: A used batch mode, while B used row mode. This was another difference to keep in mind when comparing CPU and duration. The question was no longer simply why B was slower. Why did its cached plan expect only 100 rows? Step 4: Same runtime parameter, different compiled values To understand the estimate of 100 rows, I checked the parameter information in both actual execution plans. We had executed both procedures with @CustomerId = 2. However, the plans showed an important difference: Parameter property Execution A Execution B ParameterCompiledValue 2 1 ParameterRuntimeValue 2 2 The XML made this easy to see. Execution A: <ColumnReference Column="@CustomerId" ParameterDataType="int" ParameterCompiledValue="(2)" ParameterRuntimeValue="(2)" /> Execution B: <ColumnReference Column="@CustomerId" ParameterDataType="int" ParameterCompiledValue="(1)" ParameterRuntimeValue="(2)" /> ParameterCompiledValue shows the value used when the plan was compiled. ParameterRuntimeValue shows the value used for the execution we captured. Both executions used customer 2, but their plans had been compiled for different customers. Both plans also reported that they were retrieved from cache. In our example, customer 1 has 100 orders, while customer 2 has 500,000. The estimate in B now made sense: its plan had been compiled for the customer with only 100 orders. Using a parameter value during compilation is normal behavior, commonly called parameter sniffing. It helps the optimizer use the available statistics to estimate how many rows the query will process. The difficulty appears when a plan suitable for one parameter value is reused for another value with very different needs. Here, the plan compiled for 100 orders was reused to process 500,000. Different compiled and runtime values alone do not prove a performance problem. In this investigation, however, they connected several observations: the estimate of 100 rows, the 500,000 actual rows, the repeated Key Lookups, and the additional logical reads. We had a strong explanation. Our next step was to test it by compiling for the current parameter and comparing the work again. Step 5: Test the explanation The parameter information gave us a strong clue, but I wanted to test whether a new plan compiled for the current customer would reduce the work. We executed procedure B with the same parameter, this time requesting recompilation: EXEC dbo.GetCustomerOrdersB @CustomerId = 2 WITH RECOMPILE; The new actual execution plan showed both the compiled and runtime parameter values as 2. Instead of the Index Seek followed by 500,000 Key Lookups, the optimizer selected a Clustered Index Scan. It estimated 500,000 matching rows and received 500,000. The measurements also changed: Metric B: original cached plan B: recompiled execution Logical reads 1,532,129 30,418 CPU time 954 ms 344 ms Statement elapsed time 1,284 ms 346 ms Estimated matching rows 100 500,000 Actual matching rows 500,000 500,000 These timings are individual observations, rather than benchmark averages. However, the reduction in logical reads clearly showed that the new execution performed less work. We had not changed the data, added an index, or updated statistics between these executions. The plan XML referenced the same statistics object with the same last-update timestamp and zero modifications. The important change was the plan compiled for the current parameter. It also used batch mode instead of the original plan's row mode. This supported our explanation: the original cached plan was suitable for a customer with few orders, but its repeated lookups became expensive when reused for a customer with 500,000 orders. Recompilation was useful here as a diagnostic test. However, recompiling every execution is not always the best long-term solution. We also need to consider how often the query runs, the cost of compilation, and the parameter values used by the application. What if the query is slower on another server? In this example, the execution history helped explain why equivalent queries performed different amounts of work. In a comparison between two servers, this is one possible cause, but it is not the only one. I would start with the same evidence: actual execution plans, logical reads, CPU time, and elapsed time. From there, we can decide whether to investigate different plans, waits, configuration, or other differences between the environments. For a broader troubleshooting approach, see Microsoft's guide: Troubleshoot a query that shows a significant performance difference between two servers. Can Azure SQL Database handle different parameter needs? Recompilation helped us test our explanation. But could the database use different plans for customers with different numbers of orders, without compiling the query on every execution? This is where Parameter Sensitive Plan optimization, or PSP, can help. For eligible queries, PSP can maintain multiple plan variants and select a variant according to the runtime parameter value. A customer with few orders and a customer with many orders can therefore use different plans for the same parameterized query. PSP is available in Azure SQL Database with compatibility level 160 or later, provided the feature is enabled. Eligibility still matters: enabling it does not guarantee that every query will receive multiple variants. See Parameter Sensitive Plan optimization for details. Our first test deliberately used compatibility level 150. Next, we will repeat the experiment with PSP enabled, keeping the data, indexes, and stored procedures unchanged. We will check both the measurements and the plans to see whether PSP actually intervenes. Step 6: Verify that the feature actually intervenes Next, I repeated the test at compatibility level 160, after enabling PSP in the laboratory database. We executed the procedure for the customer with 100 orders first, followed by the customer with 500,000 orders. The captured plans showed that both executions still used the same plan, compiled for customer 1. The second execution performed 500,000 Key Lookups and reported 1,532,129 logical reads. I also checked the XML for evidence of PSP variants. The captured plans did not contain a dispatcher or a query variant identifier. PSP was enabled, but the captured plans showed no evidence that it was being used. I needed to find out why it had not generated plan variants for this query. Step 7: Check PSP configuration SELECT DB_NAME() AS DatabaseName, compatibility_level FROM sys.databases WHERE database_id = DB_ID(); SELECT name, value FROM sys.database_scoped_configurations WHERE name IN ( 'PARAMETER_SENSITIVE_PLAN_OPTIMIZATION', 'PARAMETER_SNIFFING' ); The results confirmed the configuration/settings: Compatibility level: 160. PARAMETER_SNIFFING: 1. PARAMETER_SENSITIVE_PLAN_OPTIMIZATION: 1. The configuration was correct, so I used Extended Events to find out why PSP had been skipped. I captured the reason during a new compilation using an in-memory ring buffer. -- 1. Create the session DECLARE @sql nvarchar(max); SET @sql = N' CREATE EVENT SESSION Lab_PSP_Reason ON DATABASE ADD EVENT sqlserver.parameter_sensitive_plan_optimization_skipped_reason ( ACTION(sqlserver.sql_text, sqlserver.session_id) WHERE ([sqlserver].[session_id] = (' + CONVERT(nvarchar(12), @@SPID) + N')) ), ADD EVENT sqlserver.query_with_parameter_sensitivity ( ACTION(sqlserver.sql_text, sqlserver.session_id) WHERE ([sqlserver].[session_id] = (' + CONVERT(nvarchar(12), @@SPID) + N')) ) ADD TARGET package0.ring_buffer ( SET max_memory = 1024 ) WITH (MAX_DISPATCH_LATENCY = 1 SECONDS);'; EXEC sys.sp_executesql @sql; ALTER EVENT SESSION Lab_PSP_Reason ON DATABASE STATE = START; -- 2. Trigger a new compilation EXEC sys.sp_recompile N'dbo.GetCustomerOrdersB'; EXEC dbo.GetCustomerOrdersB @CustomerId = 1; EXEC dbo.GetCustomerOrdersB @CustomerId = 2; WAITFOR DELAY '00:00:02'; -- 3. Read the XML before stopping the session SELECT CAST(t.target_data AS xml) AS CapturedEvents FROM sys.dm_xe_database_session_targets AS t JOIN sys.dm_xe_database_sessions AS s ON s.address = t.event_session_address WHERE s.name = N'Lab_PSP_Reason' AND t.target_name = N'ring_buffer'; -- 4. Stop and delete the session ALTER EVENT SESSION Lab_PSP_Reason ON DATABASE STATE = STOP; DROP EVENT SESSION Lab_PSP_Reason ON DATABASE; Why did PSP not generate variants? The database was using compatibility level 160, and both PSP and parameter sniffing were enabled. However, the captured plans still showed the same plan being reused. To understand why, I captured the Extended Event parameter_sensitive_plan_optimization_skipped_reason during a new compilation. It reported: <data name="reason"> <value>30</value> <text>SkewnessThresholdNotMet</text> </data> For this compilation, the optimizer's skewness threshold for PSP was not met, so it did not generate plan variants. This did not mean that the original plan was efficient for both customers. Our earlier measurements had already shown the additional work caused by reusing it for the larger customer. That was another useful lesson from the investigation: check whether an optimization actually intervened, rather than assuming that enabling it resolved the problem. PSP can help eligible queries, but we still need to inspect their plans and measure their behavior. Step 8: Reduce the work behind the slow execution Recompilation had helped us validate the explanation. Next, I wanted to test a change that would reduce the work even when the plan was compiled for the smaller customer. The nonclustered index contained CustomerId, but the query also needed Amount. The original plan retrieved that missing value through a Key Lookup for every matching order. We extended the existing index to include Amount: CREATE NONCLUSTERED INDEX IX_Orders_CustomerId ON dbo.OrdersB (CustomerId) INCLUDE (Amount) WITH (DROP_EXISTING = ON); Then we repeated the sequence that had exposed the problem: compile for the customer with 100 orders, followed by executions for the customer with 500,000 orders. This time, we did not use WITH RECOMPILE for those executions. Metric for the larger customer Before the index change After: first execution After: second execution Logical reads 1,532,129 1,426 1,426 CPU time 984 ms 141 ms 156 ms Elapsed time 1,501 ms 144 ms 154 ms Key Lookup executions 500,000 0 0 These measurements were collected at compatibility level 160 before and after the index change. The new plan obtained the required values directly from the nonclustered index. It no longer needed to retrieve Amount separately from the clustered index for each order. An important detail remained: the plan was still compiled for customer 1 and reused for customer 2. It still estimated 100 matching rows and processed 500,000. We had not eliminated the estimation difference. We had removed the repeated lookups that made that difference expensive in this example. The improvement also did not depend on PSP generating variants: the captured executions reused the same ordinary cached plan. For this query and the tested parameter values, extending the index provided a more efficient access path. Before applying the same approach in production, we would also evaluate the additional index storage and the maintenance cost for data changes. The goal was to reduce the work that made the reused plan expensive. The actual plan and measurements showed that the change achieved that in our test. What I learned from this investigation “It’s fast on the other server” was the starting point. To investigate it, we needed to compare what happened during each execution. In our demonstration, equivalent data and indexes did not lead to equivalent execution plans. Both measured executions used the same parameter, but their cached plans had been compiled for different customers. The slower execution expected 100 matching rows and processed 500,000. Its repeated Key Lookups helped explain the additional logical reads and CPU consumption. Recompilation helped us test that explanation. We then extended the existing index to include Amount, allowing the query to retrieve the required values without those lookups. Even after the index change, the execution for the larger customer reused a plan compiled for the smaller customer. The estimate remained inaccurate for the larger customer, but the expensive lookups were gone. Logical reads dropped from 1,532,129 to 1,426 in our compatibility-level-160 test. We also verified PSP rather than assuming it would intervene. Although it was enabled, Extended Events reported SkewnessThresholdNotMet for the compilation we captured. For me, the practical lessons were: Compare logical reads and CPU alongside elapsed time. Inspect the actual work behind an Index Seek or Scan. Compare estimated and actual rows at the relevant operators. Check compiled and runtime parameter values. Validate a proposed improvement using the execution sequence that exposed the problem. Confirm whether an optimization feature actually participated. The index change addressed the additional work in this example. Other queries may need a different approach, and index changes should be evaluated against the wider workload. When a customer says, “It’s fast on the other server,” my next question is: “What do the two executions show us?” Further reading For a broader investigation of performance differences between servers, see Troubleshoot a query that shows a significant performance difference between two servers. For details about plan variants, eligibility, and diagnostic events, see Parameter Sensitive Plan optimization.415Views0likes0CommentsLessons Learned #560: SQL Is Slow — What Can Query Store and SSMS Copilot Uncover?
In our recently delivered session, “SQL Is Slow — What Can Query Store and SSMS Copilot Uncover?”, we demonstrated step by step how to investigate a performance problem by combining Query Store with Copilot’s capabilities in SSMS. The demonstration starts with a PHP program executing queries while we grow a table from a few hundred to millions of rows. As different execution plans appear and performance changes, we follow the evidence in Query Store to uncover what is happening and decide what to investigate next. One clue stood out. The query took about 12 milliseconds per execution in one interval and almost 2.5 seconds in another interval under the same Plan ID. Other plans appeared during the complete lab. Understanding both the differences between plans and the changes within a plan became part of the investigation. Along the way, we demonstrated how a guided conversation with Copilot can become an Agent investigation, and how the investigation itself can be captured in a reusable skill. The useful result was a method that keeps asking for evidence before accepting an explanation. The session brings the two tools together: Query Store supplies the recorded history, and Copilot helps us examine it and decide what to investigate next. The same troubleshooting story lets the audience follow Ask mode, Agent mode and the reusable skill without losing the connection to the underlying SQL evidence. A growing table and several execution plans For our sessions, we use a PHP program that generates 16 different simulations of performance and connectivity problems, allowing us to demonstrate how to investigate these scenarios through practical demos. We also have code developed in .NET and Java. In this demonstration, we add records to dbo.Notes in stages, reaching approximately 200, 32,000, 65,000, 2 million, and 4 million rows, while the PHP program executes dbo.GiveNotes with different @N values. This lets us observe how performance and execution plans evolve as the data volume grows. Several execution plans accumulated during the complete demonstration. We compared all of them, then inspected the runtime intervals within each Plan ID. The reference run revealed this change within the history of one plan: Average per execution Healthy interval Degraded interval Approximate increase CPU 7.69 ms 1,443.19 ms 188 times Duration 12.39 ms 2,473.68 ms 200 times Logical reads 68.39 12,233.10 179 times The duration increase was approximately 200 times. This comparison covers two intervals for one Plan ID, not the whole sequence of table sizes. It does not assign a particular plan or timing to each row-count stage. These are lab observations; identifiers and timings vary between runs. The reads were particularly revealing. Each execution was touching far more pages. A later plan change could not, by itself, explain degradation that had already started while the earlier plan remained in use. The next step was to investigate what had increased the work per execution. Build the timeline before choosing the explanation We first compared workload contributors using total CPU, elapsed duration, logical reads and execution count. Total consumption identified where the workload impact was concentrated; averages per execution helped distinguish expensive executions from a high volume of individually inexpensive calls. Next, we collected every plan for the selected query and compared runtime intervals chronologically. We discovered the identifiers from the database instead of supplying fixed Query IDs or Plan IDs. We asked both when another plan appeared and whether the cost had already increased before that change. A plan summary alone can hide this story. One average across a plan’s entire history blends its healthy and degraded periods. The interval history shows when the work changed and whether that happened before another plan appeared. Aggregation mattered. When combining runtime statistics, we weighted each average by its execution count. A simple average of interval averages would give a lightly used interval the same influence as a heavily used one. We also kept units explicit and separated execution types where needed. Weighted average = SUM(average value * execution count) / SUM(execution count) The increase in logical reads directed the investigation toward the amount of data processed and the access path. Waits could help explain elapsed time, but waits alone would not explain that increase in reads. dbo.GiveNotes filtered dbo.Notes on ID < @N and grouped by Name. The clustered primary key was on id2, a different column from the predicate. As rows were added, a reused plan could process more data; changing @N could also change how many rows qualified. A new Plan ID was a separate event to investigate, not an explanation to assume. Different @N values can qualify different numbers of rows, and table growth can increase the work even with an unchanged plan. We inspected distribution, statistics and access paths to test that explanation. Query Store interval averages alone do not tell us the parameter used by every execution, and parameter-sensitive behavior does not automatically prove parameter sniffing. One investigation through three Copilot experiences In Ask mode, we guided the conversation one question at a time. We first requested the Query Store overview, then asked which contributor to investigate and how its plans behaved over time. The staged prompts delayed statistics, index and parameter analysis until the runtime evidence justified those questions. Where required, we ran generated diagnostic T-SQL and brought the results back into the conversation. In Agent mode, we supplied the investigation goal and allowed Copilot to choose and execute diagnostic steps using the available SQL tools. We reviewed the proposed actions and kept the investigation read-only. The agent could use each result to decide what to inspect next. Finally, we captured the sequence in an Agent Skill. We wanted the next investigation to preserve the critical question: did the query become more expensive while the same plan was still being reused? Agent Skills provide task-specific instructions that Copilot can discover and use in Agent mode. We also demonstrated the reusable method through GitHub Copilot CLI. Database execution still requires a configured SQL tool or MCP server; without that capability, the workflow must generate diagnostics for the engineer to run. What we put into the reusable skill The SQL Performance Investigator pack captures the diagnostic sequence alongside the calculation rules and starting prompts. The agent is instructed to: Identify the main workload contributor and retain its Query ID. Collect all associated plans and their runtime history. Check whether degradation began while the same plan remained in use. Investigate relevant selectivity, statistics and index evidence. Separate confirmed observations from hypotheses and propose validation. A skill makes the method reusable; it does not guarantee the diagnosis is correct. Missing history, incorrect aggregation or a plausible but unsupported inference still need an engineer’s attention. We kept discovery read-only, with SQL permissions enforcing the access boundary. A proposed index still needs evidence of improvement In the demonstration, we evaluated an index with ID as its leading key and Name as an included column: CREATE NONCLUSTERED INDEX NOTES_IX1 ON dbo.Notes (ID) INCLUDE (Name); The key matches the range predicate, while the included column makes Name available for the aggregation. Whether this improves the workload depends on selectivity, data volume and the competing plans. Its storage and write costs also matter. We treated this as a remediation candidate. Validation requires a comparable workload, including parameter distribution and concurrency, followed by a Query Store comparison of reads, CPU, duration and variability. We did not equate an index recommendation with a demonstrated improvement. Statistics also need careful interpretation. An index histogram describes its leading key; adding Name as an INCLUDE column does not create a histogram on Name. An existing auto-created statistic should not be dropped merely because its column appears in a covering index. The lesson we took from the demonstration The complete story contained a growing table and multiple plans. Within that history, one plan became much more expensive before a later plan could explain the change. Comparing plans and examining changes within each plan gave us complementary evidence. Copilot helped us follow it, and the skill preserved the investigation sequence for another database. We enjoyed presenting this session. For DBAs, developers and support engineers, the session offers a practical way to watch a performance investigation unfold, from the PHP workload and Query Store history to the prompts and reusable skill. We look forward to continuing this demonstration and discussion with SQL user groups and the wider technical community. If you have encountered a query that became slower while the same plan remained in use, which evidence helped you explain the change? We would be interested to hear how you approached it. References and prerequisites For the SSMS Agent and Skills experience described here, Microsoft documents SSMS 22.7 or later with the AI Assistance workload and GitHub Copilot access. Query Store must be enabled with relevant history available. Specify the target server and database in the Agent prompt rather than relying on the active editor context. Check the current documentation before reproducing the session. GitHub Copilot Agent mode in SSMS Agent Skills in SSMS Monitoring performance by using Query Store Query Store runtime statistics Try the investigation with our prompts These prompts offer a practical starting point for the method demonstrated in our session. The Ask prompt is the opening prompt from our session workflow. The Agent prompts are adapted from our accompanying pack to make the target server, database and investigation window explicit. Replace the angle-bracket placeholders before submitting them. Start with Ask mode We began with a request for evidence, deliberately postponing diagnosis. Run the generated diagnostic query against the intended lab database and use its results for the next questions. I want to start a SQL performance troubleshooting investigation using Query Store. Generate a single read-only T-SQL query that I can execute in the current database to identify the main performance contributors. The query must use Query Store and return, for each query: * Query ID * Query text * Object or stored procedure name, when available * Number of execution plans * Number of executions * Total CPU time * Average CPU time per execution * Total duration * Average duration per execution * Total logical reads * Average logical reads per execution Aggregate Query Store runtime statistics correctly across runtime intervals and execution plans. Use weighted calculations based on count_executions. Do not calculate averages by simply averaging Query Store average values. Return CPU and duration values in milliseconds. Rank the results by total CPU consumption, but include all the metrics above so that we can determine later which resource is having the highest impact. Do not perform root-cause analysis yet. Do not include execution plan analysis, parameter sensitivity, statistics analysis, index analysis, or remediation recommendations. Only generate the read-only diagnostic T-SQL query that I should execute. We then asked which resource deserved investigation, which query contributed most, how all its plans performed over time, and whether the same Plan ID had become more expensive. Only after those answers did we investigate selectivity, statistics and indexes. The complete session workflow contains the staged follow-up prompts. Convert the conversation into an Agent investigation We moved the recurring calculation rules and diagnostic sequence into sql-performance-investigator. The starting prompt could then state the goal, scope and execution boundaries. The skill supplies the detailed method; the available SQL tools supply execution capability. The agent retains the discovered query and plan identifiers within the investigation. It should not ask the engineer to copy them between steps or assume the identifiers from a previous lab run. Run the method in SSMS Agent mode Make the skill available to SSMS, select Agent mode and verify the SQL tools are enabled. Specify the target explicitly because Agent mode does not inherit the active query editor context. Investigate the SQL performance problem on server <server>, database <database>, using Query Store for <UTC start> to <UTC end>. Use the sql-performance-investigator skill. Use the available sql-tools to execute read-only diagnostics and continue through the investigation, requesting approval where the host requires it. Automatically discover the dominant performance metric, target query, Query ID, all Plan IDs, runtime history, and any same-plan degradation. Retain the discovered identifiers internally. Investigate the evidence needed to explain the change, including selectivity, data distribution, statistics and existing indexes when relevant. Do not assume a plan change caused the degradation or label it parameter sniffing without evidence. Keep confirmed evidence, inference, hypotheses and missing evidence separate. Use execution-weighted averages and explicit units. If the requested history or permissions are unavailable, report the limitation. Do not create/drop indexes, update/drop statistics, force plans, clear caches, modify Query Store, or change data/schema. Finish with a supported diagnosis or remaining uncertainty, a proposed remediation if justified, and a Query Store before/after validation plan. Do not execute remediation. Use the same method in GitHub Copilot Our pack places the skill at .github/skills/sql-performance-investigator/SKILL.md and the Custom Agent at .github/agents/sql-performance-investigator.agent.md. The skill references workflow.md and query-store-rules.md for the detailed method. In GitHub Copilot CLI, select the SQL Performance Investigator custom agent and use this adapted starting prompt: Use the SQL Performance Investigator custom agent and the sql-performance-investigator skill. Investigate SQL performance on <server>, database <database>, for <UTC start> to <UTC end>, using Query Store from evidence to diagnosis. If a SQL execution tool/MCP is available, run only read-only diagnostics and continue through the investigation. Discover Query IDs and Plan IDs automatically and retain them internally. Follow the host approval requirements. If no SQL execution capability is available, generate one self-contained read-only diagnostic batch for me to run, then continue when I provide the result. Do not claim that SQL was executed. Do not apply remediation. Propose an index/statistics action only after the evidence supports it. Finish with a before/after Query Store validation plan. The reusable asset is the investigation procedure behind these prompts. Query Store supplies the evidence, Copilot helps carry out the investigation, and the engineer reviews whether the explanation and proposed change are supported by the results.355Views0likes0CommentsLessons Learned #558: What an Execution Plan XML Can Tell Us in Azure SQL Database
During a performance investigation in Azure SQL Database, we requested the execution plan to understand what the query was doing. While reviewing the evidence, the customer asked a broader question: when you open the XML of an execution plan, what do you usually look for? It was a useful question. The graphical plan helps us follow the flow of data, but the XML contains details about parameters, statistics, warnings and execution that can explain why the query behaved as it did. I do not read every attribute. I start with a few checks that help connect the customer symptom to the work performed by the query. In this article, I will walk through those checks: the type of plan, parameter values, estimated versus actual rows and statistics, missing indexes and implicit conversions, and reasons for a serial plan. The XML fragments below are simplified examples that use invented values or are adapted from examples discussed in previous articles in the Lessons Learned troubleshooting series. First check whether the plan contains execution evidence Plan What we can inspect Estimated plan Optimizer choices and estimates; the query has not executed Actual plan Plan plus available counters and warnings from that execution Cached or Query Store plan Compiled plan; normally no operator actuals for the incident For the checks involving actual rows, I request an actual execution plan. In SSMS, use Include Actual Execution Plan, or capture it using SET STATISTICS XML. Choose one method. The latter executes the query and returns its plan. The account needs the permissions to run the statement and SHOWPLAN permission. SET STATISTICS IO ON; SET STATISTICS TIME ON; SET STATISTICS XML ON; -- Execute the SELECT being investigated here. SET STATISTICS XML OFF; SET STATISTICS TIME OFF; SET STATISTICS IO OFF; Save the plan as a .sqlplan file and keep the Messages output. Record when it was captured, the parameters and the reported symptom. An execution captured later may not represent the incident. Review query literals, parameter values and object names before sharing the file. Check the right statement and its parameters A procedure or batch may contain several statements. I locate the relevant StmtSimple and its QueryPlan before interpreting a warning. StatementId and operator NodeId help keep the observations attached to the correct statement and operator; NodeId is not a stable identifier across different compilations. Next, I look at ParameterList. When available, it shows both the value used when the plan was compiled and the value used during the captured execution. <ParameterList> <ColumnReference Column="@CustomerId" ParameterDataType="int" ParameterCompiledValue="(42)" ParameterRuntimeValue="(900)" /> </ParameterList> Here, the plan was compiled with CustomerId 42 and executed with CustomerId 900. If one customer has a few orders and another has thousands, I would compare their data distribution and actual plans. Different values are a reason to investigate parameter sensitivity; they do not prove that plan reuse caused the problem. A missing runtime value means this capture did not provide it. It does not mean the runtime value was the same as the compiled value. Also, eligible queries can intentionally use different plan variants through Parameter Sensitive Plan optimization. Make the comparison match the application If the query is slow in the application but fast in SSMS, I compare the SQL text, parameter types and values, database context and session options. StatementSetOptions records options associated with compilation. <StatementSetOptions ARITHABORT="true" ANSI_WARNINGS="true" ANSI_NULLS="true" QUOTED_IDENTIFIER="true" ANSI_PADDING="true" CONCAT_NULL_YIELDS_NULL="true" NUMERIC_ROUNDABORT="false" /> A difference in context can help explain why the application and SSMS use different cached plans. I capture both rather than assuming that a fast SSMS execution represents the application. The difference itself still needs to be connected to the measured performance. Compare estimated and actual rows then inspect statistics I follow the rows through the plan and look for the first useful difference between what the optimizer expected and what the operator actually processed. <RelOp NodeId="3" PhysicalOp="Index Seek" LogicalOp="Index Seek" EstimateRows="100"> <RunTimeInformation> <RunTimeCountersPerThread Thread="0" ActualRows="20000" ActualRowsRead="80000" ActualExecutions="1" /> </RunTimeInformation> <!-- Access details omitted --> </RelOp> In this single-execution example, the operator estimated 100 rows and returned 20,000: a 200-fold underestimate. It also read 80,000 rows. I would ask why the estimate was inaccurate, and why the operator read substantially more rows than it returned. These are separate questions. For repeated or parallel operators, account for executions and threads before comparing totals. Do not add the rows from every operator to calculate the query result size. The next question is often whether the statistics were out of date. OptimizerStatsUsage identifies statistics consulted during compilation, where that information is exposed. <OptimizerStatsUsage> <StatisticsInfo Schema="[PlanXmlLab]" Table="[Orders]" Statistics="[IX_Orders_CustomerId]" LastUpdate="2026-10-10T07:00:00" SamplingPercent="20" ModificationCount="15000" /> </OptimizerStatsUsage> I check the relevant statistics object, its LastUpdate, SamplingPercent and ModificationCount together. An old timestamp or a low sampling percentage alone does not prove that it caused the estimate. Updated statistics cannot explain every discrepancy; parameter values, predicates and data distribution also matter. The XML describes the statistics consulted at compilation. To check their current state, I use sys.dm_db_stats_properties, as shown next. A subsequent update does not rewrite the evidence in an already saved plan. Check when the statistics were last updated -- Run in the affected database and set the actual table name. SELECT st.name AS statistics_name, sp.last_updated, sp.rows, sp.rows_sampled, sp.modification_counter FROM sys.stats AS st OUTER APPLY sys.dm_db_stats_properties( st.object_id, st.stats_id) AS sp WHERE st.object_id = OBJECT_ID(N'PlanXmlLab.Orders'); last_updated identifies the latest statistics update; rows and rows_sampled describe the population and sample at that update. modification_counter counts modifications to the leading statistics column since the update. Metadata visibility and permissions can affect the output. Compare this information with the same statistics object in the plan. Timestamps alone do not tell us whether the update was automatic or manual. If an update is justified, validate it in a controlled comparison using the same query and representative parameters, and capture a newly compiled plan. Read the access path alongside the row counts An Index Seek can still read many rows. I inspect SeekPredicates, any residual Predicate and ActualRowsRead where available. A broad seek range followed by filtering can explain why the rows read greatly exceed the rows returned. Likewise, a Key Lookup may be inexpensive once but expensive when repeated for thousands of rows. A scan can be the right choice when a large part of the table qualifies. The operator name is a starting point; the amount of work tells us more. For the customer, the useful explanation is concrete: this operator returned many more rows than expected, these were the statistics used, and this is the next comparison that will help establish why. That is more informative than recommending a statistics update from the timestamp alone. Read missing indexes and conversion warnings as clues Missing-index messages are easy to notice. I inspect the suggestion, but I also check whether it fits the query and the existing indexes. <MissingIndexes> <MissingIndexGroup Impact="85.0"> <MissingIndex Schema="[PlanXmlLab]" Table="[Orders]"> <ColumnGroup Usage="EQUALITY"> <Column Name="[CustomerId]" ColumnId="2" /> </ColumnGroup> <ColumnGroup Usage="INCLUDE"> <Column Name="[Amount]" ColumnId="3" /> </ColumnGroup> </MissingIndex> </MissingIndexGroup> </MissingIndexes> This example suggests a key on CustomerId with Amount included for coverage. EQUALITY and INEQUALITY describe predicate columns, while INCLUDE describes covering columns. The suggestion does not settle every detail of index design. Impact is an estimated reduction in optimizer cost. A value of 85 does not promise an 85% reduction in elapsed time. The XML may contain more suggestions than the graphical plan displays. Review existing indexes and write overhead, then measure the candidate change. Check which side of the predicate is converted <Warnings> <PlanAffectingConvert ConvertIssue="Seek Plan" Expression="CONVERT_IMPLICIT(nvarchar(50),[dbo].[Customers].[Code],0)" /> </Warnings> In this separate example, I would inspect the Code column type and the application parameter declaration. A varchar column compared with an nvarchar parameter can introduce a conversion on the column side because nvarchar has higher type precedence. The warning identifies something that may affect the plan, not a measured root cause. Whether a conversion prevents an efficient seek depends on the types, collation and expression. Test an appropriate parameter declaration while preserving required character semantics, and compare results, reads and CPU. A conversion in the projection is different from one in a search predicate. Look for an explicit reason when the plan is serial Customers sometimes ask why a query does not run in parallel when the database has multiple vCores. I look for NonParallelPlanReason in QueryPlan before assuming that more resources or a higher MAXDOP will change the result. <QueryPlan DegreeOfParallelism="0" NonParallelPlanReason="TSQLUserDefinedFunctionsNotParallelizable"> <!-- Other properties omitted --> </QueryPlan> Reason What I inspect next MaxDOPSetToOne Effective MAXDOP setting or query hint TSQLUserDefinedFunctionsNotParallelizable Scalar UDF and its inlining behavior NonParallelizableIntrinsicFunction The specific intrinsic function referenced A serial plan can be appropriate. The attribute can identify a restriction, but its absence does not fully explain the optimizer decision. Scalar UDF inlining can remove a restriction without guaranteeing parallel execution. DegreeOfParallelism="1" does not demonstrate parallel work. In Azure SQL Database, check database-scoped MAXDOP and query hints. More vCores do not override every restriction or guarantee selection of a parallel plan. Lessons learned The answer to the customer was a reading process: identify the statement and capture type, inspect parameters, compare estimated and actual work, and investigate the relevant statistics and warnings. Each observation should help us ask a better question and select a useful test. For a before-and-after comparison, preserve the query, parameters, data and relevant settings. Compare returned results, logical reads, CPU and duration. A plan describes one compilation or execution; Query Store can help establish whether the behavior changed over time. A short checklist Confirm that the plan belongs to the affected statement and execution. Check parameter values and the application context. Compare estimated and actual rows, accounting for repeated work. Inspect compilation statistics and their current update metadata. Review missing indexes, implicit conversions and serial-plan reasons. Validate the explanation with a measured comparison.Azure SQL Data Sync After a Database Restore: Troubleshooting Leftover Sync Metadata
Recently, I worked on an interesting Azure SQL Data Sync issue that I thought was worth sharing with the community. The scenario looked straightforward at first: a database had been restored from another environment and was being configured as a Member database in a new Data Sync group. However, synchronization wasn't working as expected. The interesting part was not the new Sync Group itself. It was what the restored database had brought with it from its previous Data Sync configuration. The scenario The Member database was a restored copy of a database that had previously participated in another Azure SQL Data Sync group. After the restored database was configured as a Member in the new environment, synchronization wasn't working as expected. During troubleshooting, another important clue emerged. The restored database still had a history with Azure SQL Data Sync, so we needed to determine whether metadata and generated objects from its previous configuration were still present. This became one of the key areas of the investigation. Understand the Data Sync architecture first Before jumping into scripts, it's important to clearly distinguish the three database roles involved in Azure SQL Data Sync: Hub Database: The central database containing the application data being synchronized. Member Database: A database that synchronizes with the Hub. Sync Metadata Database: A separate Azure SQL Database containing Data Sync metadata and logs. Microsoft's documentation explains that Data Sync follows a hub-and-spoke topology and that the Sync Metadata Database contains Data Sync metadata and logs. This distinction became particularly important during this investigation because the initial diagnostic configuration wasn't pointing to the expected Sync Metadata Database. Troubleshooting approach Here is the troubleshooting flow we followed. Step 1: Run the Azure SQL Data Sync Health Checker One of the first tools I recommend for this type of investigation is the public Azure SQL Data Sync Health Checker: Azure SQL Data Sync Health Checker on GitHub [github.com] The tool validates whether metadata associated with the Hub and Member is in place and compares the scopes against information in the Sync Metadata Database. Importantly, the Health Checker repository states that it performs validation without changing Data Sync or user objects. The tool requires the relevant connection details for: Sync Metadata Database Hub Database Member Database The GitHub repository contains the current script and execution instructions. What we observed In our investigation, the initial Health Checker output included messages similar to: WARNING: dss schema IS MISSING! WARNING: TaskHosting schema IS MISSING! Invalid object name 'dss.syncgroup'. Invalid object name 'dss.userdatabase'. Those errors were important clues, but they needed to be interpreted together with the database roles. Microsoft's documentation states that the DataSync schema is used for system-created objects in Hub and Member databases, while the dss and TaskHosting schemas are used for system-created objects in the Sync Metadata Database. That distinction helped us recognize that we first needed to validate which database was actually being supplied to the Health Checker as the Sync Metadata Database. Lesson learned Before treating a missing dss or TaskHosting schema as corruption, first make sure you're actually connected to the Sync Metadata Database. That simple validation can save a lot of investigation time. Step 2: Check the Member database for Data Sync artifacts Once we had clarified the topology, the investigation moved to the restored Member database. Because this database had previously participated in Data Sync, we wanted to understand what Data Sync objects were still present. One of the queries used during troubleshooting was: SELECT name FROM sys.tables WHERE SCHEMA_NAME(schema_id) = 'DataSync' AND name NOT LIKE '%_tracking%'; We also inspected: SELECT * FROM DataSync.schema_info_dss; And, when checking the Member database's Data Sync scope information: SELECT * FROM DataSync.scope_info_dss; These checks helped us understand the Data Sync metadata state of the restored Member database and whether it still contained artifacts associated with its previous configuration. Why this matters Microsoft's current Data Sync best-practices documentation confirms that the DataSync schema is used for system-created objects in Hub and Member databases. So, when investigating a database restored from an environment where it previously participated in Data Sync, the DataSync schema is an important part of the investigation. Step 3: Consider the history of the restored database This was really the turning point in the investigation. Instead of treating the database simply as a "new Member", we started looking at it as: A restored database that had previously been provisioned for another Data Sync configuration. That's an important difference. When troubleshooting a restored database, ask early: Was this database previously part of another Azure SQL Data Sync group? If the answer is yes, the database's previous Data Sync state should be considered during the investigation. Step 4: Remove the Member before cleanup In our scenario, the remediation sequence was essentially: Remove the restored database from the current Sync Group. Clean up the previous Data Sync metadata from the restored Member database. Re-add the database as a Member. Trigger synchronization again. For the cleanup portion, we used the following publicly available repository: SQL Data Sync Cleanup Scripts on GitHub [github.com] The repository contains several scripts for different purposes, including: Data Sync complete cleanup.sql Data Sync cleanup hub or member.sql cleanup data sync object V2.sql The specific complete-cleanup script is available here: Data Sync complete cleanup.sql Important warning about the cleanup script Please do not treat this as a general-purpose Data Sync troubleshooting script. The script itself contains a very clear warning. It immediately cleans Data Sync-related objects associated with the database and says it should be used only for the scenarios specified in the script, including when advised by the support team during a support request. The repository also explains the different purposes of its cleanup scripts. For example, the complete-cleanup script has more restrictive usage guidance, while the Hub/Member cleanup and object cleanup scripts target different scenarios. My recommendation: use the Health Checker and read-only diagnostic queries first. Do not jump directly to metadata cleanup without understanding the database topology and existing Data Sync configuration. Step 5: Validate with one table After cleaning up the previous Data Sync artifacts, we didn't immediately assume that everything was resolved. Instead, we validated with a controlled test. A test table on the Member side was truncated, the synchronization was started again, and the table began synchronizing successfully. That provided the confirmation we needed that the previous Data Sync state of the restored Member was an important part of the issue. Root cause The troubleshooting pointed to the fact that the restored Member database had previously participated in another Data Sync configuration and retained Data Sync-related metadata/artifacts from that previous state. After cleaning up the old Data Sync state and reprovisioning the restored database as a Member, synchronization was successfully validated again. The important lesson for me wasn't simply the cleanup itself. It was recognizing that restoring a database does not necessarily mean you're starting with a clean Data Sync state. A practical troubleshooting flow For similar scenarios, I would approach the investigation in this order: Confirm the architecture Identify the: Hub Database Member Database Sync Metadata Database Run the Health Checker Use: Microsoft Azure SQL Data Sync Health Checker [github.com] Review its output before making changes. Inspect the restored Member Check whether Data Sync-related objects exist: SELECT name FROM sys.tables WHERE SCHEMA_NAME(schema_id) = 'DataSync' AND name NOT LIKE '%_tracking%'; Then, where applicable to the database's current state, inspect: SELECT * FROM DataSync.schema_info_dss; and: SELECT * FROM DataSync.scope_info_dss; Ask about the database history Was the database: restored from another environment? previously a Data Sync Member? previously associated with another Sync Group? That historical context can completely change the direction of the investigation. Consider cleanup only after understanding the environment The public cleanup scripts are available here: SQL Data Sync Cleanup Scripts [github.com] These scripts make changes to Data Sync objects and should not be the first troubleshooting step. Validate using a controlled test Once the environment has been correctly cleaned/reconfigured, validate synchronization on a controlled scope before assuming the entire configuration is healthy. My key takeaways This troubleshooting experience reinforced a few lessons for me. A restored database isn't necessarily a clean Data Sync database Restoring the application data doesn't mean you should ignore the database's previous synchronization configuration. Always distinguish Hub, Member, and Sync Metadata databases This is especially important when interpreting Health Checker output. The DataSync schema is associated with system-created objects in Hub and Member databases, while dss and TaskHosting are associated with system-created objects in the Sync Metadata Database. Use diagnostics before cleanup The Azure SQL Data Sync Health Checker is designed to validate Data Sync metadata and objects without making changes. That makes it a much better starting point than immediately removing objects. Database history matters One of my favorite questions after this investigation is now: "Was this database ever part of another Data Sync Group?" It's a simple question, but in restore or copy scenarios it can reveal an important part of the troubleshooting story. Be very careful with metadata cleanup The public cleanup repository itself provides specific guidance about when each script should be used, and the complete-cleanup script includes an explicit warning before execution. Always understand the environment and protect your data before performing destructive operations. One more important consideration: SQL Data Sync retirement There is also an important longer-term architecture consideration. Microsoft currently documents that SQL Data Sync retires on September 30, 2027. Existing Sync Groups can continue operating until the retirement date, but Microsoft recommends migrating to alternative data replication and synchronization solutions before then. So, while troubleshooting existing Data Sync environments remains necessary, organizations using the service should also begin considering their migration strategy. References and useful tools Microsoft documentation Best practices for Azure SQL Data Sync [learn.microsoft.com] Troubleshooting tools Azure SQL Data Sync Health Checker [github.com] SQL Data Sync Metadata Cleanup repository [github.com] Data Sync complete cleanup.sql220Views0likes0CommentsLessons Learned #555: The First 60 Seconds of a Production Incident: Stop, Scope, Correlate
When a critical production incident starts, the first message we often receive is something like: “The database is down.” At that moment, everything suddenly becomes urgent. Engineers open monitoring dashboards. Someone starts checking logs. Another person reviews CPU and memory. Someone else asks whether there was a deployment. Connections are tested. Metrics are queried. Teams are contacted. All of these actions may eventually be necessary. But there is a more important question to answer first: What exactly does “down” mean? After working on many production incidents, one lesson becomes increasingly clear: The first 60 seconds are not about solving the incident. They are about defining the incident. A vague problem description can send troubleshooting in many different directions. A precise problem statement dramatically reduces the investigation space. This article describes a simple approach that can be applied during the first moments of an incident: Stop. Scope. Correlate. 1. Stop: Define What “Down” Actually Means The first mistake during many incidents is assuming that everyone understands the problem in the same way. Consider the statement: “The database is unavailable.” That statement could mean many different things: Applications cannot establish new connections. Existing connections are still working, but new connections fail. Queries are timing out. A specific login cannot authenticate. One database is inaccessible. One application is failing while other applications work correctly. Performance degradation makes the service appear unavailable. The application returns HTTP 500 errors, but the database itself is healthy. Connections fail intermittently. A failover is occurring. DNS or networking issues prevent the application from reaching the database. These scenarios require completely different investigation paths. Before opening ten different tools, try to transform the original statement into something more specific. For example: Instead of: “The database is down.” Try to reach something like: “Since approximately 14:32 UTC, new application connections to Database A have intermittently failed with login errors, while existing sessions remain active.” Now we have something we can investigate. The problem statement contains: a timestamp, a specific database, a specific symptom, affected connection behavior, and an indication that the issue may be intermittent. That is already much more valuable than the original alert. 2. Scope: Determine the Blast Radius Once we understand the symptom, the next question is: Who or what is affected? This is sometimes called determining the blast radius. The scope can immediately eliminate entire categories of possible causes. Ask questions such as: Is one user affected or every user? Is one application affected or several applications? Is one database affected or all databases? Are all connection types affected? Are existing connections healthy while new connections fail? Are only specific clients or drivers affected? Imagine the following situation. Application A reports database connectivity failures. However: Application B connects successfully. SSMS connects successfully. Azure metrics show the database is available. Existing sessions continue executing queries. This changes the investigation dramatically. The problem may not be: “Azure SQL is unavailable.” It may instead be: “Application A cannot establish new connections.” That distinction is extremely important. A large percentage of troubleshooting time can be saved simply by identifying the correct scope early. 3. Build the Timeline The next critical dimension is time. During an incident, timestamps are evidence. Ask: When did the issue start? Is there an exact timestamp? How long did it last? Is the issue continuous or intermittent? Did the problem recover automatically? Did the issue occur once or multiple times? Was there another event immediately before the problem? A good incident timeline may look like this: 14:31:52 UTC – Application operating normally 14:32:08 UTC – First connection error reported 14:32:10 UTC – Database failover detected 14:32:14 UTC – Additional login failures 14:32:18 UTC – New connections begin succeeding 14:32:20 UTC – Application fully recovere Now the investigation is no longer based on assumptions. We have a five-to-ten-second window that can be correlated with platform telemetry, database events, application logs, networking information, and deployment history. Without the timeline, engineers may analyze hours of logs. With the timeline, the investigation becomes focused. 4. Correlate Before Changing Anything The next step is correlation. Once we understand the symptom, scope, and timeline, we can ask: What changed at the same time? Useful correlation sources may include: application deployments, infrastructure changes, configuration changes, database failovers, scaling operations, maintenance events, firewall changes, authentication changes, networking events, DNS changes, resource utilization, query regressions, blocking, deadlocks, connection pool behavior, driver updates, platform events. etc The key word here is correlation. It is tempting during an incident to immediately change something. For example: restart the application, restart a service, scale the database, clear the connection pool, change configuration, rebuild an index, modify a query, fail over manually. Sometimes these actions are necessary. But every change also modifies the evidence. A restart may restore the service while simultaneously removing valuable diagnostic information. Whenever possible: Collect evidence before changing the environment. 5. Use Multiple Sources of Evidence Production incidents rarely provide the complete answer in one telemetry source. A better approach is to correlate multiple sources. For a database-related incident, we may investigate: Application telemetry Application logs may reveal: connection failures, authentication errors, request latency, retry attempts, timeout exceptions, HTTP errors, dependency failures. Platform metrics Cloud metrics may help determine: service availability, CPU utilization, storage pressure, connection count, throttling, resource saturation. Database telemetry Database-level information may include: active sessions, waits, blocking, query performance, login failures, failover events, resource statistics. Query Store For performance incidents, Query Store can be extremely valuable. It may help identify: query regressions, plan changes, increased execution duration, abnormal CPU consumption, changes in execution frequency. Deployment history Always ask: What changed recently? Many incidents have a strong temporal relationship with: application deployments, schema changes, configuration modifications, infrastructure updates, new releases, security changes. The goal is not to assume that the most recent change caused the incident. The goal is to determine whether the events correlate. 6. Avoid Starting With a Tool One common troubleshooting pattern is: “Open the monitoring portal.” or: “Run this query.” or: “Check this log.” Tools are essential, but tools should follow the investigation strategy. The investigation should determine which tool we need. Not the other way around. If the problem is authentication, the investigation path may focus on: login errors, authentication configuration, identity providers, user mappings, connection strings. If the problem is performance, the investigation may focus on: Query Store, waits, blocking, execution plans, resource utilization. If the problem is connectivity, we may investigate: DNS, network paths, firewalls, drivers, retries, connection pools. A clear problem definition tells us where to look. 7. Ask the Same Questions Every Time One of the most effective improvements teams can make is standardizing the first questions asked during incidents. A simple initial checklist could be: Symptom: What exactly is failing? Scope: Who or what is affected? Timeline: When did it start? Error: What exact error message or error code is being returned? Frequency: Is the issue continuous, intermittent, or already recovered? Changes: What changed immediately before the incident? Evidence : Which telemetry sources can confirm the behavior? These questions are intentionally simple. During a high-severity incident, simplicity is valuable. 8. The First 60 Seconds Framework We can summarize the approach in four steps. 1. Define: What does the reported symptom actually mean? 2. Scope: Determine the blast radius. 3. Timeline: Identify exactly when the problem occurred. 4. Correlate Connect the symptom with telemetry, events, and recent changes. Only after these steps should we decide the deeper troubleshooting path. 9. Speed Is Important, but Direction Is More Important During critical incidents, teams naturally want to move quickly. That is the correct instinct. But speed without direction can create noise. Ten engineers investigating ten different theories at the same time may generate enormous activity without producing clarity. A well-defined incident allows teams to divide the investigation intelligently. For example: One engineer investigates application telemetry. Another checks database telemetry. Another reviews platform events. Another investigates recent deployments. Another builds the incident timeline. All of them are now investigating the same defined problem. That is very different from everyone independently trying to determine what the problem might be.