How workerd, the Cloudflare Workers runtime, is built

By

Tagged: Cloudflare

I read the workerd source to explain its server, service graph, V8 isolates, JavaScript APIs, request contexts, and self-hosting model.

Cloudflare Workers runs on an open-source runtime called workerd. It executes Worker code on Cloudflare’s network, and Wrangler uses the same runtime when you develop locally.

If you’re new to Workers, start with your first Cloudflare Worker or check out my complete Cloudflare guide.

Because Cloudflare publishes workerd under the Apache 2.0 license, you can also run it on your own server. In this post (the follow-up to my breakdown of how Plausible Analytics Community Edition is built), I read through the workerd source to trace an HTTP request from the server into JavaScript and back out, and to see where self-hosting hits its limits.

Keep in mind that workerd moves fast, so file names and internal details can shift over time. This walkthrough also covers only the open-source runtime. Cloudflare doesn’t publish its full deployment and security systems in this repository, so if you self-host workerd, those pieces are on you.

The design ideas behind workerd

workerd is built to run a server rather than provide a general command-line environment. Your Worker code receives a standard Request and returns a Response, while everything the Worker is allowed to touch (sockets, services, storage, networks, and secrets) has to be declared explicitly in config.

Inside the runtime, each request gets its own IoContext to track timers, subrequests, logs, limits, and background tasks. When data crosses between C++ and JavaScript, workerd keeps it streaming instead of buffering the whole body in memory first. A single process can also host many V8 isolates that all share the same native implementation of a platform API.

Each Worker stores its compatibility policy as data through a date and optional flags. And because the runtime stays separate from the full Cloudflare platform (which isn’t in this repository), running it yourself means taking care of limits, isolation, updates, monitoring, and scaling.

The purpose of workerd

workerd is a server runtime for JavaScript and WebAssembly powered by the V8 JavaScript engine. The trailing d follows the classic Unix daemon convention, marking it as a server daemon.

It isn’t a web framework, and it isn’t a general replacement for Node.js. If you want to see the layer right above the runtime, I also traced one request through Hono from routing all the way to the final Web Response.

workerd takes care of the server plumbing for you:

  • Listening for incoming events
  • Creating and managing V8 isolates
  • Exposing web and Cloudflare APIs to JavaScript
  • Turning native HTTP data into Request, Response, and stream objects
  • Wiring Worker code to configured services through bindings
  • Tracking the lifecycle of every request
  • Running background tasks registered with waitUntil()

Because the runtime handles all of that, a Worker can be as small as this:

export default {
  async fetch(request, env, ctx) {
    return new Response('Hello from workerd')
  },
}

Notice there’s no listen() call anywhere. Unlike the usual Node.js server setup where your script starts the server itself, workerd owns the server and invokes your Worker whenever an event arrives.

The main request path

When an HTTP request hits workerd, it travels through the runtime layers shown below, using the names you’ll find in the source:

How an HTTP request moves through workerdA configured socket sends a request to a Worker service. An I/O context runs the handler in a V8 isolate and returns a streamed response.Cap'n Proto configKJ HTTP socketNamed serviceBindings andoutbound servicesHTTP clientWorkerEntrypointIoContextV8 isolate lockJavaScript fetchhandlerResponse stream

Those pieces map directly to directories in the repository. server/ holds the binary and server setup, io/ handles Workers and request lifetimes, and api/ implements the JavaScript APIs. Between C++ and V8 sits JSG (JavaScript Glue), which connects native code to the engine.

The main source directories

At the top level, the repository splits into the runtime, the API library, and the server:

workerd/
  docs/                  architecture and development documentation
  npm/                   packages for prebuilt workerd binaries
  samples/               runnable Worker configurations
  src/workerd/api/       web, Cloudflare, and Node-compatible APIs
  src/workerd/io/        isolates, requests, actors, I/O, and limits
  src/workerd/jsg/       C++ and JavaScript binding layer
  src/workerd/server/    CLI, config, sockets, and service orchestration
  src/workerd/util/      shared runtime utilities

