Skip to content

About

@coderbuzz/kvs-server - HTTP REST + WebSocket server wrapping @coderbuzz/kvs

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

34 Commits

Folders and files

Repository files navigation

KVS Server: @coderbuzz/kvs-server

HTTP REST + WebSocket server wrapper for @coderbuzz/kvs. Expose your KV store as a full-featured network API with WebSocket RPC, real-time watch, and push-based queue listeners. AI agents: see AI_KNOWLEDGE.md for expert context.

npm version npm downloads MIT License GitHub Stars CI Codecov

KVS Server wraps @coderbuzz/kvs (KVStore or AsyncKVStore) into a production-ready HTTP server built on velox (served through Bun.serve when running on Bun). Handles authentication, routing, WebSocket upgrade, and protocol translation. Pair with @coderbuzz/kvs-client for the TypeScript client SDK.


Why KVS Server?

@coderbuzz/kvs is the store engine (SQLite-backed KV operations). @coderbuzz/kvs-server is the server layer that exposes it over HTTP/WS. Separating them means:

  • The store can be embedded directly in your app without HTTP overhead
  • The server can be swapped, extended, or deployed independently
  • No unnecessary HTTP dependencies in the core KV library

Features

  • REST API: full CRUD, batch reads (/kv/get-many), list (ranges inside a prefix too), atomic transactions with sum counters, queue operations, manual expiry
  • WebSocket RPC: lower latency than REST for high-throughput workloads
  • Scoped bearer auth: read/write/queue/admin roles with encoded key-prefix and queue-topic scopes
  • Grouped WebSocket watch: one store watch and serialization per identical ordered subscription
  • Backpressure control: bounded buffers, latest-state coalescing, drain recovery, and structured slow-consumer closes
  • Push-based queue: leased messages with ack tokens, per-listener concurrency, nack/retry, dead letters and stats
  • Health checks: unauthenticated /health endpoint
  • Dual backend: createServer() for sync KVStore, createAsyncServer() for async AsyncKVStore (PostgreSQL, async SQLite)
  • Request validation: all endpoints validated via @coderbuzz/veta

Benchmarks

Numbers from github.com/coderbuzz/benchmarks (results/latest.json): cloud machine (Intel Xeon @ 2.80GHz, family 6 model 85 stepping 7, 4 cores, Linux x64), Bun 1.4.3, run of 2026-10-11 (benchmarks d3093a2). @coderbuzz/kvs-server 6.1.4: one client calling sequentially, each operation awaited, against an in-process KVStore; ops/s, best of 3 processes.

Scenario KVS direct WS RPC HTTP REST
set('k','v') 357,510 ops/s 46,361 ops/s (7.7x slower) 5,858 ops/s (61.0x slower)
get('k'), hit 441,618 ops/s 48,700 ops/s (9.1x slower) 5,619 ops/s (78.6x slower)

A remote call costs a network round trip that in-process access does not: HTTP REST is 61-79x slower than direct access (JSON serialization, a TCP request per call, velox routing). WebSocket RPC keeps one connection open and is about 7.9x faster than REST for writes and 8.7x for reads. These are sequential, one-at-a-time calls; concurrent clients amortize the round trip.

Numbers move with the machine; compare them only within one run. The source of truth is https://raw.githubusercontent.com/coderbuzz/benchmarks/main/results/latest.json.


Installation

npm install @coderbuzz/kvs @coderbuzz/velox @coderbuzz/kvs-server

KVS Server has two peer dependencies: @coderbuzz/kvs (the store engine) and @coderbuzz/velox (the HTTP/WS framework). @coderbuzz/veta (request validation) is a regular dependency and installs automatically.

Runtime: Bun 1.2.21 or newer (engines.bun), because @coderbuzz/kvs is Bun-only. Clients on Node, Deno or browsers talk to it over HTTP/WS, e.g. with @coderbuzz/kvs-client.


Quick Start

import { KVStore, AsyncKVStore } from "@coderbuzz/kvs";
import { createServer, createAsyncServer } from "@coderbuzz/kvs-server";

// Sync (SQLite via bun:sqlite)
const store = new KVStore("kv.db");
const server = createServer(store, {
  port: 3000,
  hostname: "0.0.0.0",
  accessToken: "your-secret-token",
  readToken: "player-read-token",
  adminToken: "separate-admin-token",
  legacyAccessTokenRole: "write",
  allowQueryToken: false,
});
await server.run();

