KV
KV is a key-value store in the customer's cloud for fast lookups by key: caches, sessions, feature flags, idempotency keys, rate limits, and locks. One API, with TTLs and atomic conditional writes, runs on DynamoDB, Firestore, Table Storage, or a local database.
import * as alien from "@alienplatform/core"
const sessions = new alien.Kv("sessions").build()
const api = new alien.Worker("api")
.code({ type: "source", src: "./api", toolchain: { type: "typescript" } })
.link(sessions)
.permissions("execution")
.build()
export default new alien.Stack("acme")
.add(sessions, "frozen")
.add(api, "live")
.permissions({
profiles: { execution: { sessions: ["kv/data-read", "kv/data-write"] } },
})
.build()In this stack:
.link(sessions)connects the store to theapiWorker, the workload (the running code) that uses it. Alien injects the store's connection details, its binding, into the Worker, read by the SDK client.- The
executionpermission profile, the named set of cloud permissions a workload runs with, grantskv/data-readandkv/data-write. "frozen"means the customer's admin creates the store during initial setup."live"resources, like the Worker, are created and updated by Alien on every release. See Frozen and live.
The api Worker reads and writes values by key:
import { kv } from "@alienplatform/sdk"
const sessions = kv("sessions")
await sessions.setJson("session:abc", { userId: "u1" }, { ttl: 3600 })
const entry = await sessions.getJson<{ userId: string }>("session:abc")Platforms
sessions becomes a table or collection in the customer's cloud:
| Platform | Backing service | Created by |
|---|---|---|
| AWS | DynamoDB table, on-demand capacity | Alien |
| GCP | Firestore collection in the project's (default) database | Alien |
| Azure | Table Storage table in the stack's storage account | Alien |
| Kubernetes | DynamoDB, Firestore, or Table Storage | The customer, through an external binding |
| Machines | Same services as Kubernetes | The customer, through an external binding. The resource must be "frozen". See Machines. |
| Local | Embedded database file (localkv.sqlite) | Alien |
- Kubernetes: Alien doesn't create the store. The build fails unless each KV resource has an external binding of type
kv.
Frozen or live
KV can be "frozen" (created once during initial setup by the customer's admin) or "live" (created and updated by Alien on releases). See Frozen and live.
The resource ID must be lowercase letters, digits, and hyphens.
Alternatives
KV isn't for queries, joins, or values larger than the value limit.
- Relational data: Postgres.
- A Redis-compatible server for queues, locks, streams, or pub/sub: Redis.
- Large objects: Storage.
Options
KV has no options besides .enabled(input), which creates the resource only when a boolean stack input is true. The backing service follows from the platform.
Use it from code
Get a handle with kv(name). Creating it does no I/O; the binding resolves on the first call.
import { kv } from "@alienplatform/sdk"
const sessions = kv("sessions")
await sessions.setJson("session:abc", { userId: "u1" }, { ttl: 3600 })
const entry = await sessions.getJson<{ userId: string }>("session:abc")
// entry: { key, value: { userId: "u1" }, version } or null
const page = await sessions.scan("session:", 100)
for (const item of page.items) console.log(item.key)The full method list is in the API reference.
Common patterns
Compare and set
Every read returns an opaque version, so read-modify-write loops are safe under concurrency. Pass the version back to write only if nobody changed the key since you read it:
const entry = await counters.getJson<{ n: number }>("visits")
const next = { n: (entry?.value.n ?? 0) + 1 }
const applied = await counters.setJson("visits", next, {
ifVersion: entry ? entry.version : null, // null: create only if absent
})
if (!applied) {
// Another writer won. Read again and retry.
}A failed condition isn't an error. The call resolves false and writes nothing.
Distributed lock
const acquired = await locks.setJson("lock:report", { owner: workerId }, {
ifVersion: null, // create only if absent or expired
ttl: 30,
})
if (acquired) {
try {
await generateReport()
} finally {
// Release only our own lock. If it expired and another worker took it,
// the version no longer matches and nothing is deleted.
const lock = await locks.getJson<{ owner: string }>("lock:report")
if (lock?.value.owner === workerId) {
await locks.delete("lock:report", { ifVersion: lock.version })
}
}
}Cache with TTL
async function getUser(id: string) {
const cached = await cache.getJson<User>(`user:${id}`)
if (cached) return cached.value
const user = await loadUser(id)
await cache.setJson(`user:${id}`, user, { ttl: 300 })
return user
}Keys allow only a-z A-Z 0-9 - _ : .. Use : to build namespaces such as user:123.
Expired keys read as absent immediately. Physical deletion depends on the platform; see TTL.
Use it from your hosted software
Publish the store as a remote binding to read and write it from your own backend with the same API.
Permissions
| Set | Grants |
|---|---|
kv/data-read | get, exists, and scan. |
kv/data-write | Read and write, including set and delete. |
kv/remote-data-write | Entry operations on this one store from your hosted software through a remote binding. |
kv/provision, kv/management, kv/heartbeat | Used by initial setup and by Alien's management identity. |
When a workload's profile doesn't name the store, .link() grants kv/data-write. Naming the store in the profile replaces that default. See Permissions.