valfz

Workers from first principles

Key-value storage with KV

Move links from memory into Workers KV, add expiring links, and learn what eventual consistency means for a shortener.

lesson
05 of 08
read
11 min

The Map from lesson 3 fails in two ways: it empties when its isolate goes away, and every isolate has its own copy. Links need storage outside the isolate. Workers KV is a key-value store that a Worker reaches through a binding, and it suits this data well, because a link is written once, read many times and always looked up by its exact key. This lesson moves links into KV, adds links that expire, and then looks at what KV’s consistency model means for the project.

Add the binding

cloudflare.config.ts
@@ -12,6 +12,7 @@
 			),
 			LIMITS: bindings.json({ codeLength: 6, maxUrlLength: 2048 }),
 			ADMIN_TOKEN: bindings.secret(),
+			LINKS: bindings.kv(),
 		},
 	},
 }));

bindings.kv() accepts the id of a namespace, which is KV’s name for one independent set of keys. Leave it out for now. Under cf dev the binding is backed by a local simulation that keeps its data in .cloudflare/state/, and lesson 8 creates the real namespace. In code, env.LINKS has the type KVNamespace.

Replace the store

src/links.ts
export type Link = { url: string; createdAt: string; expiresAt?: string };

// Crockford's base32 alphabet: no i, l, o or u, so codes survive being read aloud.
const ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz";

export function newCode(length: number): string {
	const bytes = crypto.getRandomValues(new Uint8Array(length));
	let code = "";
	for (const byte of bytes) {
		code += ALPHABET[byte % ALPHABET.length];
	}
	return code;
}

export function getLink(kv: KVNamespace, code: string): Promise<Link | null> {
	return kv.get<Link>(code, "json");
}

export async function createLink(
	kv: KVNamespace,
	url: string,
	codeLength: number,
	ttlSeconds?: number,
): Promise<{ code: string; link: Link }> {
	const now = Date.now();
	const link: Link = { url, createdAt: new Date(now).toISOString() };
	if (ttlSeconds !== undefined) {
		link.expiresAt = new Date(now + ttlSeconds * 1000).toISOString();
	}

	for (let attempt = 0; attempt < 3; attempt++) {
		const code = newCode(codeLength);
		if ((await kv.get(code)) !== null) continue;
		await kv.put(code, JSON.stringify(link), { expirationTtl: ttlSeconds });
		return { code, link };
	}
	throw new Error("no free code after 3 attempts");
}

kv.get(code, "json") parses the stored value and resolves to null when the key does not exist. kv.put() stores a string here; it also accepts streams and buffers. Both functions take the namespace as an argument, so this module still knows nothing about env.

The loop in createLink deals with collisions. Two random codes are unlikely to be equal, but the chance grows with the number of links stored, and silently overwriting an existing link would send its visitors somewhere else. So the function checks that a code is free before using it and draws again if it is taken.

That check is not airtight. KV has no “write only if absent” operation, so two requests that draw the same code at the same moment can both see null and both write, and the KV documentation is explicit that the last write wins. For a shortener with one administrator and a billion possible codes, that window is acceptable. If it were not, uniqueness would have to be enforced by a store that can enforce it, such as a UNIQUE column in the D1 database that lesson 6 adds.

Update the handlers

src/index.ts
@@ -1,6 +1,6 @@
 import { requireToken } from "./auth.ts";
 import { HttpError, readJsonObject } from "./http.ts";
-import { getLink, newCode, saveLink } from "./links.ts";
+import { createLink, getLink } from "./links.ts";
 
 type RouteArgs = {
 	request: Request;
@@ -51,10 +51,9 @@
 	await requireToken(request, env.ADMIN_TOKEN);
 	const body = await readJsonObject(request);
 	const target = parseTarget(body.url, env.LIMITS.maxUrlLength);
+	const ttl = parseTtl(body.ttl);
 
-	const code = newCode(env.LIMITS.codeLength);
-	const link = { url: target.href, createdAt: new Date().toISOString() };
-	saveLink(code, link);
+	const { code, link } = await createLink(env.LINKS, target.href, env.LIMITS.codeLength, ttl);
 
 	return Response.json(
 		{ code, ...link, short: new URL(`/${code}`, env.PUBLIC_ORIGIN).href },
@@ -62,15 +61,15 @@
 	);
 }
 
-function showLink({ params }: RouteArgs): Response {
+async function showLink({ env, params }: RouteArgs): Promise<Response> {
 	const code = params.code ?? "";
-	const link = getLink(code);
+	const link = await getLink(env.LINKS, code);
 	if (!link) throw new HttpError(404, "no such link");
 	return Response.json({ code, ...link });
 }
 
-function followLink({ params }: RouteArgs): Response {
-	const link = getLink(params.code ?? "");
+async function followLink({ env, params }: RouteArgs): Promise<Response> {
+	const link = await getLink(env.LINKS, params.code ?? "");
 	if (!link) throw new HttpError(404, "no such link");
 	return Response.redirect(link.url, 302);
 }
@@ -88,3 +87,11 @@
 	}
 	return target;
 }
+
+function parseTtl(value: unknown): number | undefined {
+	if (value === undefined) return undefined;
+	if (typeof value !== "number" || !Number.isInteger(value) || value < 60) {
+		throw new HttpError(400, "ttl must be a whole number of seconds, at least 60");
+	}
+	return value;
+}

The handlers are now async and pass env.LINKS down. Create a link and follow it:

curl -X POST http://localhost:8791/api/links -H 'Authorization: Bearer local-dev-token' -d '{"url":"https://developers.cloudflare.com/kv/"}'
{"code":"axttmm","url":"https://developers.cloudflare.com/kv/","createdAt":"2026-11-28T22:11:20.059Z","short":"http://localhost:8791/axttmm"}
curl -i http://localhost:8791/axttmm
HTTP/1.1 302 Found
...
location: https://developers.cloudflare.com/kv/
...

Stop the dev server, start it again and ask for the link:

curl http://localhost:8791/api/links/axttmm
{"code":"axttmm","url":"https://developers.cloudflare.com/kv/","createdAt":"2026-11-28T22:11:20.059Z"}

The link outlived the process that created it.

The request body now accepts an optional ttl in seconds, which createLink passes to KV as expirationTtl:

curl -X POST http://localhost:8791/api/links -H 'Authorization: Bearer local-dev-token' -d '{"url":"https://example.com/sale","ttl":3600}'
{"code":"zpvcbc","url":"https://example.com/sale","createdAt":"2026-11-28T22:11:20.095Z","expiresAt":"2026-11-28T23:11:20.095Z","short":"http://localhost:8791/zpvcbc"}

KV deletes the key when the time is up. After that a read returns null, and the 404 path that already exists handles it. There is no cleanup job to write. expiresAt is stored only so the API can show it.

KV’s minimum TTL is 60 seconds, and parseTtl enforces the same limit:

curl -X POST http://localhost:8791/api/links -H 'Authorization: Bearer local-dev-token' -d '{"url":"https://example.com/sale","ttl":30}'
{"error":"ttl must be a whole number of seconds, at least 60"}

Without that check KV rejects the write itself. The client would see the error boundary’s 500, and the useful message would only be in the log:

Error: KV PUT failed: 400 Invalid expiration_ttl of 30. Expiration TTL must be at least 60.

When you know a limit of the storage underneath, validate it at the edge of your API, where the failure can be a 400 that tells the client what to fix.

The consistency you get

Everything above ran against the local simulation, which behaves like an ordinary database: write, then read your write. The deployed service makes a different trade, described in How KV works.

A write goes to central storage. A read is answered from a cache in the data center that received the request, and that cache is filled on first use and refreshed in the background. Reads of popular keys are therefore fast everywhere. The price is that a change is usually visible at once in the location that made it but can take 60 seconds or more to appear in others. KV is eventually consistent.

For the shortener this has three consequences.

A missing key is cached like any other answer. If someone requests /axttmm in Frankfurt before the link exists, and you then create it from Paris, Frankfurt may keep answering 404 for about a minute.

Deleting or changing a link takes the same time to reach locations that have it cached. get() accepts a cacheTtl option, 60 seconds by default and 30 at minimum, that sets how long a location may reuse its copy. Raising it makes reads of rarely used links faster and makes changes slower to spread.

KV is the wrong tool for a counter. A counter is a read followed by a write, so concurrent requests overwrite each other’s increments, and KV rejects more than one write per second to the same key. Visit counts go to D1 in the next lesson.

The limits are generous for this use: keys up to 512 bytes and values up to 25 MiB. The Free plan allows 100,000 reads and 1,000 writes per day.

Inspect local data

cf can read and write the local simulation directly. Add --local, and pass the namespace ID. For a binding without an id, the local ID is the binding name and the Worker name joined by a hyphen:

pnpm exec cf kv keys list --namespace-id LINKS-shortlinks --local
...
[
  {
    "name": "axttmm"
  },
  {
    "name": "zpvcbc",
    "expiration": 1795907480
  }
]
pnpm exec cf kv keys get axttmm --namespace-id LINKS-shortlinks --local --text
{"url":"https://developers.cloudflare.com/kv/","createdAt":"2026-11-28T22:11:20.059Z"}

Writing works too, which is a quick way to seed a memorable code:

pnpm exec cf kv keys put docs --namespace-id LINKS-shortlinks --body '{"url":"https://developers.cloudflare.com/","createdAt":"2026-11-28T00:00:00.000Z"}' --local
curl -i http://localhost:8791/docs
{}
HTTP/1.1 302 Found
...
location: https://developers.cloudflare.com/
...

Be careful with the flag. Without --local, every cf kv command acts on your Cloudflare account. The Local Explorer at http://localhost:8791/cdn-cgi/local/explorer shows the same data in a browser, along with the local namespace IDs.

The single test still passes, because the code it asks for does not exist in KV either. Lesson 6 adds the second store: a D1 database that records every visit.

Exercises

  1. Let the client choose the code. Accept an optional code field (3 to 32 lowercase letters, digits or hyphens) and answer 409 when it is taken. The result is correct when the first POST with "code":"docs-2" returns 201 with that code, the same request again returns 409, and a POST without code still gets a random one.
  2. Add DELETE /api/links/:code, protected by the token. It should answer 204, and afterwards pnpm exec cf kv keys list --namespace-id LINKS-shortlinks --local no longer lists the code.
  3. Add GET /api/links, protected by the token, that returns every code with its creation time. Store createdAt as KV metadata on put() and build the response from list() alone, which returns key names and metadata but not values. The result is correct when the response covers all keys and the handler makes no get() calls.

keyboard

h
home
w c a
writing, courses, about
n p
next and previous lesson
j k
scroll down and up
g G
top and bottom of the page
t
switch light and dark
?
this help

shortcuts are