# Edge Computing With Cloudflare Workers: Build Faster APIs in 2026

By [Eoin Villarin](https://amvprosox.com/about). Published 2025-10-25, updated 2026-10-28. Canonical: https://amvprosox.com/blog/edge-computing-cloudflare-workers-practical-guide

> Cloudflare Workers run your code in more than 330 cities using isolates instead of containers. Learn how KV, D1, R2, Durable Objects and Hono fit together to build fast, low-cost edge APIs.

## How do Cloudflare Workers make APIs faster, and when should I use them?

Cloudflare Workers make APIs faster by running code in data centres in more than 330 cities, close to each user, using V8 isolates that start far faster than containers. They suit small, latency-sensitive work such as feature flags, auth, API aggregation and webhook receivers, but a Worker making repeated queries to a distant database can be slower.

**Key takeaways**

- The Workers free plan allows 100,000 requests per day and 10 ms of CPU time per invocation.
- The Workers paid plan has a $5 monthly minimum including 10 million requests and 30 million CPU milliseconds.
- Workers KV is eventually consistent, and writes can take 60 seconds or more to appear in other locations.
- Use D1 for relational data, R2 for files with free egress, and Durable Objects for values users must agree on.
- Setting placement mode to smart runs a Worker close to its back end when data must stay in one region.

**Cloudflare Workers** let you run API code in data centres close to every user instead of in one region on the other side of the world. For a customer in Manila or Melbourne hitting a server in Virginia, that difference is often the gap between an app that feels instant and one that feels sluggish, before your code has even started running.

The platform has matured a lot. Workers now come with a full set of storage products, a framework ecosystem led by Hono, generous limits and pricing that is easy to predict. It is also easy to misuse: put an edge function in front of a single-region database and you can make things slower, not faster.

In this guide you will learn how the Workers runtime differs from traditional servers, which storage product to pick for each job, how to build a typed API with Hono, what it costs in 2026 and when the edge is the wrong place for your code.

## What makes edge computing with Cloudflare Workers different?

Network latency is physics. A request from Singapore to a server in US-East has to cross an ocean and back before any code runs. Edge computing moves the code instead of the user. Cloudflare's network now spans more than 330 cities, and the company states that about 95% of the world's Internet-connected population is within 50 milliseconds of one of its data centres, according to its [network page](https://www.cloudflare.com/network/).

![Stacked orange shipping containers, the heavyweight model that isolates are designed to avoid](https://amvprosox.com/api/img/1793146730890-xsrksk)
*Isolates start in milliseconds instead of booting a container. Photo: Tony Webster, CC BY 2.0*

Your Worker is deployed to all of those locations at once. There is no region to choose and no load balancer to configure. A request is handled by the nearest location that can serve it.

### Isolates instead of containers

Most serverless platforms start a container or micro virtual machine for each function, which is why cold starts can take hundreds of milliseconds or more. Workers use V8 isolates, the same sandboxing technology that separates tabs in Chrome. A single runtime process hosts thousands of isolates, and Cloudflare's [documentation on how Workers works](https://developers.cloudflare.com/workers/reference/how-workers-works/) says an isolate can start around a hundred times faster than a Node process in a container, using an order of magnitude less memory.

The trade-off is that Workers are not a full Node.js server. They run on web standard APIs like `fetch`, `Request` and `Response`. With the `nodejs_compat` flag, many Node built-ins and npm packages work, but anything that relies on native binaries or long-lived processes may not.

## Which storage should you use: KV, D1, R2 or Durable Objects?

Choosing the right storage product is the most important design decision on Workers. Each one has a different consistency model, and picking the wrong one causes the bugs that are hardest to reproduce.

| Product | What it is | Best for | Watch out for |
| --- | --- | --- | --- |
| Workers KV | Global key-value store | Config, feature flags, cached API responses | Eventually consistent; writes can take 60 seconds or more to appear elsewhere |
| D1 | Serverless SQLite database | Relational app data, catalogues, user records | 10 GB per database on the paid plan; use the Sessions API for read replicas |
| R2 | S3-compatible object storage | Images, uploads, backups, static files | Operation charges apply, but egress to the Internet is free |
| Durable Objects | Single-instance stateful compute with SQLite storage | Rate limiting, counters, chat rooms, collaboration | Each object runs in one location, so design keys carefully |

A useful rule: if a stale read for a minute is acceptable, KV is cheap and fast. If you need queries and transactions, use D1. If many users must agree on the same value at the same moment, such as stock levels or a rate limit, use a Durable Object. For an existing Postgres or MySQL database in another cloud, Cloudflare's Hyperdrive service pools connections so Workers do not open a new one per request.

## How to build an API on Cloudflare Workers with Hono

You can write Workers with raw `fetch` handlers, but for anything beyond a few routes I use **Hono**. It is a small, fast framework built on web standards with an Express-like API, full TypeScript support and middleware for CORS, JWT auth, caching and secure headers. Hono 4 is the current stable release, and a v5 release candidate is available for early testers.

![Close-up of colourful lines of code, the kind of small typed API a Worker serves](https://amvprosox.com/api/img/1793146732412-z4g3ko)
*Hono keeps Workers APIs small, typed and familiar. Photo: rawpixel, CC0*

Scaffold a project with `npm create hono@latest my-api`, choose the `cloudflare-workers` template and declare your bindings in `wrangler.jsonc`:

```
{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "catalog-api",
  "main": "src/index.ts",
  "compatibility_date": "2026-10-01",
  "compatibility_flags": ["nodejs_compat"],
  "observability": { "enabled": true },
  "d1_databases": [
    { "binding": "DB", "database_name": "catalog", "database_id": "" }
  ],
  "kv_namespaces": [
    { "binding": "CACHE", "id": "" }
  ]
}
```

Run `npx wrangler types` to generate TypeScript types for those bindings. Then write the API:

```
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'

type Bindings = { DB: D1Database; CACHE: KVNamespace }

const app = new Hono()

app.use('/api/*', cors({ origin: 'https://www.example.com' }))

app.get('/api/products/:slug', async (c) => {
  const slug = c.req.param('slug')
  const cached = await c.env.CACHE.get(`product:${slug}`, 'json')
  if (cached) return c.json(cached)

  const product = await c.env.DB
    .prepare('SELECT id, slug, name, price_cents FROM products WHERE slug = ?')
    .bind(slug)
    .first()
  if (!product) return c.json({ error: 'Not found' }, 404)

  c.executionCtx.waitUntil(
    c.env.CACHE.put(`product:${slug}`, JSON.stringify(product), { expirationTtl: 300 })
  )
  return c.json(product)
})

const review = z.object({
  rating: z.number().int().min(1).max(5),
  body: z.string().min(10).max(2000),
})

app.post('/api/products/:id/reviews', zValidator('json', review), async (c) => {
  const { rating, body } = c.req.valid('json')
  await c.env.DB
    .prepare('INSERT INTO reviews (product_id, rating, body) VALUES (?, ?, ?)')
    .bind(c.req.param('id'), rating, body)
    .run()
  return c.json({ ok: true }, 201)
})

export default app
```

### What this code does well

- **Parameterised queries** with `bind()` prevent SQL injection.

- **Cache writes happen in `waitUntil`**, so the user gets a response without waiting for KV.

- **Zod validation** rejects bad input with a 400 before it reaches the database, and the validated data is fully typed. I cover this pattern in depth in my guide to [type-safe APIs with TypeScript and Zod](https://amvprosox.com/blog/typescript-zod-type-safe-api-validation).

Hono also ships an RPC mode that shares route types with a front-end client, which is a lighter alternative to the options compared in my article on [GraphQL vs REST vs tRPC](https://amvprosox.com/blog/graphql-vs-rest-vs-trpc-2025).

## Real-world use cases that suit the edge

Workers shine when the work is small, latency matters and the data needed is either in the request or cached nearby:

- **A/B tests and feature flags:** read the variant from a cookie or KV and serve the right response with no client-side flicker.

- **Geolocation personalisation:** use the country from `request.cf` to show local currency, shipping messages or legal notices.

- **API aggregation:** call several upstream APIs in parallel and return one merged response, saving mobile clients multiple round trips.

- **Auth and bot filtering:** verify JWTs, check rate limits in a Durable Object and block abusive traffic before it reaches your origin.

- **Webhook receivers:** accept webhooks from Shopify, Stripe or a CMS, verify signatures and queue the work.

- **Image delivery:** serve files from R2 and resize them on the fly, which pairs well with the techniques in my [Core Web Vitals guide](https://amvprosox.com/blog/core-web-vitals-perfect-score-2025).

## When should you not run code at the edge?

The edge is not automatically faster. If your Worker runs in Sydney but makes five sequential queries to a database in Frankfurt, every query pays the full round trip and the user waits longer than they would with a server next to the database.

![Cockpit display screen with navigation data, like monitoring latency and errors by region](https://amvprosox.com/api/img/1793146733665-ym9zsx)
*Watch latency and errors per region after every deploy. Photo: usbotschaftberlin, CC0*

> Move your data to the edge before you move your logic there. A fast function talking to a distant database is still a slow request.

When your data has to stay in one region, turn on placement. Setting `"placement": { "mode": "smart" }` lets Cloudflare run the Worker close to the back end it talks to most, while still terminating the user's connection at the nearest location. Also be careful with:

- **CPU-heavy work** such as video processing or large PDF generation, which suits containers or queues better.

- **Libraries that need native Node modules** or a full file system.

- **Long-running connections** that would be simpler on a traditional server, unless you use Durable Objects for WebSockets.

## What do Cloudflare Workers cost in 2026?

Pricing is one of the platform's strengths, mainly because you pay for CPU time rather than wall-clock time. Waiting on `fetch`, KV or D1 does not count. According to the official [Workers pricing page](https://developers.cloudflare.com/workers/platform/pricing/):

- **Free plan:** 100,000 requests per day and 10 ms of CPU time per invocation.

- **Paid plan:** a $5 monthly minimum that includes 10 million requests and 30 million CPU milliseconds, then $0.30 per additional million requests and $0.02 per additional million CPU milliseconds.

- **Static assets:** requests for static files served by Workers are free.

The paid plan also bundles generous KV and D1 allowances, and CPU time per request defaults to 30 seconds with an option to raise it to five minutes. For most small business APIs, the bill stays at the $5 minimum.

## Deploying, testing and observing your Worker

Local development runs on the same open source runtime as production. `npm run dev` starts Wrangler on port 8787 with local versions of D1, KV and R2, and `npx wrangler deploy` pushes to every location in seconds. My workflow for production APIs:

- Write tests with the Cloudflare Vitest integration so they run inside the Workers runtime, not Node.

- Apply D1 schema changes with `wrangler d1 migrations` and commit the migration files.

- Use preview URLs or a staging environment in `wrangler.jsonc` before production.

- Keep observability enabled to collect logs and traces, and set alerts for error rates.

- Store secrets with `wrangler secret put`, never in the config file.

If you still host sites on Cloudflare Pages, Cloudflare now recommends Workers with static assets for new projects, since Workers support Durable Objects, Cron Triggers and better observability. Migration is usually a config change.

## Frequently asked questions

### Are Cloudflare Workers free?

There is a free plan with 100,000 requests per day and 10 ms of CPU time per invocation, which covers many hobby projects and small APIs. Production apps usually move to the paid plan, which has a $5 monthly minimum including 10 million requests and 30 million CPU milliseconds. Static asset requests are free on both plans.

### Do Workers have cold starts?

Not in the way container-based serverless platforms do. Workers run in V8 isolates inside an already running process, so starting a new isolate takes far less time and memory than booting a container. In practice, cold starts are rarely noticeable, although very large bundles still take longer to load than small ones.

### Can I use Node.js packages in a Worker?

Many of them, yes. Enable the `nodejs_compat` compatibility flag to get support for common Node built-ins such as `Buffer`, `crypto` and streams. Packages that depend on native binaries, child processes or direct file system access usually will not work, so check compatibility before you build a project around one.

### Is D1 a replacement for Postgres?

For many small and medium apps, yes. D1 is SQLite with a managed API, up to 10 GB per database on the paid plan and optional read replication. If you need Postgres features, larger datasets or an existing database, keep Postgres and connect through Hyperdrive, which pools connections and caches queries for Workers.

## Next steps: bring your API closer to your users

Start small. Move one latency-sensitive endpoint, such as product lookups, redirects or a webhook receiver, onto a Worker with Hono and KV caching, then measure the difference from the regions where your customers actually are. Add D1 or Durable Objects only when the data model needs them.

If you want help designing an edge API or speeding up an existing site, [contact me through the form on my homepage](https://amvprosox.com/#contact-form). You can also browse my [development case studies](https://amvprosox.com/case-studies) to see the kind of projects I deliver.