Most of the codebase is written in C++. While V8 executes your JavaScript, the asynchronous C++ components around it come from KJ, which is part of the Cap’n Proto project. workerd relies on KJ for promises, HTTP, streams, networking, and object ownership. You’ll also find JavaScript, TypeScript, Rust, and Python in the repo alongside the C++.

Configuration defines the service graph

Most application servers start by running your code. workerd flips that around and starts from a Cap’n Proto configuration.

This example wires up one Worker and one HTTP socket:

using Workerd = import "/workerd/workerd.capnp";

const config :Workerd.Config = (
  services = [
    (name = "main", worker = .mainWorker),
  ],
  sockets = [
    (
      name = "http",
      address = "*:8080",
      http = (),
      service = "main"
    ),
  ]
);

const mainWorker :Workerd.Worker = (
  modules = [
    (
      name = "worker.js",
      esModule = embed "worker.js"
    ),
  ],
  compatibilityDate = "2026-06-01"
);

That file defines three things:

  1. A Worker named main.
  2. An HTTP socket listening on port 8080.
  3. A route connecting the socket to the Worker.

Your JavaScript never picks a port, because the configuration handles that for you.

A service can have different implementations

In the Service schema, a service doesn’t have to be a Worker. It can point to any of these targets:

  • A Worker
  • A network
  • An external server
  • A directory that workerd exposes as an HTTP service

Sockets expose a service to external clients, while bindings expose a service to another Worker. That same model handles incoming requests, Worker-to-Worker calls, files, internal backends, and outbound network access.

Bindings give capabilities to a Worker

Everything that shows up in env comes from the bindings list. A binding can hold text, JSON, binary data, a key, a service, or a storage interface.

For example, this config gives a Worker access to a service named api:

bindings = [
  (name = "API", service = "api"),
]

Inside the Worker, you call that service straight through the binding:

const response = await env.API.fetch('https://api/users')

The binding determines the destination regardless of what hostname you pass in the URL. If api is another Worker running in the same workerd process, the call stays in-process without opening a network socket. Cloudflare calls this kind of service a nanoservice.

Global fetch() also uses a capability

Even the global fetch() function runs through a service. By default, workerd creates an internet service whose network policy allows public addresses and blocks private ones.

That default helps prevent SSRF (server-side request forgery) attacks, since user input can’t trick fetch() into reaching a private backend. If a Worker needs to talk to an internal backend, you add an explicit service binding for it. You can also change the default policy in config, keeping that security boundary visible in one place.

The workerd start sequence

Startup begins in workerd.c++. When you run the serve command, workerd loads the configuration, initializes V8, creates a Server, and calls Server::run().

Inside Server::run(), startup splits into two main phases:

startServices()
listenOnSockets()

workerd builds the full internal service graph before it starts accepting traffic. In the first phase, it creates Workers, networks, external servers, disk services, bindings, actor namespaces, and tail workers, and validates all service references. Then the second phase opens the configured sockets and sends each socket’s traffic to its chosen service.

One process contains one V8 system

As the JSG documentation explains, workerd creates a single process-wide V8System once at startup, and every Worker isolate lives inside it.

Each isolate gets its own JavaScript heap and can’t directly share JS objects with another isolate. Packing isolates into one process uses far fewer resources than running a separate OS process for every Worker.

JSG gives native APIs to JavaScript

V8 implements JavaScript itself, not Cloudflare’s runtime APIs. It doesn’t know anything about KVNamespace, R2Bucket, DurableObjectState, or ExecutionContext.

workerd implements those APIs in C++ and exposes them to JavaScript through JSG. In WorkerdApi, the runtime declares all the types an isolate can use, grouped into these areas:

  • Global-scope APIs
  • HTTP and stream APIs
  • Web Crypto
  • WebSockets and sockets
  • Cache, KV, and R2
  • Durable Objects and queues
  • SQL interfaces
  • Node.js compatibility
  • Tracing
  • WebAssembly and Python support

