LLI Wiki — My Digital Knowledge Base

Azure SQL Database: tracing long queries, timeouts and SQL errors with Extended Events, even on a geo-secondary

One XEvents session to Blob (managed identity) for performance and errors: queries over 10 min, client timeouts, SQL errors, with application, host, login and SQL text; created on the primary, started on the read-only geo-secondary.

The classic scenario: every night, a query runs for hours at 100 % CPU on a read-only geo-secondary, then ends in a client-side timeout. Monitoring shows the CPU curve, but not who runs the query nor what it runs exactly. And on the same day, someone also asks "and the SQL errors of this database, where do we see them?".

My answer: one Extended Events session that covers both needs, performance (long queries, timeouts) and errors, with the application, host, login and SQL text on every row. The .xel files go to a Blob container through the managed identity of the logical server: no SAS, no secret.

Event What it gives
sqlserver.attention The request cancelled or cut by the client timeout, and by whom
sqlserver.rpc_completed RPC calls longer than 10 min: duration, CPU, reads, result (OK, Error, Abort after an attention)
sqlserver.sql_batch_completed The same for ad hoc batches
sqlserver.error_reported Every SQL error (severity ≥ 11) with its message and the SQL that raised it
flowchart LR
    P["Primary: CREATE EVENT SESSION"] --> R["Definition replicated"]
    R --> S["Geo-secondary: STATE = START"]
    S --> MI["Managed identity of the secondary server"]
    MI --> B["Blob container (.xel)"]
    B --> Q["fn_xe_file_target_read_file"]

The geo-secondary trap

On a read-only database, CREATE EVENT SESSION is refused. The fix, documented by Microsoft: create the session on the primary. The definition replicates to the secondary, and you start it on the secondary, where it runs independently of the primary.

Second trap: the managed identity used to write to Blob is the one of the logical server that runs the session. The primary's role is useless for the secondary: its own identity needs Storage Blob Data Contributor on the storage account, otherwise START fails with Msg 25602, OS error 5 Access is denied. And a role that was just granted takes a few minutes to apply: same error right after, it works a bit later.

Create (on the primary)

IF NOT EXISTS (SELECT 1 FROM sys.symmetric_keys WHERE name = N'##MS_DatabaseMasterKey##')
    CREATE MASTER KEY;

-- Credential name = container URL, without a trailing "/"
IF NOT EXISTS (SELECT 1 FROM sys.database_scoped_credentials
               WHERE name = N'https://stdbacontoso.blob.core.windows.net/xevents')
    CREATE DATABASE SCOPED CREDENTIAL [https://stdbacontoso.blob.core.windows.net/xevents]
    WITH IDENTITY = 'MANAGED IDENTITY';

CREATE EVENT SESSION [xe_long_query] ON DATABASE
ADD EVENT sqlserver.attention
    (ACTION (sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.username,
             sqlserver.session_id, sqlserver.sql_text)),
ADD EVENT sqlserver.rpc_completed
    (ACTION (sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.username,
             sqlserver.session_id, sqlserver.sql_text)
     WHERE duration > 600000000),          -- microseconds: 10 min
ADD EVENT sqlserver.sql_batch_completed
    (ACTION (sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.username,
             sqlserver.session_id, sqlserver.sql_text)
     WHERE duration > 600000000),
ADD EVENT sqlserver.error_reported
    (ACTION (sqlserver.client_app_name, sqlserver.client_hostname, sqlserver.username,
             sqlserver.session_id, sqlserver.sql_text)
     WHERE severity >= 11)
ADD TARGET package0.event_file
    (SET filename = N'https://stdbacontoso.blob.core.windows.net/xevents/xe_long_query.xel',
         max_file_size = 100, max_rollover_files = 5)
WITH (STARTUP_STATE = OFF, EVENT_RETENTION_MODE = ALLOW_SINGLE_EVENT_LOSS,
      MAX_DISPATCH_LATENCY = 30 SECONDS);

Start and check (on the secondary)

ALTER EVENT SESSION [xe_long_query] ON DATABASE STATE = START;

-- Running here? Writing to which file?
SELECT s.name, s.create_time,
       CAST(t.target_data AS xml).value('(EventFileTarget/File/@name)[1]', 'nvarchar(4000)') AS current_file
FROM sys.dm_xe_database_sessions AS s
JOIN sys.dm_xe_database_session_targets AS t ON s.address = t.event_session_address
WHERE s.name = N'xe_long_query';

Two-second test: SELECT qsdfqsdf; must show up in the read below (error 207).

Read

DECLARE @file nvarchar(4000) =
(
    SELECT CAST(t.target_data AS xml).value('(EventFileTarget/File/@name)[1]', 'nvarchar(4000)')
    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'xe_long_query' AND t.target_name = N'event_file'
);

SELECT
    x.value('(event/@timestamp)[1]',                            'datetime2(3)')  AS ts_utc,
    x.value('(event/@name)[1]',                                 'sysname')       AS event_name,
    x.value('(event/data[@name="error_number"]/value)[1]',      'int')           AS error_number,
    x.value('(event/data[@name="message"]/value)[1]',           'nvarchar(max)') AS message,
    x.value('(event/data[@name="duration"]/value)[1]', 'bigint') / 1000000      AS duration_s,
    x.value('(event/data[@name="cpu_time"]/value)[1]', 'bigint') / 1000000      AS cpu_s,
    x.value('(event/data[@name="result"]/text)[1]',             'nvarchar(60)')  AS result,
    x.value('(event/action[@name="client_app_name"]/value)[1]', 'nvarchar(256)') AS client_app,
    x.value('(event/action[@name="client_hostname"]/value)[1]', 'nvarchar(256)') AS client_host,
    x.value('(event/action[@name="username"]/value)[1]',        'sysname')       AS username,
    x.value('(event/action[@name="sql_text"]/value)[1]',        'nvarchar(max)') AS sql_text
FROM (SELECT CAST(event_data AS xml) AS x
      FROM sys.fn_xe_file_target_read_file(@file, NULL, NULL, NULL)) AS e
ORDER BY ts_utc DESC;

What I look for the next morning: an attention row and, at the same time on the same session, an rpc_completed or sql_batch_completed with result = Abort, its duration and CPU. Application, host, login and SQL text go to the team that owns the application.

Clean up

Stop the session on the secondary (STATE = STOP), drop it on the primary (DROP EVENT SESSION, replicated), then delete the .xel files. The credential and master key stay if other sessions write to the same container.

Pitfalls

Symptom Cause
Empty read although the errors did happen A wildcard xe_long_query*.xel in fn_xe_file_target_read_file does not work on Blob: you need the exact file name, from target_data or from the container
Msg 25602, OS error 5 at START on the secondary Secondary server identity without a role on the storage account, or role not propagated yet
Msg 25625 already exists on ALTER ... ADD EVENT The event is already in the session: check sys.database_event_session_events, or drop and create
Nothing the next morning STARTUP_STATE = OFF: a failover or maintenance stopped the session; the files are still there
Several files Rollover: read each one by its name, or download them and merge them in SSMS (Merge Extended Events files)

Lessons learned

See also: errors, deadlocks and timeouts with Extended Events and live blocking: who, why, how.

Mastodon LLIMastodon SocialFosstodon