Cloudflare Workers
Deploy JavaScript at the edge with Cloudflare Workers - ultra-low latency APIs, KV storage, Durable Objects, R2, and D1 SQLite at 275+ locations.
skill: Cloudflare Workers category: Backend tags: [Cloudflare Workers, Edge Computing, CDN, KV, Durable Objects] readingTime: 5
Cloudflare Workers run your code in 275+ data centers worldwide - the compute is where the user is, eliminating round-trip latency. With KV, Durable Objects, R2, and D1, Cloudflare provides a complete edge application stack. Use Workers for latency-critical APIs, personalization at the CDN edge, and auth middleware.
Workflow
- Write a Worker with WranglerWrangler is Cloudflare's CLI - it handles local development, TypeScript compilation, and deployment in one tool.
- Store data with KVWorkers KV is a globally replicated key-value store - reads are fast everywhere (eventually consistent), writes propagate in seconds.
- Use Durable Objects for stateful edge logicDurable Objects are single-instance globally addressable objects - perfect for rate limiting, WebSocket coordination, and game state.
- Store files with R2 and query with D1R2 is S3-compatible object storage with zero egress fees. D1 is SQLite at the edge - runs SQL queries co-located with your Worker.
- Handle routing with HonoHono is an ultra-fast web framework designed for edge runtimes - Express-like routing for Workers.
Output Format
Cloudflare Workers: Hono routing, KV for sessions, D1 for relational data, R2 for files, Durable Objects for coordination.
wrangler.toml: kv_namespaces, d1_databases, r2_buckets
src/index.ts: Hono app + D1 queries
wrangler dev → wrangler deployExamples
Input
Output
Edge Cases & Gotchas
- CPU time limits - Workers have a 10ms CPU time limit on the free plan, 50ms on paid. For longer-running work, use Workers Queues to process asynchronously.
- KV consistency - KV is eventually consistent - writes may not be visible on reads for up to 60 seconds globally. For strong consistency, use Durable Objects.
- WebSocket with Durable Objects - Stateful WebSocket connections need Durable Objects - each socket room is a Durable Object instance that holds all WebSocket connections for that room.
- Wrangler local dev differences - wrangler dev uses Miniflare to emulate the Workers runtime - mostly accurate but some APIs behave slightly differently (D1, Queues). Always test production deploy.
When to Break These Rules
- Use AWS Lambda@Edge instead of Workers for AWS-native integrations (accessing S3, DynamoDB, RDS) - Cloudflare KV/D1/R2 are Cloudflare-only.
- Use traditional servers (Node.js, Python) when your runtime needs exceed Workers' CPU time limits or require Node.js APIs unavailable in the edge runtime.
Reference Files
https://developers.cloudflare.com/workers/https://hono.dev/