Skip to content
Learni
View all tutorials
Backend

How to Optimize Cloudflare Workers in Production 2026

Lire en français

Introduction

Cloudflare Workers let you run JavaScript and WebAssembly code at the network edge. In 2026, advanced use cases include state management with Durable Objects, persistent storage via KV and R2, and queue processing. This tutorial walks you through creating a robust, scalable edge architecture from a TypeScript setup to an optimized deployment.

Prerequisites

  • Node.js 20+ and Wrangler CLI v3.50+
  • Cloudflare account with Workers Pay-as-you-go
  • Strong knowledge of TypeScript and HTTP

Project Initialization

terminal
npm create cloudflare@latest my-worker -- --template=cloudflare/workers-sdk/templates/typescript
cd my-worker
npm install

This command generates a TypeScript-ready Workers skeleton. The template already includes TypeScript configuration and Cloudflare types.

Advanced wrangler Configuration

wrangler.toml
name = "my-advanced-worker"
main = "src/index.ts"
compatibility_date = "2025-12-01"

[[kv_namespaces]]
binding = "CACHE"
id = "your_kv_id"

[[durable_objects.bindings]]
name = "SESSION"
class_name = "SessionDO"

[vars]
ENVIRONMENT = "production"

The wrangler.toml file declares KV and Durable Object bindings. The compatibility_date ensures access to the latest Workers APIs.

Main Worker with Routing

src/index.ts
import { SessionDO } from './session';

export interface Env {
  CACHE: KVNamespace;
  SESSION: DurableObjectNamespace;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    if (url.pathname.startsWith('/session')) {
      const id = env.SESSION.idFromName('global');
      const stub = env.SESSION.get(id);
      return stub.fetch(request);
    }
    return new Response('OK', { status: 200 });
  }
};

This worker routes requests to a Durable Object for state management. The idFromName pattern ensures a single global instance.

Durable Object Implementation

src/session.ts
import { DurableObject } from 'cloudflare:workers';

export class SessionDO extends DurableObject {
  async fetch(request: Request): Promise<Response> {
    const session = await this.ctx.storage.get('session') || {};
    return Response.json(session);
  }
}

The Durable Object persists state via storage. This class is exported and referenced in wrangler.toml.

Using KV and Caching

src/cache.ts
export async function getCachedData(env: Env, key: string) {
  const cached = await env.CACHE.get(key, 'json');
  if (cached) return cached;
  const fresh = await fetchDataFromOrigin();
  await env.CACHE.put(key, JSON.stringify(fresh), { expirationTtl: 3600 });
  return fresh;
}

This helper combines KV reads with a fallback and TTL caching. Avoid frequent writes to control costs.

Best Practices

  • Always use bindings declared in wrangler.toml
  • Limit KV and Durable Object payload sizes
  • Implement centralized error handling with try/catch
  • Version Workers using separate environments
  • Monitor metrics with Workers Analytics

Common Mistakes to Avoid

  • Forgetting to declare Durable Objects in wrangler.toml
  • Using mutable global variables without ctx.storage
  • Ignoring the 100ms CPU limit on free tier requests
  • Not handling KV errors in transactional mode

Going Further

Check out our advanced Cloudflare courses to master queues, R2, and observability.