KV provides schema-validated key-value storage with optional TTL expiration and atomic operations (setIfNotExists, incr, compareAndSwap).
Use KV for sessions, tokens, cursor checkpoints, counters, and lookup state. For read-through caching with stampede protection and tag invalidation, see Cache.
Declaring a KV namespace
Plain TypeScript SDK (@chimp-labs/keel/sdk)
import { k } from "@chimp-labs/keel/sdk"
export const SessionsKv = k.kv(
"sessions",
k.object({
userId: k.string(),
role: k.string(),
}),
{ ttl: "24 hours" }
)
export const PageViewsKv = k.kv("page-views", k.int())
Configuration options
| Option |
Type |
Default |
Description |
ttl |
Duration.Input |
None |
Default expiration duration for keys, for example "5 minutes" or "24 hours". You can override this duration per call. |
Effect v4 (@chimp-labs/keel/kv)
import { Schema } from "effect"
import { KV } from "@chimp-labs/keel/kv"
const SessionSchema = Schema.Struct({
userId: Schema.String,
role: Schema.String,
})
export class SessionKV extends KV<
"sessions",
`sess:${string}`,
typeof SessionSchema
>("sessions", {
value: SessionSchema,
ttl: "24 hours",
}) {}
Attaching to a Service
export const AuthService = k.service("auth", {
resources: [SessionsKv],
operations: { /* ... */ },
})
Operations reference
Basic read, write, and delete
// Write with default namespace TTL or per-call override
await keel.sessions.set("sess:abc", { userId: "usr_1", role: "admin" })
await keel.sessions.set("sess:tmp", { userId: "usr_2", role: "guest" }, { ttl: "15 minutes" })
// Read (returns T | undefined in SDK, Option<T> in Effect)
const session = await keel.sessions.get("sess:abc")
// Delete
await keel.sessions.delete("sess:abc")
Atomic operations (AtomicKV)
// Create only if key does not already exist (returns true if acquired)
const created = await keel.sessions.setIfNotExists(
"sess:once",
{ userId: "usr_1", role: "member" },
{ ttl: "1 hour" }
)
// Atomic integer increment (returns new value)
const hits = await keel.pageViews.incr("/pricing", 1, { ttl: "1 day" })
// Optimistic concurrency via compare-and-swap (returns true if swapped)
const swapped = await keel.sessions.compareAndSwap(
"sess:abc",
{ userId: "usr_1", role: "member" },
{ userId: "usr_1", role: "admin" }
)
SDK and Effect API mapping
SDK method (keel.<kv>.*) |
Effect function (@chimp-labs/keel/kv) |
Requirement |
Description |
get(key) |
kvGet(kv, key) |
KeyValueStore |
Fetch and decode a value (T | undefined in SDK, Option<T> in Effect). |
set(key, val, { ttl? }) |
kvSet(kv, key, val, opts) |
KeyValueStore |
Encode and store a value with an optional TTL. |
delete(key) |
kvDelete(kv, key) |
KeyValueStore |
Delete a key. |
setIfNotExists(key, val, { ttl? }) |
kvSetIfNotExists(kv, key, val, opts) |
AtomicKV |
Write a value atomically only when the key is absent. |
incr(key, delta?, { ttl? }) |
kvIncr(kv, key, delta?, opts) |
AtomicKV |
Increment a numeric key atomically. |
compareAndSwap(key, expected, next, opts?) |
kvCompareAndSwap(kv, key, expected, next, opts) |
AtomicKV |
Swap a value atomically if the current value matches expected. |
Errors and failure modes
| Error tag |
Category |
HTTP status |
Retryable |
When it occurs |
KvStoreError |
internal |
500 |
Yes |
Backend storage or network error. |
SchemaError |
invalid |
400 |
No |
Value fails schema encoding or decoding. |
Backends and infrastructure
- Memory uses an in-process map with Effect
Clock TTL expiration and full AtomicKV support.
- PostgreSQL 17 (
KeelPostgresLive, KvPostgresLive, or backend: "postgres") uses a durable keel_kv JSONB table with TTL expiration and single-statement atomic ON CONFLICT upserts for setIfNotExists, incr, and compareAndSwap.
- SQLite uses an embedded KV table with atomic transactions.
- SurrealDB 4 stores namespaced KV records with TTL checks, atomic compare-and-swap, and atomic increment.
Testing in memory
await using keel = await createKeel({
backend: "memory",
resources: { sessions: SessionsKv, pageViews: PageViewsKv },
})
await keel.sessions.set("sess:1", { userId: "u1", role: "admin" })
const got = await keel.sessions.get("sess:1")
// got?.userId === "u1"
const count = await keel.pageViews.incr("home", 3)
// count === 3