Skip to content
Back to Deployment

Deploying Cloudflare Workers

Serverless compute on Cloudflare's global edge with 0ms cold starts, KV, R2, and D1.

EdgeIntermediate

Why

Cloudflare Workers run in 300+ locations with 0ms cold starts (V8 isolates, not containers). KV gives global eventually-consistent storage, R2 is S3-compatible with no egress fees, D1 is edge SQLite.

Cloudflare's edge network spans 330+ cities with sub-50ms p95 latency globally. Edge functions reduce TTFB by 60-80% compared to origin servers, and Akamai reports 40% of enterprises now use edge compute in 2024.

When

Use Workers for edge APIs, auth proxies, A/B testing, and geo-routing. Avoid for long-running tasks (>30s CPU) or heavy compute.

How

1. Write — src/index.ts, export default { fetch() {} } 2. Config — wrangler.toml for name, bindings, vars 3. Dev — npx wrangler dev for local testing 4. Deploy — npx wrangler deploy 5. KV — kv namespace create, bind in wrangler.toml 6. R2 — r2 bucket create, S3-compatible object storage 7. D1 — d1 create, edge SQLite database

Example

// src/index.ts export default { async fetch(req: Request, env: Env): Promise<Response> { const country = req.cf?.country || "unknown"; const count = parseInt(await env.KV.get("count") || "0") + 1; await env.KV.put("count", count.toString()); return Response.json({ country, count }); }, }; // wrangler.toml name = "my-worker" main = "src/index.ts" compatibility_date = "2024-01-01" [[kv_namespaces]] binding = "KV" id = "abc123"

Common Problems

  • ⚠Worker exceeds 1MB size — bundle too large, use dynamic imports or split into multiple Workers
  • ⚠KV eventual consistency — writes take up to 60s to propagate globally, use cache API for immediate reads
  • ⚠Configuration drift between environments — use infrastructure-as-code (Terraform/Pulumi) to keep dev/staging/prod identical

Best Practices

  • ✓Use wrangler.toml for all config — version controlled, not just dashboard settings
  • ✓Leverage req.cf for geo data — country, city, timezone available without external API
  • ✓Set up health checks and graceful shutdown — handle SIGTERM to drain in-flight requests before exit

FAQ