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

ItemValue
ProtocolKWP/1. Default TCP port 15432, loopback (127.0.0.1) only by default. Not PostgreSQL wire compatible
Frame8-byte header (length 4, type 1, flags 1, reserved 2). Maximum 16MiB per frame
EncryptionTLS 1.3. When on, TLS starts from the first byte (no mid-stream switch, no plaintext fallback)
AuthenticationNone (default) or SCRAM-SHA-256 (PBKDF2, 4,096 iterations)
Maximum connectionsmax_connections, default 0 (no limit). Counts sessions that finished the handshake
Concurrent statements per connectionOne. Pipelining (sending frames back to back without waiting for responses) is possible
Named statements64 per session
Portals64 per session. Dropped after 60 seconds idle
Result a portal can hold16MiB of encoded rows. The statement fails if exceeded
Row batchBatched toward 64KiB per send
Compiled plan cacheNone. Compiled on every execution
Result cacheNone
SQL PREPARE, DECLARE CURSOR, FETCHNone (rejected as unknown commands)
Transaction lifetime limittxn_lifetime_ceiling_ms, default 60,000ms. Rolled back if exceeded
Idle session limitidle_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.

  1. The client starts with C_HELLO. A server with authentication on does not send S_HELLO right away; it sends it after the SCRAM exchange of S_AUTH and C_AUTH finishes. If authentication fails, the server sends one fixed error sentence in S_AUTH and disconnects. It does not tell the client the reason for the failure.
  2. S_HELLO carries the session ID and the cancel key. A connection that exceeds max_connections receives a RESOURCE_EXHAUSTED error in place of S_HELLO and 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.
  3. S_READY reports the current transaction state (idle, in a transaction, failed transaction). It arrives again each time C_SYNC is sent.
  4. 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 next C_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 settingStatement that changes it
NamespaceUSE <name>
Isolation levelSET ISOLATION LEVEL … (Transactions)
Durability gradeSET DURABILITY … (Durability grades)
PrioritySET PRIORITY …
Reset everythingRESET 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

ConditionSetting (default)Result
Too many connectionsmax_connections (0)RESOURCE_EXHAUSTED, connection refused
Idle sessionidle_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 lifetimetxn_lifetime_ceiling_ms (60,000)Rolls back the transaction. After that, rejects every statement except ROLLBACK. The connection stays
Dead peertcp_keepalive_s (60)Cleaned up after roughly twice that time
Corrupt frame, handshake failureDisconnects. 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. What C_PARSE does 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). So WHERE id = 42 and WHERE id = ? have the same shape. C_PARSE does not reject a statement for a syntax error; syntax errors surface at execution.
  • Stored parse. For a named SELECT, INSERT, UPDATE, or DELETE, 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_BIND receives 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 resolution and compile run 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

IdentifierHow it is madeWhere it is used
pattern_idHash of the whole statement with literals and ? replaced by markersReturned by S_PARSE_OK
fetch_idHash of the shape of a SELECT without its select list. Same as pattern_id for other statementsEvery structure in the table below
arg_hashHash of literals and bind valuesDistinguishes each individual execution of the same shape
What hangs off fetch_idScopeContentIf deleted
Statement statistics (sys.statement_stats)4,096 shapes per coreCall count, time, rows and pages readOnly the statistics disappear
Captured plan (sys.plans)Instance, up to 65,536 shapesThe join order first chosen. Survives a restartCaptured again on the next execution
Admin plan (CREATE PLAN)InstanceJoin order and access method set by the administratorFalls back to the captured order or to search
Plan memo512 × 2 slots per coreThe join order chosen by search. Only when join_order = plannedSearched again
Waystone traceOnly shapes the administrator pickedThe position where the previous execution found its rowsDescends the tree again
Plan advice (sys.plan_advice)Memory, up to 1,024 shapesSuggestions 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 SELECT scan with no ORDER BY and 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 for txn_lifetime_ceiling_ms (60 seconds) during this wait, the statement ends as CANCELLED.
  • Max rows 1 or more. The row limit splits delivery, not execution. The statement runs to the end on the first C_EXECUTE and the result collects in the portal's memory. After that, C_CONTINUE only 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 with RESOURCE_EXHAUSTED and the portal disappears.

The differences from the cursors of other DBMSs are summarized below.

PropertyKDBS portal
DirectionForward only. There is no frame for going back
What the server holds when fetching in chunksA copy of the whole result (memory)
Size limit16MiB
Idle limit60 seconds. Checked every 15 seconds and dropped silently; the client learns of it as an error the next time it calls that portal
Count limit64 per session
When it disappearsStatement failure, C_CLOSE, RESET SESSION, idle expiry, connection close
SQL statementNone

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 fieldObserved value
max_connections / reserved_admin_connections32 / 3
connection_sessions / connection_refusals1 / 0
idle_session_closes1
plan_memo_hits / plan_memo_misses0 / 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_id in sys.session_state is 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 sys views.

Comparison with other DBMSs

KDBSPostgreSQLMySQLOracleSQL Server
Execution plan cacheNone. Keeps only the join orderSession local, prepared statements onlyNoneShared pool (all sessions)Plan cache (all sessions)
What a prepared statement savesParsingParsing, analysis, and (for a generic plan) planningParsing, preparationAll of parsingAll of compilation
Identifying a statement shapefetch_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 chunksPortal (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 DDLNone by designReplanned through invalidation messagesNot applicableCursor invalidationRecompilation

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 earlier v3.4 image. Where the design document and the code differ (for example, the design document says C_PARSE builds 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 survives COMMIT, and the code has no place that removes portals at commit.

Related pages