Article

Back to blog

Just-in-Time Compute: Why Cloudflare Workers Is My New Default

9 min read
cloudflareworkersserverlessleaninfrastructuredurable-objects

At a glance

  1. Pull, not push: pay for compute when a request asks for it

  2. $5/month covers a small company's backend

  3. Sits behind Cloudflare's DDoS and WAF by default

  4. Durable Objects + alarms for long-running work

  5. workerd is open source: self-host the same code

  6. I/O in Workers, heavy CPU in sidecars

Just-in-Time Compute: Why Cloudflare Workers Is My New Default

TL;DR: Cloudflare Workers is the closest thing I have found to lean computing. You don't rent idle machines; compute is pulled into existence by each request, billed by CPU time, and sits behind Cloudflare's network security by default. Add D1, R2 and Durable Objects and $5/month goes a very long way. The runtime (workerd) is open source, so the same code can be self-hosted. It is great for I/O-bound business logic and weak at CPU-heavy work, which belongs in companion sidecars.


How I stumbled into it

I didn't go looking for Workers. I was moving my DNS to Cloudflare while mitigating an attack, and "Workers" showed up in the dashboard. My first thought: just another serverless platform.

What made me look twice were the limits. They were generous. Then: "is Cloudflare starting its own cloud infrastructure now?" I got curious and dug in, found D1 (SQLite as a service) and R2 (S3-compatible object storage with free egress), tried them, and had the best time of my life building on them. It was a moment of clarity and, honestly, a paradigm shift.

Later I recognized something familiar. I had read about Microsoft Orleans and the actor model: small, addressable units of state and logic that the platform activates on demand. Durable Objects are exactly that idea, shipped as a product.

A pull system for servers

The timing was funny. I had just finished The Toyota Way and its chapter on pull systems: produce only when the next step actually asks for it, instead of pushing output based on available capacity.

Renting a VPS is a push system. You buy CPU and RAM up front, and you pay for them whether they are busy or idle at 3 a.m. Workers is a pull system: a request arrives, an isolate spins up in milliseconds, does the work, and you are billed for the CPU time it used. Time spent waiting on the database or an API is not billed as CPU.

To be fair, the $5 subscription is a fixed cost too, and you pay it even in a quiet month. But to be pedantic about it: $5 for Workers versus maybe $10–20 for a VPS that gives you comparable capacity, plus a global network, plus zero servers to patch. The point stands.

The numbers (as of 28 November 2026)

From Cloudflare's pricing docs:

FreeWorkers Paid ($5/month)
Worker requests100,000 / day10 million / month, then $0.30 / million
CPU time10 ms per invocation30 million CPU-ms / month, then $0.02 / million CPU-ms (up to 5 min CPU per invocation)
Wall-clock durationnot billednot billed
Static asset requestsfree, unlimitedfree, unlimited
D1 rows read5 million / day25 billion / month, then $0.001 / million
D1 rows written100,000 / day50 million / month, then $1.00 / million
D1 storage5 GB5 GB, then $0.75 / GB-month
Durable Object requests100,000 / day1 million / month, then $0.15 / million
Durable Object duration13,000 GB-s / day400,000 GB-s / month, then $12.50 / million GB-s
R2 storage10 GB-month free$0.015 / GB-month, egress free
R2 operations1M writes, 10M reads / month free$4.50 / million writes, $0.36 / million reads

$5 buys a lot, and every unit past the included amount is priced very low. Cloudflare's own example: 15 million requests a month at 7 ms CPU each comes to about $8. For a small-to-medium company, that is very hard to beat.

"What if someone DDoSes my bill?"

This was my first worry about usage-based pricing, and the reason I (and I suspect many people) hesitate with AWS Lambda and similar services: an attacker hammering your endpoint turns directly into an invoice.

With Workers, your code sits behind Cloudflare by default. That is the same network I moved my DNS to because I was under attack. DDoS mitigation, the WAF, bot management and rate-limiting rules run at the edge, so traffic they drop never invokes your Worker. Add a rate-limiting rule for your expensive routes and the worst case gets much less scary.

The code is boring, in a good way

A Worker looks just like a Hono app on Bun or Node. Here is a small todo API on D1, with Drizzle as a type-safe query builder instead of hand-written SQL.

First, the schema:

// src/schema.ts
import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';

export const todos = sqliteTable('todos', {
    id: integer('id').primaryKey({ autoIncrement: true }),
    title: text('title').notNull(),
    done: integer('done', { mode: 'boolean' }).notNull().default(false),
    createdAt: integer('created_at', { mode: 'timestamp' })
        .notNull()
        .$defaultFn(() => new Date()),
});

export type Todo = typeof todos.$inferSelect;

Then the routes:

// src/index.ts
import { desc, eq } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/d1';
import { Hono } from 'hono';
import { todos } from './schema';

type Bindings = { DB: D1Database };

const app = new Hono<{ Bindings: Bindings }>();

app.get('/todos', async (c) => {
    const db = drizzle(c.env.DB);

    return c.json(await db.select().from(todos).orderBy(desc(todos.id)));
});

app.get('/todos/:id', async (c) => {
    const db = drizzle(c.env.DB);
    const todo = await db
        .select()
        .from(todos)
        .where(eq(todos.id, Number(c.req.param('id'))))
        .get();

    return todo ? c.json(todo) : c.notFound();
});

app.post('/todos', async (c) => {
    const db = drizzle(c.env.DB);
    const { title } = await c.req.json<{ title: string }>();
    const [todo] = await db.insert(todos).values({ title }).returning();

    return c.json(todo, 201);
});

export default app;

No server, no process manager, no connection pool to babysit. The database is a binding on env, and every query is typed from the schema.

Migrations with drizzle-kit and Wrangler

Drizzle generates the SQL migrations from the schema; Wrangler applies them to D1. Point drizzle-kit at the schema:

// drizzle.config.ts
import { defineConfig } from 'drizzle-kit';

export default defineConfig({
    dialect: 'sqlite',
    schema: './src/schema.ts',
    out: './migrations',
});

Bind the database in the Wrangler config and tell it where the migrations live:

// wrangler.jsonc
{
    "name": "todo-api",
    "main": "src/index.ts",
    "compatibility_date": "2026-11-28",
    "d1_databases": [
        {
            "binding": "DB",
            "database_name": "todo-db",
            "database_id": "<id printed by wrangler d1 create>",
            "migrations_dir": "migrations"
        }
    ]
}

Then the whole lifecycle is a handful of commands:

# one time: create the database (copy the database_id into wrangler.jsonc)
npx wrangler d1 create todo-db

# every schema change: generate SQL from src/schema.ts into ./migrations
npx drizzle-kit generate

# apply to the local dev database (used by `npx wrangler dev`)
npx wrangler d1 migrations apply todo-db --local

# check what is pending in production, then apply it
npx wrangler d1 migrations list todo-db --remote
npx wrangler d1 migrations apply todo-db --remote

# ship the Worker
npx wrangler deploy

Wrangler records applied migrations in a d1_migrations table, so apply only runs what is new. Commit the migrations/ folder; it is the history of your schema.

But what about long-running tasks?

This was my biggest doubt. Serverless functions are short-lived. How do you run a job that takes an hour, like importing a big file, sending thousands of emails, or polling an external API until something finishes?

Enter Durable Objects. A Durable Object is a single-threaded actor with its own persistent storage, addressed by an ID. It can schedule an alarm: a wake-up call at a future time. Alarms are guaranteed to run at least once and are retried with exponential backoff if they fail.

So you stop thinking "one long-running process" and start thinking state machine: do one small step, save where you are, schedule the next wake-up. It is like a recursive function that calls itself through the scheduler, or like green threads where the platform does the yielding for you.

import { DurableObject } from 'cloudflare:workers';

export class ImportJob extends DurableObject {
    async start(total: number) {
        await this.ctx.storage.put({ cursor: 0, total, state: 'running' });
        await this.ctx.storage.setAlarm(Date.now());
    }

    async alarm() {
        const cursor = (await this.ctx.storage.get<number>('cursor')) ?? 0;
        const total = (await this.ctx.storage.get<number>('total')) ?? 0;

        // One small, idempotent step.
        const next = await importBatch(cursor, 100);
        await this.ctx.storage.put('cursor', next);

        if (next < total) {
            // Throttle: one batch per second.
            await this.ctx.storage.setAlarm(Date.now() + 1_000);
        } else {
            await this.ctx.storage.put('state', 'done');
        }
    }
}

Two rules make this work:

  1. Make each step idempotent. At-least-once means a step can run twice.
  2. Rate-limit yourself. A loop that keeps waking itself up is a loop that keeps getting billed. Space the alarms, cap the batch size, and give every job an end state.

Self-hosting: still fine

There is no lock-in at the runtime level. Workers runs on workerd, which is open source. The same code runs on your own machine with a few adjustments: swap D1 for Postgres or SQLite, and R2 for a self-hosted S3-compatible store like RustFS.

One caveat: a single workerd process effectively uses one CPU core. To use a multi-core machine, run one instance per core and put a load balancer in front:

workerd0 -> cpu0 -> :8080
workerd1 -> cpu1 -> :8081
workerd2 -> cpu2 -> :8082
example.com {
    reverse_proxy 127.0.0.1:8080 127.0.0.1:8081 127.0.0.1:8082 {
        lb_policy least_conn
    }
}

That is Caddy with least-connections. Nginx with least_conn or plain round-robin works just as well.

Know what it is good at

1. Great for I/O, bad for heavy CPU. Workers shines when most of the time is spent waiting on databases, APIs and storage, and you don't pay CPU for that waiting. It is the wrong place for image processing, audio/video transcoding or model inference.

2. Separate the concerns. Workers is ideal for:

  • Business processes and workflows
  • Authentication, authorization and validation
  • Anything a browser could do: plain JS logic, Web Crypto, fetch, streams

For heavier jobs, use companion modules that Workers calls into:

  • A Python sidecar for image/video processing, AI inference or a recommendation engine
  • A Rust sidecar for voice/video calls and real-time streaming

3. Cloudflare is not outage-free. It has had real, widely felt outages, and even the SLAs on its higher plans are a promise of service credits, not a promise that nothing breaks. Realistically you are buying something like 99.99%. That is still better than what I would get managing servers myself, and it is someone else's pager at 3 a.m.

My new default

Overall, I think Cloudflare Workers is genuinely revolutionary: lean by design, cheap at small scale, safe by default, and not locked to one vendor. It is what I will be reaching for first when I build software. This very site is a static site on a Worker.

Compute should be pulled by demand, not pushed by capacity.