SQL Server Memory and Thread Structure

The SQL Server database engine is one sqlservr process. Inside it, a layer called SQLOS manages thread scheduling, memory allocation, and I/O completion handling in place of the operating system. Two things differ most from other DBMSs. First, a connection (session) does not hold a thread permanently; only a running request uses a worker thread. Second, workers run under cooperative (non-preemptive) scheduling, yielding voluntarily rather than being switched out by the operating system. Within the max server memory limit, the buffer pool, the plan cache, and query workspace memory trade memory among themselves.

Key Specifications

ItemValue
Execution modelOne process (sqlservr), thread model. SQLOS does the scheduling
SchedulerOne per logical CPU (sys.dm_os_schedulers). Only one worker runs at a time on a scheduler
Scheduling methodCooperative. A worker yields on its own when it uses its quantum (4ms) or has to wait
Worker count limitmax worker threads, default 0 (automatic). On 64-bit, 512 for 4 CPUs or fewer, and for more (up to 64) 512 + (number of CPUs − 4) × 16
Connection count limituser connections, default 0 = up to 32,767
Connections and workersA session uses no worker while idle. When a request arrives, a task is bound to a worker
Memory upper limitmax server memory (MB), default 2,147,483,647 (effectively unlimited). Can be changed while running
Memory lower limitmin server memory (MB), default 0. Memory once acquired is not returned below this value
Query workspace memoryMemory grant. The needed amount is reserved before execution. At least min memory per query (default 1,024KB)
Parallel executionmax degree of parallelism (default 0), cost threshold for parallelism (default 5)
Operating system cacheBypassed
LinuxThe same engine runs on top of the SQLPAL layer. The memory limit is memory.memorylimitmb (MSSQL_MEMORY_LIMIT_MB)

Thread Structure

Figure. SQLOS schedulers and workers

flowchart TB
  CL["Client"] -->|"① Connect, log in"| SE["Session<br/>no worker while idle"]
  SE -->|"② A request (batch) arrives"| TK["Task<br/>unit of work that runs the request"]
  TK -->|"③ Bound to a worker"| SC
  subgraph SC ["Scheduler (one per logical CPU)"]
    RN["Running worker (RUNNING)<br/>one per scheduler"]
    RQ["Run queue (RUNNABLE)<br/>waiting for a CPU"]
    WL["Waiter list (SUSPENDED)<br/>waiting for locks, I/O, memory"]
  end
  RN -->|"Yields after using the 4ms quantum"| RQ
  RN -->|"When it has to wait"| WL
  WL -->|"When the resource is granted"| RQ
  RQ -->|"When its turn comes"| RN
  subgraph SYS ["System tasks (background)"]
    LW["LOG WRITER"]
    CP["CHECKPOINT, RECOVERY WRITER"]
    LZ["LAZY WRITER"]
    LM["LOCK MONITOR, RESOURCE MONITOR"]
  end
  subgraph DISK ["Disk"]
    DF["Data file .mdf"]
    LF["Transaction log file .ldf"]
  end
  LW -->|"Write log blocks"| LF
  CP -->|"Write dirty pages"| DF
  LZ -->|"Write to free buffers"| DF

Diagram description: The upper part shows how a request gets a worker, and the middle box is the inside of one scheduler.

  1. When a client logs in, a Session is created (①). A session is a structure that holds only state such as login information and SET options, and it uses no thread while it has no request. Ten thousand idle connections do not mean ten thousand threads.
  2. When a request (a batch or an RPC) arrives (②), a Task is created to run it, assigned to one scheduler, and bound to a worker (③). A parallel query creates several tasks and spreads them over several schedulers.
  3. The three compartments inside the Scheduler box are worker states. Each scheduler has only one Running worker. After using its 4ms quantum, a worker moves itself to the end of the Run queue, and if it has to wait for a lock or I/O, it goes to the Waiter list. Even after getting what it was waiting for, a worker does not run immediately; it passes through the run queue once.
  4. So the time a request waits splits into two kinds. Time on the waiter list is resource wait, and time on the run queue is signal wait (CPU wait). If signal_wait_time_ms in sys.dm_os_wait_stats is large, the CPU is short.
  5. The System tasks box holds background work that runs on the same schedulers as user requests. LOG WRITER writes log blocks to the Transaction log file, and CHECKPOINT, RECOVERY WRITER and LAZY WRITER write dirty pages to the Data file.

Terms

TermMeaningWhere to look
ConnectionA network connection (TDS)sys.dm_exec_connections
SessionA logged-in state. Session ID (SPID)sys.dm_exec_sessions
RequestThe batch or RPC currently runningsys.dm_exec_requests
TaskThe unit of work that runs a request. With parallelism, several per requestsys.dm_os_tasks
WorkerA SQLOS logical thread that runs a task. Bound to one operating system threadsys.dm_os_workers
ThreadAn operating system threadsys.dm_os_threads
SchedulerTakes charge of one logical CPU and runs workers in turnsys.dm_os_schedulers

System tasks

Task (command)What it does
LOG WRITERWrites the log buffer (log blocks) to the transaction log file. A commit responds only after this write finishes
CHECKPOINTWrites dirty pages at automatic and manual checkpoints
RECOVERY WRITERAt indirect checkpoints (TARGET_RECOVERY_TIME), keeps writing dirty pages to meet the recovery time target
LAZY WRITERWhen free buffers run short, evicts pages unused for the longest time (writing them first if dirty). Also runs when memory is returned to the operating system
LOCK MONITORPeriodically looks for deadlocks and picks a victim
RESOURCE MONITORDetects memory pressure and makes the caches shrink
GHOST CLEANUPPhysically removes records that were only marked as deleted from pages
SIGNAL HANDLER, TRACE QUEUE TASK, XE DISPATCHERHandle shutdown signals and deliver traces and extended events

When workers run short. When the worker count reaches max worker threads, new requests wait for a worker (THREADPOOL wait). This happens when requests blocked on locks pile up while holding workers, or when many queries with a high degree of parallelism run at once. Regular logins are blocked at that point, so connect through the dedicated administrator connection (DAC), which uses a separate scheduler, and look for the cause.

A worker that does not yield. Because scheduling is cooperative, if a worker does not yield for a long time, other workers on the same scheduler starve. SQL Server detects this and writes non-yielding scheduler to the error log.

Memory Structure

Figure. Memory under max server memory

block-beta
  columns 6
  t1["Area bounded by max server memory: shared out by memory clerks"]:6
  bp["Buffer pool<br/>data and index pages (8KB)"]:3 pc["Plan cache<br/>compiled execution plans"]:2 qm["Query workspace memory<br/>memory grants"]
  lk["Lock manager"] lp["Log pool"] mc["Metadata cache"] cs["Columnstore pool"] xt["In-Memory OLTP"] ot["Other clerks"]
  t2["Outside max server memory"]:6
  ts["Worker thread stacks"]:2 ex["External modules<br/>extended procedures, linked server providers"]:2 os["SQLOS and the executable itself"]:2
  class t1,t2 plain
  class bp data
  class pc slot
  class qm hot
  class lk,lp,mc,cs,xt,ot meta
  class ts,ex,os muted

Diagram description: The top two rows are the area bounded by max server memory, and the bottom row is outside it.

  • Engine components receive memory through a window called a memory clerk, and the usage per clerk appears in sys.dm_os_memory_clerks. The Buffer pool is MEMORYCLERK_SQLBUFFERPOOL, the Plan cache is CACHESTORE_SQLCP (ad hoc and prepared statements) and CACHESTORE_OBJCP (procedures and triggers), and Query workspace memory is MEMORYCLERK_SQLQERESERVATIONS.
  • There are no fixed boundaries between the areas. Normally the buffer pool uses almost all the spare memory, and when the plan cache or memory grants need more, RESOURCE MONITOR shrinks the buffer pool and caches to free it.
  • Query workspace memory is the memory used by sorts, hash joins, and hash aggregates. It is not taken a little at a time during execution; before execution starts, SQL Server computes the needed amount from the optimizer's estimated row count and reserves it all at once (the memory grant).
  • The bottom row is not counted in max server memory. For that reason, set max server memory so that it leaves room for the operating system and this area.

Memory grants

ItemDescription
When reservedBefore execution. Computed from the estimated row count and row size
Upper limit for one query25% of the workspace memory the resource pool can give (REQUEST_MAX_MEMORY_GRANT_PERCENT)
If memory is shortWaits for the grant (RESOURCE_SEMAPHORE wait). If the query wait time is exceeded, error 8645
If the estimate was too smallSpills to tempdb during execution (sort and hash warnings)
If the estimate was too largeHolds memory it does not use, so other queries wait
CorrectionMemory grant feedback (batch mode from 2017, row mode from 2019) adjusts the grant for the next execution

Unlike PostgreSQL, where work_mem gives each operation a fixed limit, SQL Server gives each query a different amount based on estimates derived from statistics. When statistics are stale, grants go wrong.

Memory limits and the operating system

  • If max server memory is left at its default, SQL Server grows the buffer pool until the operating system signals memory shortage. Always set it when other processes share the server.
  • On Windows, if you grant the service account the Lock Pages in Memory privilege, the buffer pool is not paged out. sys.dm_os_sys_info.sql_memory_model_desc changes to LOCK_PAGES (or LARGE_PAGES).
  • Resource Governor can split memory grant limits and CPU limits per workload group.

The Path One Statement Takes

Figure. The threads an UPDATE and COMMIT pass through

sequenceDiagram
  participant C as Client
  participant W as Worker thread
  participant M as Memory
  participant L as LOG WRITER
  participant F as Log file
  participant K as CHECKPOINT
  participant D as Data file
  C->>W: UPDATE batch
  W->>M: Find the plan in the plan cache, compile if missing
  W->>M: Modify the page in the buffer pool
  W->>M: Append a log record to the log buffer
  C->>W: COMMIT
  W->>L: Request a flush up to the commit record, WRITELOG wait
  L->>F: Write the log block
  L-->>W: Write complete
  W-->>C: Commit complete
  Note over K,D: From here on, later and independent of the commit
  K->>M: Collect dirty pages
  K->>D: Write pages

Diagram description: Time flows from top to bottom.

  1. The Worker thread that received the batch looks in the plan cache in Memory for a plan with the same text, and if there is none, compiles one and stores it.
  2. It modifies the page in the buffer pool and appends a log record to the log buffer. The old value goes into the log record (transaction log).
  3. At COMMIT, the worker asks LOG WRITER for a flush and goes to the waiter list. This wait is WRITELOG. When LOG WRITER writes the log block to the Log file, the worker wakes up and responds. The commits of several sessions ride together in one log block. If delayed durability is on, the worker does not wait.
  4. Below the Note is later work. CHECKPOINT (or RECOVERY WRITER for indirect checkpoints) writes dirty pages to the Data file.

In the Sandbox

These are values seen in this site's SQL Server sandbox (2022 CU28 Developer, Linux container, MSSQL_MEMORY_LIMIT_MB = 2048).

ItemValue
Operating system processesTwo sqlservr: a watchdog parent (3 threads) and the engine (271 threads)
Logical CPUs / schedulers24 / 24 VISIBLE ONLINE, 1 for the dedicated administrator connection, 11 hidden schedulers
Workers144 (sys.dm_os_workers). Limit max_workers_count = 256
Memory recognized by the engine2,048MB. Target (committed_target_kb) 1,336MB, currently committed 315MB
Memory modelCONVENTIONAL
max server memory2,147,483,647 (the default as is)
Large memory clerksMEMORYCLERK_SOSNODE 70MB, MEMORYCLERK_SQLBUFFERPOOL 41MB, CACHESTORE_SQLCP 26MB, CACHESTORE_PHDR 22MB
System tasks running4 LOG WRITER, CHECKPOINT, RECOVERY WRITER, LAZY WRITER, LOCK MONITOR, 3 RESOURCE MONITOR, and others

Applying the formula above to 24 logical CPUs gives a worker limit of 832, but the sandbox value was 256. In a small-memory environment, the value is set lower than the formula.

Configuration and Inspection

-- CPU, schedulers, worker limit, memory target
SELECT cpu_count, scheduler_count, max_workers_count,
       committed_kb / 1024 AS committed_mb, committed_target_kb / 1024 AS target_mb, sql_memory_model_desc
FROM sys.dm_os_sys_info;

-- Number of tasks waiting to run on each scheduler (a persistent value above 0 means CPU shortage)
SELECT scheduler_id, current_tasks_count, runnable_tasks_count, current_workers_count, active_workers_count
FROM sys.dm_os_schedulers WHERE status = 'VISIBLE ONLINE';

-- Who is using memory
SELECT TOP 10 type, SUM(pages_kb) / 1024 AS mb
FROM sys.dm_os_memory_clerks GROUP BY type ORDER BY SUM(pages_kb) DESC;

-- Memory grants: queries that got one and queries waiting
SELECT session_id, requested_memory_kb, granted_memory_kb, used_memory_kb, wait_time_ms
FROM sys.dm_exec_query_memory_grants;

-- System tasks
SELECT session_id, command, status, wait_type FROM sys.dm_exec_requests WHERE status = 'background';

-- Set the limit
EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
EXEC sp_configure 'max server memory (MB)', 12288; RECONFIGURE;
  • Find the cause of waits in sys.dm_os_wait_stats. SOS_SCHEDULER_YIELD (yielded after using the quantum), THREADPOOL (worker shortage), RESOURCE_SEMAPHORE (waiting for a memory grant), WRITELOG (waiting for a log write), and PAGEIOLATCH_* (reading a page from disk) correspond directly to the structure in this document.
  • In Azure SQL Database, the memory and worker limits are set by the service tier and the number of vCores, and cannot be changed with sp_configure.

Comparison with Other DBMSs

SQL ServerPostgreSQLMySQLOracleKDBS
One connectionA session. A worker per requestA processA threadA server process (dedicated server)A connection inside a per-core reactor
SchedulingCooperative (SQLOS)Operating systemOperating systemOperating systemCooperative (reactor)
Working memoryMemory grant before executionwork_mem (per operation)Session buffersPGA (instance-wide aggregate target)Row count limit
Memory limitOne max server memoryPer-area settingsPer-area settingsSGA_TARGET, PGA_AGGREGATE_LIMITbuffer_pool_frames

The full comparison is in DBMS Architecture at a Glance.

In the Articles

NOTE The worker limit formula and the defaults can vary by version, edition, and platform. This document is written for SQL Server 2022.

Related pages