Docs

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.

alien.ts
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 the api Worker, 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 execution permission profile, the named set of cloud permissions a workload runs with, grants kv/data-read and kv/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:

api/src/sessions.ts
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:

PlatformBacking serviceCreated by
AWSDynamoDB table, on-demand capacityAlien
GCPFirestore collection in the project's (default) databaseAlien
AzureTable Storage table in the stack's storage accountAlien
KubernetesDynamoDB, Firestore, or Table StorageThe customer, through an external binding
MachinesSame services as KubernetesThe customer, through an external binding. The resource must be "frozen". See Machines.
LocalEmbedded 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.

src/sessions.ts
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

SetGrants
kv/data-readget, exists, and scan.
kv/data-writeRead and write, including set and delete.
kv/remote-data-writeEntry operations on this one store from your hosted software through a remote binding.
kv/provision, kv/management, kv/heartbeatUsed 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.

Next

On this page