JSG handles converting values between C++ and JavaScript, exposing C++ resources and methods as regular JS objects and methods (so a native stream becomes a JavaScript ReadableStream). Keeping these APIs in native C++ also cuts down on duplicate code, since workerd doesn’t have to load a separate JavaScript implementation of each API into every isolate.

Compatibility dates select runtime behavior

Every Worker config includes a compatibility date, like this:

compatibilityDate = "2026-06-01"

That value isn’t just deployment metadata; it actively controls how the runtime behaves for that Worker. During setup, compileCompatibilityFlags() reads the date along with any optional flags and produces the final behavior flags for that Worker:

compatibility date
      +
explicit enable and disable flags
      |
      v
compiled runtime behavior flags
      |
      v
API surface and semantics for this isolate

workerd rejects any date that’s in the future or newer than the runtime itself. On the flip side, a new version of workerd can still provide older behavior for an older Worker, which lets Cloudflare update V8 without changing every application on the same day. You’ll also notice that workerd’s version numbers include the release date plus a revision number.

workerd prepares the Worker script

The main script loading code lives in worker.c++. Inside the runtime, a Worker::Isolate owns the V8 isolate and runtime API, while a Worker::Script owns the compiled application running inside it.

When constructing a script, workerd takes the isolate lock and creates a V8 context. For an ES module Worker, it loads the modules, resolves imports, compiles the main module, and finds the exported handlers. For Service Worker syntax, it compiles a single global script and sends events to the registered handlers later.

ES modules are the current syntax:

export default {
  async fetch(request, env, ctx) {
    return new Response('Hello')
  },
}

workerd finishes all of this script preparation up front, before any normal request arrives.

The path of one HTTP request

Say a client sends a request like this:

curl http://localhost:8080/hello

It hits the configured http socket first, and from there it passes through a few C++ and JavaScript layers before a response comes back.

Fig 1 · 1/6One request
configured · http socket on :8080 routes to main

KJ accepts the request

The HTTP server lives in server.c++. Each incoming connection implements the KJ HttpService interface, whose request() method gets:

  • The HTTP method
  • The URL
  • Native headers
  • An asynchronous request-body stream
  • A native response object

If your config asks for it, the server modifies request metadata or headers right here, then hands the request off to the target service.

The service creates a Worker entrypoint

When that target is a Worker service, WorkerService::startRequest() builds a WorkerEntrypoint. That object bridges the generic HTTP server and your Worker’s export, and it also wires up a request observer plus any configured tail workers for logs and traces.

At this stage everything is still native HTTP data, and no JavaScript has run yet.

Each request gets one IoContext

Next, WorkerEntrypoint::init() creates an IoContext for the stateless request. This is where workerd tracks everything tied to the active request:

  • A reference to the Worker
  • Outbound channels and bindings
  • Timers and subrequests
  • Abort state
  • Logs and traces
  • waitUntil() tasks
  • Request metrics
  • Resource-limit hooks
  • Native I/O objects exposed to JavaScript

That context also enforces an ownership boundary. Because workerd ties every native resource to its IoContext, an I/O object from one request can’t be reused in another. If your code touches a resource outside the context that owns it, the runtime throws an error.

The request waits for the isolate lock

A single V8 isolate can’t run JavaScript on two threads at once, so WorkerEntrypoint::request() calls context.run() and waits on a fair asynchronous lock. Once it gets its turn, it takes the V8 isolate lock and enters the right JavaScript context.

From there, workerd can safely work with JavaScript objects. KJ promises and JSG connect async native work to JavaScript promises, routing each continuation back into the right context once an operation finishes.

Native HTTP becomes web-standard JavaScript

The entrypoint calls ServiceWorkerGlobalScope::request() to turn the native HTTP data into standard JavaScript objects: a Headers instance and a Request carrying the method, URL, metadata, abort signal, and body.

Instead of buffering the whole request body into memory up front, workerd wraps the native input stream in a JavaScript ReadableStream. You can stream it straight back out as the response body:

export default {
  async fetch(request) {
    return new Response(request.body)
  },
}

