Skip to content

Control Plane and REST API

Mohammad Rasoul Kazemi edited this page Dec 2, 2026 · 11 revisions

Control Plane and REST API

kingresd is the control-plane server of KingresDB. It runs on every server of a cluster and serves, on one port (default 127.0.0.1:8091), the management REST API and the embedded Web Console. The REST contract is kingres/api/openapi.yaml, revision 0.34.0 in 0.1.0 and 0.1.1 (178 operations on 142 paths and 330 schemas); 0.2.0 has 0.35.0 (14 operations added for extension management, 192 in all, additive only; released in 0.2.0, see Extensions); 0.2.1 has 0.37.0 (199 operations, additive only: six added for the ledger checks and the audit of the publication at 0.36.0, and resumeTask at 0.37.0), OpenAPI 3.1, base path /api/v1.

Roles of kingresd

  • Agent. On each server it creates, configures, starts and stops the PostgreSQL instances (initdb, postgresql.conf, pg_hba.conf, pg_ctl), holds the server's certificates, and sends heartbeats.
  • Manager (leader). One server is the manager leader: the server that runs the primary of the map group (ADR 0018). It runs tasks and the recurring jobs. A mutating cluster operation that reaches another server is forwarded to the leader, and the response is the leader's.
  • Client router. An optional TCP entry point that forwards client connections to the current primary, or to a local standby for lag-tolerant reads (see High Availability).

kingres-cli, the command-line client of the API, is part of release 0.2.0 (2026-11-30) (kingres/control-plane/cmd/kingres-cli); 0.1.0 and 0.1.1 have only kingresd and kingres-watchdog, so with them use the REST API or the console. See Command Line Client.

State that belongs to the control plane (tasks, cluster settings, server groups, alerts, managed network rules) lives in a system database, kingres_system, schema kingres_cp, with embedded migrations (ADR 0019). There is no bundled metrics store: kingresd samples and exports metrics itself (ADR 0020). Panel accounts are PostgreSQL roles (ADR 0015).

Status

The control plane is part of the first release, 0.1.0, published on 2026-11-28 (Release Notes). It covers setup, servers, databases and tables, roles and grants, network access, rebalance and drain, high availability (standbys, failover, switchover of the map group, escrow of the CA key), the ledger operations, configuration from the console, distributed schemas, the table lifecycle and the export and import of tables and databases. It passes its integration suite on PostgreSQL 18 and 19. For the state of each phase see Status and Roadmap.

Running it

cd kingres/control-plane
go build -o kingresd ./cmd/kingresd
./kingresd -pg-dsn "host=127.0.0.1 port=5432 dbname=postgres user=kingresd password=..." -data-dir ./data

While a node is uninitialized, kingresd writes a one-time setup token to <data-dir>/setup-token and logs only the file name. GET /api/v1/setup/state and /healthz work at once.

Start a one-server cluster by hand (from the README):

kingresd -data-dir /var/lib/kingres -pg-bin-dir /opt/kingres/bin -listen 127.0.0.1:8091
curl -s -X POST http://127.0.0.1:8091/api/v1/setup/init-cluster \
  -H "X-Setup-Token: $(cat /var/lib/kingres/setup-token)" -H 'Content-Type: application/json' \
  -d '{"clusterName":"prod","admin":{"username":"root_admin","password":"a-long-password"},
       "dataPaths":{"dataDirectory":"/var/lib/kingres"},"memoryQuota":{"totalMegabytes":4096}}'
curl -s http://127.0.0.1:8091/api/v1/setup/state

See Cluster Setup for the whole procedure, ports and certificates. A second server joins with POST /api/v1/setup/join-cluster (it registers with the leader at existingNodeAddress, receives the certificates, and creates a primary of a new shard group and the standby of a neighbouring group; it appears as pendingRebalance and no data moves until a rebalance is started). Joining, adding and removing servers need internal-listen, the mutual-TLS listener of the internal server-to-server API (by convention the REST port plus one). See Configuration for the settings and Installing and Packaging for the package.

Rebalance

