All posts

Moving Bucket0 to Cloudflare Workers and Open-Sourcing It

11 min read...
Moving Bucket0 to Cloudflare Workers and Open-Sourcing It

Back in April, I wrote about how Bucket0 ran for under $8 a month: one Hetzner VPS, one Docker container, Next.js on Bun, and Caddy out front. At the time, the codebase was closed source, and the single-box setup did its job. It kept the bill tiny and proved you don't need a cluster to ship a storage platform.

Bucket0 now runs on Cloudflare Workers, the Hetzner server is gone, and the repository is open source. This post covers why I made the switch, what broke when one process became distributed isolates, the workerd runtime issues I hit, and how production cut over without copying a single user file.

Why Leave the Hetzner VPS#

The April post ended with five conditions that made the $8/month architecture work. Four still hold: object storage does the heavy lifting, egress is free, document tools run in the browser, and the database sleeps when idle.

The fifth condition was one instance is enough. For steady traffic it still was, but the surrounding tradeoffs kept getting worse:

Single point of failure. A kernel update that needed a reboot, a full disk, or a bad container deploy took the entire product offline. Even routine maintenance meant downtime.

Ops overhead with zero product value. Docker, Caddy, TLS certificates, OS security patches, disk alerts, and log rotation are all easy individually, and together they are pure maintenance tax.

Compute and storage lived in different data centers. Bucket0's files were already on Cloudflare R2. Every upload, download, and thumbnail read talked to R2 anyway, while the Hetzner box sat elsewhere coordinating requests for bytes stored on Cloudflare's network.

No auto-scaling. On a single VPS, a traffic spike means either hitting a ceiling or manually resizing the box and adding a load balancer. On Cloudflare, the compute layer scales per request across edge isolates automatically, Queues absorbs bursty thumbnail work, and Containers scales media instances on demand. That does not magically auto-scale your Postgres free-tier limits or prevent overages past included Workers usage, but it removes compute sizing and load balancing from the list of things you have to manage.

Architecture: Before and After#

Before and after topology comparing the single Hetzner VPS container against the Cloudflare Workers edge stack

LayerHetzner VPS (Before)Cloudflare (After)
ComputeSingle VPS, Docker, Bun (~$5-$7)Cloudflare Workers ($5 plan)
FrameworkNext.js App RouterReact Router 8 + Hono
HTTPS / TLSCaddy + Let's EncryptCloudflare edge
Rate LimitingIn-memory MapDurable Object counters
Upload TrackingIn-memory tracker (globalThis)Postgres table (chunked_uploads)
S3 ConcurrencySingle-process assumptionsPer-object leases in Postgres
Thumbnailssharp, ffmpeg, GraphicsMagick in-containerPrivate Cloudflare Container fed by a Queue
Background WorkFire-and-forget promisesCloudflare Queue + dead-letter queue

R2, serverless Postgres, Clerk, billing, and the client-side PDF and image tools all stayed on the same vendors and tiers. The migration replaced the single box in the middle.

Replacing Next.js with React Router 8 and Hono#

Next.js can run on Cloudflare Workers through adapters, and I tested that first. I ended up moving to React Router 8 in framework mode on Vite, with Hono for the API, wired up through Cloudflare's Vite plugin.

The reason was control. Most of Bucket0 is its API: chunked uploads, encrypted range-request streaming, an S3-compatible gateway, share links, AgentBucket, and an MCP bridge. When debugging streaming decryption or S3 signature quirks inside a Worker, plain request handlers are much easier to trace than a framework runtime translated into a Worker bundle.

To avoid rewriting dozens of API endpoints by hand, I kept the Next.js-shaped route files (app/api/teams/[teamId]/files/route.ts exporting GET/POST handlers taking NextRequest) and built a thin adapter around them:

Hono build-time route walker and compatibility shim layer running Next.js route files on Cloudflare Workers

  • A Hono router walks server/routes/**/route.ts at build time and maps file paths to routes. [teamId] becomes :teamId, [[...path]] becomes a catch-all, and static segments win over dynamic ones.
  • Small compatibility shims implement NextRequest, NextResponse, and Clerk's auth() on top of Hono's request context.
  • On the frontend, lightweight shims for next/link, navigation hooks, images, and metadata let existing React components move over with minimal edits.

That kept the framework swap mechanical and freed up time for the real problem: removing everything that depended on a single process.

Removing Single-Process State#

On Hetzner, one Bun process handled every request, so module-level memory acted like a free shared store. On Cloudflare Workers, requests land on many short-lived isolates across edge locations with zero shared memory. Every single-process shortcut had to become explicit distributed state.

Mapping single-process shortcuts to Durable Objects, Postgres leases, and Cloudflare Queues

Rate Limiting with Durable Objects#

In the April post, the in-memory Map rate limiter worked because there was only one container. On Workers, each isolate starts with an empty Map, so per-isolate counters barely enforce anything.

Rate limiting now runs on a Durable Object: one small counter per actor, giving every isolate a single consistent count. Throughput still scales across users because each actor maps to its own Durable Object. IP-based limits key off the client IP Cloudflare reports on the connection rather than a forwarded header a client can spoof. Callers get the same X-RateLimit-* headers without paying for an external Redis instance.

Upload Tracking in Postgres#

The three-phase upload pipeline (slot acquisition, atomic quota reservation, then vendor upload creation) relied on an in-memory tracker to reserve a per-file slot and return 409 Conflict on concurrent uploads to the same path. It even used a globalThis trick so Next.js HMR wouldn't wipe active uploads in dev.

That tracker now lives in Postgres in a chunked_uploads table. Slot acquisition, quota reservation, and abandoned-upload cleanup all run as SQL operations. It adds a database round-trip compared to a local Map, and in exchange it is correct across every isolate, survives deploys, and needs no globalThis hack.

S3 Concurrency Leases#

The S3-compatible gateway had a sharper version of the same race. A PutObject checks whether an object already exists at that key, reads its old size, and adjusts the user's quota by the delta. Two concurrent writes hitting different isolates could both read the old size and both apply their own quota adjustment.

Every S3 write and delete now takes a per-object lease in Postgres around the size check and quota update. For "save to my drive" on shared links, a partial unique index enforces the same guarantee at the schema level so a double-click cannot create duplicate files.

Background Jobs and Cloudflare Queues#

On the VPS, post-response work meant firing a promise without awaiting it. Workers bound post-response execution (around 30 seconds) and kill anything still running past that window.

Background work is now split into two strict categories:

  1. Required writes. Anything tied to correctness, such as inserting the database row that makes an uploaded file exist, is awaited before returning the response.
  2. Optional work. Tasks like thumbnail generation go onto a Cloudflare Queue with automatic retries and a dead-letter queue. Instead of disappearing into container logs, persistent failures land where they can be inspected and replayed.

Thumbnail Pipeline on Cloudflare Containers#

Thumbnail generation requires native binaries (sharp, ffmpeg, GraphicsMagick, and Ghostscript) that JavaScript isolates cannot run. Rather than keeping a VPS around just for media processing, it moved into a separate media service inside a private Cloudflare Container. It has no public URL; only the Worker can invoke it.

Thumbnail pipeline streaming decrypted AES-GCM chunks from R2 through a Cloudflare Queue into a private Cloudflare Container

The chunked AES-GCM format from the April post paid off again here. Because each 8MB chunk is independently encrypted and authenticated, generating a thumbnail for a 4GB video still only streams a few megabytes to the container. The container image is pinned by digest, so native dependencies only change when a new tested image is deliberately shipped.

Runtime Gotchas in workerd#

Several bugs passed cleanly in Node and only surfaced inside workerd:

Module scope runs at deploy time. Cloudflare evaluates modules while validating a deploy, before runtime secrets exist. Any top-level process.env read captured undefined permanently. Every environment read moved inside request-time functions.

No timers at module scope. workerd rejects setInterval created outside a request context, which killed the old upload tracker's cleanup sweep. Moving cleanup to Postgres removed the need for it.

Don't fetch your own public URL. Internal calls to the app's own HTTP endpoints loop back out through Cloudflare's edge on Workers. Those became direct function calls.

Vite mixing browser and Node AWS SDK exports. Vite's server build resolved browser entry points for some AWS SDK packages alongside Node entry points. Builds and Node unit tests passed, then every R2 call in workerd threw emitWarningIfUnsupportedVersion is not a function. Fixing Vite's server export resolution solved it, and storage tests now run inside workerd as well as Node.

Since nearly every request path was already open on the bench, I used the migration to ship a security audit alongside it: stricter S3 gateway request checks, quota enforcement on every path that adds a file, immediate access revocation after deletes and team changes, and response headers that prevent user-uploaded content from executing in the app's origin.

Zero-Copy Production Cutover#

The cutover rule was strict: no user notices, and no file gets copied.

Because Bucket0 stores encrypted files, pointing the production Worker at the wrong R2 bucket, Postgres database, or encryption key would make files vanish or fail decryption. The production Worker reused everything from Hetzner: the same Postgres database, R2 bucket, encryption keys, Clerk instance, API keys, and MCP OAuth config.

Instead of trusting manual .env checks, the deploy script hashes each production setting and compares the hashed fingerprints against fingerprints captured from the running Hetzner VPS. It never prints or stores secrets, and if the database URL or any key differs by a single character, the deploy aborts.

Pre-deploy secret fingerprint verification gate and zero-copy cutover timeline from staging to Hetzner deletion

The rollout ran in six steps:

  1. Staging first. A separate Worker, Postgres branch, and thumbnail bucket to test uploads, S3, and failures safely.
  2. Manual schema migrations. The chunked_uploads and S3 lease tables were applied to production Postgres by hand before cutover. The deploy script verifies they exist and refuses to run DDL itself.
  3. Compatible thumbnail paths. The Worker writes thumbnails to the exact R2 keys the VPS expected, keeping rollback safe.
  4. Throwaway-account smoke test. Uploads, downloads, share links, the S3 API, and an MCP connection were tested against production with a temporary user, whose files, rows, and OAuth grants were deleted immediately after.
  5. Route cutover. On November 12, bucket0.com, www.bucket0.com, and s3.bucket0.com switched to the Worker.
  6. Two-week rollback window. The Hetzner VPS stayed online in maintenance mode for two weeks.

Nothing needed rolling back. On November 26, I deleted the Hetzner server.

Cost Breakdown#

LayerChoiceMonthly Cost
Compute + CoordinationCloudflare Workers plan (Workers, Durable Objects, Queues, Containers within included usage)$5
DatabaseServerless PostgreSQL (free tier)$0
Object StorageCloudflare R2 (zero egress)Pennies
Auth & BillingManaged providers (free tiers)$0
Total~$5-$6

The monthly bill ended up slightly lower than the Hetzner box, while trading single-machine ops and manual scaling for managed edge compute, Durable Objects, Queues, and on-demand Containers.

Open-Sourcing Bucket0#

When I wrote the April post, Bucket0 was closed source. You had to take my word for how chunked AES-GCM, range requests, or the upload pipeline actually worked.

Once the migration finished and the VPS was gone, opening the repo was the obvious next step. Everything described in both posts (the encryption pipeline, the Hono route loader, Durable Object rate limiting, Postgres upload tracking and S3 leases, the private thumbnail container, and the fingerprint-checked deploy script) is now public at github.com/buddhsen-tripathi/bucket0.

Newsletter

Get the next post in your inbox. No spam, unsubscribe any time.