That way, the runtime never has to allocate one giant string or ArrayBuffer for the entire body.

workerd calls the exported handler

For an ES module Worker, workerd calls your exported fetch handler with three arguments:

request, env, ctx

You get request with the JavaScript request data, env with your configured bindings, and ctx with request controls like waitUntil() and passThroughOnException(). Your handler can return a Response directly or a Promise<Response>.

The response returns to C++

Once the handler finishes, workerd checks that you returned a valid Response and writes the status, headers, and body back to the KJ response interface. If the body is a ReadableStream, it can keep producing data after fetch() returns, and the native HTTP server sends each chunk out to the client as it arrives.

A client disconnect causes an abort

While all of this runs, the runtime watches the client connection. If the client disconnects before the response finishes, workerd can fire the request’s AbortSignal.

It also blocks further reads from an expired native request stream, something the source calls neutering. Even though your JavaScript only sees a clean Request object, there’s still a real native socket underneath with a shorter lifetime.

The function of waitUntil()

Sometimes you want to return the response right away and finish a background task afterward, like sending a log request:

export default {
  async fetch(request, env, ctx) {
    ctx.waitUntil(env.LOGS.fetch('https://logs/write'))

    return new Response('ok')
  },
}

Under the hood, the ExecutionContext::waitUntil() implementation adds that promise to the current IoContext. After the response finishes, WorkerEntrypoint waits to drain the remaining tasks tied to the request.

Keep in mind that waitUntil() runs inside the current process. If the process crashes, any unfinished task disappears with it, so it isn’t a durable job queue. When work needs to survive failures and retry reliably, use Cloudflare Queues instead.

Subrequests use configured channels

Calling global fetch() or fetch() on a binding doesn’t open a Node.js socket directly. Instead, each call asks the current IoContext for an outbound channel, using a channel number that points to a configured destination.

Global fetch() normally goes through the internet service, while env.API.fetch() uses whatever service you attached to the API binding. That destination can be:

  • The public network
  • A fixed external server
  • Another Worker
  • A storage implementation speaking the expected binding protocol
  • A disk service

Your JavaScript code stays identical either way because the config decides what sits behind the binding. That also helps when testing: you can swap a production backend for a small mock Worker in your test config without touching your application code.

Same-process services remove a network operation

Microservices give you clean boundaries between services, but every network hop adds serialization, routing, authentication, retries, timeouts, and new failure modes.

With workerd, you can run multiple Workers inside one process and connect them with service bindings. The caller still talks to a service interface, while workerd can deliver the request right inside the same process and thread. The original workerd announcement calls this a nanoservice model.

That cuts down the runtime cost of each boundary, though splitting an app into too many small services can still make it harder to understand.

workerd and Node.js have different host models

Node.js usually gives JavaScript broad access to the operating system. A Node.js app can open ports, read files, spawn child processes, and load native modules.

workerd flips that model. The host sets up the server and hands your Worker only the capabilities you configure. Out of the box, you work with web standards:

  • Request
  • Response
  • fetch()
  • URL
  • Web Crypto
  • Web Streams
  • WebSockets

Turning on the nodejs_compat flag adds a wide set of Node.js compatibility APIs and modules, though it still won’t give you a standard Node.js process. Packages that expect unrestricted file access, native addons, child processes, or their own global server can still fail or behave differently, since workerd stays event-based and capability-based.

Wrangler uses workerd locally

If you haven’t used Wrangler yet, start with my Wrangler guide.

You start a local Workers dev environment with one command:

npx wrangler dev

Behind the scenes, Miniflare prepares the local environment and workerd runs your Worker code. Miniflare supplies local implementations for services like D1, KV, R2, Queues, Durable Objects, and the Cache API.

Here’s how those pieces line up locally:

Wrangler
  -> Miniflare builds the local service graph
  -> workerd executes Worker code
  -> local services implement development bindings

In this stack, workerd provides the runtime and binding interfaces, while Miniflare provides most of the local development platform around it. I use this setup when I run Cloudflare D1 locally, and it gives good runtime parity without trying to copy all of Cloudflare onto your laptop.

