Serverless & Edge Computing: Workers, Lambda, R2

Serverless and edge computing runs your code close to the visitor, scales to nothing when nobody is there, and bills you for work actually done. That fits redirects, APIs, personalization, image handling and small data lookups far better than a server that idles all night. It fits a large database and a long PHP request rather badly, and pretending otherwise is how projects get expensive.

At CodeWiz we design that split. Cloudflare Workers for logic at the edge, AWS Lambda where the rest of the system is already on AWS, and KV, D1 or R2 when the data is small enough to live next to the code. The origin server, when you still need one, stays boring and small.

This is for teams paying for idle capacity, sites that need different behaviour per country or cookie, and products that spike and then go quiet. If every request is a heavy page render with a big database, we will say so and keep the server.

Edge: Aerial night view of a city intersection lit by street and traffic lights

Cloudflare Workers at the Edge

A Worker is a JavaScript, TypeScript or WebAssembly function that runs in Cloudflare’s network, in the same places your visitors already connect. There is no machine to patch and no idle bill. The limit is the model: short CPU time, no local disk, and a request that should finish quickly.

Where a Worker earns its place

  • Redirects, pretty URLs and A/B routing before the request ever reaches your origin.
  • Authentication gates, geolocation and bot checks on paths that do not need the full application.
  • HTML transforms, cookie-based personalization and small JSON APIs.
  • Aggregating a few backend calls so the browser makes one request instead of six.

A Worker that only decides where a request goes is often a few dozen lines. The official Workers documentation covers the runtime. A minimal pass-through with one early exit looks like this:

export default { async fetch(request, env) { const url = new URL(request.url); if (url.pathname === "/health") { return new Response("ok"); } return fetch(request); }, };

We deploy with Wrangler, keep secrets in the Workers environment rather than in the repo, and put staging on a separate route. Cache and WAF behaviour around that route is the same craft as the rest of a Cloudflare zone, which we have written up in our guide to professional Cloudflare configuration. The Worker is the new piece. The zone around it should already be tidy.

AWS Lambda and Other Serverless Functions

AWS Lambda runs a function when something happens: an HTTP request through API Gateway or a Function URL, a file landing in a bucket, a message on a queue, a schedule. It fits when the event already lives on AWS, or when the job is bursty and you do not want a process waiting for it.

Cloudflare WorkersAWS LambdaA small VPS
Where it runsHundreds of edge locationsOne region you chooseOne machine, one place
Cold startNegligible for typical scriptsReal, especially with large runtimesNone, the process is already up
Best workRouting, personalization, small APIsEvents, bursts, glue between AWS servicesLong requests, big databases, PHP apps
Idle costZeroZero, plus anything you leave attachedThe server, every hour
Hard limitCPU time and no local diskTimeout, memory, concurrencyYou operate the box

How we keep Lambda from becoming a surprise

  • One function, one job. A grab-bag handler that imports the whole application is how cold starts get long and bills get odd.
  • Memory sized to what the function uses, not to the maximum, because duration and memory are priced together.
  • Idempotent handlers for queues and webhooks, so a retry does not double-charge a customer or send two emails.
  • Logs and a concurrency cap, so a bug cannot fan out into thousands of parallel invocations.

The Lambda developer guide is the reference for event shapes and limits. Choosing Lambda versus a Worker versus a plain server is the same judgement we use when placing the rest of a system, described in our multi-cloud deployment guide. Region, egress and who will operate it matter more than the logo.

Close-up of colorful source code on a computer monitor in a dark room

Edge Storage: KV, D1 and R2

Code at the edge is only useful if the data it needs is close as well. Cloudflare offers three stores with very different shapes, and using the wrong one is the usual design bug.

  • KV is a key-value store, readable everywhere, with writes that take a moment to be seen worldwide. It fits config, feature flags, redirect maps and session-like lookups. It does not fit a counter that must be exact, or a query.
  • D1 is SQLite at the edge. It fits small relational data that you would rather query than stuff into keys: a directory, a lightweight CMS, an allow-list. It is not a stand-in for a large Postgres that your shop already depends on.
  • R2 is object storage with an S3-compatible API and no egress fee to the internet. It fits public media and exports that a Worker or the CDN will serve. The application still decides what is public.

We pick one store per kind of data and write down why. A Worker that reads KV on every request, then D1, then the origin, will be slower and pricier than the origin alone. Bindings, not hard-coded account ids, keep staging and production apart.

Edge Caching and Personalization

The cheapest request is the one your origin never sees. Caching at the edge and a little personalization are often the whole project: HTML that is the same for everyone stays cached, and a Worker varies only the piece that depends on a cookie, a country or an experiment.

Patterns we use

  • Cache the anonymous page and bypass the cache for carts, accounts and anything with a session cookie.
  • HTML rewriting for a banner, a price block or a translated snippet, without a separate origin per variant.
  • Geolocation and language from the request Cloudflare already annotates, not from a lookup that hits your database.
  • Stale-while-revalidate so a slow origin does not become a slow site the moment the cache expires.

Personalization that changes the entire HTML for every visitor defeats the cache. We keep the varied part small. When the right answer is a well-tuned origin rather than a function, that is the recommendation, including the open-source panel route we have described for affordable production hosting.

City lights glowing through fog below dark hills at night

Serverless and Edge Computing Costs

Scale to zero is real, and so is a bill that tracks a loop. Serverless and edge computing cost optimization starts by knowing which meter is running.

  • Requests and CPU time on Workers. A function that runs on every asset, including images and fonts, multiplies the count for no benefit. Routes should be narrow.
  • KV reads and D1 queries inside the hot path. Caching the answer for a minute is often the whole saving.
  • Lambda duration and memory, and the extras people forget: API Gateway, NAT gateways, logs, and data transferred out of the region.
  • R2 operations versus a CDN cache. Serving the same object from R2 on every view is unnecessary once the edge can cache it.
  • A comparison with a small server. Steady traffic on a chatty function can cost more than a VPS. We put both numbers next to each other before you commit.

We set billing alerts on the account and a budget for the Worker or the function. A launch that succeeds should not be the thing that surprises the invoice.

When a Server Is the Better Tool

Serverless and edge computing is a layer, not a religion. We keep a normal server, or recommend one, when the work does not fit the limits.

  • WordPress, WooCommerce, Laravel and other PHP applications that expect a process, a filesystem and a local database.
  • Requests that run for many seconds: reports, imports, video, large PDF generation.
  • A relational database with real transactions, joins and a backup story you already trust.
  • Background jobs that are simpler as a queue worker next to the app than as a mesh of functions.

The useful design is usually a mix. The origin renders or stores. The edge caches, routes, authenticates a path, and holds the small state that must be fast everywhere. Moving the whole monolith into a function is rarely the cheap option it sounds like in a slide.

Common Serverless and Edge Computing Mistakes

  • A Worker on /* that runs for static files and quietly dominates the bill.
  • Secrets in the repository, or one environment shared by staging and production.
  • KV used as a database, with a value rewritten on every request and read-after-write assumed to be instant worldwide.
  • No idempotency on a Lambda behind a queue, so retries duplicate orders or emails.
  • Logs so verbose that storing them costs more than the function.
  • No route for rolling back. A bad deploy of a Worker is instant and global, which is wonderful until it is wrong.

How We Work

  1. Discovery: what the request does today, where users are, and which work is routing versus real application logic.
  2. Plan: Worker, Lambda or a server, which data may live at the edge, and what the monthly meters should look like.
  3. Build: the function, bindings or IAM, routes, and a staging environment that is not production.
  4. Test: the paths that must stay cached, the paths that must not, and a failure of the origin while the edge still answers.
  5. Launch: a narrow route first, then a wider one, with a one-step rollback.
  6. Watch: request counts, errors and the first invoices, then tighten routes and caches.

Why CodeWiz

  • We write the application too. Laravel, Node.js, WordPress and shops, so the edge is designed around how the code actually behaves.
  • Open-source first, and portable where it matters. Standard APIs, no framework you cannot leave.
  • Honest about the fit. If a small server is cheaper and simpler, that is the proposal.
  • Performance in the same hands as the rest of the stack. More about CodeWiz.
  • Fair pricing. Founded in Banja Luka in 2023, working remotely with clients locally and internationally.

Frequently Asked Questions

How much does serverless and edge computing cost?

A Worker that handles redirects and cache rules is a small project. Several functions, edge storage and a careful migration of an API take longer. You get an estimate after we see the traffic and the code. The running cost scales with use, and we compare it with a small server before you choose.

Should I use Cloudflare Workers or AWS Lambda?

Workers when the logic should sit in front of every visitor, next to the cache. Lambda when the trigger is already on AWS: a bucket, a queue, a schedule. Many systems use both, and some should use neither. The table above is the decision, not a brand preference.

Will cold starts make the site feel slow?

On Workers, not in any way a visitor notices for ordinary scripts. On Lambda, a cold start is real for heavier runtimes and shows up on infrequent paths. We keep those functions small, and we do not put a cold start on the checkout path if a warm process would be simpler.

Can you run WordPress on Workers?

Not as the place PHP and MySQL execute. Workers sit in front: cache, redirects, a country-specific banner, a gate on a path. The WordPress origin stays on a server. That split is usually what you wanted from “the edge” in the first place.

Is KV or D1 a replacement for my database?

KV replaces a lookup, not a database. D1 replaces a small SQLite-shaped dataset. Orders, stock and anything with transactions stay on Postgres or MySQL. We will not move them to make the architecture look newer.

What happens if a deploy breaks production?

Workers and Lambda both deploy quickly, which cuts both ways. We ship to a staging route first, keep the previous version, and roll back in one step. A global change is never the first time the code has run.

Ready to Put Code at the Edge?

Tell us what is slow, idle or too far from your users. We will say whether it belongs in front of your origin, beside it, or not at all. Contact us to start, or see the rest of our development services.