KDBS Memory and Thread Architecture
A KDBS server is one kds_server process. At startup it creates as many reactor threads as the cores setting, and each reactor runs the statements of the connections that arrive on its core from start to finish (thread-per-core). A reactor is not a thread pool that the operating system preempts and swaps. It is a cooperative event loop in which a statement yields by itself at fixed points. Only work that can block for a long time on disk (WAL sync, data file sync, reading a page that is not in the buffer pool) is moved out to a small number of auxiliary threads. For memory, all cores share the buffer pool and WAL ring, of which the instance has exactly one, while the catalog cache and statistics are kept separately per core.
Key Specifications
| Item | Value |
|---|---|
| Execution model | One process, one reactor thread per core |
| Number of reactors | cores, default 1, max 64. Startup is refused if it exceeds the machine's CPU count |
| CPU pinning | Reactors from number 1 onward are pinned to the CPU with the same number (on failure it only logs a warning and continues). Reactor 0 is pinned only when reactor_cpus is given |
| Statement execution unit | C++20 coroutine task. No preemption |
| Scheduling groups | foreground, maintenance, system. Shares 1000 : 100 : 50 |
| Socket I/O | epoll per reactor |
| Data file I/O | Buffered I/O (pread, pwrite). O_DIRECT and io_uring are not used |
| Buffer pool | buffer_pool_frames. No default (required). One frame is 8KB. The whole instance shares one |
| Buffer eviction | CLOCK. Per-frame usage count (max 5) |
| WAL buffer | 1MiB WAL ring (no setting). One WAL stream per instance |
| Working memory | Row count limits. sort_max_rows 1,048,576, aggregate_max_groups 65,536, join_build_max_rows 65,536. Does not spill to disk |
| Total memory limit | None. Only the buffer pool size and the per-core statistics area size are configured |
| Max connections | max_connections, default 0 (unlimited). reserved_admin_connections default 3 |
| Changing settings | Every key is read only at startup. No reload |
Thread Architecture
Figure. Reactors and auxiliary threads
flowchart TB
CL["Client"] -->|"connect (KWP/1)"| KN["Kernel<br/>assigns one core via SO_REUSEPORT"]
KN --> R0
KN --> R1
subgraph RS ["Reactor threads (cores of them)"]
R0["reactor 0<br/>main thread"]
R1["reactor 1"]
end
subgraph SH ["Instance shared memory structures"]
BP["Buffer pool"]
WR["WAL ring"]
LT["Lock table"]
end
subgraph AUX ["Auxiliary threads"]
WW["1 WAL writer"]
DS["1 data file writer<br/>1 data file syncer"]
PR["4 page readers"]
end
subgraph DISK ["Disk"]
WF["WAL segment files"]
DF["Data file kds.db"]
end
R0 -->|"read and modify pages"| BP
R1 -->|"read and modify pages"| BP
R0 -->|"WAL records"| WR
R1 -->|"WAL records"| WR
R0 -->|"row locks"| LT
WW -->|"fdatasync"| WF
DS -->|"pwrite, fsync"| DF
PR -.->|"prefetch missing pages"| DF
Diagram explanation: The reactors in the middle row execute statements, and the auxiliary threads below them take over the work that blocks on disk.
- When there are two or more cores, every reactor opens the same port with
SO_REUSEPORT, and theKernelpicks one reactor per connection. No dedicated thread accepts connections. A connection stays on the reactor that received it, and can be moved to a less busy core at the moment it starts a transaction. reactor 0is the main thread of the process, and fromreactor 1onward they are threads created at startup. A statement runs only on the reactor that holds its connection. There are no parallel queries.- All reactors use the
Buffer pool,WAL ring, andLock tabletogether. A page that core 1 has read is not read from disk again by core 0. The latches of these structures are turned on only whencoresis 2 or more. With one core, only the reactor uses them, so no locking is needed. - The
WAL writeris the only thread that deliberately blocks on the log device. Itfdatasyncs the WAL of statements waiting for commit and, when done, wakes the waiting reactors. - The
data file writeranddata file syncerthreads handle thepwriteandfsyncof the dirty pages the checkpoint picked. The fourpage readersdo not return results directly, as the dotted arrow shows. When a single-rowSELECTor aSELECTscan meets a page that is not in the buffer pool, they load that page into the operating system cache and wake the reactor, so the reactor does not stall waiting for disk. In all other cases, the reactor reads a page missing from the buffer pool directly withpread.
One Turn of the Reactor
Figure. Reactor event loop
flowchart LR
A["① Reap I/O completions<br/>epoll"] --> B["② Run timers"]
B --> C["③ Run tasks<br/>up to 64 per turn"]
C --> D["④ WAL drain hook<br/>group commit"]
D --> E["⑤ Submit I/O"]
E --> F["⑥ Wait if nothing to do<br/>up to 10ms"]
F --> A
Diagram explanation: The reactor loops from ① through ⑥ endlessly.
- ① Reap I/O completions. It finds connections that have something to read on their socket, parses frames, and registers a statement as a task in the
foregroundgroup. - ② Run timers. Periodic work such as the checkpoint interval (
checkpoint_interval_ms, default 5,000ms), the 50ms writeback, and the 1-second plan statistics cleanup is registered as tasks here. - ③ Run tasks. It picks and runs tasks in proportion to the group shares (1000 : 100 : 50). A task runs until it stops by itself. The outer scan of a
SELECTyields every 64 pages, anUPDATEorDELETEthat finds rows by scan yields between leaves, and index creation yields every fixed number of leaves. Lock waits and commit waits are not yields but parking the task (park). Single-row lookups, the inner lookup of a join, and index lookups do not yield midway, andmax_rows_touched(default 100 million rows) is the upper bound. - ④ WAL drain hook. It sends the records that the statements run in this turn put into the WAL ring to the device in one go. Group commit, where several commits share one
fsync, happens at this point. - ⑥ Wait. If there is no task to run, it sleeps up to 10ms until the next timer or I/O. If another core has something to wake, it writes the shared state first and wakes it with an eventfd. There is no message queue between cores.
Threads and Periodic Work
| Name | Kind | Count / interval | What it does |
|---|---|---|---|
| reactor | Thread | cores (default 1) | Receives connections, parses frames, executes statements, runs timer work |
| WAL writer | Thread | 1 | Periodic sync for the relaxed level, group commit sync when there are two or more cores, deletion of used-up segments |
| Data file syncer | Thread | 1 | Every fsync of the data file. Aborts the process on failure |
| Data file writer | Thread | 1 | pwrite of the pages the checkpoint writes |
| Page reader | Thread | 4 (fixed) | Preloads pages missing from the buffer pool into the operating system cache |
| WAL segment preparer | Thread | 1 (started when first needed) | When the current segment is half full, creates the next 64MiB segment ahead of time, fills it with zeros, and syncs it |
| WAL archiver | Thread | Only when archive_dir or archive_command is given | Archives used-up segments |
| Checkpoint | Reactor task (system) | checkpoint_interval_ms 5,000ms. Cores take turns | Writes dirty pages in batches of 64 pages and records the checkpoint position |
| writeback | Timer on core 0 | 50ms | Keeps a reserve of free frames (1/16 to 1/8 of capacity), empties the dirty eviction queue |
| WAL drain | Reactor hook + timer | Every turn, wal_drain_interval_us 1,000µs | Group commit |
| Plan statistics cleanup | Timer on core 0 | 1 second | Merges per-core statistics and refreshes the statistics used for join order |
| Cabin controller | Timer on core 0 | 10 seconds (cabin_optimizer, default off) | Creates and drops Cabins |
| ASH sample | Inside the reactor loop | ash_interval_ms 1,000ms | Records session state samples into per-core rings |
Memory Structure
Figure. Instance-shared area and per-core area
block-beta
columns 6
t1["Instance-shared: used together by all reactors"]:6
bp["Buffer pool<br/>8KB frames, buffer_pool_frames"]:3 wr["WAL ring<br/>1MiB"] lt["Lock table<br/>64 partitions"] cb["Cabin store"]
vw["Visibility window<br/>running transactions"]:2 pl["Captured plans<br/>administrator plans"]:2 cl["Connection limit<br/>cancel registry"]:2
t2["Per core: separate per reactor, no latches"]:6
cc["Catalog cache"] pm["Plan memo"] ss["Statement stats<br/>4,096 shapes"] as["ASH ring<br/>4MiB"] tx["Transaction manager"] cn["Connections and sessions"]
t3["Per connection and statement"]:6
io["I/O buffers"]:2 ps["64 named statements<br/>64 portals"]:2 wm["Sort, aggregate, join working memory<br/>limited by row count"]:2
class t1,t2,t3 plain
class bp data
class wr hot
class lt,cb,vw,pl,cl meta
class cc,pm,ss,as,tx,cn slot
class io,ps,wm muted
Diagram explanation: The sharing scope narrows from the top.
- The two instance-shared rows are structures of which the process has only one each. For the
Buffer pool,buffer_pool_framesis the frame count of the whole instance and is not divided by the core count. TheWAL ringis a 1MiB buffer that collects WAL records not yet written to the device. When it is full, an append fails, and it is retried after emptying. TheLock tableis split into 64 partitions and is not persisted to disk. TheCabin storelives only in memory and is emptied on restart. - The per core row consists of structures that a single reactor uses alone, so there are no latches. The
Catalog cacheholds table names and definitions. It has no size limit or eviction, and instead it is discarded entirely when DDL occurs. ThePlan memoremembers only the join order in 512 × 2 slots.Statement stats(sys.statement_stats) holds 4,096 shapes per core, about 5MB. - The per connection and statement row is memory that appears and disappears with requests. Working memory for sort, aggregate, and join has no byte setting and is limited by row count. When the limit is exceeded, it does not spill to disk and fails the statement.
Buffer Pool
| Item | Description |
|---|---|
| Size | buffer_pool_frames × 8KB. Each frame also costs about 48 bytes of metadata plus the page table |
| Minimum size | Resident page count + 256 frames. Startup is refused if smaller |
| Allocation | Grows in batches of 1,024 frames (about 8MiB) when needed. A batch, once grown, is not returned |
| Eviction | CLOCK. The hand sweeps, lowering usage counts, and picks a frame whose count is 0 |
| Free frames | Kept between 1/16 and 1/8 of capacity. The 50ms writeback on core 0 refills them |
| When full | The statement fails with ResourceExhausted |
| Resident (never evicted) pages | System pages (below number 128), pinned Cabin pages |
| Other things in the buffer pool | Undo pages, var-heap pages that hold long values, Waystone trace pages |
| Latches | One frame table latch and a page latch per frame. Not partitioned. Off when there is one core |
Data files are read and written with buffered I/O through the operating system page cache. As in PostgreSQL, the same page can exist in both the buffer pool and the operating system cache.
Working Memory Limits
| Setting | Default | When exceeded |
|---|---|---|
sort_max_rows | 1,048,576 rows | The statement fails. No disk sort |
aggregate_max_groups | 65,536 groups | The statement fails |
aggregate_max_distinct | 1,048,576 | The statement fails |
join_build_max_rows | 65,536 rows (24 bytes per entry) | Gives up building the hash and falls back to the lookup method |
max_rows_touched | 100,000,000 | The statement fails. 0 means unlimited |
max_insert_rows | 1,024 rows | The statement is rejected |
max_locks_per_txn | 65,536 | The transaction fails |
The Path of One Statement
Figure. Threads that UPDATE and COMMIT pass through (two or more cores, group level)
sequenceDiagram
participant C as Client
participant R as reactor
participant M as Shared memory
participant W as WAL writer
participant F as WAL segment
participant K as Checkpoint task
participant D as Data file
C->>R: UPDATE
R->>M: Modify the page in the buffer pool, record an Undo page
R->>M: Append records to the WAL ring
C->>R: COMMIT
R->>M: Append the commit record, this task waits
R->>W: Hand over this turn's WAL (drain hook)
W->>F: pwrite and fdatasync
W-->>R: Write complete, wake the reactor
R-->>C: Commit complete
Note over K,D: From here on, later and independent of the commit
K->>M: Pick dirty pages 64 at a time
K->>D: The writer thread does pwrite, the syncer thread does fsync
Diagram explanation: Time flows from top to bottom.
- The
reactorcompiles theUPDATEinto a step chain and runs it. In the buffer pool ofShared memoryit modifies the page in place, leaves the previous value in an Undo page, and puts the WAL records of both changes into the WAL ring. - The task running
COMMITputs a commit record into the ring and then sleeps until that position is recorded on the device. The reactor does not stall and keeps running the tasks of other connections. - When all tasks of this turn finish, the drain hook sends the records accumulated in the ring all at once. With one core, the reactor syncs directly. With two or more, the
WAL writerwrites to theWAL segment, runsfdatasync, and then wakes the waiting reactors. All transactions that committed in the same turn ride on this one sync. - What is below the
Notehappens later. TheCheckpoint taskruns on the reactor in thesystemgroup, picks dirty pages 64 at a time and hands them over, and the auxiliary threads do the actualpwriteandfsync. Before writing a page, the storage layer checks that the WAL for that page is already on the device.
The strict, group, and relaxed levels, which change the meaning of the commit response, are covered in Durability Levels.
Files on Disk
| File | Default location | Content |
|---|---|---|
| Data file | data_file (kds.db) | A single file. Page number × 8KB is the position in the file. Page 0 is the superblock. Grows in units of 64 pages |
| WAL segments | wal_dir (<data_file>.wal) | wal-0-<number>.log, 64MiB per segment. Segments the checkpoint has passed are deleted |
| Server log | kdb.log in log_dir | Startup, checkpoints, warnings |
| Archive | archive_dir (optional) | Copies of used-up WAL segments |
In the Sandbox
The KDBS sandbox on this site starts with cores = 2, buffer_pool_frames = 65536 (512MiB), and max_connections = 32. These are the values observed there.
| Item | Value |
|---|---|
| Operating system process | One kds_server |
| Thread count | 8 |
| Process RSS | About 15MB. The buffer pool is not reserved in advance and grows as it is used |
pool_budget / pool_slots / pool_resident | 65,536 / 1,024 / 28 |
pool_hits / pool_misses | 8,818 / 28 |
| Checkpoint | Every 5 seconds, with core=0 and core=1 alternating in the log |
| Data file | kds.db about 725MiB, with a kds.db.wal directory beside it |
Configuration and Inspection
-- The whole instance state (section, field, value). Shows the values of the core this connection is on
SHOW META;
-- Buffer pool, WAL, reactor, connections
SELECT field, value FROM sys.meta WHERE section = 'pool';
SELECT field, value FROM sys.meta WHERE section = 'wal';
SELECT field, value FROM sys.meta WHERE section = 'sched';
SELECT field, value FROM sys.meta WHERE section = 'connections';
-- What was waited for: per core, per session
SELECT core, event, class, count, total_us, max_us FROM sys.wait_stats;
SELECT session_id, state, event, elapsed_us, txn_age_us FROM sys.session_state;
-- Recent checkpoints
SELECT * FROM sys.checkpoints;
SHOW META field | Meaning |
|---|---|
pool_budget, pool_resident | The buffer pool's frame limit and the number of pages currently loaded |
pool_hits, pool_misses | Buffer pool hits and misses |
pool_refused | Number of times the buffer pool was full and refused |
wal_syncs, wal_group_commits, wal_mean_group_batch | Number of device syncs, number of group commits, and the average number of commits carried by one sync |
wal_ring_full | Number of times the WAL ring was full |
sched_iterations, sched_idle_blocks | Number of reactor turns and number of times it went into waiting |
sched_<group>_longest_poll_us, sched_<group>_polls_over_10ms | The time of the longest-running task in one go, and the number of times it did not yield for over 10ms |
connection_sessions, connection_refusals | Current session count and the number of connections refused because of the limit |
Run the statements above in an administration tool. The sandbox blocks the sys views.
Comparison with Other DBMSs
| KDBS | PostgreSQL | MySQL | Oracle | SQL Server | |
|---|---|---|---|---|---|
| One connection | A connection inside a per-core reactor | Process | Thread | Server process (dedicated server) | Session. A worker per request |
| Scheduling | Cooperative, one thread per core | Operating system | Operating system | Operating system | Cooperative, a scheduler per CPU with several workers |
| Parallel query | None | Parallel workers | Partial (parallel scan) | Parallel execution servers | Parallel plans |
| Working memory | Row count limit, fails when exceeded | work_mem, temp files when exceeded | Session buffers, temp files when exceeded | PGA, temporary tablespace when exceeded | Memory grant, tempdb when exceeded |
| Buffer pool size | Required setting, no default | 128MB | 128MB | Automatic from SGA_TARGET | Automatic within the allowed memory |
SQL Server's SQLOS is also cooperative, but it has several workers per scheduler, and when a worker waits it switches to another worker. KDBS has only one thread per core, and what switches is a coroutine task. The full comparison is in DBMS Architecture at a Glance.
NOTE KDBS is an engine under development. The structure and defaults in this document are based on source
v3.5.1, and the sandbox uses an earlierv3.4image, so details such as the thread count can differ. Where the source's design document and the code disagree (for example, the design document says every reactor is pinned to a CPU, but the code does not pin reactor 0 by default), the code was followed.
Related pages
- DBMS Architecture at a Glance
- KDBS
- KDBS connections, portals, and statement cache
- Durability Levels (strict, group, relaxed)
- Transactions and Isolation Levels
- Step Chain and ANALYZE
- Cabin and Secondary Indexes
- Waystone
- PostgreSQL Memory and Process Architecture
- MySQL memory and thread structure
- Oracle memory and process structure
- SQL Server Memory and Thread Structure