Direct operation of workerd

Wrangler is convenient, but you don’t need it to run workerd. Create a project folder and install workerd directly:

mkdir workerd-demo
cd workerd-demo
npm init -y
npm install --save-dev workerd

Next, put this handler into worker.js:

export default {
  async fetch(request) {
    const url = new URL(request.url)

    return Response.json({
      message: 'Hello from workerd',
      path: url.pathname,
    })
  },
}

Reuse the config.capnp file from the earlier example and start the server:

npx workerd serve config.capnp

From another terminal, send a quick request:

curl http://localhost:8080/hello

You’ll get this back:

{"message":"Hello from workerd","path":"/hello"}

Everything here runs locally without a Cloudflare account and without deploying anything to Cloudflare’s network.

A self-contained executable

With serve, workerd reads your configuration and source files on startup. If you’d rather ship one standalone binary, compile packs them all together:

npx workerd compile config.capnp > workerd-demo
chmod +x workerd-demo

The resulting executable bundles:

  • The workerd runtime
  • The encoded configuration
  • Your embedded Worker modules and data

Then run the binary directly:

./workerd-demo

Once it’s compiled, you don’t need worker.js, config.capnp, Node.js, or node_modules at runtime. Keep in mind the binary is tied to its OS and CPU architecture, so you’ll need to build an executable for each deployment target.

Production self-hosting

You can self-host workerd in production. The workerd README describes it as an application server for self-hosted Worker apps, and the repo includes a production example using systemd socket activation. In that setup, systemd owns ports 80 and 443, launches workerd as an unprivileged user, and restarts it if the process fails.

You can also run workerd inside a VM or container. Whatever you pick, pin an exact workerd version in production rather than pulling an unspecified latest version every time it starts.

Because workerd is only the application server, you’re responsible for the rest of the production stack around it:

  • Process supervision
  • A secure TLS and load-balancing layer
  • Structured logs and monitoring
  • OS resource limits
  • Health checks
  • A tested update and rollback process
  • Backups for persistent local data

On Cloudflare’s managed platform, Workers observability gives you logs and traces out of the box. A self-hosted setup needs its own equivalent.

Storage in a self-hosted system

The workerd config supports interfaces for KV, R2, Queues, Analytics Engine, Hyperdrive, and other Cloudflare services, but the standalone binary doesn’t bundle Cloudflare’s managed storage backends. Most of those bindings forward API operations to a configured service, so you need to run a service that implements the right protocol.

Durable Objects are a bit different because workerd gives you two local storage options: in-memory storage, and an experimental disk mode that writes to SQLite files. (My Durable Objects guide explains how the managed platform handles state and storage.)

Each local Durable Object stays scoped to one runtime instance, since workerd doesn’t distribute them across a cluster. In-memory storage loses your data when the process stops, while disk mode survives restarts but remains experimental and instance-local. Miniflare gives you extra implementations for development, though a single local process still won’t give you Cloudflare’s distributed storage.

The standalone server does not apply Cloudflare limits

workerd defines limit interfaces in limit-enforcer.h covering:

  • JavaScript CPU time
  • Isolate memory
  • Startup execution
  • Subrequest counts
  • KV operations
  • Buffer sizes
  • Background drain time
  • SQLite memory

Cloudflare plugs its enforcement systems into these interfaces on the managed platform. The standalone server uses NullIsolateLimitEnforcer, and its per-request enforcer doesn’t apply limits either.

The standalone binary has no way of knowing your machine size, tenant model, billing rules, or orchestration setup. Don’t assume self-hosted workerd will enforce Cloudflare’s CPU, memory, or subrequest limits for you. Use OS controls, VMs, containers, or your process supervisor to cap the process instead.

workerd is not a complete hostile-code sandbox

V8 isolates separate JavaScript heaps, but that separation alone isn’t enough to safely run arbitrary hostile code. The workerd README warns about this directly: the open-source repo doesn’t include all of Cloudflare’s production security layers.

