“Edge computing” is one of those phrases that means everything and nothing in marketing copy. In practice, for most web teams, it means running small pieces of code in data centers close to users, in front of or instead of your origin server. Cloudflare is the most widely used platform for this: its network spans hundreds of cities, and its developer platform bundles compute (Workers), storage (KV, R2, D1, Durable Objects) and security (WAF, rate limiting, bot management).
This article is about using it well. We cover what runs at the edge and how, the use cases that pay off, the limits that surprise people, and a way to reason about cost.
How Workers differ from servers and containers
A Cloudflare Worker is JavaScript, TypeScript or WebAssembly code that runs in a V8 isolate. Isolates are lightweight: they start in milliseconds, with no container boot, so cold starts are effectively negligible for most requests. A single Worker deploys to the whole network, and requests are handled by the nearest location.
The trade-offs follow from that design:
- Not Node.js. Workers implement web-standard APIs (
fetch,Request,Response,crypto, streams). Node compatibility has improved considerably through compatibility flags, but native modules, long-lived sockets and large dependency trees do not fit well. - Strict resource limits. CPU time per request, memory (128 MB per isolate), and bundle size are bounded. The exact figures vary by plan and change over time, so check the official Workers limits page before designing around them.
- No local disk or persistent process. State lives in bindings: KV, R2, D1, Durable Objects, Queues. Anything held in a global variable may disappear between requests.
- Billing is by requests and CPU time, not wall-clock time spent waiting on I/O, which makes network-bound workloads cheap.
The storage options, and when to use each
| Service | Model | Consistency | Good for | Poor for |
|---|---|---|---|---|
| KV | Key-value, global | Eventually consistent (changes can take up to about a minute to propagate) | Configuration, feature flags, redirects, cached lookups | Counters, anything needing read-after-write |
| R2 | Object storage, S3-compatible API | Strong | Images, video, backups, user uploads, large files | Small high-frequency transactional records |
| D1 | SQLite-based relational database | Strong within a primary, read replicas available | Small to medium relational data, per-app databases | Heavy write throughput, large analytic scans |
| Durable Objects | Single-instance stateful object with storage | Strong, serialized | Coordination, rate limiters, WebSocket rooms, per-entity state | Data that needs wide fan-out reads |
| Queues | Message queue | At-least-once delivery | Background work, webhook fan-out | Strict ordering guarantees |
R2 deserves attention on cost grounds: it charges no egress fees, which changes the economics of serving large files compared with typical cloud object storage. Storage and operation costs still apply.
The edge is not a faster place to run your whole application. It is a good place to run the decisions that must happen before a request ever reaches it.

Use cases that pay off
1. Request routing, redirects and rewrites
Marketing sites accumulate thousands of redirects. Storing them in KV and resolving them in a Worker keeps them out of the application and answers in a few milliseconds from the nearest location. The same pattern handles locale-based routing, A/B test assignment through a cookie, and gradual migration from an old stack to a new one by proxying selected paths to different origins.
export default {
async fetch(request, env) {
const url = new URL(request.url);
const target = await env.REDIRECTS.get(url.pathname);
if (target) {
return Response.redirect(new URL(target, url).toString(), 301);
}
return fetch(request); // pass through to origin
},
};
2. Authentication and authorization at the door
Validating a signed token (a JWT or an opaque session checked against KV) in a Worker lets you reject unauthenticated traffic before it consumes origin capacity. This is especially useful for protecting internal tools and staging environments, and for gating downloads on a per-user basis through signed URLs.
3. Image and asset optimization
Cloudflare Images and image resizing transform formats and dimensions on demand and cache the result. Serving WebP or AVIF to browsers that accept them and appropriately sized variants to mobile devices often delivers the single largest performance gain per hour of engineering work.
4. API gateway and caching in front of slow origins
A Worker can cache API responses with fine-grained keys using the Cache API, collapse concurrent identical requests, and return stale data while revalidating in the background. When an origin lives in a single region, such as a database server in the US, global users benefit from cached reads served nearby. Tiered caching reduces origin load further.
5. Security controls
The Web Application Firewall applies managed rulesets against common attacks (SQL injection, cross-site scripting, known CVE exploit patterns) and lets you write custom rules based on country, ASN, path, header or request rate. Rate limiting rules protect login, signup and search endpoints. Bot management and Turnstile (a CAPTCHA alternative) reduce credential stuffing and scraping. Practical advice:
- Run new custom rules in log or managed challenge mode before blocking.
- Lock the origin so it only accepts traffic from Cloudflare (authenticated origin pulls or a tunnel); otherwise attackers can bypass the WAF by hitting the origin IP directly.
- Review WAF events weekly in the first month to tune false positives.
6. Personalization on cached pages
Edge code can inject small pieces of dynamic content, such as a user’s name or a regional price, into an otherwise cached HTML page using HTMLRewriter, a streaming parser. This keeps most of the page static and fast while personalizing it.
7. Webhooks and lightweight APIs
Receiving webhooks from payment providers, verifying signatures, writing the event to a queue, and returning 200 quickly is an ideal Worker task. The processing then happens elsewhere, with retries. The same shape suits form handlers, link shorteners, and small public APIs.
Where the edge is the wrong tool
Be honest about workloads that do not fit:
- Chatty database access. If every request makes five queries to a Postgres database in Virginia, running the code in Singapore adds latency rather than removing it. Either use connection pooling and placement features that run the Worker near the database, cache aggressively, or keep the logic at the origin.
- Heavy CPU work. Image processing in JavaScript, large PDF generation and machine learning inference beyond what Workers AI offers will hit CPU limits.
- Long-running processes. Batch jobs, cron work that takes minutes, and video encoding belong on queues plus containers or traditional servers. Workers have cron triggers, but each invocation is bounded.
- Large existing Node applications. Porting a framework app with native dependencies is often more costly than the performance gain justifies. Frameworks such as Next.js have adapters for Cloudflare, but verify feature coverage for your specific version.
- Strong global consistency. KV’s eventual consistency will bite you if you store anything users expect to read back instantly.
Debugging is also different. You rely on wrangler dev, tail logs, and tracing, and local behavior can differ subtly from production. Budget for building good observability from the beginning.
Cost: how to estimate before committing
Cloudflare’s pricing is usage-based and has a generous free tier plus a paid plan with a low monthly base fee. Exact prices change, so confirm on the official pricing page, but the structure is stable and you can model it:
- Workers requests and CPU time. Estimate monthly requests and average CPU milliseconds per request. Network-bound code that mostly awaits
fetchuses very little CPU time. - KV operations. Reads are cheap, writes and list operations cost more, so design for read-heavy usage.
- R2 storage and operations. Charged per GB-month plus Class A (writes, lists) and Class B (reads) operations. No egress fees.
- D1 and Durable Objects. Charged by rows read and written for D1, and by requests plus duration for Durable Objects.
- WAF, bot management and advanced rate limiting. Some features need Pro, Business or Enterprise plans, and enterprise bot features are quoted individually.
A worked example, with deliberately round assumptions: a site handling 50 million requests per month, with a Worker that does a KV lookup and passes through to origin, will typically cost tens of dollars on the paid plan rather than hundreds. The same traffic through a container-based service in a single region, with the egress charged by a hyperscaler, usually costs more and is slower for distant users. Conversely, a CPU-heavy Worker running 50 ms per request on 50 million requests consumes significant billable CPU time, so measure with real traffic using a staged rollout and the analytics dashboard.
Hidden costs matter too: engineering time to adapt code, vendor lock-in through proprietary bindings (mitigated by keeping business logic portable and using standard APIs), and the operational overhead of a second runtime to monitor.
A pragmatic adoption path
- Put the domain behind Cloudflare with caching and the WAF in front of the existing origin. This alone delivers DDoS protection, TLS and static asset caching with no code changes.
- Add Workers for redirects, headers and routing, moving rules out of the application.
- Move static and user-uploaded assets to R2 with a custom domain, and measure the egress savings.
- Introduce edge logic gradually: token checks, caching of public API responses, personalization.
- Consider full-stack edge applications only for new, edge-friendly services, using D1 or Durable Objects where their consistency models fit.
At each step, define a rollback: keep the origin reachable, use gradual rollouts through routes on a subset of paths, and version Workers so you can revert in seconds. In our work at Datainter, the first two steps usually capture most of the value, and the more advanced ones are warranted only when a measured bottleneck points to them.
Key takeaways
- Workers run in lightweight isolates with negligible cold starts, but they are not Node.js and have firm CPU, memory and size limits; read the current limits before designing.
- Choose storage by consistency needs: KV for read-heavy configuration, R2 for objects with no egress fees, D1 for modest relational data, Durable Objects for coordination.
- The best use cases are routing, redirects, token checks, image optimization, API caching, webhook intake and WAF-based protection.
- Avoid the edge for chatty access to a distant database, CPU-heavy work, long-running jobs and workloads that need immediate global consistency.
- Model cost from requests, CPU milliseconds, storage operations and plan-gated security features, then validate with real traffic.
- Adopt in stages, starting with caching and the WAF in front of the origin, and lock the origin so attackers cannot bypass the edge.