A rebalance is one task of kind rebalance on the leader: check the cluster, compute the plan, move buckets (and distributed schemas) one at a time, write the report. It can be stopped and started again, is taken over after a restart or a leader change, and has a page in the console. The plan can be by bucket count or by disk size, servers have weights, an automatic mode exists (off by default), and a drain empties a server for removal and hands the map group over. See Rebalancing for the procedure and Sharding for bucket moves in the extension.

Authentication model

  • POST /auth/login signs in a PostgreSQL role by user name and password. The role needs LOGIN and membership in at least one cluster role. The response sets the kingres_session cookie (HttpOnly, Secure, SameSite=Strict) and a CSRF token that browsers send as X-CSRF-Token on every mutating request. With issueToken: true the response also holds a bearer token for scripts.
  • A session belongs to the server that created it: the same value on another server is 401, and a restart ends the session. A client signs in once per server.
  • The four cluster roles are memberships in kingres_admin, kingres_ops, kingres_readonly and kingres_stats, with the hierarchy admin > ops > readonly > stats. Every operation names its minimum role in x-required-role (the contract has 76 operations for admin, 23 for ops, 68 for readonly, 4 for stats and 7 without a role).
  • The setup operations use the one-time X-Setup-Token header, and only from loopback addresses unless allow-remote-setup is true.
  • Every request passes one guard in this order: node-state gating, cross-site check, rate limit, authentication, CSRF check, role check, query-parameter validation, then the handler. Audited operations are written to an append-only audit log.
  • Errors are RFC 9457 application/problem+json; long-running operations answer 202 with a Task and a Location header.

See Security Model.

Operation groups

All paths are below /api/v1. The list is taken from openapi.yaml; the full list of 178 operations with their roles, the error codes and the versioning rules are on REST API Reference.

Tag Paths (examples)
Health /healthz, /readyz
Auth /auth/login, /auth/logout, /auth/session
Setup /setup/state, /setup/init-cluster, /setup/join-cluster, /setup/token-check
This server /this-server, /this-server/resources, /this-server/instances, /this-server/instances/{instanceId}/start, /stop, /restart, /this-server/settings, /this-server/leave-cluster, /this-server/logs
Cluster, Servers /cluster, /cluster/summary, /servers, /servers/{serverId}, /servers/{serverId}/failover, /servers/{serverId}/drain, /servers/{serverId}/drain-preview, /servers/{serverId}/certificates/renewals, /servers/{serverId}/certificates/revocations, /certificate-authority/escrow, /server-groups
Databases, Tables, Shards /databases, /databases/{databaseName}, /databases/{databaseName}/tables, .../tables/{tableName}/distribution, .../tables/{tableName}/partitions, .../tables/{tableName}/storage, .../tables/{tableName}/partition-policy, /databases/{databaseName}/schemas, /databases/{databaseName}/colocation-groups, .../buckets/{bucket}/split, /databases/{databaseName}/bucket-distribution
Data transfer .../tables/{tableName}/export, .../tables/{tableName}/import, /databases/{databaseName}/export, /database-imports, /data-uploads, /data-exports
Replication, failover /replication/topology, /replication/restore-preferred-primaries, /failover, /failover/map/abandon, /failover/reports, /settings/cluster/auto-failover/reset
Rebalance /rebalance (status and start), /rebalance/plan, /rebalance/stop, /rebalance/reports, /rebalance/reports/{reportId}
Tasks /tasks, /tasks/{taskId}, /tasks/{taskId}/cancel
Roles, Grants, Network access, Audit, Settings /roles, /roles/{roleName}, /cluster-roles, /grants, /settings/network-access, /audit, /settings/cluster
Configuration /config/parameters, /config/changes/preview, /config/changes, /config/servers, /config/summary, /config/time, /config/time-zones, /config/restarts
Ledger /ledger/status, /databases/{databaseName}/ledger/blocks, .../digests, .../verifications, .../inclusion-proofs, /ledger/signing/keys, /ledger/publication, /ledger/anchor-targets, .../ledger/anchors, .../ledger/bundles, .../ledger/client-keys; /ledger/publication/audit, .../ledger/check-reports and .../ledger/publication/audit/acknowledge (0.36.0, in 0.2.1)
Query /query, /query/statements/{statementId}/cancel
Alerts, Logs, Metrics /alerts, /logs, /metrics/query