A bug in V8, workerd, the OS, or the CPU can still cross an isolate boundary. If you need to execute untrusted user code, put it inside a stronger sandbox, such as a properly configured VM, and don’t assume a regular container is a complete security boundary against hostile code.

If you’re running your own trusted application code, it’s a normal server deployment. Untrusted user programs are a different story and need a dedicated security platform around them.

workerd is not the complete Cloudflare platform

workerd sits at the heart of Cloudflare Workers, but it’s still just one piece of the product.

If you run a self-hosted workerd server on your own machine, you don’t get the rest of Cloudflare’s stack:

  • The global Cloudflare network
  • Deployments across many locations
  • Traffic routing between those locations
  • Automatic scaling
  • The Workers control plane
  • Managed KV, D1, R2, Queues, and other services
  • Multi-tenant security layers
  • Per-request resource limits
  • Managed monitoring and billing
  • Automatic security updates for the runtime

Here’s how the open-source runtime compares to managed Cloudflare Workers:

Open-source workerdManaged Cloudflare Workers
JavaScript and WebAssembly runtimeRuntime and global hosting platform
V8 isolates and Worker APIsExtra multi-tenant security layers
Configured sockets and servicesGlobal traffic routing
Local process lifecycleDeployment and orchestration control plane
Binding interfacesManaged storage implementations
Limit hooks without standalone enforcementCloudflare resource policies and metering
Infrastructure you operate yourselfInfrastructure Cloudflare operates for you

Having an open-source runtime makes your JavaScript code portable, though it doesn’t automatically make the whole platform portable. If your Worker depends on D1, R2, Queues, Durable Objects, or AI services, moving the code is only step one. You still have to migrate your data, wire up replacements for those services, and run the operations yourself, because those managed services are where most of the lock-in comes from.

Failure and behavior boundaries

To really understand how a runtime behaves, you need to look at where it breaks and where its guarantees stop.

waitUntil() tasks are not durable

workerd keeps every waitUntil() background task inside the request context. If the process stops cleanly, it can drain those tasks before exiting, but a sudden crash wipes them out immediately.

Whenever background work needs to survive a process failure, put it in a durable queue instead. I wrote up a full pattern for that in an idempotent scheduled job with Cloudflare Queues and D1.

Memory storage disappears

In-memory storage for a Durable Object only lasts while the workerd process is alive. Switching to local disk storage persists your data across restarts, though it’s still stuck on that single runtime instance.

One Worker can use all machine resources

The standalone limit enforcers won’t stop a trusted Worker from burning through all the CPU or memory on the machine. You need to enforce those resource limits in the operating environment around the process.

A compatibility date does not freeze dependencies

Pinning a compatibility date locks in the Worker API behavior you selected, but it doesn’t freeze your dependencies. You still have to update workerd itself whenever V8 or the runtime ships security fixes, and the underlying native dependencies and operating system will keep changing too.

Local parity has limits

Because Wrangler uses workerd under the hood, your local JavaScript behavior stays very close to what runs in production. Still, local storage bindings are simulations or separate implementations, and your local machine can’t reproduce global routing, placement decisions, or distributed network failures.

Reasons for the architecture

When you zoom out, workerd splits the whole system into distinct layers. Here’s how a request travels through them:

Cap'n Proto config   declares services and capabilities
server               opens sockets and builds the service graph
WorkerService        selects a Worker and entrypoint
WorkerEntrypoint     connects an event to one Worker execution
IoContext            owns request I/O and background work
Worker::Isolate      owns the V8 execution environment
JSG                  exposes native APIs to JavaScript
GlobalScope          converts HTTP and calls the handler
KJ                   carries asynchronous I/O and streams

Each layer has a clear job. The service graph decides where an incoming request goes, and bindings decide what that Worker is allowed to touch. Compatibility flags control which runtime behaviors are active, while IoContext tracks the native resources created during a request. Below that, JSG exposes C++ APIs to JavaScript, and KJ handles pushing the response bytes out to the socket.

