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

ItemValue
Execution modelOne process, one reactor thread per core
Number of reactorscores, default 1, max 64. Startup is refused if it exceeds the machine's CPU count
CPU pinningReactors 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 unitC++20 coroutine task. No preemption
Scheduling groupsforeground, maintenance, system. Shares 1000 : 100 : 50
Socket I/Oepoll per reactor
Data file I/OBuffered I/O (pread, pwrite). O_DIRECT and io_uring are not used
Buffer poolbuffer_pool_frames. No default (required). One frame is 8KB. The whole instance shares one
Buffer evictionCLOCK. Per-frame usage count (max 5)
WAL buffer1MiB WAL ring (no setting). One WAL stream per instance
Working memoryRow 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 limitNone. Only the buffer pool size and the per-core statistics area size are configured
Max connectionsmax_connections, default 0 (unlimited). reserved_admin_connections default 3
Changing settingsEvery 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.

  1. When there are two or more cores, every reactor opens the same port with SO_REUSEPORT, and the Kernel picks 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.
  2. reactor 0 is the main thread of the process, and from reactor 1 onward they are threads created at startup. A statement runs only on the reactor that holds its connection. There are no parallel queries.
  3. All reactors use the Buffer pool, WAL ring, and Lock table together. 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 when cores is 2 or more. With one core, only the reactor uses them, so no locking is needed.
  4. The WAL writer is the only thread that deliberately blocks on the log device. It fdatasyncs the WAL of statements waiting for commit and, when done, wakes the waiting reactors.
  5. The data file writer and data file syncer threads handle the pwrite and fsync of the dirty pages the checkpoint picked. The four page readers do not return results directly, as the dotted arrow shows. When a single-row SELECT or a SELECT scan 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 with pread.

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 foreground group.
  • ② 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 SELECT yields every 64 pages, an UPDATE or DELETE that 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, and max_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

NameKindCount / intervalWhat it does
reactorThreadcores (default 1)Receives connections, parses frames, executes statements, runs timer work
WAL writerThread1Periodic sync for the relaxed level, group commit sync when there are two or more cores, deletion of used-up segments
Data file syncerThread1Every fsync of the data file. Aborts the process on failure
Data file writerThread1pwrite of the pages the checkpoint writes
Page readerThread4 (fixed)Preloads pages missing from the buffer pool into the operating system cache
WAL segment preparerThread1 (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 archiverThreadOnly when archive_dir or archive_command is givenArchives used-up segments
CheckpointReactor task (system)checkpoint_interval_ms 5,000ms. Cores take turnsWrites dirty pages in batches of 64 pages and records the checkpoint position
writebackTimer on core 050msKeeps a reserve of free frames (1/16 to 1/8 of capacity), empties the dirty eviction queue
WAL drainReactor hook + timerEvery turn, wal_drain_interval_us 1,000µsGroup commit
Plan statistics cleanupTimer on core 01 secondMerges per-core statistics and refreshes the statistics used for join order
Cabin controllerTimer on core 010 seconds (cabin_optimizer, default off)Creates and drops Cabins
ASH sampleInside the reactor loopash_interval_ms 1,000msRecords 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_frames is the frame count of the whole instance and is not divided by the core count. The WAL ring is 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. The Lock table is split into 64 partitions and is not persisted to disk. The Cabin store lives 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 cache holds table names and definitions. It has no size limit or eviction, and instead it is discarded entirely when DDL occurs. The Plan memo remembers 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

ItemDescription
Sizebuffer_pool_frames × 8KB. Each frame also costs about 48 bytes of metadata plus the page table
Minimum sizeResident page count + 256 frames. Startup is refused if smaller
AllocationGrows in batches of 1,024 frames (about 8MiB) when needed. A batch, once grown, is not returned
EvictionCLOCK. The hand sweeps, lowering usage counts, and picks a frame whose count is 0
Free framesKept between 1/16 and 1/8 of capacity. The 50ms writeback on core 0 refills them
When fullThe statement fails with ResourceExhausted
Resident (never evicted) pagesSystem pages (below number 128), pinned Cabin pages
Other things in the buffer poolUndo pages, var-heap pages that hold long values, Waystone trace pages
LatchesOne 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

SettingDefaultWhen exceeded
sort_max_rows1,048,576 rowsThe statement fails. No disk sort
aggregate_max_groups65,536 groupsThe statement fails
aggregate_max_distinct1,048,576The statement fails
join_build_max_rows65,536 rows (24 bytes per entry)Gives up building the hash and falls back to the lookup method
max_rows_touched100,000,000The statement fails. 0 means unlimited
max_insert_rows1,024 rowsThe statement is rejected
max_locks_per_txn65,536The 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.

  1. The reactor compiles the UPDATE into a step chain and runs it. In the buffer pool of Shared memory it 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.
  2. The task running COMMIT puts 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.
  3. 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 writer writes to the WAL segment, runs fdatasync, and then wakes the waiting reactors. All transactions that committed in the same turn ride on this one sync.
  4. What is below the Note happens later. The Checkpoint task runs on the reactor in the system group, picks dirty pages 64 at a time and hands them over, and the auxiliary threads do the actual pwrite and fsync. 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

FileDefault locationContent
Data filedata_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 segmentswal_dir (<data_file>.wal)wal-0-<number>.log, 64MiB per segment. Segments the checkpoint has passed are deleted
Server logkdb.log in log_dirStartup, checkpoints, warnings
Archivearchive_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.

ItemValue
Operating system processOne kds_server
Thread count8
Process RSSAbout 15MB. The buffer pool is not reserved in advance and grows as it is used
pool_budget / pool_slots / pool_resident65,536 / 1,024 / 28
pool_hits / pool_misses8,818 / 28
CheckpointEvery 5 seconds, with core=0 and core=1 alternating in the log
Data filekds.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 fieldMeaning
pool_budget, pool_residentThe buffer pool's frame limit and the number of pages currently loaded
pool_hits, pool_missesBuffer pool hits and misses
pool_refusedNumber of times the buffer pool was full and refused
wal_syncs, wal_group_commits, wal_mean_group_batchNumber of device syncs, number of group commits, and the average number of commits carried by one sync
wal_ring_fullNumber of times the WAL ring was full
sched_iterations, sched_idle_blocksNumber of reactor turns and number of times it went into waiting
sched_<group>_longest_poll_us, sched_<group>_polls_over_10msThe time of the longest-running task in one go, and the number of times it did not yield for over 10ms
connection_sessions, connection_refusalsCurrent 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

KDBSPostgreSQLMySQLOracleSQL Server
One connectionA connection inside a per-core reactorProcessThreadServer process (dedicated server)Session. A worker per request
SchedulingCooperative, one thread per coreOperating systemOperating systemOperating systemCooperative, a scheduler per CPU with several workers
Parallel queryNoneParallel workersPartial (parallel scan)Parallel execution serversParallel plans
Working memoryRow count limit, fails when exceededwork_mem, temp files when exceededSession buffers, temp files when exceededPGA, temporary tablespace when exceededMemory grant, tempdb when exceeded
Buffer pool sizeRequired setting, no default128MB128MBAutomatic from SGA_TARGETAutomatic 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 earlier v3.4 image, 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