SQL Server – Managing Locks Caused by Async Stats Update

maintenancesql serverstatistics

SQL Server has an option for statistics to autoupdate asynchronously (AUTO_UPDATE_STATISTICS_ASYNC).

But, even if this option is ON, from time to time I see locks like this on pic below: say, spid 549 locks spid 42 and spid 42 locks 8 other sessions. As I can see, system spid tries to change old statistics to a newly computed one, so it waits for SCH-M lock to acquire.

enter image description here

Suddenly, it turns out, async stats update is not so async: any long-running SELECT (which, of course, holds SCH-S lock) can freeze system spid, which, in turn, can gather queue of many other sessions. Even worse, whole queue wait time depends on of locker’s SELECT duration. It means, if I have a long OLAP query, all the stalled sessions could be timed out.

So, my question is: am I missing something or it works just by design? Can I somehow avoid these sudden locks, caused by autoupdated statistics?

Best Answer

It has nothing to do with SCH-S. Select queries which acquire S and IS locks are compatible with SCH-S, which is called Schema Stability and all it does, it prevents table during query execution from being modified which means SCH-S and SCH-M are not compatible. SCH-S is compatible with all other locks.

Your problem however is that you have auto update stats enabled, which are triggered whenever there is certain amount of data changed within a table (20% pre SQL2016 or with 2371 traceflag counts % depending on number of rows) and it does when you execute the query.

So what might have happened is that your table was pretty busy and query optimizer decided it should update statistics, so you had to wait.

You should disable auto update statistics and update it manually