// Async (SQLite or PostgreSQL via bun:sql)
const asyncStore = new AsyncKVStore("postgres://user:pass@localhost:5432/kvdb");
const asyncServer = createAsyncServer(asyncStore, {
  port: 3001,
  accessToken: "your-secret-token",
});
await asyncServer.run();

Graceful Shutdown

// Sync
process.on("SIGINT", () => {
  store.close();
  process.exit(0);
});

// Async
process.on("SIGINT", async () => {
  await asyncStore.close();
  process.exit(0);
});

Upgrading from kvs-server 6.0

kvs-server 6.1 needs @coderbuzz/kvs 0.6. Additions only:

  • POST /kv/get-many (and WS /kv/get-many): up to 1000 keys in one call, one slot per key.
  • /kv/atomic takes { "type": "sum", "key": [...], "value": <number> } mutations.
  • /kv/list with prefix plus start/end narrows the range inside the prefix (6.0: a 400). A bound outside the prefix is still a 400, for every credential.
  • Over WebSocket, an unknown mutation type in /kv/atomic is an error and nothing is written (6.0 skipped it and committed the rest with { ok: true }).

Upgrading from kvs-server 5

kvs-server 6 needs @coderbuzz/kvs 0.5:

  • A credential scoped to a key prefix reaches the prefix key itself and its children, not a string sibling that shares its bytes (["tenant", "a\u0000x"] for ["tenant", "a"]).
  • /kv/list with prefix returns the children only (not the prefix key), prefix: [] lists every key, and prefix with start/end is a 400 (6.1 accepts bounds inside the prefix).
  • Entry versions are store-wide versionstamps, not 1, 2, 3 per key.
  • A key over 2 KiB encoded, NaN in a key, or a value kvs cannot store is a 400.
  • A stored bigint is sent as a decimal string (it used to be impossible to store; JSON has no bigint). Date, Map, Set and Uint8Array values go out as JSON.stringify writes them.

Upgrading from kvs-server 4

kvs-server 5 needs @coderbuzz/kvs 0.4. The queue protocol changed:

  • /queue/ack takes { id, token }; token comes with every dequeued or pushed message.
  • A WebSocket listener pushes at most concurrency (default 1) messages until they are acked or nacked. kvs-server 4 pushed and forgot, so every message was out at once and nothing was retried until the store's timer.
  • New routes: /queue/nack, /queue/extend, /queue/dead, /queue/retry-dead, /queue/delete-dead, /queue/stats.
  • A topic-scoped queue credential can now ack (with the token).
  • A body that fails its schema is a 400, not a 500.

API

createServer(store: KVStore, options: CreateServerOptions): AppServer

Creates an HTTP server with REST + WebSocket endpoints wrapping a sync KVStore.

Param Type Default Description
store KVStore required Sync store instance from @coderbuzz/kvs
options.port number 3000 HTTP server port
options.hostname string "0.0.0.0" Bind address
options.accessToken string required Bearer token for auth
options.readToken string none Read/list/watch-only credential
options.writeToken string none Read/write/atomic/queue-enqueue credential
options.adminToken string none Administrative credential
options.credentials KvsCredential[] [] Role credentials with key/topic scopes
options.legacyAccessTokenRole KvsRole "admin" Compatibility role for accessToken
options.allowQueryToken boolean true Allow deprecated ?token= WS auth; set false in production
options.maxPayloadLength number 4 MiB Maximum inbound WebSocket RPC frame
options.authTimeoutMs number 5000 Time allowed for post-connect authentication
options.watch WatchHubOptions see below Watch count, event, buffer, and grace limits

Returns a velox AppServer instance with methods:

Method Description
.run() Start the server
.stop() Stop the server
.printRoutes() Debug endpoint registration

createAsyncServer(store: AsyncKVStore, options: CreateAsyncServerOptions): AppServer

Same interface as createServer but accepts AsyncKVStore instead of KVStore. All store calls are awaited internally.

Param Type Default Description
store AsyncKVStore required Async store instance from @coderbuzz/kvs
options.port number 3000 HTTP server port
options.hostname string "0.0.0.0" Bind address
options.accessToken string required Bearer token for auth
other options Every other CreateServerOptions field (readToken, credentials, watch, ...) applies unchanged

HTTP Endpoints

All endpoints except GET /health require: Authorization: Bearer <ACCESS_TOKEN>

