---
title: "Cloudflare Workers KV: build a redirect service"
description: "Build a small Hono redirect service with Workers KV. Test it locally, understand stale reads and expiration, and learn when to choose KV, D1, or Durable Objects."
author: "Omar Albeik"
date: 2026-11-30
type: tutorial
topics: [infrastructure]
language: en
reading_time_minutes: 13
canonical_url: https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-kv
translation_url: https://omaralbeik.com/ar/blog/series/cloudflare/understanding-cloudflare-kv
source_url: https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-kv.md
---

# Cloudflare Workers KV: build a redirect service

You put a link in a newsletter. A month later, the page moves. You can fix your website, but you cannot edit the copies sitting in people's inboxes.

A link you control, such as `/go/cloudflare-d1`, gives you a stable address to share. The service looks up its current destination and sends the browser there. When the article moves, you update the stored address.

[Workers KV](https://developers.cloudflare.com/kv/) suits this kind of lookup: we know the key, need one small value, and expect far more visits than edits. It also comes with a condition we need to accept: after an update, some readers may temporarily reach the previous destination.

In [part five](/en/blog/series/cloudflare/understanding-cloudflare-d1), we used D1 to save drafts and protect them from conflicting edits. Here we'll build a separate Hono service and manage its links with Wrangler. You can follow along without the earlier project.

- [Understand where KV fits](#when-kv-fits).
- [Build and test a redirect locally](#start-with-a-local-namespace).
- [See what happens after an update](#why-a-link-can-still-return-its-old-destination).
- [Separate caching from expiration](#separate-caching-from-expiration).
- [Deploy and estimate the cost](#give-the-deployed-worker-its-own-namespace).
- [Diagnose an unexpected response](#when-a-link-doesnt-behave-as-expected).

## When KV fits

For this service, a record is just two strings:

```text
Key:    link:cloudflare-d1
Value:  https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-d1
```

A **namespace** is a collection of these pairs. A **binding** gives the Worker access to that namespace as `env.LINKS`. The `link:` prefix is our naming convention; it is not a folder or a permissions boundary.

KV caches values across Cloudflare's network as they are accessed. Frequently requested values can be served from a nearby cache. A lookup without a cached value—a *cold read*—may need to reach storage farther away. Calling `put()` does not immediately place a copy in every location.

That makes KV useful for lookup tables and application settings where a delay in seeing updates is acceptable. A bank balance, inventory reservation, or access decision that must reflect the latest change needs stronger guarantees. Cloudflare describes this behavior in [How KV works](https://developers.cloudflare.com/kv/concepts/how-kv-works/).

For a few fixed redirects, rules in your site configuration may be enough. Here we want to change destinations independently of the Worker's code. We'll maintain a directory of article links ourselves; visitors will only be able to follow them.

**From short link to article**

Follow a request to /go/cloudflare-d1 from the first lookup to the article.

**01 · Reader → Worker — GET /go/cloudflare-d1**

Hono matches the route and validates the slug.

**02 · Worker → KV — get("link:cloudflare-d1")**

KV returns the destination for this key, or null if the lookup finds nothing.

**03 · Worker → Reader — 302 + Location**

The Worker validates the destination and sends a temporary redirect with Cache-Control: no-store.

**04 · Reader → Destination — GET /en/blog/…**

The browser follows the Location header and requests the article.

A missing key returns 404. An invalid destination or a failed lookup returns 503.

*KV supplies the destination. The browser makes a separate request to open it; the Worker does not fetch the article on the reader's behalf.*

## Start with a local namespace

Use a Node.js version supported by [Wrangler](https://developers.cloudflare.com/workers/wrangler/install-and-update/). In a new directory:

```bash
mkdir link-router
cd link-router
npm init -y
npm install hono@4
npm install -D wrangler@4 typescript
mkdir src
```

We'll keep using Wrangler, as in the earlier articles. Create this configuration:

```jsonc title="wrangler.jsonc"
{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "link-router",
  "main": "src/index.ts",
  "compatibility_date": "2026-11-30",
  "compatibility_flags": ["nodejs_compat"],
  "upload_source_maps": true,
  "observability": { "enabled": true },
  "kv_namespaces": [
    {
      "binding": "LINKS",
      "id": "00000000000000000000000000000000"
    }
  ]
}
```

The all-zero ID is a placeholder for local development. We haven't created a remote namespace. With local bindings, Wrangler keeps the data under `.wrangler/state`; restarting the server preserves it. Add `node_modules/`, `.wrangler/`, and `.dev.vars*` to `.gitignore`.

Generate the binding types:

```bash
npx wrangler types
```

Add a TypeScript configuration so the editor and compiler can find them:

```json title="tsconfig.json"
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "lib": ["ES2022"],
    "types": ["./worker-configuration.d.ts"],
    "strict": true,
    "skipLibCheck": true,
    "noEmit": true
  },
  "include": ["src/**/*.ts", "worker-configuration.d.ts"]
}
```

## Read one key and return a redirect

The route accepts a slug such as `cloudflare-d1`, reads its destination, and returns a `302`. We allow lowercase letters, numbers, and hyphens between them, up to 64 characters. Destinations must be HTTPS blog pages on this site. Replace the origin and allowed paths when adapting the example for your own site.

```ts title="src/index.ts"
import { Hono } from "hono";

const app = new Hono<{ Bindings: Env }>();
const slugPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;

function allowedDestination(value: string): string | null {
  try {
    const url = new URL(value);
    const isBlog =
      url.pathname.startsWith("/en/blog/") ||
      url.pathname.startsWith("/ar/blog/");

    if (
      url.origin !== "https://omaralbeik.com" ||
      url.username ||
      url.password ||
      !isBlog
    ) {
      return null;
    }

    return url.href;
  } catch {
    return null;
  }
}

app.use("*", async (c, next) => {
  c.header("Cache-Control", "no-store");
  await next();
});

app.get("/health", (c) => c.json({ ok: true }));

app.get("/go/:slug", async (c) => {
  const slug = c.req.param("slug");
  if (slug.length > 64 || !slugPattern.test(slug)) {
    return c.text("Link not found", 404);
  }

  const value = await c.env.LINKS.get(`link:${slug}`);
  if (value === null) return c.text("Link not found", 404);

  const destination = allowedDestination(value);
  if (destination === null) {
    console.error({ event: "invalid_link_destination", slug });
    return c.text("Link temporarily unavailable", 503);
  }

  return c.redirect(destination, 302);
});

app.all("/go/:slug", (c) => {
  c.header("Allow", "GET, HEAD");
  return c.text("Method not allowed", 405);
});

app.onError((error, c) => {
  console.error({ event: "link_lookup_failed", message: error.message });
  c.header("Cache-Control", "no-store");
  return c.text("Link temporarily unavailable", 503);
});

export default app;
```

[`get()` returns text by default](https://developers.cloudflare.com/kv/api/read-key-value-pairs/) and returns `null` for a missing key. A storage error is different: it reaches `onError`, which returns `503` rather than telling the reader the link does not exist. `/health` only checks that the Worker responds; it does not test access to KV.

The destination check rejects malformed URLs, other origins, embedded credentials, and paths outside the blog. Comparing the parsed `origin`—scheme, hostname, and port—rejects lookalike domains such as `omaralbeik.com.example.net`. Visitors cannot set a destination through a query parameter or a write request.

The path check also rejects direct links back to `/go/`. It does not follow the destination to inspect any redirects that page might return.

We use a [temporary redirect](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/302) because destinations can change. `Cache-Control: no-store` asks browsers and shared HTTP caches not to retain the response. It does **not** bypass KV's internal cache.

## Try your first link

Save a destination into the local namespace, then start the Worker:

```bash
npx wrangler kv key put "link:cloudflare-d1" \
  "https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-d1" \
  --binding LINKS --local

npx tsc
npx wrangler dev --local
```

In a second terminal, inspect the response without following it:

```bash
curl -i http://localhost:8787/go/cloudflare-d1
```

Expect a `302` with these headers; capitalization and order may differ:

```http
Location: https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-d1
Cache-Control: no-store
```

Open that same localhost URL in a browser to follow the redirect. Then try `/go/not-created`: it should return `404`. A `POST` to an existing short link should return `405`. Hono also handles `HEAD` through the `GET` route and omits the response body, so `curl -I` works too.

To change the destination, write the same key again. This time, send the reader to the Arabic article:

```bash
npx wrangler kv key put "link:cloudflare-d1" \
  "https://omaralbeik.com/ar/blog/series/cloudflare/understanding-cloudflare-d1" \
  --binding LINKS --local
```

Repeat the `curl` request. You should now see the Arabic article's address. Keep all commands in the same project directory so they use the same configuration and local state.

Local testing verifies our routing, validation, and storage operations. It does not reproduce KV's global cache behavior. Seeing a new value immediately on your machine does not tell you when a reader in another region will see it.

## Why a link can still return its old destination

Suppose requests from Amsterdam and Singapore have both read the English article's address. You change the destination to the Arabic article. A later lookup from one location may return the new address while the other still returns the old one.

The write succeeded, but the readers received different cached versions. With *eventual consistency*, reads converge on the updated value after writes stop. Until then, even a read at the location that performed a write may return an older value. [Cloudflare documents delays of 60 seconds or more](https://developers.cloudflare.com/kv/concepts/how-kv-works/#consistency), depending on cached values and their lifetime. That is not a fixed deadline by which every reader will see the update.

**One key, two possible answers**

Switch the link from the English article to the Arabic article, then see what two locations might read.

**Before the change — Both locations have the English destination**

Stored destination: English article. Amsterdam: English article. Singapore: English article.

Earlier requests left a cached address for the English article in both locations.

**The write succeeds — The stored link now points to the Arabic article**

Stored destination: Arabic article. Amsterdam: English article (cached). Singapore: English article (cached).

The write has completed. Either location may still read the previous destination.

**Two later reads — Amsterdam reads the new address; Singapore reads the old one**

Stored destination: Arabic article. Amsterdam: Arabic article. Singapore: English article.

In this example, a read from Amsterdam gets the updated address. A read from Singapore gets the cached English destination. Either location could have received the update first.

**Later, after refresh — Both reads return the Arabic destination**

Stored destination: Arabic article. Amsterdam: Arabic article. Singapore: Arabic article.

Both locations now return the updated address. The steps are not equally spaced in time, and other sequences are possible.

The result “key not found” can be cached too. Someone who requested a link before it existed may still receive that result after you create it.

*Step through one possible sequence. The locations are illustrative, and the steps have no fixed duration; this is not a measurement of Cloudflare's network.*

The result “key not found” is cached too. If someone requests `/go/new-article` before you create it, that location may continue seeing a missing key after the write succeeds. Create links before sharing them and check the deployed route. A successful check confirms that request worked; other locations may still return an older result.

Keep the old destination working while the update becomes visible. For an urgent takedown, do not assume deleting a KV key stops all readers immediately: [deletion also takes time to become visible](https://developers.cloudflare.com/kv/api/delete-key-value-pairs/). If your service must disable a link immediately, KV alone cannot enforce that requirement.

## Separate caching from expiration

TTL means *time to live*, but the important question is what expires: a cached lookup, the stored key, or an HTTP response.

**What each setting controls**

Choose the setting for the layer you want to change: KV lookup, stored key, or HTTP response.

**KV lookup cache — cacheTtl**

Set on get(). Controls how long a lookup result is cached in a network location. It does not delete the stored key.

**Stored key — expirationTtl**

Set on put(); --ttl in Wrangler. Deletes the key after the chosen lifetime. Key expiration takes precedence over the KV cache lifetime.

**HTTP response — Cache-Control**

Set on the response. Our no-store header asks browsers and shared HTTP caches not to store the redirect. It does not control KV's cache.

Our route uses the default KV cache lifetime, keeps ordinary links until we delete them, and sends no-store on HTTP responses.

*A cached lookup, a stored key, and an HTTP response have different lifetimes. Setting one does not set the others.*

Our `get()` uses the default 60-second KV cache lifetime. You can supply [`cacheTtl` on a read](https://developers.cloudflare.com/kv/api/read-key-value-pairs/); its documented minimum is 30 seconds. A longer lifetime can reduce trips to central storage, at the cost of potentially serving older values for longer. Setting it to `0` is not a supported way to bypass the cache.

For a link that should disappear after an hour, set expiration when writing:

```bash
npx wrangler kv key put "link:weekend-reading" \
  "https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-d1" \
  --binding LINKS --local --ttl 3600
```

Wrangler calls this flag `--ttl`; the binding API calls the equivalent option `expirationTtl`. Absolute expiration uses a Unix timestamp **in seconds**, not JavaScript's milliseconds. Both forms require an expiration at least 60 seconds in the future. An expired key reads as missing, so this service returns `404`.

[Key expiration takes precedence over KV's cache lifetime](https://developers.cloudflare.com/kv/api/write-key-value-pairs/#expiring-keys). It cannot undo a redirect the browser has already followed. When updating an expiring link, include its expiration in the new write too.

## Maintain the directory without an admin API

For a small directory, the [Wrangler commands](https://developers.cloudflare.com/workers/wrangler/commands/kv/) are enough:

```bash
npx wrangler kv key get "link:cloudflare-d1" --binding LINKS --local
npx wrangler kv key list --prefix "link:" --binding LINKS --local
npx wrangler kv key delete "link:weekend-reading" --binding LINKS --local
```

`get` is useful for checking what you stored. `list` finds keys with the prefix; it does not give you SQL filters over their values. If you later use the binding's [`list()` API](https://developers.cloudflare.com/kv/api/list-keys/), follow its cursor until `list_complete` is true. An empty page alone does not prove the listing is finished.

Wrangler uses your Cloudflare credentials for remote writes; the public Worker exposes only reads. In a team, review changes and give automation an API token with only the permissions it needs. If you add a dashboard for editors, verify who they are, check which links they may change, and record their edits.

KV does not offer an atomic “create only if absent” operation through `get()` followed by `put()`. Two writers can both see a missing key, then overwrite each other. We can keep this directory manageable by publishing changes through one process. If several editors need to reserve names concurrently, use a unique constraint in D1 or coordinate requests through a Durable Object.

For the same reason, don't add a click counter by reading a number, incrementing it, and writing it back to KV. Concurrent requests can lose increments, and KV limits writes to the same key to one per second. Use an analytics system for traffic reporting, or storage designed for the counting guarantees you need.

## Give the deployed Worker its own namespace

Everything so far has stayed on your machine. When you are ready to deploy your own service, log in and create its remote namespace:

```bash
npx wrangler login
npx wrangler kv namespace create LINKS
```

Use the returned namespace ID in `wrangler.jsonc`, replacing the all-zero placeholder. If Wrangler offers to update the file, inspect the resulting binding rather than adding a duplicate. The binding name must remain `LINKS`.

Add the link to the remote namespace before deploying:

```bash
npx wrangler kv key put "link:cloudflare-d1" \
  "https://omaralbeik.com/en/blog/series/cloudflare/understanding-cloudflare-d1" \
  --binding LINKS --remote

npx wrangler types
npx tsc
npx wrangler deploy
```

Local data is not uploaded by `deploy`. A namespace also lives independently of a Worker version: rolling back code does not undo a destination edit. Keep the link definitions in a versioned file, or maintain another copy you can restore.

Use the deployment URL Wrangler prints and append `/go/cloudflare-d1`. Check its status and `Location` header with `curl -i`, then follow it in a browser. Use `npx wrangler tail` to inspect the structured errors if a lookup returns `503`.

Keep preview and production namespaces separate. Two Workers bound to the same namespace share data, regardless of their names or Git branches. Continue using explicit `--local` and `--remote` flags when maintaining links; they make the target visible in the command you're about to run.

To use your own domain, attach a dedicated hostname such as `go.your-domain.com`, as covered in [the hosting article](/en/blog/series/cloudflare/hosting-a-website-on-cloudflare-workers). This example's path would then be `https://go.your-domain.com/go/cloudflare-d1`. Serving `/go/*` on an existing website instead requires integrating the handler with that site's routing.

## What does a redirect cost?

Each `GET` or `HEAD` request with a valid slug makes one KV read, including a missing link. A warm KV cache can improve latency; it does not remove the billable read. Invalid slugs and unsupported methods are rejected before accessing KV.

These are the [published KV allowances and rates](https://developers.cloudflare.com/kv/platform/pricing/), checked on November 30, 2026:

| Operation | Free plan | Included with Workers Paid | Additional usage on Paid |
| --- | --- | --- | --- |
| Read keys | 100,000/day | 10 million/month | $0.50/million |
| Write keys | 1,000/day | 1 million/month | $5/million |
| Delete keys | 1,000/day | 1 million/month | $5/million |
| List requests | 1,000/day | 1 million/month | $5/million |
| Stored data | 1 GB | 1 GB | $0.50/GB-month |

For example, 12 million KV reads in a month on Paid would add **$1 in KV read charges** after the 10 million included reads. That is not the total application bill: Workers plan and execution charges, other KV operations, and other applications sharing the allowance still matter. Free allowances reset daily at midnight UTC; exceeding one makes further operations of that type fail until the allowance resets.

The [limits](https://developers.cloudflare.com/kv/platform/limits/) most relevant here are 512 bytes per key, 25 MiB per value, and one write per second to the same key. Our destinations are tiny; a busy editor or a bot requesting many nonexistent slugs is more likely to expose an operational problem than value size. Workers request and CPU limits also apply. Monitor usage and add rate limits where traffic warrants them.

## When a link doesn't behave as expected

Inspect the first response with `curl -i`, without `-L`, so you can see what the redirect Worker actually returned. Start with the status and `Location` header:

| What you see | What to check |
| --- | --- |
| Local links work, but the deployed route returns `404` | Did you write the key to the remote namespace? Does its ID match the deployed binding? `deploy` does not copy local keys. |
| A newly created link returns `404` | Check spelling, the `link:` prefix, expiration, and the namespace. A previous missing-key lookup may also be cached. |
| The response has the old `Location` | Check the namespace you updated, then consider KV's cached value. Repeated writes do not force every location to refresh. |
| `curl` shows the new `Location`, but a browser opens an old page | Inspect the browser's network trace, including any further redirects. An earlier HTTP redirect, a service worker, or the destination itself may be involved. |
| The route returns `503` | Read the Worker logs. Our code distinguishes an invalid stored URL from a failed lookup, which can include a quota error. |

One request only tells you what that request saw. Use it to narrow the problem, not to conclude that every location has the same value.

## Choosing between KV, D1, and Durable Objects

Choose storage based on the operations you need and the delays or conflicts your application can tolerate:

| Requirement | A useful starting point |
| --- | --- |
| Resolve a known key; occasional older values are acceptable | KV |
| Find drafts by owner, enforce unique slugs, or update several related rows | D1 |
| Coordinate requests around shared state, such as a room or a live session | Durable Objects |

A Durable Object can coordinate writes to KV, but requests that read from KV can still receive older values. Coordinating writes does not change the guarantees of those reads.

KV fits this directory because edits are infrequent and the previous destination remains usable during an update. If you need immediate takedowns or coordinated editing, revisit the storage choice before adding more workarounds.

Have you debugged a link that kept sending readers to an old destination? I'd like to hear where the stale value turned out to be. If this guide helped, share it with someone choosing storage for a Worker.
