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
| Item | Value |
|---|---|
| Execution model | One process (sqlservr), thread model. SQLOS does the scheduling |
| Scheduler | One per logical CPU (sys.dm_os_schedulers). Only one worker runs at a time on a scheduler |
| Scheduling method | Cooperative. A worker yields on its own when it uses its quantum (4ms) or has to wait |
| Worker count limit | max 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 limit | user connections, default 0 = up to 32,767 |
| Connections and workers | A session uses no worker while idle. When a request arrives, a task is bound to a worker |
| Memory upper limit | max server memory (MB), default 2,147,483,647 (effectively unlimited). Can be changed while running |
| Memory lower limit | min server memory (MB), default 0. Memory once acquired is not returned below this value |
| Query workspace memory | Memory grant. The needed amount is reserved before execution. At least min memory per query (default 1,024KB) |
| Parallel execution | max degree of parallelism (default 0), cost threshold for parallelism (default 5) |
| Operating system cache | Bypassed |
| Linux | The 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.
- When a client logs in, a
Sessionis created (①). A session is a structure that holds only state such as login information andSEToptions, and it uses no thread while it has no request. Ten thousand idle connections do not mean ten thousand threads. - When a request (a batch or an RPC) arrives (②), a
Taskis 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. - The three compartments inside the
Schedulerbox are worker states. Each scheduler has only oneRunning worker. After using its 4ms quantum, a worker moves itself to the end of theRun queue, and if it has to wait for a lock or I/O, it goes to theWaiter list. Even after getting what it was waiting for, a worker does not run immediately; it passes through the run queue once. - 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_msinsys.dm_os_wait_statsis large, the CPU is short. - The
System tasksbox holds background work that runs on the same schedulers as user requests.LOG WRITERwrites log blocks to theTransaction log file, andCHECKPOINT, RECOVERY WRITERandLAZY WRITERwrite dirty pages to theData file.
Terms
| Term | Meaning | Where to look |
|---|---|---|
| Connection | A network connection (TDS) | sys.dm_exec_connections |
| Session | A logged-in state. Session ID (SPID) | sys.dm_exec_sessions |
| Request | The batch or RPC currently running | sys.dm_exec_requests |
| Task | The unit of work that runs a request. With parallelism, several per request | sys.dm_os_tasks |
| Worker | A SQLOS logical thread that runs a task. Bound to one operating system thread | sys.dm_os_workers |
| Thread | An operating system thread | sys.dm_os_threads |
| Scheduler | Takes charge of one logical CPU and runs workers in turn | sys.dm_os_schedulers |
System tasks
Task (command) | What it does |
|---|---|
LOG WRITER | Writes the log buffer (log blocks) to the transaction log file. A commit responds only after this write finishes |
CHECKPOINT | Writes dirty pages at automatic and manual checkpoints |
RECOVERY WRITER | At indirect checkpoints (TARGET_RECOVERY_TIME), keeps writing dirty pages to meet the recovery time target |
LAZY WRITER | When 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 MONITOR | Periodically looks for deadlocks and picks a victim |
RESOURCE MONITOR | Detects memory pressure and makes the caches shrink |
GHOST CLEANUP | Physically removes records that were only marked as deleted from pages |
SIGNAL HANDLER, TRACE QUEUE TASK, XE DISPATCHER | Handle 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. TheBuffer poolisMEMORYCLERK_SQLBUFFERPOOL, thePlan cacheisCACHESTORE_SQLCP(ad hoc and prepared statements) andCACHESTORE_OBJCP(procedures and triggers), andQuery workspace memoryisMEMORYCLERK_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 MONITORshrinks the buffer pool and caches to free it. Query workspace memoryis 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, setmax server memoryso that it leaves room for the operating system and this area.
Memory grants
| Item | Description |
|---|---|
| When reserved | Before execution. Computed from the estimated row count and row size |
| Upper limit for one query | 25% of the workspace memory the resource pool can give (REQUEST_MAX_MEMORY_GRANT_PERCENT) |
| If memory is short | Waits for the grant (RESOURCE_SEMAPHORE wait). If the query wait time is exceeded, error 8645 |
| If the estimate was too small | Spills to tempdb during execution (sort and hash warnings) |
| If the estimate was too large | Holds memory it does not use, so other queries wait |
| Correction | Memory 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 memoryis 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_descchanges toLOCK_PAGES(orLARGE_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.
- The
Worker threadthat received the batch looks in the plan cache inMemoryfor a plan with the same text, and if there is none, compiles one and stores it. - 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).
- At
COMMIT, the worker asksLOG WRITERfor a flush and goes to the waiter list. This wait isWRITELOG. When LOG WRITER writes the log block to theLog 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. - Below the
Noteis later work.CHECKPOINT(orRECOVERY WRITERfor indirect checkpoints) writes dirty pages to theData 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).
| Item | Value |
|---|---|
| Operating system processes | Two sqlservr: a watchdog parent (3 threads) and the engine (271 threads) |
| Logical CPUs / schedulers | 24 / 24 VISIBLE ONLINE, 1 for the dedicated administrator connection, 11 hidden schedulers |
| Workers | 144 (sys.dm_os_workers). Limit max_workers_count = 256 |
| Memory recognized by the engine | 2,048MB. Target (committed_target_kb) 1,336MB, currently committed 315MB |
| Memory model | CONVENTIONAL |
max server memory | 2,147,483,647 (the default as is) |
| Large memory clerks | MEMORYCLERK_SOSNODE 70MB, MEMORYCLERK_SQLBUFFERPOOL 41MB, CACHESTORE_SQLCP 26MB, CACHESTORE_PHDR 22MB |
| System tasks running | 4 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), andPAGEIOLATCH_*(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 Server | PostgreSQL | MySQL | Oracle | KDBS | |
|---|---|---|---|---|---|
| One connection | A session. A worker per request | A process | A thread | A server process (dedicated server) | A connection inside a per-core reactor |
| Scheduling | Cooperative (SQLOS) | Operating system | Operating system | Operating system | Cooperative (reactor) |
| Working memory | Memory grant before execution | work_mem (per operation) | Session buffers | PGA (instance-wide aggregate target) | Row count limit |
| Memory limit | One max server memory | Per-area settings | Per-area settings | SGA_TARGET, PGA_AGGREGATE_LIMIT | buffer_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
- DBMS Architecture at a Glance
- SQL Server / Azure SQL
- SQL Server Connections, Cursors, and Plan Cache
- SQL Server Buffer Pool
- SQL Server Transaction Log
- Delayed Durability
- Operating system cache and direct I/O
- PostgreSQL Memory and Process Architecture
- MySQL memory and thread structure
- Oracle memory and process structure
- KDBS Memory and Thread Architecture