Launch week: the Season Pass & Fundamentals Week are 50% off — ends in 20d 14h 24mSee the sale

Performance Tuning

What Happens When Multiple Queries Compile at Once?

An interesting question came in on PollGab. DBAmusing asked:

If a query takes 5-7s to calculate the execution plan (then executes <500ms) if multiple SPIDS all submit that query (different param values) when there’s no plan at start, does each SPID calc the execution plan, one after the other after waiting for the prior SPID to finish?

Well, it’s easy enough to demonstrate! Let’s take a query from my Fundamentals of Query Tuning class that takes tens of seconds (or longer) to generate a plan on most versions and compat levels:

And then let’s run it simultaneously across 10 threads with SQLQueryStress:

And run sp_BlitzWho to see what’s happening:

We see that most of the sessions are piled up waiting on RESOURCE_SEMAPHORE_QUERY_COMPILE. That means queries are waiting on memory in order to build execution plans. It’s not that the SQL Server is out of memory altogether – it’s just that it has gateways to prevent too many queries from compiling at once.

Most DBAs can go their entire career without seeing that bottleneck, but given my weirdo job – I’m like an emergency room trauma surgeon for SQL Servers – I see it at least a couple times a year when:

  • A SQL Server is under serious memory pressure (typically due to queries getting oversized memory grants), and
  • There are seriously complex queries in the workload (typically reporting queries), and
  • Those queries aren’t parameterized (because if they were properly parameterized, they’d stick around in the plan cache, avoiding the compilation problem)

In that situation, my first line of defense is to improve plan caching like we discuss in this module of my Mastering Server Tuning class. The last line of defense would be trace flag 6498, which allows more large queries to compile simultaneously. I’ve never needed that in my life, and I hope you don’t either!

Free, 3× a week

Get my new posts by email

Three posts a week, plus a Monday roundup of the best database news from around the web.

5 comments

  1. Hello!

    I assume that with them piling up that by the time the next one executes it would see the plan the first one made and follow along with that then? The answer to the question isn’t explicitly stated so was curious if the final result lines up with that assumption.

    1. Well, part of the reason I use open source databases and share all my scripts here is so that if you’ve got additional experiments or questions, you can pick it up and run with it to see things for yourself, without waiting on me (or asking me to do more work for ya, heh.) By all means, give it a shot to find out!

Leave a comment

Your email address will not be published. Required fields are marked *