# KV and cache

env.kv is durable on ack, env.cache is eventual with a TTL — the binding carries the intent.

`env.kv` and `env.cache` are the platform's key-value primitives: an
embedded store living beside your releases, fast enough to read on every
request. Both come with one manifest grant, `"kv": true` in
`pilvia.app.json`; without it every call throws and says so. The bindings
are in bundles built by `pilvia` 0.2.8 or newer (`pilvia --version`); a push
deploy builds with a current one for you.

```ts
await env.kv.put('lead:42', body);                          // durable on ack
await env.cache.put('page:/pricing', html, { ttl: 300 });   // eventual, expires
await env.kv.increment('visits:2026-09-02');                // contention-free
const lead = await env.kv.get('lead:42', 'json');
```

## The API

| Call | Answers |
|---|---|
| `get(key, type?)` | the value, or `null`. `type` is `'text'` (default), `'json'`, `'arrayBuffer'` or `'bytes'` (a `Uint8Array`); `{ type }` works too |
| `getEntry(key, type?)` | `{ value, contentType, expiresAt }` or `null` — what you need to serve a stored page |
| `put(key, value, { ttl?, contentType? })` | nothing. A string is stored as text, an `ArrayBuffer` or typed array as bytes, anything else as JSON, each with that content type unless you name one |
| `delete(key)` | nothing |
| `list({ prefix?, cursor?, limit? })` | `{ keys: [{ name, contentType, expiresAt }], cursor, complete }`, in key order, at most 1000 a page; pass `cursor` back for the next |
| `increment(key, by = 1, { ttl? })` | the counter's new value; an absent key counts from 0 |
| `append(key, value, { ttl? })` | nothing; an absent key starts empty |
| `add(key, member, { ttl? })` | whether `member` was new to the set, stored as a JSON array of strings |

`env.cache` has `get`, `getEntry`, `put` and `delete`. The counters are
`env.kv`'s alone: a store that may lose its last few writes is no place to
count. `ttl` is in seconds and `expiresAt` in milliseconds since the epoch.

## Two bindings, one substrate

The difference is the promise, not the API:

- **`env.kv` is durable by default.** An acknowledged `put` is on disk. A
  contact-form lead acked during a deploy survives the deploy — silent loss
  is the bug class nobody finds, so it is not representable.
- **`env.cache` is eventual by default.** A lost entry is a cache miss, so
  the cache is allowed to be cheaper and faster about writes: a `put`
  returns as soon as it is buffered. Entries always expire — after an hour
  unless you pass a `ttl`, after thirty days at most.

Your app chooses semantics by choosing the binding, not by reading a flag.

## Counters without a write limit

`increment`, `append` and `add` are commutative, and the store exploits
that: a burst of increments to one key coalesces into a single write
instead of contending. There is **no per-key write-rate limit** to design
around — the platforms that have one inherited it from last-writer-wins
`put` semantics, and these operations simply do not conflict. They cover
essentially every per-request write a website makes: view counters,
appended logs, accumulating sets.

## The consistency contract, stated openly

Reads are **read-your-writes on the same node, bounded staleness (seconds)
across nodes**. On a single-node installation the distinction disappears.
Writes during a node failover fail closed while reads keep serving — for a
website, the right trade, and stated here rather than discovered. A `list`
waits for writes this node already accepted, so it includes them.

On a multi-replica installation every replica keeps a local copy, and one
of them is the app's writer. A write reaching any other replica is handed
to the writer, and that replica answers only once it holds the result
itself — so read-your-writes holds wherever the write came in. An
acknowledged `env.kv` write is in the installation's object store, not
only on a node's disk. A host that cannot replicate refuses the grant, and
the app's status says why; it never lets each replica keep a store of its
own.

## Limits, as backpressure

Keys up to 512 bytes, values up to 1 MiB — anything larger belongs in
[object storage](/hosting/storage.md), which is planned. Keys may not start with a NUL
character; those belong to the platform. Pending writes are a bounded
resource: over it, writes first slow down, then throw an error whose
`code` is `kv_overloaded` — retryable, and safe to branch on. Never a "you
have spent this second's writes" cliff.

## `localStorage`, the browser face

> [!NOTE]
> **Planned**
>
> Not built yet: it is the next step on the same store. What follows is the
> intended behavior.
>
> With the `kv` grant your app will also get the Web Storage API you already
> know: `localStorage` is a synchronous view of the same store, scoped to
> your app the way Deno scopes it to an origin — shared by every request,
> 10 MB, no cookies, nothing per visitor.
>
> ```ts
> localStorage.setItem('theme', 'dark');
> const theme = localStorage.getItem('theme'); // same node: what you just wrote
> ```
>
> Reads are local and take microseconds, which is what makes a synchronous
> API honest on a server. A `setItem` is stored before your response leaves
> the node, so "returned means stored" holds — at the response boundary
> rather than per call. Over 10 MB, `setItem` throws `QuotaExceededError`.
> Without the grant, `localStorage` is simply not defined, so the
> `typeof localStorage` feature test every isomorphic library relies on does
> the right thing.
>
> Code written against Deno's `localStorage` runs unchanged. The one thing
> Deno's single process never had to tell you: across nodes, the
> [consistency contract](#the-consistency-contract-stated-openly) above
> applies. `sessionStorage` is not provided — an execution context here is
> one request, and a store that vanished with it would be spec-shaped and
> useless. If you need per-visitor state, that is a session store, a
> different thing; it is not this.

## What it is not

- **Not rolled back with code.** The store lives beside releases, not
  inside them: `pilvia app rollback` rolls your code back and leaves your
  data alone. It belongs to the app, so a preview deploy reads and writes
  the same store as production.
- **Not a queue.** There is no enqueue/dequeue surface. Writes that trigger
  *work* — send mail, call a webhook, process a document — belong on
  [the job queue](/data/jobs.md).
