KDBS connections, portals, and statement cache
A KDBS connection is a single struct inside a reactor, so it is lightweight (Memory and thread architecture), and the way it handles statements sits at the opposite end from other DBMSs. It does not cache a compiled execution plan anywhere. Even if you prepare a named statement, it re-checks names and recompiles into a step chain on every execution. Compilation is cheap because there is no plan search and the only choice is the join order. Instead, statistics and join orders hang off the statement shape (fetch_id), which has the literals removed, and deleting any of them never changes a result. There are no SQL statements such as DECLARE CURSOR and PREPARE; the same work is done with protocol frames.
Key specs
| Item | Value |
|---|---|
| Protocol | KWP/1. Default TCP port 15432, loopback (127.0.0.1) only by default. Not PostgreSQL wire compatible |
| Frame | 8-byte header (length 4, type 1, flags 1, reserved 2). Maximum 16MiB per frame |
| Encryption | TLS 1.3. When on, TLS starts from the first byte (no mid-stream switch, no plaintext fallback) |
| Authentication | None (default) or SCRAM-SHA-256 (PBKDF2, 4,096 iterations) |
| Maximum connections | max_connections, default 0 (no limit). Counts sessions that finished the handshake |
| Concurrent statements per connection | One. Pipelining (sending frames back to back without waiting for responses) is possible |
| Named statements | 64 per session |
| Portals | 64 per session. Dropped after 60 seconds idle |
| Result a portal can hold | 16MiB of encoded rows. The statement fails if exceeded |
| Row batch | Batched toward 64KiB per send |
| Compiled plan cache | None. Compiled on every execution |
| Result cache | None |
SQL PREPARE, DECLARE CURSOR, FETCH | None (rejected as unknown commands) |
| Transaction lifetime limit | txn_lifetime_ceiling_ms, default 60,000ms. Rolled back if exceeded |
| Idle session limit | idle_session_timeout_s, default 0 (none). tcp_keepalive_s default 60 |
Connections
Figure. The handshake and one statement
sequenceDiagram
participant C as Client
participant R as Connection in the reactor
C->>R: C_HELLO (protocol version, feature bits, auth method)
R->>C: S_AUTH (SCRAM server message)
C->>R: C_AUTH (SCRAM client message)
R->>C: S_HELLO (session ID, cancel key, server version)
R->>C: S_READY (transaction state)
C->>R: C_PARSE (statement name, SQL text)
C->>R: C_BIND (portal name, parameter values and types)
C->>R: C_EXECUTE (portal name, max rows)
C->>R: C_SYNC
R->>C: S_PARSE_OK (pattern_id), S_BIND_OK
R->>C: S_ROW_DESC, S_ROW_BATCH
R->>C: S_COMPLETE (tag, rows processed)
R->>C: S_READY
Diagram explanation: Time flows from top to bottom.
- The client starts with
C_HELLO. A server with authentication on does not sendS_HELLOright away; it sends it after the SCRAM exchange ofS_AUTHandC_AUTHfinishes. If authentication fails, the server sends one fixed error sentence inS_AUTHand disconnects. It does not tell the client the reason for the failure. S_HELLOcarries the session ID and the cancel key. A connection that exceedsmax_connectionsreceives aRESOURCE_EXHAUSTEDerror in place ofS_HELLOand is disconnected. The slot is taken when the handshake finishes, so a connection that did not pass authentication does not count toward the connection total.S_READYreports the current transaction state (idle, in a transaction, failed transaction). It arrives again each timeC_SYNCis sent.- A statement is sent as three frames:
C_PARSE,C_BIND,C_EXECUTE. There is no frame dedicated to simple queries; a statement that is not prepared uses the same three frames with the unnamed statement (""). As in the figure, the four frames can be sent together without waiting for responses. If an error occurs partway, the server discards frames up to the nextC_SYNC.
Assigning a connection. With two or more cores, the kernel picks one reactor for each incoming connection, and that connection goes into that reactor's connection table. A connection holds I/O buffers, a frame parser, authentication state, and a session. It does not create a process or thread.
State a session holds. Named statements, portals, an open transaction, and four settings. When the connection drops, all of them disappear and an open transaction is rolled back.
| Session setting | Statement that changes it |
|---|---|
| Namespace | USE <name> |
| Isolation level | SET ISOLATION LEVEL … (Transactions) |
| Durability grade | SET DURABILITY … (Durability grades) |
| Priority | SET PRIORITY … |
| Reset everything | RESET SESSION. Also discards all statements and portals. Rejected inside a transaction. Used when a connection pool reuses a connection |
Cancel. A cancel cannot be sent over the connection that is running, so the client opens a new connection, sends C_CANCEL with the session ID and cancel key, and closes it. If the key is wrong, the server ignores it with no response. The cancel is checked at points where the statement yields (such as every 64 pages of a SELECT scan). The cancel connection does not count toward the connection limit.
Conditions that drop a connection
| Condition | Setting (default) | Result |
|---|---|---|
| Too many connections | max_connections (0) | RESOURCE_EXHAUSTED, connection refused |
| Idle session | idle_session_timeout_s (0 = none, 1 to 59 rejected) | Sends RESOURCE_EXHAUSTED and disconnects. Sending only C_PING and C_SYNC does not count as activity |
| Transaction lifetime | txn_lifetime_ceiling_ms (60,000) | Rolls back the transaction. After that, rejects every statement except ROLLBACK. The connection stays |
| Dead peer | tcp_keepalive_s (60) | Cleaned up after roughly twice that time |
| Corrupt frame, handshake failure | Disconnects. Other errors keep the connection |
Statement processing
Figure. From frame to execution
flowchart TB
P["C_PARSE<br/>statement name, SQL text"] --> FP["Compute shape<br/>replace literals and question marks with the same marker, then hash"]
FP --> KP{"Is it a named<br/>SELECT, INSERT, UPDATE, or DELETE"}
KP -->|"Yes"| KS["Stored parse<br/>syntax tree with empty question-mark slots"]
KP -->|"No"| TX["Store the text only"]
B["C_BIND<br/>parameter values"] --> BS["Statement with values filled in"]
KS --> BS
TX --> BS
BS --> NR["Name resolution<br/>the core's catalog cache"]
NR --> CP["Compile into a step chain<br/>on every execution"]
JO["Join order<br/>admin plan, captured order, statistics"] --> CP
CP --> EX["Execute"]
EX --> PO["Portal<br/>result batches"]
Diagram explanation: Processing proceeds from top to bottom.
Compute shape. WhatC_PARSEdoes is compute the shape of the text. It scans the tokens, replaces every literal and?with the same marker, folds identifiers and keywords to lowercase, and produces a 64-bit hash (pattern_id). SoWHERE id = 42andWHERE id = ?have the same shape.C_PARSEdoes not reject a statement for a syntax error; syntax errors surface at execution.Stored parse. For a namedSELECT,INSERT,UPDATE, orDELETE, the session keeps a syntax tree with the?slots empty (for text up to 64KiB). For an unnamed statement or any other statement, it keeps only the text and parses at execution.Statement with values filled in.C_BINDreceives a type with each parameter and fills the empty slots in the syntax tree. Values go into the literal positions, so the shape is the same as that of a statement that wrote the same values as literals.Name resolutionandcompilerun on every execution. The stored parse holds no catalog information at all. Table and column names are looked up again in that core's catalog cache on every execution, and the step chain is rebuilt as well. So by design, a stale plan cannot run after DDL.Join order. This is the only decision compilation takes from outside. If an admin plan (CREATE PLAN) is enabled, it follows that; otherwise the captured order; otherwise it picks by statistics or uses the order as written (Join order and plans).
Statement shape and what hangs off it
| Identifier | How it is made | Where it is used |
|---|---|---|
pattern_id | Hash of the whole statement with literals and ? replaced by markers | Returned by S_PARSE_OK |
fetch_id | Hash of the shape of a SELECT without its select list. Same as pattern_id for other statements | Every structure in the table below |
arg_hash | Hash of literals and bind values | Distinguishes each individual execution of the same shape |
What hangs off fetch_id | Scope | Content | If deleted |
|---|---|---|---|
Statement statistics (sys.statement_stats) | 4,096 shapes per core | Call count, time, rows and pages read | Only the statistics disappear |
Captured plan (sys.plans) | Instance, up to 65,536 shapes | The join order first chosen. Survives a restart | Captured again on the next execution |
Admin plan (CREATE PLAN) | Instance | Join order and access method set by the administrator | Falls back to the captured order or to search |
| Plan memo | 512 × 2 slots per core | The join order chosen by search. Only when join_order = planned | Searched again |
| Waystone trace | Only shapes the administrator picked | The position where the previous execution found its rows | Descends the tree again |
Plan advice (sys.plan_advice) | Memory, up to 1,024 shapes | Suggestions from ADVISE PLAN FOR |
None of them holds a compiled step chain or result rows. Even when it receives a join order, it recompiles with that order.
Compilation cost
In the engine's own measurements (v3.4.17), the server CPU for a prepared statement was 6.07µs for a single-row SELECT, 6.37µs for a single-row UPDATE, and 9.38µs for a three-table join, of which parsing was 0.77µs, 0.76µs, and 1.93µs. The stored parse was introduced to remove this parsing share. Even with parsing removed, compilation still takes 8.1% of a single-row SELECT and 18.9 to 22.1% of a three-table join, and the fact that compiled chains are not kept is on the engine's list of known limitations.
Portals
A portal is the result window for one statement with its values filled in. C_BIND creates it and C_EXECUTE pulls rows from it. The behavior is entirely different depending on the max rows of C_EXECUTE.
Figure. Two behaviors by max rows
flowchart TB
E["C_EXECUTE (portal, max rows)"] --> Q{"Is max rows 0"}
Q -->|"0: no limit"| S{"Is it a simple SELECT scan<br/>with no sort or aggregation"}
S -->|"Yes"| ST["Streaming<br/>sends a row batch every 64 pages read"]
S -->|"No"| BF["Run to the end, then send everything"]
Q -->|"1 or more"| CAP["Run the statement to the end and<br/>collect the result in portal memory (up to 16MiB)"]
CAP --> SU["Send only the requested number of rows,<br/>then S_PORTAL_SUSPENDED"]
SU --> CO["C_CONTINUE (portal, max rows)"]
CO --> SU
SU --> DN["S_COMPLETE when all are sent"]
ST --> DN
BF --> DN
Diagram explanation: The left branch is unlimited execution, and the right branch is fetching in chunks.
- Max rows 0, simple scan. A basic-syntax
SELECTscan with noORDER BYand no aggregation emits rows as it executes. If the client does not read, the scan stays stopped while holding a read view and waits. If the client does not read fortxn_lifetime_ceiling_ms(60 seconds) during this wait, the statement ends asCANCELLED. - Max rows 1 or more. The row limit splits delivery, not execution. The statement runs to the end on the first
C_EXECUTEand the result collects in the portal's memory. After that,C_CONTINUEonly pulls from what was collected. A suspended portal holds only memory, and holds no page pins or read views. If the collected result exceeds 16MiB, the statement fails withRESOURCE_EXHAUSTEDand the portal disappears.
The differences from the cursors of other DBMSs are summarized below.
| Property | KDBS portal |
|---|---|
| Direction | Forward only. There is no frame for going back |
| What the server holds when fetching in chunks | A copy of the whole result (memory) |
| Size limit | 16MiB |
| Idle limit | 60 seconds. Checked every 15 seconds and dropped silently; the client learns of it as an error the next time it calls that portal |
| Count limit | 64 per session |
| When it disappears | Statement failure, C_CLOSE, RESET SESSION, idle expiry, connection close |
| SQL statement | None |
So to read a large result in chunks, key-based pagination fits better than a portal. The client manual also recommends this form because there are no cursors.
SELECT * FROM orders WHERE ord_id > 0 ORDER BY ord_id LIMIT 1000;
SELECT * FROM orders WHERE ord_id > 1000 ORDER BY ord_id LIMIT 1000; -- the last ord_id received before
Catalog cache
Table names, table and column definitions, the table list, and the shapes picked by Waystone go into the catalog cache that each core has. There is no size limit and no eviction. At the start of each statement, each core reads the instance's schema version value; if the value changed (DDL happened on any core), it discards the whole cache and refills it. It never invalidates a single table.
In the sandbox
The sandbox on this site starts with auth = scram, max_connections = 32, idle_session_timeout_s = 600, and txn_lifetime_ceiling_ms = 60000. For each request it starts with BEGIN READ ONLY ISOLATION LEVEL REPEATABLE READ, runs the statement, and does ROLLBACK.
SHOW META field | Observed value |
|---|---|
max_connections / reserved_admin_connections | 32 / 3 |
connection_sessions / connection_refusals | 1 / 0 |
idle_session_closes | 1 |
plan_memo_hits / plan_memo_misses | 0 / 0 (the memo is not used because join_order is not planned) |
Settings and checks
-- Connection count, refusals, and idle closes
SELECT field, value FROM sys.meta WHERE section = 'connections';
-- What each session is doing and waiting for
SELECT session_id, state, event, elapsed_us, txn_age_us FROM sys.session_state;
SELECT session_id, event, count, total_us FROM sys.session_waits;
-- Cumulative cost by statement shape
SELECT fetch_id, kind, calls, total_us, shape_text FROM sys.statement_stats;
-- Captured plans and admin plans
SHOW PLANS;
SELECT field, value FROM sys.meta WHERE section = 'join_order';
-- Shapes picked by Waystone
SHOW PATTERNS;
-- The shape of one statement and what it actually did
ANALYZE SELECT * FROM orders WHERE ord_id = 42; -- fetch_id= in the output
- There is no view that shows a session's portals or named statements. The
session_idinsys.session_stateis an internal engine number and differs from the session ID received in the handshake. - Run the statements above in an admin tool. The sandbox blocks the
sysviews.
Comparison with other DBMSs
| KDBS | PostgreSQL | MySQL | Oracle | SQL Server | |
|---|---|---|---|---|---|
| Execution plan cache | None. Keeps only the join order | Session local, prepared statements only | None | Shared pool (all sessions) | Plan cache (all sessions) |
| What a prepared statement saves | Parsing | Parsing, analysis, and (for a generic plan) planning | Parsing, preparation | All of parsing | All of compilation |
| Identifying a statement shape | fetch_id (literals excluded) | queryid (for statistics) | Digest (for statistics) | SQL_ID (literals included) | query_hash (for statistics), the cache key is the text |
| Fetching in chunks | Portal (collects the result in memory, 16MiB) | Portal and cursor (continues the execution) | Protocol cursor (temporary table) | Cursor (continues the execution) | Server cursor |
| Stale plan after DDL | None by design | Replanned through invalidation messages | Not applicable | Cursor invalidation | Recompilation |
The full comparison is in DBMS architecture at a glance.
NOTE KDBS is an engine under development, and its protocol and limits have changed over time. This document is based on source
v3.5.1, and the sandbox is an earlierv3.4image. Where the design document and the code differ (for example, the design document saysC_PARSEbuilds the syntax tree, but the code does not parse an unnamed statement at that point), the code was followed. The documentation does not say whether a portal survivesCOMMIT, and the code has no place that removes portals at commit.
Related pages
- DBMS Architecture at a Glance
- KDBS
- KDBS Memory and Thread Architecture
- Step Chain and ANALYZE
- Join Order and Plans (CREATE PLAN)
- Waystone
- Transactions and Isolation Levels
- PostgreSQL connections, cursors, and SQL cache
- MySQL Connections, Cursors, and SQL Cache
- Oracle Connections, Cursors, and the SQL Cache
- SQL Server Connections, Cursors, and Plan Cache