Splitting things up like this also closes off whole classes of runtime bugs. Because capabilities live in configuration, a Worker can’t accidentally reach a service you didn’t grant it. Isolates keep JavaScript heaps separated, request-scoped context ownership stops one request from holding onto another request’s native resources, and compatibility dates keep runtime upgrades from silently breaking older code.

Ideas for other applications

You don’t need to build a global edge runtime to borrow good ideas from workerd. A few of its core habits translate directly to everyday server apps.

Pass capabilities like database, email, and storage clients into your handlers explicitly so you can see every dependency at a glance. Bundle each request’s logger, trace ID, abort signal, deadlines, and background tasks into a single request context, and stick to standard Request and Response types so tests and future migrations stay painless. Whenever you handle a body, keep it as a stream unless you genuinely need the whole payload in memory, and separate your storage interfaces from their concrete implementations so tests can swap them out without touching application code.

It also pays to make important behavioral choices explicit and version them on purpose, instead of letting silent defaults drift over time. Remember that a language isolate is just one layer of defense, so treat runtime safety and platform safety as separate problems. Design around operational needs from the start too: resource limits, restarts, logs, runtime updates, and data placement shape how your app behaves in production just as much as your handler code does.

A runtime controls boundaries around the engine

It’s easy to think of workerd as V8 bolted onto an HTTP server, but those two pieces barely tell half the story.

Most of the real engineering lives in the boundaries around the engine. You have the service graph deciding what can talk to what, bindings handing out specific capabilities, and JSG translating native C++ APIs into JavaScript objects. Meanwhile, the isolate lock coordinates execution, IoContext cleans up native resources when a request finishes, and compatibility dates keep behavioral changes predictable.

Your fetch() handler stays tiny because the runtime handles all of that boundary work behind the scenes. That’s what a server runtime does in practice: it defines the rules for how JavaScript runs inside an asynchronous server process.

A small educational version

If you want to build a small Workers-style runtime to learn how these pieces fit together, you can skip Web Crypto, Durable Objects, and Node.js compatibility. Starting with a single process and one JavaScript module is more than enough.

One process and one handler

Have your server turn each incoming HTTP request into a standard Request, pass it to an exported fetch() handler, and convert the returned Response back into native HTTP bytes. You don’t need multiple isolates, a service graph, or dynamic Worker loading in version one.

One explicit environment object

Pass an env object that exposes only the capabilities your handler needs, like this:

const env = {
  DATABASE: databaseClient,
  EMAIL: emailClient,
}

That gives you the same binding pattern without having to invent a whole configuration language up front.

One request context

Keep the per-request state inside a single ctx object:

  • An abort signal
  • A logger
  • A trace ID
  • A list of waitUntil() promises

Once you’ve sent the response, let the server drain those waitUntil() promises up to a fixed timeout.

Streaming request and response bodies

Keep both request and response bodies as standard web streams from day one. That way, even a tiny prototype won’t buffer every upload or download into a single chunk of memory.

Isolation for a real security requirement

If your server only runs your own trusted code, a single JavaScript process is fine. The moment you run code from multiple users, the threat model changes completely, and you need a strong sandbox well before you need more web APIs.

Putting those pieces together gives you a compact starting architecture:

A small educational Worker runtimeAn HTTP server creates standard web objects and calls one JavaScript handler with explicit environment and context objects.HTTP clientHTTP serverWeb RequestJavaScript fetchhandlerExplicit envcapabilitiesAbort, logs,waitUntilWeb Response

Start with that baseline: one process, one handler, explicit capabilities, a request context, and streaming bodies. Bring in a service graph once you have services that need independent configuration, and add compatibility versions when you need to support multiple API behaviors side by side. Wait to add isolated execution until one workload can block another, and put a hardened sandbox plus strict resource limits in place before you ever run user-supplied code.

workerd is what you get after years of running those ideas at production scale. It’s a great architectural reference to study, even when your own runtime only needs a fraction of it.

Want me to talk about your product? You can sponsor this site.

Related posts about cloudflare: