Skip to content

Hono & Cloudflare Workers

Q (basic): What are Cloudflare Workers?

Say this (30 sec): Workers is Cloudflare’s serverless platform. Your code is deployed to every Cloudflare data center, and each request runs at the location closest to the user. Instead of a container per function, Workers run many scripts inside V8 isolates in one process. That’s the same sandbox Chrome uses for tabs. Isolates are very light, so startup takes milliseconds and memory overhead is low.

Follow-ups they ask: “What’s an isolate?” It’s a separate V8 instance with its own heap. Code in one isolate can’t see memory in another, but they share the process and runtime. That’s cheaper than a container, which needs its own OS process and filesystem.

Q (mid): Do Workers have cold starts?

Say this (30 sec): Not in the Lambda sense. Lambda’s cold start has to boot a micro-VM or container and load the runtime, which can take hundreds of ms or more. A Worker isolate starts in a few milliseconds. Cloudflare also pre-warms the Worker during the TLS handshake, so in most cases the startup is hidden. Your script still has to be loaded and its top-level code run, so a huge bundle with heavy global setup still adds some delay.

Common wrong answer: “Zero cold start ever.” Say “negligible cold starts” instead.

Q (mid): What are the main Workers limits?

Say this (30 sec):

  • CPU time per request: about 10 ms on the Free plan. On Paid it defaults to 30 s and can be configured higher. This is CPU time, not wall-clock time. Time spent awaiting fetch or a DB doesn’t count.
  • Memory: about 128 MB per isolate.
  • Bundle size limit, and limits on subrequests per request.
  • No full Node.js: there is no real filesystem and you can’t spawn processes, so no FFmpeg. Only some Node modules are available, through nodejs_compat.
  • Raw TCP is available only through the connect() sockets API. Long-running background work needs Queues, Durable Objects, or Workflows.

Follow-ups they ask: “So can I do video transcoding in a Worker?” No. That needs CPU, a filesystem, and native binaries. Use a container or VM, or a managed service like Cloudinary.

Limits change, so say “roughly” and mention you’d check the current docs.

Q (mid): What does the nodejs_compat flag do?

Say this: It’s a compatibility flag in wrangler.toml (or wrangler.jsonc) that turns on Node.js APIs in the Workers runtime: Buffer, crypto, AsyncLocalStorage, events, stream, path, util, and others. Some are implemented natively and others are polyfilled. It lets many npm packages (some DB drivers, for example) work. It does not make Workers a full Node server. There’s still no real fs access to disk and no child_process.

Example:

compatibility_date = "2024-09-23"
compatibility_flags = ["nodejs_compat"]
Q (mid): Workers vs AWS Lambda vs a traditional server?

Say this (30 sec):

Workers Lambda Traditional server (VM/container)
Runtime V8 isolates, Web APIs Container/micro-VM, full Node/Python/etc. Anything
Cold start ~ms 100 ms – seconds None (always on)
Location Every edge PoP One region you choose One region you choose
Limits Tight CPU/memory, no fs Up to 15 min, up to 10 GB RAM No limits beyond the box
Good for APIs, auth, routing, edge logic Event processing, heavier jobs Long jobs, WebSocket servers, FFmpeg, stateful apps

Pick Workers for lightweight, globally distributed request handling. Pick a server for heavy compute or long-running processes.

Q (basic): Cloudflare Pages vs Workers?

Say this: Pages was built for static sites and frontend frameworks, with Git-based deploys, preview URLs per branch, and optional Pages Functions (which run on Workers underneath). Workers is the general compute platform. Cloudflare now recommends Workers with Static Assets for new full-stack projects, because it serves static files and API code from one deploy. In short, Pages is frontend-first and Workers is compute-first.

Q (basic): What is Hono and why did you use it?

Say this (30 sec): Hono is a small, fast web framework built on Web Standards: the standard Request/Response and the Fetch API. Its API looks like Express, but it runs on Cloudflare Workers, Deno, Bun, Node, Vercel, and Lambda. I used it because Express depends on Node’s http module, so it doesn’t fit Workers naturally. Hono was made for this kind of runtime. It’s tiny, it has good TypeScript support, it has built-in middleware (CORS, JWT, logger), and it has a typed RPC client.

Common wrong answer: “Hono is faster than Express so it makes the app fast.” Your latency is mostly network and DB. The router speed rarely matters.

Q (basic): Show a basic Hono app on Workers.

Example:

import { Hono } from 'hono';
import { cors } from 'hono/cors';
type Bindings = { DB_URL: string; BUCKET: R2Bucket };
const app = new Hono<{ Bindings: Bindings }>();
app.use('/api/*', cors());
app.get('/api/posts/:id', async (c) => {
const id = c.req.param('id');
return c.json({ id });
});
export default app; // Workers calls app.fetch(request, env, ctx)

Say this: c is the Context. Use c.req for the request, c.json() and c.text() for responses, c.env for bindings, and c.set()/c.get() to pass values between middleware.

Q (mid): How does middleware work in Hono vs Express?

Say this: In Hono, middleware is async (c, next) => { ...; await next(); ... }, the “onion” model like Koa. Code after await next() runs after the handler, so you can measure timing or change the response. In Express, next() isn’t awaited, so it’s awkward to run code after the handler.

Example:

app.use('*', async (c, next) => {
const start = Date.now();
await next();
c.header('X-Response-Time', `${Date.now() - start}ms`);
});
Q (mid): What is Hono RPC / the typed client?

Say this (30 sec): You export the app’s type: export type AppType = typeof routes. On the frontend, hc<AppType>(baseUrl) gives a client where routes, params, request bodies, and response types are inferred from the server code. It’s end-to-end type safety without code generation, similar to tRPC but over plain HTTP. If you rename a field on the server, the frontend fails at compile time.

Example:

const client = hc<AppType>('/');
const res = await client.api.posts[':id'].$get({ param: { id: '1' } });
const data = await res.json(); // typed
Q (mid): How do you validate input in Hono?

Say this: Use @hono/zod-validator. Pass the target (json, query, param, form, header) and a zod schema. Invalid input returns 400 automatically. The validated data is typed through c.req.valid('json'), and those types also flow into the RPC client.

Example:

app.post('/posts', zValidator('json', z.object({ title: z.string().min(1) })), (c) => {
const { title } = c.req.valid('json');
return c.json({ title }, 201);
});
Q (basic): What is Wrangler?

Say this: Wrangler is Cloudflare’s CLI for Workers. wrangler dev runs locally using workerd, the open-source Workers runtime, through Miniflare. wrangler deploy publishes. wrangler secret put stores secrets. wrangler tail streams live logs. It also has commands for KV, D1, and R2. Config lives in wrangler.toml or wrangler.jsonc.

Q (mid): What are bindings?

Say this (30 sec): Bindings connect a Worker to resources such as KV namespaces, R2 buckets, D1 databases, Durable Objects, Queues, Hyperdrive, other Workers (service bindings), env vars, and secrets. They’re declared in the Wrangler config and arrive as the env object: c.env.BUCKET in Hono, or env in fetch(req, env, ctx). There are no API keys in code. The runtime injects the resource, and it’s scoped to that Worker.

Example:

[[r2_buckets]]
binding = "BUCKET"
bucket_name = "media"
await c.env.BUCKET.put(key, file.stream());
Q (mid): Env vars vs secrets in Workers?

Say this: Plain vars go in wrangler.toml under [vars]. They’re visible in config and fine for non-sensitive values. Secrets are set with wrangler secret put NAME or in the dashboard. They’re encrypted and never shown again after you set them. Locally, put them in .dev.vars (gitignored). Both are read from env, not the traditional process.env. Recent compatibility dates with nodejs_compat can also expose them on process.env, but env is the standard way.

Q (tricky): What is ctx.waitUntil?

Say this: It lets work continue after the response is sent, like logging, analytics, or cache writes, without slowing the user’s response. Without it, the runtime can cancel unfinished promises once the response is returned. In Hono, use c.executionCtx.waitUntil(promise).

Q (mid): KV vs D1 vs R2 vs Durable Objects: when do you use each?

Say this (30 sec):

  • KV: a global key-value store, eventually consistent (writes can take around 60 s to reach everywhere). Very fast reads at the edge. Use it for config, feature flags, and cached data. Don’t use it for counters or anything where you must read your own writes.
  • D1: a managed SQLite database. Use it for relational data in small to medium apps, with read replicas.
  • R2: object storage with an S3-compatible API and zero egress fees. Use it for images, videos, and uploads.
  • Durable Objects: a single instance per ID with strongly consistent storage (SQLite-backed) and in-memory state. Use it for coordination: chat rooms, rate limiters, collaborative editing, and WebSockets (with hibernation).

Common wrong answer: Using KV as a database for frequently changing data.

Q (mid): Why R2 instead of S3?

Say this: It has the same S3 API, so existing SDKs work. The big difference is no egress (bandwidth) fees, which matters a lot for serving media. It also has a native Worker binding and public buckets or custom domains through Cloudflare’s CDN. Use presigned URLs so clients upload directly to R2.

Q (tricky): How do you connect a Worker to Postgres (e.g. Azure PostgreSQL)? What is Hyperdrive?

Say this (30 sec): A normal Postgres connection takes several round trips: TCP, the TLS handshake, and auth. From an edge location far from the DB, each round trip might take 100+ ms, and Workers can’t keep a long-lived pool between requests the way a Node server can. Hyperdrive fixes this. It keeps a warm connection pool near your database, so the Worker connects quickly to Cloudflare’s network instead of building a full connection to Azure. It can also cache read query results. You bind it and pass env.HYPERDRIVE.connectionString to a driver like postgres or pg, then use Drizzle on top.

Follow-ups they ask: “Does Hyperdrive make queries faster?” It removes connection setup cost and can cache reads. The query itself still has to reach the DB’s region. Write-heavy or uncached queries still pay the round trip from the edge to Azure. Alternatives include an HTTP-based driver like Neon’s serverless driver, or Smart Placement, which runs the Worker near the backend instead of near the user.

Q (mid): How do you measure API latency properly?

Say this (30 sec): Look at percentiles, not averages. p50 is the typical request. p95/p99 is the slow tail that real users notice. Measure TTFB (time to first byte) separately from total time. Measure from several regions, with tools like k6, autocannon, curl’s -w timing, or Cloudflare analytics. Report cold vs warm, and include DB time. Use the Server-Timing header to split server time into DB vs compute.

Example:

Terminal window
curl -o /dev/null -s -w "dns:%{time_namelookup} connect:%{time_connect} tls:%{time_appconnect} ttfb:%{time_starttransfer} total:%{time_total}\n" https://api.example.com/posts
Q (tricky): If Workers run at the edge, why might your API still be slow?

Say this: Because of data locality. Compute runs near the user, but the data lives in one region. Several sequential DB queries per request multiply the round trips. Fixes: cache at the edge (Cache API or KV), use Hyperdrive for pooling and caching, batch queries or use joins to cut round trips, use Smart Placement to run the Worker near the DB, or use read replicas in more regions.

Q (mid): What is the Cache API in Workers?

Say this: caches.default lets a Worker store and look up Response objects in the local data center’s cache. Responses can also be cached by the CDN through Cache-Control headers. It’s per-location, not global. For globally shared cached data, use KV.