skip to content

Workers KV

KV is a global key-value store cached near readers: reads are fast, but a write can take 60 seconds or more to show elsewhere. Interviewers ask when that rules KV out.

on this pageshow

explore

questions

6

In Workers KV, how does a Worker read and write a feature flag through its binding, and what does get() return for a missing key?

level: juniorimportance: must knowfreq 70%

answer

  1. binding name on env
  2. type option decides the return shape
  3. options object on put()
  4. absent key is not an exception

basics

~20 s

A Worker reads with env.FLAGS.get(key), passing type "json" to get a parsed object, and writes with env.FLAGS.put(key, value, options). Both return promises to await, and get() resolves to null when the key does not exist.

solid answer

~40 s

The namespace is bound in the Wrangler file under `kv_namespaces` with a `binding` name and the namespace `id`, so the Worker sees it as `env.FLAGS`. `await env.FLAGS.get("flags:global", { type: "json" })` returns the parsed value; the type can be `text` (the default), `json`, `arrayBuffer` or `stream`. A missing key resolves to `null`, not an error, so the code supplies its own default. `put(key, value, options)` takes a string, `ArrayBuffer` or `ReadableStream` and optional `expiration` (epoch seconds), `expirationTtl` (seconds from now, at least 60) and `metadata` (JSON up to 1024 bytes). `delete(key)` succeeds even for a missing key. Keys are at most 512 bytes and values at most 25 MiB.

code

json · 6 lines
json
{
  "name": "site-edge",
  "main": "src/index.js",
  "compatibility_date": "2026-10-10",
  "kv_namespaces": [{ "binding": "FLAGS", "id": "<namespace id>" }]
}

go deeper

for a junior

Recall the four calls on the binding (get, getWithMetadata, put, delete), that every one returns a promise, and that a missing key gives null.

for a middle

Explain the type option and its four shapes, the difference between expiration and expirationTtl, and the size limits on keys, values and metadata.

for a senior

Show you handle the null case with a safe default, keep metadata small, and never leave a write unawaited outside ctx.waitUntil().

for a principal

Treat the API's simplicity as the trap: it hides propagation delay and per-key write limits that decide whether KV fits the data at all.

## The binding: how a Worker reaches a namespace A **KV namespace** is one key-value store in an account. A Worker does not connect to it with a URL or a client library; it receives a **binding**, an object the runtime places on `env` under a name you choose. The Wrangler file declares it: ```json { "kv_namespaces": [{ "binding": "FLAGS", "id": "<namespace id>" }] } ``` - `binding` is the variable name the code uses (`env.FLAGS`). It does not have to match the namespace's title. - `id` identifies the namespace in the account; `wrangler kv namespace create <name>` prints it. - `preview_id` is optional and names a separate namespace for `wrangler dev`. Every method on the binding returns a **promise**. Awaiting it is how the Worker learns that a read finished or a write was accepted. ## Reading: get() and its type option `env.FLAGS.get(key)` returns the stored value as a string. A second argument chooses the shape, either as a bare string (`get(key, "json")`) or as an options object (`get(key, { type: "json", cacheTtl: 300 })`): | `type` | What the promise resolves to | |---|---| | `text` (default) | a `string` | | `json` | the value parsed with JSON rules | | `arrayBuffer` | an `ArrayBuffer` for binary data | | `stream` | a `ReadableStream`, best for large values | For large values the documented order from fastest to slowest is `stream`, `arrayBuffer`, `text`, `json`, because parsing costs CPU time. `get()` also accepts an **array of up to 100 keys** and then resolves to a `Map` from each key to its value, with `null` for keys that are absent. That bulk form supports only `text` and `json`. **`getWithMetadata(key)`** returns `{ value, metadata }`, so a Worker can read a value and the small JSON object stored beside it in one call. ## The missing-key case A key that does not exist is not an error. `get()` resolves to `null`, and `getWithMetadata()` resolves to `{ value: null, metadata: null }`. Code that reads a flag therefore writes its own fallback: ```javascript const flags = (await env.FLAGS.get("flags:global", { type: "json" })) ?? { newCheckout: false }; ``` The fallback matters: a flag store that has not been seeded yet, or a key that has expired, must not turn every request into a 500. ## Writing: put() and its options `env.FLAGS.put(key, value, options)` creates the key or replaces its value. The value may be a `string`, an `ArrayBuffer` or a `ReadableStream`, so binary data does not need base64 encoding. The options are: 1. **`expiration`**: an absolute time in **seconds since the UNIX epoch** after which the key is deleted. 2. **`expirationTtl`**: a number of **seconds from now**. The minimum is 60, and an expiration target less than 60 seconds in the future is rejected for both forms. 3. **`metadata`**: any JSON-serialisable object up to **1024 bytes** once serialised, returned by `getWithMetadata()` and by `list()`. After expiry the key behaves as if it never existed, and it stops counting towards stored data. An expiration also wins over a longer read-side `cacheTtl`: an expired key is deleted even where a location still holds a cached copy. `put()` returns a promise that resolves when the write is accepted. Await it, or hand it to `ctx.waitUntil()` if the response must not wait; an unawaited write can be cut off when the invocation ends, and its error is never seen. ## Deleting `env.FLAGS.delete(key)` removes the key and its value. Deleting a key that does not exist is reported as success. Like a write, a delete takes time to be seen in other locations. ## Limits a first-time user meets | Item | Limit | |---|---| | Key size | 512 bytes; not empty, not `.` or `..` | | Value size | 25 MiB | | Metadata | 1024 bytes of serialised JSON | | `expirationTtl` | at least 60 seconds | | Keys per bulk `get()` | 100 | Two behaviours shape every design built on these calls, and both have their own lessons in this material: a write can take 60 seconds or more to be visible in other locations, and a single key accepts at most one write per second. A feature-flag store suits KV because it is read on every request and written by an admin a few times a day.

  • In Workers KV, what goes wrong if a Worker calls put() without awaiting it or passing it to ctx.waitUntil()?
    The response can be returned before the write finishes. Once the invocation ends, outstanding work may be cancelled, so the write can be lost, and any rejection, such as a rate-limit error, is never observed. Await the promise when the caller needs to know the write happened, or wrap it in `ctx.waitUntil()` when the response should not wait.
  • In Workers KV, how do you read twenty flags in one call instead of twenty?
    Pass an array to `get()`: `env.FLAGS.get(["a", "b"], "json")` accepts up to 100 keys and resolves to a `Map` with `null` for absent keys. It counts as one operation against the per-invocation limit, though each key is billed as a read. The bulk form supports only `text` and `json`; binary values need individual reads in parallel.
  • In Workers KV, which wins when a key's expiration passes but a reader asked for a long cacheTtl?
    The expiration. The documentation states that expiration always takes precedence over `cacheTtl`: the key is deleted at its expiration time even if a location was told to cache it for longer.

  • get() throws an error when the key does not exist
  • KV values must be strings, so binary data has to be base64-encoded first
  • expirationTtl is given in milliseconds, like setTimeout
  • An expirationTtl of 10 seconds is fine for short-lived keys
  • The binding name in the Wrangler file must match the namespace's title
  • Metadata can hold large documents because it is stored separately from the value
open as a page

In Workers KV, why can a feature flag an admin just switched off still read as on in other locations, and what does cacheTtl change?

level: middleimportance: must knowfreq 65%

basics

~20 s

Workers KV writes go to central stores while each location serves its cached copy, so other locations may see the old value for 60 seconds or more. cacheTtl sets that cache time: 60 seconds by default, 30 at minimum.

open as a page

In Workers KV, how do you seed thousands of site-configuration keys at once when the Worker binding offers no bulk write?

level: middleimportance: should knowfreq 30%

basics

~20 s

Write them outside the Worker: wrangler kv bulk put with a JSON array file, or the REST API's bulk endpoint, which takes up to 10,000 pairs per request. In Wrangler 4 the command writes to local storage unless it is given --remote.

open as a page

In Workers KV, how do you page through every key under a prefix with list(), and when should small values live in metadata instead?

level: middleimportance: should knowfreq 40%

basics

~20 s

Call env.FLAGS.list({ prefix, cursor }) in a loop, passing the returned cursor and the same prefix each time, until list_complete is true. list() returns key names, expirations and metadata but not values, so small values kept in metadata avoid one get() per key.

open as a page

A team proposes keeping a per-user request counter in Workers KV, incremented on every request; what breaks in production, and where should the counter live instead?

level: seniorimportance: should knowfreq 50%

basics

~20 s

A Workers KV key accepts one write per second, so a busy user's increments start failing with 429 errors. A get-then-put is not atomic, so concurrent requests overwrite each other, and stale reads in other locations lose more. Counters belong in a Durable Object.

open as a page

As a platform lead, what rule would you set for which data a team may keep in Workers KV, and what evidence would make you move a dataset out of it?

level: principalimportance: should knowfreq 30%

basics

~20 s

Allow Workers KV only for data read far more than written, with one writer well under once a second per key, that tolerates reads a minute or more old. Move it out on 429s, lost updates, stale-read bugs or query-shaped access.

open as a page