How I Built a Full Image-to-3D Studio on ONE Cloudflare Worker + D1 (Zero Queues, Zero KV, Zero FFmpeg)
TL;DR: You can run a complete production Image-to-3D studio—including async AI inference orchestration, an atomic FIFO credit ledger, GLB binary verification, interactive PBR/skeletal viewing, and 1080p 360° MP4/WebM/GIF
TL;DR: You can run a complete production Image-to-3D studio—including async AI inference orchestration, an atomic FIFO credit ledger, GLB binary verification, interactive PBR/skeletal viewing, and 1080p 360° MP4/WebM/GIF turntable export—inside a single Cloudflare Worker plus one D1 database, with zero Cloudflare Queues, zero Durable Objects, zero KV, zero mandatory object storage, and zero server-side FFmpeg. That is the exact production architecture running Idol Max today.
Below is the concrete engineering breakdown: every boundary, timeout, binary parser, SQLite batch guard, and browser WebCodecs decision—along with the real constraints and tradeoffs we accepted to keep infrastructure overhead near zero.
Why I Refused to Build a Distributed Stack for an AI 3D App
When developers plan an AI 3D web app, the whiteboard usually explodes into six services before a single line of UI exists: an API server, a Redis/Queue broker, a background worker fleet, an S3/R2 bucket for uploads and outputs, a headless Chromium or FFmpeg container for turntable video rendering, and a Postgres cluster for billing.
For an independent product, every extra moving part carries two hidden costs: operational fragility and unbounded variable cloud bills. I built Idol Max under four strict architectural constraints:
-
One Cloudflare Worker serves SSR pages, JSON APIs, static assets, and the cron trigger (
{ fetch, scheduled }). - One Cloudflare D1 (SQLite) database holds users, generation jobs, share tokens, site settings, thumbnails, and the full credit ledger.
-
Zero source images written to disk—user photos are resized in the browser, verified in memory, and passed straight to the inference provider with
X-Fal-Store-IO: 0. - Zero server-side video rendering—every PNG screenshot, 360° GIF, and 1080p MP4/WebM turntable is rendered deterministically on the user's GPU inside Three.js and encoded locally via WebCodecs or a Web Worker.
The stack is TanStack Start (file-based routing unifying SSR pages and API handlers) + Vite 8 + @cloudflare/vite-plugin + Drizzle ORM + Better Auth + Stripe Checkout + Three.js 0.187 + mediabunny + gifenc.
1. One Worker, Two Entry Points: fetch and scheduled
In src/server.ts, the entire backend exports just two handlers:
-
fetch: delegates to TanStack Start's server entry, plus a small guard (jsonApiFallthrough) that converts HTML fallthroughs on/api/*into strict404or405JSON responses so malformed API calls never accidentally return an SSR page. -
scheduled: driven by a single 1-minute Cloudflare Cron Trigger inwrangler.jsonc. Rather than adding Cloudflare Queues or Workflows, one minute-level tick fans out three time-sliced jobs with isolated error boundaries (guarded()):-
Every 1 minute:
syncInFlightModels(25)advances pending AI 3D jobs so generations finish and save cleanly even if the user closed their browser tab immediately after clicking Generate. -
Every 5 minutes:
reconcileBilling(25)checks for any crash window between marking a modelreadyand settling its credit reservation (or revoking failed jobs). -
Daily at 03:17 UTC:
deleteExpiredModels(100)enforces storage retention (30 days for unpurchased accounts, 365 days once a user buys any credit pack) and prunes rate-limit rows older than 24 hours.
-
Every 1 minute:
This eliminates an entire queue infrastructure layer while keeping job completion latency indistinguishable from real time—because active browser sessions also poll GET /api/models/:id, which calls the exact same idempotent syncModel() function.
2. The Generation State Machine and Binary Safety Gates
Every 3D generation passes through a strict five-state machine:
queued → processing → saving → ready | failed
Here is what actually happens on POST /api/generations before a single cent of GPU compute is spent:
Step A: Zero-Dependency Binary Image Inspection
Even though the client downsizes images before upload, the Worker never trusts Content-Type or file extensions. checkSourceImage(bytes) enforces:
- Maximum payload size: 6 MB (
MAX_UPLOAD_BYTES). - Minimum and maximum pixel edge: 64 px to 4,096 px.
- Real magic-byte and header parsing in pure TypeScript (
DataView) for PNG (IHDR bytes 16–24), JPEG (walking0xFFmarkers toSOF0..SOF15), and WebP (RIFF....WEBPacrossVP8X,VP8, andVP8Lchunks).
This blocks spoofed files and decompression bombs (tiny compressed payloads that expand into massive bitmaps at the inference provider) using zero native image binaries inside the Worker isolate.
Step B: Idempotency, Cost Gates, and 3-Phase Credit Reservation
-
Idempotency: Each request carries a
clientRequestId. Double-clicks or network retries match(userId, idempotencyKey)and return the existing job without double-charging. -
Three cost gates: Global daily cap (
maxPerDayGlobal, where0acts as an instant emergency kill switch), per-user daily cap (maxPerUserPerDay), and per-user concurrency cap (maxInFlightPerUser). -
3-phase reservation: Before calling
queue.fal.run, we freeze credits incredit_reservationsusingreservationId = model.idwith a 90-minute hold. If the HTTP submission to fal.ai fails, we immediately callrevokeReservation()and return the error. -
Privacy-first submission: The verified bytes are encoded as a chunked base64
data:URI (chunk size0x8000to avoid call-stack overflow on multi-megabyte inputs) and sent to fal.ai withX-Fal-Store-IO: 0so neither our server nor fal's request history keeps the source photo.
Step C: Binary GLB Validation Before Settling Credits
When fal.ai reports COMPLETED for Idol Max Turbo (speridlabs/idol/max/turbo, ~20s, 10 base credits) or Idol Max (speridlabs/idol/max, ~50s, 20 base credits), syncModel() claims the transition to saving using a conditional SQL update so concurrent browser polls and cron ticks cannot double-process the job.
Before marking the model ready and settling the credit reservation, the Worker downloads the GLB and runs inspectGlb(buffer)—a 70-line binary glTF 2.0 validator that checks:
- The
glTFmagic header (0x46546c67) and version2. - Total declared byte length against actual
buffer.byteLength(catches truncated downloads). - Valid
JSONchunk (0x4e4f534a) andasset.version === "2.0". - Non-zero vertex and triangle counts computed directly from
meshes[].primitives[].attributes.POSITIONandindicesaccessors, plus skin and animation clip counts.
If the GLB is corrupt or empty, the job fails and 100% of reserved credits are refunded. Even better: if the user paid extra for skeletal rigging (+3 credits on Turbo, +5 credits on Max) and fal.ai returns a valid mesh whose rig step failed (rig.succeeded === false), our settlement logic automatically refunds the rigging portion—mirroring fal.ai's own billing behavior. And if a job never completes within 30 minutes (MODEL_STALE_MS), it is marked failed and refunded automatically.
3. An Atomic FIFO Credit Ledger on D1 Without Interactive Transactions
Cloudflare D1 executes db.batch([...]) as a single serialized transaction, but it does not expose long-lived interactive BEGIN ... SELECT ... UPDATE ... COMMIT locks across network round trips. Naive SELECT balance followed by UPDATE balance = balance - cost leaks race conditions under concurrent requests.
To make the ledger rock-solid on SQLite/D1:
-
Batches are the source of truth: Every credit award (purchase pack, refund, admin grant) creates a row in
credit_grantswithamount,remaining,expiresAt, andstatus. -
FIFO ordering: Consumption prioritizes grants with the earliest
expiresAtfirst (expiresAt IS NULLlast), then oldestcreatedAt. -
Pre-state guard + per-row optimistic updates: After computing the FIFO allocation plan in memory, we execute a single
db.batch()where:- The transaction ledger
INSERTis gated byfifoGuard(allocations)—a subquery checking that the count of rows incredit_grantsstill matching(id = grantId AND remaining = remainingBefore)equalsallocations.length. - Every grant
UPDATEincludesWHERE id = ? AND remaining = ? AND status = 'active'. - The cached
user_credits.creditscolumn is recomputed in the same batch viaSELECT COALESCE(SUM(remaining), 0) FROM credit_grants WHERE status = 'active' AND (expires_at IS NULL OR expires_at > now).
- The transaction ledger
If two requests race on the same user's grants, the second batch sees a mismatched snapshot, fails cleanly without partial deduction, and retries. Because the cached balance is always recalculated from SUM(remaining) on every write, cache drift is self-healing by construction. Every payment webhook from Stripe also keys off payment_intent ID for strict idempotency and verifies the exact paid amount and currency.
4. Zero-FFmpeg Client-Side 360° Export: Three.js + WebCodecs + Web Workers
Rendering 360° turntable videos on a backend requires GPU containers or FFmpeg workers that burn money every time someone exports a clip. Instead, we built a single Three.js engine (ModelViewerEngine) shared across the paid Studio, public share pages, our free online GLB viewer, and our free 3D turntable maker.
Four engineering details make browser-side exports reliable:
-
Zero external HDRI downloads: All four lighting presets (
Studio,Soft,Dramatic,Outdoor) are generated procedurally using Three.jsRoomEnvironmentand a vertex-colored sky dome with a procedural sun baked into a PMREM cubemap (PMREMGenerator). Combined withACESFilmicToneMappingandPCFShadowMap, the viewer stays lightweight and loads instantly. -
On-demand rendering + WYSIWYG Composition Mode: The WebGL canvas does not spin a 60 fps
requestAnimationFrameloop while idle; it renders only whenOrbitControlsfireschange, damping settles, or a skeletal clip (walk,run,jump,idle) plays. When exporting, the viewport enters a letterboxed composition frame locked to the chosen aspect ratio, model scale (0.5–1.2), and a12°elevation angle—guaranteeing the exported pixels match the preview. -
Deterministic angles, never real-time capture: Rather than using
MediaRecorder(which drops frames on slower laptops and produces stuttering loops), frameiofNis explicitly positioned atstartAngle ± 360 * (i / N). Because frameN - 1stops one exact increment before360°, every exported loop is mathematically seamless regardless of hardware speed. -
True WebCodecs MP4/WebM + off-thread GIF:
- For video (
720por1080pshort-edge,24or30fps), we probe real browser encoder capability withmediabunny'scanEncodeVideo('avc' | 'vp9' | 'vp8', ...)—we never fake an MP4 by renaming a WebM blob. Supported browsers encode H.264 into an in-memory fast-start MP4 (Mp4OutputFormat({ fastStart: 'in-memory' })) or VP9/VP8 into WebM directly fromCanvasSource. - For GIFs (
320,480, or640px long edge at10or15fps), RGBA frames are transferred asArrayBuffers to a dedicated Web Worker runninggifenc(rgb565256-color quantization). To avoid GIF's centisecond rounding drift (where naive15 fps → 7 csturns a 6.0-second turntable into 6.3 seconds), each frame delay is computed as the difference between rounded cumulative timestamps (6, 7, 7, 6, 7...). - Between frames, the loop yields via a
MessageChannelmicro-task (nextTask()) instead ofsetTimeout, preventing Chromium/Safari background-tab throttling from stalling an export when the user switches tabs.
- For video (
Honest Tradeoffs and Verification Conditions
This architecture is deliberately constrained, and those constraints come with real tradeoffs:
-
Browser encoder variance: Safari, Chrome, and Linux Firefox expose different WebCodecs H.264/VP9 hardware profiles. Probing
canEncodeVideo()avoids broken files, falling back cleanly to WebM or GIF when H.264 encoding is unavailable on a given OS/browser. -
Storage proxy without R2: By default, Idol Max runs with zero mandatory R2 storage—serving GLB downloads through
/api/models/:id/file(checking user ownership or public share tokens) and storing 1200×630 JPEG thumbnails in D1model_assetsunder SQLite's 2 MB row ceiling. If R2 (MODELSbinding) is attached later, the code automatically mirrors GLBs and sets a 24-hourX-Fal-Object-Lifecycle-PreferenceTTL on fal's CDN copies. -
Mesh/animation scope: The viewer supports plain, Meshopt-compressed, and Draco-compressed glTF 2.0 GLB files (with Draco decoders vendored locally under
public/vendor/draco/). It is an inspection and showcase studio—not a full vertex-level DCC replacement for Blender.
All unit and integration behaviors—the FIFO D1 credit ledger (tested against in-memory libsql with production Drizzle migrations), model lifecycle timeouts/retries/refunds, fal.ai queue client, binary GLB/image parsers, and pricing math—are verified continuously via bun test.
If you want to inspect the Three.js viewer, test WebCodecs turntable export on your own local GLB file without creating an account, or try an Idol Max Turbo generation yourself, you can test everything live at Idol Max (idolmax.net).
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.