Auth middleware protects both /kv/* and /queue/*. Per-operation role, encoded key-prefix, atomic-item, and queue-topic authorization is enforced after authentication. A missing or unknown token returns 401 (plain-text body from the bearer middleware). A known token without permission returns 403 with { "error": "Forbidden", "reason": "..." }.

Health

GET /health

Auth: None.

Response:

{ "ok": true, "uptime": 123.456 }

uptime in seconds from process.uptime().

KV Endpoints (all POST, all authenticated)

POST /kv/get

// Request
{ "key": ["users", "alice"] }

// Response (found)
{ "entry": { "key": ["users", "alice"], "value": { "name": "Alice" }, "version": 1 } }

// Response (not found)
{ "entry": null }

POST /kv/get-many

// Request: up to 1000 keys
{ "keys": [["users", "alice"], ["users", "nobody"], ["settings", "alice"]] }

// Response: one slot per key, in order, null when absent or expired
{ "entries": [
  { "key": ["users", "alice"], "value": { "name": "Alice" }, "version": 1843 },
  null,
  { "key": ["settings", "alice"], "value": { "theme": "dark" }, "version": 1790 }
] }
  • A get for authorization: the read role may call it, and a credential scoped to key prefixes gets a 403 when any key is outside them (nothing is read).
  • More than 1000 keys, an empty key or a key over 2 KiB is a 400. "keys": [] returns { "entries": [] }.
  • The keys are read in one statement (one read transaction on createServer), so the entries come from one snapshot.

POST /kv/set

// Request
{ "key": ["users", "alice"], "value": { "name": "Alice" }, "ttl": 60000 }

// Response
{ "ok": true, "version": 1 }
  • ttl optional, milliseconds, min 0.
  • Every set increments version by 1.

POST /kv/delete

// Request
{ "key": ["users", "alice"] }

// Response
{ "ok": true }

POST /kv/list

// Request: prefix
{ "prefix": ["users"] }

// Request: range
{ "start": ["events", 1000], "end": ["events", 2000] }

// Request: a range inside a prefix (start inclusive, end exclusive)
{ "prefix": ["orders"], "start": ["orders", "2026-09"], "end": ["orders", "2026-10"] }

// Request: paginated
{ "prefix": ["logs"], "limit": 20, "cursor": "Abc..." }

// Request: reverse
{ "prefix": ["logs"], "limit": 5, "reverse": true }

// Response
{
  "entries": [
    { "key": ["users", "alice"], "value": { "name": "Alice" }, "version": 1 },
    { "key": ["users", "bob"], "value": { "name": "Bob" }, "version": 1 }
  ],
  "cursor": "Xyz..." | null
}
  • cursor is base64-encoded exclusive start key for pagination. null = no more pages.
  • Default limit: 100, max 1000.
  • An invalid cursor (outside the requested prefix or range) or limit, or a start/end that is not a key inside prefix, returns 400 { "error": "Bad Request", "reason": "..." }.
  • prefix lists the children of the prefix, not the prefix key itself; prefix: [] lists every key (kvs 0.5).
  • A credential scoped to key prefixes must send a prefix inside its scope; its start/end must then be inside that prefix (else 400), so it can never read past its scope.

POST /kv/atomic

// Request
{
  "checks": [
    { "key": ["counter"], "version": 3 },
    { "key": ["new-key"], "version": null }
  ],
  "mutations": [
    { "type": "set", "key": ["counter"], "value": 4 },
    { "type": "set", "key": ["meta"], "value": { "updatedAt": 123456 }, "ttl": 3600000 },
    { "type": "sum", "key": ["stats", "updates"], "value": 1 },
    { "type": "delete", "key": ["old-key"] }
  ],
  "enqueues": [
    {
      "payload": { "task": "notify" },
      "options": { "topic": "jobs", "delay": 0, "maxAttempts": 3 }
    }
  ]
}

// Response (success)
{ "ok": true, "version": 4 }

// Response (check failed)
{ "ok": false }
  • All operations run in a single transaction. If any check fails, entire operation is rolled back.
  • version: null = "key must not exist".
  • version: number = "key must be at this exact version".
  • All three sections (checks, mutations, enqueues) are optional but at least one should be present.
  • sum adds value (a finite number) to the number at key: a missing or expired key becomes value, a live key keeps its TTL. A sum on a stored non-number, or a value that is not a finite number, is a 400 with a reason (kvs: atomic().sum() needs a number, ... / ... delta must be a finite number, ...) and nothing is written. sum is a write: roles and key scopes apply as for set.

POST /kv/reset

// Request
{}

// Response
{ "ok": true }

Deletes ALL data from kv and queue tables. Active watches receive reset tombstones and remain subscribed. Admin role is required.

POST /kv/clean-expired

// Request
{}

// Response
{ "ok": true, "deleted": 42 }

Manually delete expired KV entries. Returns count of removed rows. Auto-runs every 60s on server. Note: response field is deleted (keep existing API shape). Admin role is required.

POST /kv/watch-stats

// Request
{}

// Response
{ "store": { "activeWatchers": 1, "committedBatches": 10, ... }, "server": { "groups": 1, "peers": 3, ... }, "queue": { "listeners": 2, "inFlight": 1, "delivered": 40, ... } }

Returns core watch counters (KvWatchDiagnostics), WatchHub counters (WatchHubDiagnostics) and the store's queue listener counters (KvQueueDiagnostics). Admin role is required.

Queue Endpoints (all POST)

A dequeued message is leased: it carries a token, and only that token can ack, nack or extend it. If it is neither acked nor nacked before lockedUntil, it is delivered again; after maxAttempts deliveries it is dead-lettered. Invalid arguments (a fractional limit, maxAttempts: 0, an empty token) are a 400.

POST /queue/enqueue

// Request
{
  "payload": { "to": "[email protected]" },
  "topic": "emails",
  "delay": 5000,
  "maxAttempts": 5
}

// Response
{ "ok": true, "id": 1 }
  • topic default: "default", delay default: 0, maxAttempts default: 3 (integer >= 1).

POST /queue/dequeue

// Request
{ "topic": "emails", "limit": 10, "visibilityTimeout": 60000 }

// Response
{
  "messages": [
    {
      "id": 1,
      "topic": "emails",
      "payload": { "to": "[email protected]" },
      "enqueuedAt": 1700000000000,
      "deliverAt": 1700000005000,
      "attempts": 1,
      "maxAttempts": 5,
      "token": "3f0c6c1e-8a1d-4a51-9a53-2b6f4c7d9e10",
      "lockedUntil": 1700000035000,
      "lastError": null
    }
  ]
}
  • topic default: "default", limit default: 1 (max 1000), visibilityTimeout default: the store's (30 s).

POST /queue/ack

{ "id": 1, "token": "3f0c6c1e-..." }   →   { "ok": true }

Deletes the message (or keeps it as done under the store's doneRetention). "ok": false when the lease is no longer held under that token.

POST /queue/nack

{ "id": 1, "token": "3f0c6c1e-...", "error": "SMTP 451", "delay": 10000 }   →   { "ok": true }

Retry after delay ms (default: the store's backoff), or dead-letter on the last attempt. error becomes lastError.

POST /queue/extend

{ "id": 1, "token": "3f0c6c1e-...", "visibilityTimeout": 60000 }   →   { "ok": true }

The lease now ends visibilityTimeout ms from now; 0 hands the message back.

POST /queue/dead, /queue/retry-dead, /queue/delete-dead

{ "topic": "emails", "limit": 100, "after": 0 }   →   { "messages": [{ "id": 1, …, "lastError": "SMTP 451", "failedAt": 1700000100000 }] }
{ "topic": "emails", "id": 1 }                    →   { "count": 1 }      // omit id: every dead message of the topic

POST /queue/stats

{ "topic": "emails" }   →   { "stats": [{ "topic": "emails", "pending": 3, "delayed": 1, "processing": 2, "dead": 0, "done": 0, "oldestPendingAt": 1700000000000 }] }

Omit topic for every topic (unscoped credentials only).


WebSocket

Endpoint: ws://host:port/ws

Uses JSON-RPC format. All methods mirror their REST counterparts. Server defaults:

Setting Value
maxPayloadLength 4 MiB (options.maxPayloadLength)
backpressureLimit 4 MiB (options.watch.hardBufferBytes)
pingInterval 30 s
pongTimeout 10 s
idleTimeout 120 s
perMessageDeflate disabled

KVS also enables runtime close-on-backpressure and applies these watch defaults:

Watch option Default
maxWatchKeys 32
maxEventBytes 2 MiB
softBufferBytes 2 MiB
hardBufferBytes 4 MiB
slowConsumerGraceMs 15,000 ms

Auth

Two modes:

Mode 1: Query parameter (deprecated compatibility mode)

ws://host:port/ws?token=ACCESS_TOKEN
  • If token matches → connection upgraded with the resolved principal
  • If token wrong → rejected with HTTP 401 "Unauthorized"
  • If allowQueryToken: false and ?token= is present → rejected with HTTP 401 "Query token authentication is disabled"
  • If no ?token= → connection must authenticate with Mode 2 within authTimeoutMs, otherwise it is closed with code 4001 authentication_timeout
  • Set allowQueryToken: false in production so credentials do not enter URL/proxy logs.

Mode 2: Post-connect RPC auth

// Client sends (must be first message after connect):
{ "id": 1, "method": "auth", "params": { "token": "ACCESS_TOKEN" } }

// Server responds:
{ "id": 1, "result": { "ok": true } }
  • If wrong token → { "id": 1, "error": "Unauthorized" } + connection closed (code 4001)
  • If any non-auth method sent before auth → { "id": 1, "error": "Unauthorized" } + connection closed (code 4001)

Message Format (JSON-RPC style)

Client → Server (request):

{ "id": 1, "method": "/kv/get", "params": { "key": ["users", "alice"] } }

Server → Client (response):

{ "id": 1, "result": { "entry": { "key": [...], "value": ..., "version": 1 } } }

Server → Client (error):

{ "id": 1, "error": "Error message" }

Server → Client (push: unsolicited, no id):

{ "type": "watch", "entries": [...], "sequence": 42 }   // "reset": true is added only for reset tombstones
{ "type": "queue", "topic": "...", "message": {...} }

RPC Methods

Method Parameters Result
auth { token: string } { ok: true }
/kv/get { key: KvKey } { entry: KvEntry | null }
/kv/get-many { keys: KvKey[] } (max 1000) { entries: (KvEntry | null)[] }
/kv/set { key, value, ttl? } KvCommitResult
/kv/delete { key } { ok: true }
/kv/list { prefix?, start?, end?, limit?, cursor?, reverse? } KvListResult
/kv/atomic { checks?, mutations?, enqueues? } (mutation type: set, delete, sum) KvCommitResult | { ok: false }
/kv/reset {} { ok: true }
/kv/clean-expired {} { ok: true, deleted }
/kv/watch { keys: KvKey[] } (no response, push events follow)
/kv/unwatch {} (no response)
/queue/enqueue { payload, topic?, delay?, maxAttempts? } { ok: true, id }
/queue/dequeue { topic?, limit?, visibilityTimeout? } { messages: QueueMessage[] }
/queue/ack { id, token } { ok: boolean }
/queue/nack { id, token, error?, delay? } { ok: boolean }
/queue/extend { id, token, visibilityTimeout? } { ok: boolean }
/queue/dead { topic?, limit?, after? } { messages: QueueDeadMessage[] }
/queue/retry-dead { topic?, id? } { count }
/queue/delete-dead { topic?, id? } { count }
/queue/stats { topic? } { stats: QueueStats[] }
/queue/listen { topic?, concurrency?, visibilityTimeout? } (topic default "default") (no response, push events follow)
/queue/unlisten { topic? } (no response)
/debug/watch-stats {} { store: KvWatchDiagnostics, server: WatchHubDiagnostics, queue: KvQueueDiagnostics } (admin)

Watch

Subscribe to key-change notifications:

// Subscribe
{ "id": 5, "method": "/kv/watch", "params": { "keys": [["config", "theme"], ["config", "lang"]] } }

// Push event (fires immediately + on every mutation)
{
  "type": "watch",
  "entries": [
    { "key": ["config", "theme"], "value": "dark", "version": 3 },
    { "key": ["config", "lang"], "value": "en", "version": 1 }
  ],
  "sequence": 7
}

// Unsubscribe
{ "id": 6, "method": "/kv/unwatch" }

Behavior:

  • Only ONE watcher per connection. Calling again cancels the previous.
  • Connections requesting the same ordered key list share one store watcher, one committed snapshot, and one JSON serialization.
  • Fires immediately with current values for all keys on subscribe.
  • One callback is emitted per committed batch. Atomic changes to multiple watched keys do not duplicate the event.
  • Expiry and reset emit null tombstones. Reset keeps the subscription active.
  • entries matches the order and length of requested keys. null for non-existent keys.
  • sequence is process-local ordering metadata, not a durable resume cursor.
  • A blocked peer retains only the latest pending snapshot. Persistent slow consumers close with code 4008; oversized events close with 4009.

Queue Listen

// Subscribe: at most 4 unacked messages at a time
{ "id": 7, "method": "/queue/listen", "params": { "topic": "emails", "concurrency": 4 } }

// Push event
{
  "type": "queue",
  "topic": "emails",
  "message": { "id": 1, "topic": "emails", "payload": { "to": "[email protected]" }, "attempts": 1, "maxAttempts": 3,
               "token": "3f0c6c1e-...", "lockedUntil": 1700000030000, "lastError": null, "enqueuedAt": 1700000000000, "deliverAt": 1700000000000 }
}

// Finish it
{ "id": 8, "method": "/queue/ack", "params": { "id": 1, "token": "3f0c6c1e-..." } }

// Unsubscribe
{ "id": 9, "method": "/queue/unlisten", "params": { "topic": "emails" } }

Behavior:

  • One listener per topic per connection. Calling again for same topic replaces it.
  • Multiple topics per connection supported simultaneously.
  • The server pushes at most concurrency (default 1, max 1000) messages and then waits: a slot frees when the client acks or nacks the message (over this socket or HTTP), when its lease ends, or when the connection closes. @coderbuzz/kvs-client acks when the handler resolves and nacks when it throws.
  • Listeners on other connections (and other processes on the same database) share the topic: whoever has a free slot gets the next message.
  • New messages are pushed at once, including ones from /kv/atomic; delayed messages, retries and expired leases within a second.
  • Closing the connection hands its unacked messages back at once (their leases are released), so another listener gets them.

Error Handling

Scenario Response
Unknown method (with id) { "id": N, "error": "Unknown method: <method>" }
Invalid JSON / parse failure (with id) { "id": N, "error": "<message>" }
Invalid JSON without id { "error": "Invalid message" }
Handler errors (caught) { "id": N, "error": "<error message>" }
Handler error for a message without id { "error": "Invalid message" }
Authorization denied { "id": N, "error": "Forbidden: <reason>" } (id omitted if the request had none)

Connection Cleanup

On WebSocket close:

  1. The peer is removed from its WatchHub group; the shared store watcher is canceled when its last peer leaves.
  2. All queue listeners are canceled, and the leases of messages pushed to this connection but not yet acked are released, so they are delivered again at once.

Message Lifecycle (Server-Side)

enqueue → pending ──dequeue / push──▶ processing (leased) ──ack──▶ deleted (or done)
             ▲                           │
             └── nack, or lease expired ─┤  (retried after the backoff)
                                         └── last attempt failed ──▶ dead ── retry-dead ─▶ pending
  • TTL cleanup and queue maintenance: every 60s in the store (expired entries, leases that expired on their last attempt, retention of done/dead).
  • Expired leases go back to pending before the store's next dequeue (at most once a second).
  • Listener poll: every 1s while listeners exist.

Gotchas

  1. accessToken is required. No default. Unknown tokens return 401; known tokens without permission return 403.
  2. createServer() → sync KVStore, createAsyncServer() → async AsyncKVStore. Wrong pairing causes runtime errors.
  3. Query token auth is retained for compatibility but should be disabled with allowQueryToken: false in production.
  4. Only ONE watcher per WebSocket connection. Calling /kv/watch again cancels the previous.
  5. Queue listeners are per-topic per-connection. Calling /queue/listen for same topic overwrites. Multiple topics per connection OK. A listener waits for the client's ack or nack before pushing more than concurrency messages.
  6. Both /kv/* and /queue/* require authentication. Authorization is applied again per operation, key prefix, and queue topic.
  7. reset() is admin-only, deletes ALL data, and emits reset tombstones while preserving active watches. It is not reversible.
  8. The server uses velox internally: AppServer has .printRoutes() for debugging registered endpoints.
  9. TTL cleanup and queue maintenance timers run within the KVStore instance, not the server. KVStore starts them on construction, AsyncKVStore on its first operation; both stop on store .close().
  10. No increment HTTP/WS endpoint. Use a sum mutation in /kv/atomic for counters: it is atomic on every backend and needs no read. The response is { ok, version }, not the new value; read it with /kv/get when you need it.

Watch benchmark harness

Run a real-socket load test against a separately started server:

bun run --cwd packages/kvs-server bench:watch -- \
  --url http://127.0.0.1:3000 --token TOKEN \
  --clients 5000 --channels 1 --payload-bytes 100000 --updates 3

The harness reports connection time, p50/p95/p99/last delivery, runtime metadata, and exact store/WatchHub counters. Establish production SLOs from measured host and network results rather than the example workload.


License

MIT © 2026 Indra Gunawan

About

@coderbuzz/kvs-server - HTTP REST + WebSocket server wrapping @coderbuzz/kvs

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages