Production at the Edge
By Flavio
Updated
Tagged: Cloudflare
A practical mini-course on running real apps on Cloudflare with Workers, Pages, D1, KV, R2, Queues, Durable Objects, AI, and more.
I’ve built quite a few apps on Cloudflare recently, ranging from static sites to full apps with authentication, payments, databases, AI features, scheduled jobs, and user uploads. One of them is a multi-tenant SaaS with more moving parts than I’d usually put in a single project.
Working across all of those apps made one thing clear: there isn’t one “Cloudflare stack.” Instead, you have a small set of products, each built for one job, and the real challenge is knowing which piece to reach for and when to stop adding more.
That’s what this mini-course is about. We’ll start with a plain static site and layer in server code, data, file storage, background jobs, coordination, analytics, security, and AI step by step. Along the way, I’ll walk through the architecture I use for real projects, including the mistakes and production details that hello-world tutorials skip. You won’t need everything in here, and most apps are better off using only a handful of these pieces.
What does “at the edge” mean?
A traditional app usually lives in a single region. You rent a server in Frankfurt, Virginia, or Singapore, and every request travels there so the server can talk to its database, render a response, and send it back.
Cloudflare Workers work differently. You deploy your code to Cloudflare, and when a request comes in, Cloudflare can run it close to the person making that request. You don’t have to keep a server process running, open a port, or patch an OS. Your code takes a standard Request and returns a standard Response.
Keep in mind that “at the edge” doesn’t mean every piece of your app sits in every Cloudflare data center. Your Worker might run right next to the user, while your D1 database still has a primary location, a Durable Object lives as one authoritative instance in one place, and external APIs might run on another continent. You get rid of a lot of server plumbing, yet distance, consistency, and where your data lives still shape how you build.
The architectures behind this mini-course
Everything here comes from real projects with very different requirements, spread across these shapes:
| Project shape | Cloudflare products used |
|---|---|
| Static content sites | Pages, DNS, build cache |
| Static site with a few server routes | Pages, Pages Functions, KV, Turnstile, Workers AI |
| Full-stack Astro app | Workers, static assets, observability |
| App with accounts and payments | Workers, D1, KV, Turnstile, AI Gateway |
| Multi-tenant SaaS | Workers, D1, KV, R2, Queues, Cron Triggers, Durable Objects, Analytics Engine |
| Long-running AI report | Workers, Durable Objects, Workflows, Workers AI |
On the lightweight end, I run several content-heavy sites that stay completely static, plus one large static Astro site on Pages that only uses a handful of Pages Functions for webhooks and private data retrieval. Moving up a step, a group of member apps runs Astro server rendering on a Worker while Cloudflare serves the static assets directly, and two paid developer tools add D1, KV, payments, and AI calls on top of that.
At the heavier end, there’s a multi-tenant SaaS that uses almost every storage and background-processing product in this guide because it needs all of them. Another app builds long-running AI reports by holding the canonical interview state inside a Durable Object and then starting a Workflow to build the final report in reliable steps.
Looking at those projects side by side shows a clear progression: start with almost nothing, and only add more infrastructure when a specific feature demands it.
Start with the smallest possible architecture
Whenever I start a new project on Cloudflare, the first question I ask myself is how much work I can avoid doing when a request arrives. If a page can be generated at build time, I make it static. If some calculation runs fine in the browser, I leave it in the browser, and if a small endpoint doesn’t need a database, I skip the database.
That leads to a rough order you can follow as an app grows:
- Static HTML, CSS, and JavaScript
- A Worker or Pages Function for dynamic routes
- KV for simple, read-heavy key-value data
- D1 for relational data
- R2 for files
- Queues for reliable background work
- Durable Objects for coordination
- Workflows for long-running multi-step processes
Treat this as a way to keep complexity in check rather than a fixed rule. Cloudflare makes it tempting to wire up another service because attaching a binding takes a few lines of config, yet every binding brings extra data, new failure modes, configuration, and another moving part you’ll have to understand in production.
Lesson 1: choose Pages or Workers
The first decision is where your app runs. In practice, I rely on two deployment setups, plus a middle ground when a static site only needs a couple of server routes.
Use Pages for a static site
If your build outputs a folder of static files, Cloudflare Pages fits right out of the box. For an Astro site, the build flow is straightforward:
Your Wrangler config only needs a few lines:
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "my-static-site",
"pages_build_output_dir": "./dist",
"compatibility_date": "2026-07-24"
}
You can connect the repo to Git so Cloudflare builds after every push, or deploy straight from the command line:
npx wrangler pages deploy dist --project-name my-static-site
Pages handles preview deployments, custom domains, HTTPS, redirects, and static asset delivery for you. For content sites, directories, documentation, and browser-only tools, you often don’t need anything beyond this, and having almost no request-time code means very little can break in production.
Use a Worker with static assets for a full-stack app
When the Worker itself is the application, I deploy the static files and server code together. Your Wrangler config points Cloudflare to both:
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "my-app",
"main": "./src/worker.ts",
"compatibility_date": "2026-07-24",
"compatibility_flags": ["nodejs_compat"],
"assets": {
"binding": "ASSETS",
"directory": "./dist"
},
"observability": {
"enabled": true
}
}
By default, when a request matches a static asset, Cloudflare serves it directly without running your Worker. Only requests without a matching asset reach your code. That keeps CSS, images, and generated HTML fast and cheap while letting dynamic routes run server logic. You can change this behavior with run_worker_first, though you should do it intentionally, because middleware that runs in front of every asset turns every request into compute.
This is the setup I use for full-stack Astro 7 apps. The @astrojs/cloudflare adapter produces the server entrypoint, and a small custom Worker delegates incoming HTTP requests to Astro:
import { handle } from '@astrojs/cloudflare/handler'
export default {
fetch(request, env, ctx) {
return handle(request, env, ctx)
},
}
At first glance that file looks like unnecessary boilerplate, until the day you need to add a scheduled handler, a queue consumer, a Workflow, or a Durable Object export to the same Worker. I walk through the basic deployment model in Serving a website with Cloudflare Workers static assets.
Pages Functions are the middle ground
Sometimes a site is completely static except for two or three routes, which is how this site works. Pages Functions map files directly to routes:
functions/purchase.js → /purchase
functions/api/course-access/send.js → /api/course-access/send
That lets you keep a static Pages project and add only the endpoints you need, instead of turning the whole site into a server-rendered app.
Watch out for root middleware here. Adding a functions/_middleware.js file at the root can cause every request, including pages, images, stylesheets, and other static assets, to invoke a Function. If you use middleware, add a _routes.json file to control which paths run code, like this:
{
"version": 1,
"include": ["/purchase", "/api/*"],
"exclude": []
}
Whether you’re on Pages or Workers, always keep track of which requests run code and which ones stay static.
Lesson 2: understand the Worker programming model
Instead of thinking of a Worker as an Express server running somewhere else, think of it as a request handler built around standard web platform APIs. Here’s the smallest useful Worker you can write:
export default {
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url)
return Response.json({
path: url.pathname,
method: request.method,
})
},
}
You’ll use those three arguments constantly:
requestcontains the incoming HTTP requestenvcontains your bindings, variables, and secretsctxcontrols work connected to the request lifecycle
A more realistic handler looks like this:
interface Env {
DB: D1Database
CACHE: KVNamespace
RESEND_API_KEY: string
}
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext,
): Promise<Response> {
const cached = await env.CACHE.get('homepage')
if (cached) {
return new Response(cached)
}
return new Response('Not cached', { status: 404 })
},
}
Bindings are one of my favorite parts of the platform. Your code doesn’t have to open a database connection or construct an S3 client, since Cloudflare attaches those resources directly to env. As a bonus, your architecture stays visible in wrangler.jsonc: open that one file and you can see everything the Worker depends on.
Workers are not normal Node.js servers
Workers run on the workerd runtime, which gives you fetch, Request, Response, URL, Headers, streams, and Web Crypto out of the box. Cloudflare also supports many Node APIs through compatibility flags, so if a library requires them, you can enable them in your config:
{
"compatibility_date": "2026-07-24",
"compatibility_flags": ["nodejs_compat"]
}
Even with that flag enabled, you still don’t have a long-lived Node server. Memory can disappear between requests, and any work that continues after you return a response needs explicit handling.
My advice is to stick with web APIs whenever they’re enough. For example, call an email provider directly with fetch instead of installing a large Node SDK, which is the pattern I use in Transactional email from Workers with Resend.
Lesson 3: make Wrangler the source of truth
Wrangler is Cloudflare’s command line tool. I still open the dashboard when I want to inspect things, while defining everything through Wrangler and files checked into the repository.
Here are the commands I use most:
npx wrangler dev
npx wrangler types
npx wrangler deploy --dry-run
npx wrangler deploy
npx wrangler tail
Here’s what each command does:
wrangler devruns your app locally with the Workers runtime and local bindings.wrangler typesgenerates TypeScript definitions from your configuration.wrangler deploy --dry-runbuilds the Worker bundle without making it live.wrangler deploycreates and deploys a new version.wrangler tailshows live production logs.
Configuration belongs right next to your code because the two change together. Adding a D1 binding changes your app’s types, bumping the compatibility date can alter runtime behavior, and adding a queue consumer changes how failures get retried. All of those belong in version control and code review rather than buried in dashboard settings.
Pin the compatibility date
The compatibility date tells Cloudflare which runtime behavior your project expects, letting the platform roll out improvements without silently breaking older Workers. Skip copying a random old date from a tutorial. Set it explicitly for your project, update it intentionally, and test after changing it.
Generate binding types
There’s no reason to maintain a large Env interface by hand when Wrangler can generate it for you. Run this whenever your config changes:
npx wrangler types
Then let TypeScript warn you when a binding is missing or has the wrong shape before you deploy.
Lesson 4: separate variables from secrets
Every production app has public configuration and private credentials. Plain variables can live right in wrangler.jsonc:
{
"vars": {
"APP_ENV": "production",
"APP_URL": "https://myapp.com",
"TURNSTILE_SITE_KEY": "public-site-key"
}
}
Secrets shouldn’t be in that file. Set them through Wrangler instead:
npx wrangler secret put RESEND_API_KEY
npx wrangler secret put TURNSTILE_SECRET_KEY
npx wrangler secret put WEBHOOK_SECRET
At runtime, both appear on env, so the real difference is where Cloudflare stores them and whether they end up in your repository. Pay attention to naming too: a Turnstile site key is public because the browser needs it, while the secret key stays private and is used only by the Worker. I cover the full setup in Cloudflare Workers: secrets and environments.
Use separate environments
Larger apps need more than a single production deployment. Wrangler environments let you define different Worker names, bindings, variables, and resources in one config:
{
"name": "my-app-dev",
"vars": {
"APP_ENV": "dev"
},
"env": {
"staging": {
"name": "my-app-staging",
"vars": {
"APP_ENV": "staging"
}
},
"production": {
"name": "my-app-production",
"vars": {
"APP_ENV": "production"
}
}
}
}
Deploy a specific environment like this:
npx wrangler deploy --env production
Watch out for one gotcha: many binding sections don’t inherit into named environments. If production needs D1, KV, R2, Queues, or Cron Triggers, make sure the production environment declares them explicitly. Wrangler prints warnings when inherited config is missing, so pay close attention to them when deploying.
Lesson 5: choose the right place for data
Cloudflare gives you several storage products, and they overlap just enough that it’s easy to grab the wrong one early on. Pick the product that matches the guarantees your data needs instead of reaching for whichever API looks easiest.
Here’s how I split them up:
| Data | Product |
|---|---|
| Relational application data | D1 |
| Read-heavy key-value data and caches | KV |
| Files and uploads | R2 |
| Strongly consistent per-entity state | Durable Objects |
| High-volume product metrics | Analytics Engine |
Use D1 for relational application data
D1 is Cloudflare’s managed database with SQLite semantics. I use it for structured app data like users, sessions, reports, subscriptions, settings, and products.
You can create a new database with Wrangler:
npx wrangler d1 create my-app
Then drop the binding Wrangler prints into your config:
{
"d1_databases": [
{
"binding": "DB",
"database_name": "my-app",
"database_id": "paste-the-generated-id",
"migrations_dir": "migrations"
}
]
}
Even for a tiny app, set up migrations right away instead of editing tables by hand. Start by generating a migration file:
npx wrangler d1 migrations create my-app create_users
Inside that file, you can write regular SQL:
CREATE TABLE users (
id TEXT PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
created_at TEXT NOT NULL
);
CREATE INDEX users_email_idx ON users(email);
Run your migrations locally first so you can test them before touching production:
npx wrangler d1 migrations apply my-app --local
Once everything looks good, apply them to the remote database:
npx wrangler d1 migrations apply my-app --remote
In your Worker code, the D1 binding gives you prepared statements:
const user = await env.DB
.prepare('SELECT id, email FROM users WHERE email = ?')
.bind(email)
.first()
Always bind your values rather than building SQL by joining user input into a string. For Astro projects, I also often add Drizzle on top to get typed queries, which I walk through in Astro SSR with D1 and Drizzle ORM.
D1 is not a database in every edge location
Even though your Worker runs close to the visitor, the D1 primary database still lives in a single region, so every write has to travel there. You can enable read replication to bring reads closer to users, though replicas add a consistency tradeoff because a recent write might not show up on every replica right away.
Measure the real request path instead of assuming everything happens at the edge. If a Worker spends most of its time talking to one database, Smart Placement often helps more than running the Worker right next to the user, since Cloudflare can place the compute closer to your backend instead.
Use KV for read-heavy key-value data
KV stores a value under a key, and it’s a great fit for configuration, cached results, access lists, or anything you read far more often than you change.
Start by creating a namespace:
{
"kv_namespaces": [
{
"binding": "CACHE",
"id": "paste-the-namespace-id"
}
]
}
From your Worker, you can write a cached value like this:
await env.CACHE.put(
`report:${reportId}`,
JSON.stringify(report),
{ expirationTtl: 3600 },
)
And read it back as JSON when you need it:
const report = await env.CACHE.get(
`report:${reportId}`,
'json',
)
One catch is that KV is eventually consistent. A write in one location can take a little while to replace an older cached value somewhere else, which makes KV a poor fit for exact balances, unique inventory reservations, or strict global counters.
I do use KV for simple daily AI usage limits, where a small amount of disagreement between locations is fine because those caps are deliberately soft. I wrote about that tradeoff in Rate limiting with Cloudflare KV. Whenever a limit has to be exact, use a Durable Object instead.
Use R2 for files
R2 is Cloudflare’s object storage, and it’s where images, generated PDFs, exports, backups, and user uploads belong.
First, create a bucket:
npx wrangler r2 bucket create my-app-uploads
Then add the bucket binding to your config:
{
"r2_buckets": [
{
"binding": "UPLOADS",
"bucket_name": "my-app-uploads"
}
]
}
From there, you can store an uploaded file like this:
const form = await request.formData()
const file = form.get('file')
if (!(file instanceof File)) {
return new Response('File required', { status: 400 })
}
await env.UPLOADS.put(`uploads/${crypto.randomUUID()}`, file.stream(), {
httpMetadata: {
contentType: file.type,
},
})
R2 is S3-compatible and doesn’t charge egress fees when you serve data directly from it. You still pay for storage and operations, so think through your keys, caching, and upload limits up front.
The pattern I come back to in almost every app splits the job in two:
- file bytes in R2
- file metadata and ownership in D1
That way you don’t end up stuffing large files into D1 just because it’s already set up, or trying to cram relational metadata into R2 object keys.
Use Durable Objects when requests must agree
Durable Objects exist for coordination. Each object has a unique identity, so every request targeting that ID hits the same authoritative instance, backed by strongly consistent storage that processes events in order.
That makes them useful for workloads like:
- exact rate limits
- chat rooms
- collaborative documents
- booking and inventory coordination
- one state machine per user or job
- tenant provisioning locks
In one multi-tenant SaaS, a Durable Object handles precise rate limiting while another serializes database provisioning and migrations for each tenant. In another app, a single Durable Object owns the full interview state, making it much easier to prevent out-of-order answers and duplicate report generation.
The trickiest design call is usually naming the object, because each instance should represent one unit of coordination. If you’re building a rate limiter, you might key one object per visitor:
const id = env.RATE_LIMITER.idFromName(visitorId)
const limiter = env.RATE_LIMITER.get(id)
const result = await limiter.check(10, 60)
In a chat app, that unit is a room; for tenant provisioning, it’s a workspace. Whatever you pick, don’t funnel the whole application through one global Durable Object, or you’ll create a single global bottleneck.
Lesson 6: design the request path
When a request hits a full-stack app, you should be able to trace where it goes without guessing.
For a standard authenticated page, the path might look like this:
Browser
↓
Static asset or Worker route
↓
Middleware loads session
↓
Astro page or API handler
↓
D1 query
↓
Response
For a public widget or a high-volume API endpoint, though, I’ll often skip Astro completely:
Browser
↓
Worker
↓
Hono API route
↓
KV, D1, or Analytics Engine
↓
Response
One public widget app uses that exact split: visitor-facing embeds, widget renders, and analytics ingestion go straight to a small Hono app, while dashboard pages run through Astro. There’s nothing wrong with Astro here; you just save tiny API requests from passing through rendering machinery they don’t need.
Validate input at the boundary
Your Worker sits at the public edge of the system, so validate the HTTP method, content type, size, and data shape before kicking off any expensive work. Here’s an example of those early checks:
if (request.method !== 'POST') {
return new Response('Method Not Allowed', { status: 405 })
}
const contentType = request.headers.get('content-type') ?? ''
if (!contentType.includes('application/json')) {
return new Response('Expected JSON', { status: 415 })
}
Right after that, parse the body with a schema library like Zod before you run a database write or an AI call.
Return boring errors
Never leak stack traces, provider responses, database errors, or secret names back to users. Log the useful detail on the server and hand the user a plain message instead:
try {
return await handleRequest(request, env)
} catch (error) {
console.error(JSON.stringify({
message: 'request failed',
path: new URL(request.url).pathname,
error: error instanceof Error ? error.message : String(error),
}))
return new Response('Internal Server Error', { status: 500 })
}
Logging structured fields like this also makes it much easier to filter production issues later than digging through improvised sentences.
Lesson 7: protect public endpoints
Any public URL will eventually get called by scripts, and any form you put online will attract bots.
Add Turnstile to expensive forms
Turnstile gives the browser a token, and your Worker has to verify that token with Cloudflare before trusting the request. Adding the browser widget on its own does nothing.
Here’s the full trust boundary from browser to Worker:
Browser completes Turnstile
↓
Browser sends token with form
↓
Worker calls Siteverify
↓
Worker checks success
↓
Worker performs protected action
A minimal verification function looks like this:
async function verifyTurnstile(
token: string,
ip: string,
secret: string,
): Promise<boolean> {
const response = await fetch(
'https://challenges.cloudflare.com/turnstile/v0/siteverify',
{
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify({
secret,
response: token,
remoteip: ip,
}),
},
)
const result = await response.json<{ success: boolean }>()
return result.success
}
Turnstile tokens expire and can only be used once. Use Cloudflare’s test keys locally, and keep production widgets locked down to your production hostnames.
Rate limit before expensive work
When an endpoint calls an AI model, run your checks in this order:
Validate request
↓
Verify Turnstile
↓
Check per-visitor limit
↓
Check global daily limit
↓
Call the model
Always check your spending cap before running the paid operation, never after calling the model. I also keep a global cap alongside per-visitor limits, since per-visitor throttling alone won’t protect you from a distributed attack.
Verify webhook signatures
Payment and email providers talk back to your Workers through webhooks, and you can’t trust a request just because it arrived at a secret-looking URL. Verify the signature using the raw request body first, then make the operation idempotent.
Duplicates will happen in production: providers retry failed deliveries, some emit more than one event for the same business action, queues can deliver a message more than once, and users refresh callback pages. To handle that safely, store the provider’s event ID in D1 with a unique constraint, or use the provider’s idempotency key support. That matters most for payments, credits, emails, and provisioning.
I cover the broader model in Webhooks explained, and there’s a complete payment flow in How I added Polar payments to an Astro app.
Lesson 8: decide how background work should run
Not every task needs to finish before you return an HTTP response. A single signup, for instance, might need to:
- create the account
- send a welcome email
- update analytics
- call a webhook
- notify an administrator
Making the user sit there while all of that finishes slows the whole flow down, so Cloudflare gives us a few different ways to run work in the background.
Use waitUntil() for small attached work
When you have a quick, non-critical task tied to a request, ctx.waitUntil() lets it keep running after the response is ready:
ctx.waitUntil(
sendAnalyticsEvent(env, event).catch((error) => {
console.error('analytics failed', error)
}),
)
return Response.json({ ok: true })
Just don’t treat waitUntil() as a replacement for a real job system. If losing that work would be serious, put it on a Queue instead. Also make sure you never start a promise and return without either awaiting it or passing it to waitUntil(), because the Worker can stop as soon as the response is sent.
Use Queues for reliable background jobs
Cloudflare Queues separate incoming requests from the background processing they trigger. Inside the request handler, you send a small message to the queue:
await env.EVENT_QUEUE.send({
type: 'send_welcome_email',
userId,
})
Then a consumer picks it up and handles it:
export default {
async queue(batch, env) {
for (const message of batch.messages) {
try {
await processEvent(message.body, env)
message.ack()
} catch (error) {
console.error('queue message failed', error)
message.retry({ delaySeconds: 60 })
}
}
},
}
In your Wrangler config, you set up the producer, consumer, retries, and dead letter queue:
{
"queues": {
"producers": [
{
"binding": "EVENT_QUEUE",
"queue": "my-app-events"
}
],
"consumers": [
{
"queue": "my-app-events",
"max_batch_size": 10,
"max_batch_timeout": 5,
"max_retries": 3,
"dead_letter_queue": "my-app-events-dlq"
}
]
}
}
Catch errors per message inside the consumer, because an error thrown from the whole batch handler can cause Cloudflare to retry messages that already succeeded. Since Queues provide at-least-once delivery, the same message can arrive more than once, so your consumers need to be idempotent.
In one multi-tenant app, scheduled jobs fan out by pushing one queue message per tenant, so a slow or broken tenant can’t block maintenance for everyone else and each tenant gets its own retry.
Use Cron Triggers for schedules
Cron Triggers run your Worker’s scheduled handler on a timer. You add the schedule in Wrangler:
{
"triggers": {
"crons": ["10 2 * * *", "0 7 * * 1"]
}
}
Then handle those events in your Worker:
export default {
async scheduled(controller, env, ctx) {
if (controller.cron === '10 2 * * *') {
ctx.waitUntil(runNightlyMaintenance(env))
}
if (controller.cron === '0 7 * * 1') {
ctx.waitUntil(sendWeeklyDigests(env))
}
},
}
If the job is small, you can run the work right inside the scheduled handler. Once a job grows larger, let the schedule push messages onto a Queue so the Queue handles distribution and retries.
Use Workflows for durable multi-step processes
Queues work great for independent messages, while Cloudflare Workflows fit better when a single job runs through several dependent steps. An AI report, for example, might:
- Load a canonical snapshot
- Call an AI model
- Build a deterministic report
- Save the final result
A Workflow persists its progress between steps, so if step three fails, Cloudflare can retry from there instead of repeating every step that already succeeded. Here’s what the shape of a Workflow looks like:
import {
WorkflowEntrypoint,
type WorkflowEvent,
type WorkflowStep,
} from 'cloudflare:workers'
export class ReportWorkflow extends WorkflowEntrypoint<Env, Params> {
async run(
event: WorkflowEvent<Params>,
step: WorkflowStep,
): Promise<void> {
const snapshot = await step.do(
'load report data',
async () => loadSnapshot(event.payload.reportId),
)
const summary = await step.do(
'generate summary',
{ retries: { limit: 2, delay: '2 seconds' } },
async () => generateSummary(this.env, snapshot),
)
await step.do(
'save report',
async () => saveReport(snapshot, summary),
)
}
}
When you have independent messages to process, a Queue is the simpler tool. Reach for a Workflow once a job has dependent steps and you want Cloudflare to persist progress between retries.
Lesson 9: add AI without losing control of cost
Cloudflare has two separate AI products, and I reach for each one in a different situation.
Workers AI runs models through a binding
Workers AI lets you run models directly on Cloudflare’s infrastructure without juggling an external provider API key in your Worker. To set it up, add the AI binding to your config:
{
"ai": {
"binding": "AI"
}
}
Once that binding is in place, you can call a model straight from your code:
const result = await env.AI.run('@cf/openai/gpt-oss-20b', {
messages: [
{
role: 'system',
content: 'Write one concise summary using only supplied facts.',
},
{
role: 'user',
content: JSON.stringify(facts),
},
],
})
Even without an external API key to manage, the model name is still a production dependency because models get updated, changed, or retired over time. Keep the model call in a single adapter module instead of scattering model IDs across your route handlers, so swapping it later is a one-file edit. I also keep a deterministic fallback alongside it whenever possible. If the feature can still return something useful without calling a model, your app degrades much more gracefully when a model fails or you hit a spending cap.
AI Gateway sits in front of external providers
When I call OpenAI or another third-party provider, I put AI Gateway in front of it. It gives me one place to inspect requests, tokens, latency, errors, and cost, plus options for caching, rate limits, and routing.
Your code keeps talking to the same provider API, with the base URL pointed through Cloudflare:
const response = await fetch(env.OPENAI_BASE_URL, {
method: 'POST',
headers: {
'authorization': `Bearer ${env.OPENAI_API_KEY}`,
'cf-aig-authorization': `Bearer ${env.CF_AIG_TOKEN}`,
'content-type': 'application/json',
},
body: JSON.stringify(payload),
})
In production, use an authenticated Gateway. Store the provider API key and the Gateway token as two separate secrets, since the first authorizes the call to the model provider and the second protects access to your Gateway endpoint.
Put a hard cap before every AI call
Because AI APIs charge by usage, a runaway bug or sudden traffic spike can turn into an unexpected bill fast. Whenever I put an AI feature behind a public endpoint, I add these guardrails:
- a per-visitor daily limit
- a global daily limit
- a cheap model by default
- maximum input length
- maximum output tokens
- a timeout
- a deterministic fallback
Check your global cap in code before making the model call. Provider dashboards and warning emails are fine for visibility, but they only alert you after the money has already been spent.
Lesson 10: build observability before you need it
When your app runs on serverless infrastructure you don’t manage, you can’t just SSH in and inspect a server when something breaks. Don’t wait for your first production error to add logs. Turn on Workers observability from the start:
{
"observability": {
"enabled": true,
"logs": {
"enabled": true,
"head_sampling_rate": 1
},
"traces": {
"enabled": true,
"head_sampling_rate": 0.01
}
}
}
Choose a sampling rate that fits your traffic and budget. On a small new app, logging every request is usually fine, while on a high-volume endpoint it’ll get noisy and expensive quickly.
Write structured log objects instead of plain strings so you can search and filter them later:
console.log(JSON.stringify({
message: 'report created',
reportId,
userId,
durationMs,
}))
Be strict about keeping sensitive data out of those logs, including access tokens, cookies, full webhook bodies, email content, and private AI prompts.
You can stream live logs from a deployed Worker with:
npx wrangler tail
Traces are worth enabling alongside logs because they show where time went across fetch calls and Cloudflare bindings. That’s especially helpful when your Worker code is fast, yet the overall request is slow because of a D1 query, an external API, or an AI provider. You can find the full setup in Cloudflare Workers observability: logs and traces.
Analytics Engine is not your application database
Analytics Engine is built for high-volume event data that you want to aggregate and analyze later. It works well for product metrics such as:
- endpoint usage
- widget views
- feature usage per tenant
- request duration
- usage-based billing measurements
Writing a data point from your Worker takes one call:
env.ANALYTICS.writeDataPoint({
blobs: [route, method, status],
doubles: [durationMs, 1],
indexes: [workspaceId],
})
Once those events are recorded, you can query the dataset with SQL whenever you need reports. Keep Analytics Engine strictly for measurements and telemetry, and use D1 for user accounts or anything your app needs to read back during a request as canonical state.
Lesson 11: test the runtime you deploy
An app can work fine in astro dev and still break in a Worker because Node.js and the Workers runtime aren’t identical. A Node package might import an unsupported API, a binding might be missing, a library might expect a writable filesystem, or environment handling might behave differently.
Before deploying, I run this minimum verification loop:
npm run check
npm test
npm run build
npx wrangler deploy --dry-run
For Worker integration tests, use Cloudflare’s Vitest pool so your tests execute inside the real Workers runtime. For browser flows, run Playwright against a local Worker preview instead of the framework dev server:
npm run build
npx wrangler dev
That lets you test your real routes, headers, redirects, cookies, and bindings before anything goes live.
Local and remote resources are different
Wrangler emulates D1, KV, R2, Queues, and Durable Objects locally, which keeps day-to-day development fast and safe. Before launch, you still need to check your remote setup directly, since configuration mismatches cause most deployment failures:
- remote bindings exist
- remote migrations ran
- production secrets exist
- custom domains point to the right Worker
- production Turnstile hostnames are allowed
- webhook URLs use the production domain
- scheduled triggers appear in the deployed Worker
Keep local state persistent
When you want local D1 and Durable Object data to survive restarts, point Wrangler at a persistent state directory:
npx wrangler dev --persist-to .wrangler/state
Keep .wrangler out of Git so your local database files stay on your machine and never get committed to the repository.
Lesson 12: deploy without treating deployment as the finish line
When wrangler deploy succeeds, all you’ve confirmed is that Cloudflare accepted and uploaded your bundle. Right after every deploy, run a quick smoke test against production:
curl -I https://myapp.com
curl https://myapp.com/api/health
Verify one authenticated flow, one database write, and one external integration. If your app receives webhooks, trigger a test event from the provider. If it uses a Queue, make sure the consumer processes a message, and if it has a Cron Trigger, check that the schedule shows up on the deployed Worker now rather than waiting until tomorrow to find out it’s missing.
Use Custom Domains when the Worker is the origin
When the Worker is your application, attach it using a Custom Domain in your configuration:
{
"routes": [
{
"pattern": "myapp.com",
"custom_domain": true
},
{
"pattern": "www.myapp.com",
"custom_domain": true
}
]
}
Use a route like example.com/* only when the Worker sits in front of another origin server. Keeping those two setups separate avoids a lot of routing headaches.
Know what a rollback does
Cloudflare tracks Worker versions and deployments, so rolling back your code is fast. Keep in mind that rolling back a Worker doesn’t undo D1 migrations, KV writes, R2 objects, or Durable Object storage.
Because your stored data stays on the newer schema even if you revert your code, make database changes backward compatible so you never break the currently deployed Worker mid-rollout. A safe sequence looks like this:
- Add the new column or table
- Deploy code that can use both old and new shapes
- Backfill data if needed
- Switch reads to the new shape
- Remove old data in a later deployment
Gradual deployment does not remove version skew
Workers let you split traffic between versions for gradual rollouts, which means two versions of your code will run side by side for a while. A single user might hit the old version on one request and the new version on the next, and Service Bindings can connect apps that are on different rollout stages.
Keep your APIs, storage formats, and internal contracts compatible across both versions during a rollout. The same goes for frontend assets, since new HTML can’t assume an older JavaScript bundle has disappeared from every cache right away.
Lesson 13: understand the failure modes
Operating on Cloudflare gets much simpler once you know how each part of the platform fails.
A Worker can disappear after the response
Once your Worker sends a response, the runtime can terminate it right away. Always await required work before returning, use ctx.waitUntil() for short optional tasks, and send anything that needs reliable delivery and retries to a Queue.
KV can return an older value
KV is eventually consistent, so reads can return a slightly older value right after a write. Only reach for KV when eventual consistency is acceptable, and use D1 or a Durable Object whenever the latest write has to be authoritative.
A Queue can deliver twice
Queues guarantee at-least-once delivery, so you should expect duplicate messages to show up from time to time. Guard your consumers with idempotency keys and unique database constraints so handling the same message twice doesn’t break anything.
A Cron Trigger can start too much work
Don’t process every tenant inside one big scheduled handler, because a single timeout or error can hold up the whole run. Have the Cron Trigger fan out jobs to a Queue so each unit of work gets its own retry and failure boundary.
A Workflow step can run again
If a Workflow retries a step, any side effect inside it will run again. Keep side effects idempotent, and pass an idempotency key to external API calls whenever the provider supports one so a retry won’t repeat the same business action.
A Durable Object can become a bottleneck
Because each Durable Object handles requests through a single instance, routing unrelated users into one global object will quickly create a bottleneck. Pick one object per unit of coordination, such as a single room, document, or tenant.
An AI model can change or disappear
Keep your model calls behind one adapter module, cap inputs and outputs, and keep a fallback ready. Check the current model catalog before deploying so you aren’t caught off guard by a retired model.
A webhook can be valid and still be a duplicate
Verifying the webhook signature confirms who sent the request, and you also need an idempotency check in your database to make sure you haven’t already processed that event. Providers retry webhooks routinely, so put both checks in every webhook handler.
A static asset can accidentally invoke a Worker
Check your Pages _routes.json and your Workers static asset routing rules so static files don’t accidentally trigger Worker executions. Serving assets directly keeps both latency and request counts down.
A practical architecture for a new app
Suppose we’re building a small SaaS that creates reports. Users sign in, answer a set of questions, generate a report, pay to unlock it, and download a PDF. Here’s the architecture I’d start with:
┌──────────────┐
│ Turnstile │
└──────┬───────┘
│ verify
Browser ── static assets ──> Cloudflare Worker
│
┌──────────────┼──────────────┐
│ │ │
▼ ▼ ▼
D1 KV R2
users/reports soft limits generated PDFs
│
▼
Queue ──────> email/webhooks
│
▼
Workflow ────> AI report generation
│
▼
Workers AI or
AI Gateway
You don’t need every piece of that diagram on day one. The first version might only need the Worker and D1. Once you start generating PDFs, bring in R2 to store them, and add KV if repeated lookups need caching or soft limits.
The async pieces can wait until you feel the need for them too. Reach for a Queue when sending emails or processing webhooks makes your request handlers slow or unreliable, and introduce a Workflow when report generation grows into a multi-step job. You only need a Durable Object here if the report interview requires one authoritative state machine, or if report generation has to start exactly once. Add each service when your app runs into the problem it solves, instead of wiring up the whole stack on day one.
My production checklist
Before launching a Cloudflare app, I run through this checklist.
Runtime and routing
- The compatibility date is explicit and recent
nodejs_compatis enabled only when needed- Static assets don’t invoke the Worker unnecessarily
- Pages Functions have a narrow
_routes.json - The production custom domain points to the right Worker
- Root and
wwwbehavior is intentional
Configuration
- Public variables live in
wrangler.jsonc - Secrets are stored with Wrangler and never committed to Git
- Staging and production use different resources
- Generated binding types are up to date
- Environment-specific bindings are repeated where Wrangler requires them
Data
- D1 migrations are committed and tested locally
- Remote migrations ran before dependent code went live
- Database changes are backward compatible
- KV isn’t used for strict consistency
- R2 uploads have size and content-type limits
- Durable Objects are sharded by a real unit of coordination
Security
- Public input is validated before expensive work
- Turnstile is verified on the server
- Rate limits run before AI and third-party API calls
- Webhook signatures are checked against the raw body
- Webhook and Queue handlers are idempotent
- Logs don’t contain secrets or private user data
Background work
- Required work is awaited
- Short optional work uses
waitUntil() - Reliable work uses a Queue
- Failed messages go to a dead letter queue
- Scheduled jobs fan out instead of doing unbounded work
- Workflow steps can safely retry
Operations
- Observability is enabled
- Logs are structured and useful
- Trace sampling matches traffic and budget
- A production smoke test exists
- Rollback behavior is understood, including what happens to stored data
- AI features have global spending caps and fallbacks
You don’t need a big operations team to run this stack, just a clear decision on each of these points before you launch.
What I would not add yet
Cloudflare has a lot more products than the ones we covered here. There’s Vectorize for embeddings, Hyperdrive for connecting to existing Postgres and MySQL databases, Browser Rendering, Images, Email Workers, Containers, service bindings, and more.
They’re all useful once your app needs them, but it’s easy to reach for them too early. One AI feature isn’t a reason to pull in Vectorize, and an app logo doesn’t need R2. You don’t need a Queue for one short database write, and you don’t need a Durable Object just because the name sounds powerful.
If you can’t point to the specific problem or requirement a product solves, leave it out of your setup until you can.
Where to go next
Now you’ve got the full picture of how these pieces fit together in production. Whenever you want to go deeper on a specific part, pick up the dedicated tutorial for it:
- Cloudflare Workers: your first serverless function
- Wrangler: the Cloudflare Workers command line tool
- Serving a website with Cloudflare Workers static assets
- Cloudflare Workers: secrets and environments
- Cloudflare D1: a SQL database for your Workers
- Cloudflare KV: a key-value store for your Workers
- Cloudflare R2: object storage without egress fees
- Cloudflare Queues: run work in the background
- Cloudflare Durable Objects tutorial
- Cloudflare Cron Triggers: run a Worker on a schedule
- Cloudflare Turnstile: stop bots without annoying CAPTCHAs
- Cloudflare Workers observability: logs and traces
You can also browse The Cloudflare Guide for the full index of everything I’ve written about the platform.
If you’re starting a new project, begin with a static site, add a single Worker route, and attach one binding when a feature calls for it. Get that shipped and running in production before you add another product.
Want me to talk about your product? You can sponsor this site.
Related posts about cloudflare: