Track Application Query Timeouts with the Attention Event
An application reports "Timeout expired." The client waited out its command timeout, typically 30 seconds, and cancelled the query. On the server, that cancel shows up as an Attention event, error 3617. The script below creates an Extended Events session that writes every attention event from user sessions to a small rolling file, along with the SQL text, database, user name, host and application for each one.
Purpose and Overview
A query timeout is different from a connection or login timeout. A connection or login timeout happens when the first connection to the server reaches its timeout period. At that point the client has not sent any query. If an application sets its query timeout to 0 (no time limit), the Database Engine runs the query until it finishes, so that application never produces a timeout attention event.
The script needs SQL Server 2016 or later as written, because its read query passes NULL for the metadata path, which SQL Server 2016 and later accept. It drops and recreates a server-scoped session named AppExecutionTimeout. It captures the sqlserver.attention event for user processes only and writes to an event_file target capped at two 5 MB files. A read query in the header comment returns one row per event: the event name, the event as XML, and the file name and offset where the event is stored.
The executable part of the script is the stop, drop, create and start statements, plus the checks against sys.dm_xe_sessions and sys.server_event_sessions. These statements build and start the session. The commented read query passes NULL as the metadata path. A .xem metadata path is needed only to read files written by SQL Server 2008 and 2008 R2; from SQL Server 2012 the parameter is kept only for backward compatibility.
The script runs as written on SQL Server. On Azure SQL Managed Instance, files created by the event_file target are always stored as blobs in an Azure Storage container, so the local file name AppExecutionTimeout.xel won't work there: the target needs an Azure Storage blob URL, and reading it back needs a credential for that container. The session is server-scoped, so it does not apply to Azure SQL Database, which supports only database-scoped sessions.
Code Breakdown
The script stops and drops any old copy of the session, creates it fresh, then starts it.
1/*
2SELECT
3 object_name
4 , convert(xml, event_data) AS event_data
5 , file_name
6 , file_offset
7FROM sys.fn_xe_file_target_read_file(N'AppExecutionTimeout*.xel',NULL,NULL,NULL);
8GO
9*/
10
11/* Stop trace if started */
12IF EXISTS (SELECT * FROM sys.dm_xe_sessions WHERE name = 'AppExecutionTimeout')
13 ALTER EVENT SESSION AppExecutionTimeout ON SERVER STATE = STOP;
14
15/* Delete trace if exists */
16IF EXISTS (SELECT * FROM sys.server_event_sessions WHERE name = 'AppExecutionTimeout')
17 DROP EVENT SESSION AppExecutionTimeout ON SERVER;
18
19/* Create trace */
20CREATE EVENT SESSION AppExecutionTimeout ON SERVER
21ADD EVENT sqlserver.attention
22(ACTION (sqlserver.session_id, sqlserver.database_id, sqlserver.database_name,
23sqlserver.username, sqlserver.sql_text, sqlserver.client_hostname,
24sqlserver.client_app_name)
25WHERE ([package0].[equal_boolean]([sqlserver].[is_system],(0))))
26ADD TARGET package0.event_file(SET filename=N'AppExecutionTimeout.xel',
27max_file_size=(5),max_rollover_files=(2));
28GO
29
30ALTER EVENT SESSION AppExecutionTimeout ON SERVER STATE = START;
31GO
The read query in the header comment
The SELECT against sys.fn_xe_file_target_read_file sits inside the opening /* ... */ block, so running the script only builds and starts the session. When you want the data, copy the query out and run it separately.
The path N'AppExecutionTimeout*.xel' uses * as a wildcard, so one call reads every file the session has rolled over to. The second argument, mdpath, is NULL. SQL Server 2016 and later accept that because they no longer use .xem metadata files. The third, initial_file_name, is also NULL, which makes the function read all the files found in the path instead of starting from a named file.
event_data comes back as nvarchar(max) text that holds the event in XML format. CONVERT(xml, event_data) turns that text into the xml type, which you need before you can pull out fields such as sql_text or client_app_name. file_name and file_offset show where each event sits on disk.
Stop and drop: two different checks
The first IF EXISTS reads sys.dm_xe_sessions, which returns only server-scoped Extended Events sessions that are active. If the session is running, it appears there and the script stops it.
The second check reads sys.server_event_sessions, the catalog view of session definitions. A session that was created but never started, or was stopped, is missing from sys.dm_xe_sessions but still has a definition. If the script used the DMV for both checks, it would skip the drop for a stopped session, and that session would still exist when CREATE EVENT SESSION runs.
CREATE EVENT SESSION: the event, actions and filter
The session has one event, sqlserver.attention. Microsoft describes an attention event as a cancel, a client-interrupt request or a broken client connection, and notes that data access driver time-outs show up as cancels. A user cancelling a query in SSMS raises the same event. SSMS and sqlcmd run with a timeout of 0, so attention rows from those tools are manual cancels, not timeouts.
The ACTION list adds seven fields to each event: session_id, database_id, database_name, username, sql_text, client_hostname and client_app_name. The most useful is session_id, because it ties an attention event to the sql_batch_completed or rpc_completed event for the same query. sql_text gives the statement. client_app_name and client_hostname show which application sent it and from which machine.
The WHERE clause uses package0.equal_boolean to compare sqlserver.is_system with 0. That keeps events from user sessions and drops events from system sessions.
The script sets no WITH options, so the session runs with the defaults. That means 4 MB of MAX_MEMORY for event buffers and a MAX_DISPATCH_LATENCY of 30 seconds, which is how long events can wait in memory before the session sends them to the target.
The event_file target
max_file_size=(5) caps each file at 5 MB, and max_rollover_files=(2) sets how many files the session keeps. Together they hold about 10 MB of attention history.
Neither the filename value nor the read query's path names a folder. A read path with no folder reads from the instance's default folder, \MSSQL\Log inside its installation folder. filename also accepts a full path such as N'C:\xe\AppExecutionTimeout.xel'. If you use one, put the same folder in the read query's wildcard path.
Starting the session
CREATE EVENT SESSION stores the definition but does not start the session. ALTER EVENT SESSION ... ON SERVER STATE = START starts it immediately. The GO before that statement closes the create batch first.
Key Benefits and Use Cases
- A record of each cancel — cancels land in the file with the statement and the calling application, so you can take the failing statement to the application team.
- A tuning list — slow queries are the most common cause of timeouts, and the recommended fix is to tune the query rather than only raise the timeout, so the captured
sql_textvalues form your work queue. - Before and after a release — compare attention counts per application across a deployment to catch a new query that runs past the client timeout.
Performance Considerations
- Buffer memory: the session uses the default 4 MB
MAX_MEMORYfor buffering. Add aWITH (MAX_MEMORY = ...)clause if you need a different size. - Write delay: with the default 30 second dispatch latency, a cancel from a few seconds ago may still be in memory and not yet in the file.
- Lost events:
dropped_event_countinsys.dm_xe_sessionscounts events dropped when the buffers were full. On SQL Server 2017 and later,buffer_full_countshows how many buffers were full when they were processed. - Short retention: two 5 MB files make a small window on a server with frequent cancels, so copy the rows you need out of the files before they roll over.
- Reading in SSMS: reading a large result set from
sys.fn_xe_file_target_read_filein Management Studio can raise an error. For big reads, switch to Results to File (Ctrl+Shift+F).
Practical Tips
- Survive restarts — add
WITH (STARTUP_STATE = ON)to theCREATE EVENT SESSIONstatement so the session starts again when the Database Engine is stopped and restarted. - Confirm it is running — look up the session by name in
sys.dm_xe_sessions.create_timeshows when it was started, and on SQL Server 2017 and latertotal_bytes_generatedshows the bytes it has written to the file target. - Add the event time — on SQL Server 2017 and later,
sys.fn_xe_file_target_read_filealso returnstimestamp_utc, the event time in UTC. Add it to the read query to match rows against the application's error log. - Get the duration — trace
sql_batch_completedandrpc_completedalong with the attention event and match them onsession_id. If a completed event is followed at once by an attention event, and its duration is close to the timeout setting, you have found the query. - Grant the right permissions — grant
ALTER ANY EVENT SESSION.CREATE ANY EVENT SESSION, added in SQL Server 2022, covers theCREATE EVENT SESSIONstatement, butALTER EVENT SESSION, which stops and starts the session, requiresALTER ANY EVENT SESSION. Readingsys.dm_xe_sessionsand the files needsVIEW SERVER STATEon SQL Server 2019 and earlier, andVIEW SERVER PERFORMANCE STATEon SQL Server 2022 and later.
Conclusion
This script gives a server an ongoing record of attention events (client-side query cancels, client interrupts and broken client connections), with the SQL text and the calling application attached to each one. Run it first when timeout errors appear. Then tune the statements it captures, using the completed events matched on session_id to get their durations.
References
- How to detect query timeout errors with Extended Events (sqlgrease, Franklin Yamamoto) — the original script, as copied in AppExecutionTimeout.sql (ktaranov/sqlserver-kit)
- sys.fn_xe_file_target_read_file (Transact-SQL) — wildcard path, NULL mdpath from SQL Server 2016, .xem only for SQL Server 2008 and 2008 R2 files, blob storage on Managed Instance with a credential, default folder \MSSQL\Log, initial_file_name, event_data as XML text, timestamp_utc, large result sets in SSMS, read permissions
- CREATE EVENT SESSION (Transact-SQL) — MAX_MEMORY and MAX_DISPATCH_LATENCY defaults, STARTUP_STATE, starting with ALTER EVENT SESSION, file size in MB and retained files, full-path filename in the event_file example, create permissions
- Attention Event Class — attention events cover cancels, client-interrupt requests and broken client connections; driver time-outs appear as cancels
- Troubleshoot query time-out errors — attention event and error 3617, typical 30 second timeout, timeout of 0 in apps, SSMS and sqlcmd, connection and login timeouts, correlating on session_id, tuning over raising the timeout
Posts in this series
- SQL Server Table Row Count Report: Complete T-SQL Script
- Generate sp_spaceused Commands for All User Tables in T-SQL
- SQL Server Blocking Detection: Find Blocked Sessions
- SQL Server Database Size Report for All Databases
- SQL Server Long-Running Queries: Find Active Sessions
- SQL Server TempDB Usage and Contention Report
- SQL Server Database File Space Usage Report
- SQL Server Get Table and Index Storage Size Report Script
- Age Open Transactions with sys.dm_tran_active_transactions
- Decode PLE and Buffer Cache Hit Ratio via cntr_type Codes
- Spot Low-Memory Conditions with sys.dm_os_process_memory
- Track Azure SQL Database Load with sys.dm_db_resource_stats
- Inventory Open Cursors per Session with sys.dm_exec_cursors
- Track Application Query Timeouts with the Attention Event