Every operation is built (178 of 178 at 0.34.0, 192 of 192 in 0.2.0, 199 of 199 in 0.2.1 and 0.2.2); unsupported_operation (422) is left for a request that a server cannot run, and, in release 0.2.0 and earlier, for the anchors check of startLedgerVerification (built in release 0.2.1). The reference is openapi.yaml itself; conventions are in kingres/api/README.md. Example calls:

POST /api/v1/auth/login        {"username":"alice","password":"s3cret","issueToken":true}
GET  /api/v1/rebalance
POST /api/v1/servers/{serverId}/failover   (body: {"mode":"hard","dryRun":true})

Process model

  • One unit. The package has one systemd unit, kingres.service: kingresd starts and adopts the PostgreSQL instances, which are independent processes. A crash or a restart of kingresd leaves the database running (to restart only the manager send it SIGTERM); systemctl stop stops the database too (ExecStop runs kingresd -stop-instances; KillMode=process, TimeoutStopSec=120). kingresd sends READY=1 and STOPPING=1 to systemd. The unit is sandboxed (no capabilities, ProtectSystem=strict, writes only under /var/lib/kingres).
  • Watchdog. kingres-watchdog is a small standard-library program next to kingresd; it covers a dead or hung kingresd by reading a lease file that kingresd replaces after every renewal (it holds no time of day) and stopping the instance with an immediate shutdown when the lease would have lapsed. See High Availability.
  • Scheduler. The manager leader runs the recurring jobs. On becoming leader it waits one lease-margin, increments the term and starts its jobs; every write made under a term is guarded by it.
  • Task engine. Tasks are durable, resumable step by step, and fenced by leases and an epoch: a holder that lost a lease writes nothing. A task is claimed by one server at a time.

Internal API

Servers talk to each other over a separate TLS 1.3 listener (internal-listen, mutual TLS under the cluster certificate authority; the public listener never accepts a client certificate and the internal listener never accepts a session or token). It is not part of the public contract, carries the header X-Kingres-Internal-Version and a server answers 409 version_mismatch to a peer of another version. The certificate is checked at every request, and a revoked or expired certificate is refused. The calls are authorised by a fixed table: leader-only calls (instances, trust, certificates, globals, apply) cannot be made by a server that is not the leader. See Cluster Setup and Security Model. Reference: internal-api.md.

Headers and cookies

Every response of the listener, including errors, the console files and /metrics, carries a strict content security policy (default-src 'self', no inline script or style, no external origin, frame-ancestors 'none'), X-Frame-Options: DENY, X-Content-Type-Options: nosniff, Referrer-Policy: no-referrer, Cross-Origin-Opener-Policy and Cross-Origin-Resource-Policy: same-origin, and a Permissions-Policy that disables camera, microphone and geolocation. Strict-Transport-Security is sent only when TLS is on (tls-cert-file set), never over plain HTTP, and X-Forwarded-Proto is not trusted. API responses, errors and /metrics are no-store; index.html is no-cache; hashed assets are public, max-age=31536000, immutable. A TLS-terminating proxy in front of a plain kingresd must add HSTS itself. The session cookie is kingres_session, HttpOnly; Secure; SameSite=Strict, with no Domain; Secure is set even without TLS, as the contract states.

Observability

Structured logs (text or JSON, no query strings, headers or bodies), the audit log audit.jsonl, alerts (GET /alerts), cluster-wide log search, and metrics: a short in-memory history for the console charts and a Prometheus-format /metrics endpoint for an external store (no bundled metrics store, ADR 0020). The alert kinds and their meaning are on Monitoring and Alerts.

The settings of kingresd

Flags, environment variables and defaults are on Configuration; they are defined in kingres/control-plane/internal/config.

Related pages

Administrator Guide, REST API Reference, Cluster Setup, Servers Databases and Roles, Rebalancing, High Availability, Configuration, Web Console, Upgrades.

Tests

go vet ./..., gofmt -l ., golangci-lint run ./... and go test ./... need no database. Integration tests run against real PostgreSQL instances when KINGRES_PG_BIN is set; scripts/run-integration.ps1 runs them in WSL2 and takes -Install to test another major. See Development and Testing.

Sources

Clone this wiki locally