I Built a Full-Stack AI App on Cloudflare Workers With Postgres, Workflows, and Queues — Here's What Actually Worked
TL;DR
clickfolio.me runs on Cloudflare's edge stack: TanStack Start on Workers, Postgres behind Hyperdrive, R2, Queues, Workflows, Durable Objects, and OpenRouter via AI Gateway. Claim-check uploads, hash dedup, WebSocket status updates, and far fewer platform workarounds than I expected.
Key Takeaways
- Workers + Hyperdrive + PostgreSQL gives you real Postgres at the edge: JSONB, transactions, booleans, and Drizzle types that don't lie.
- The Claim Check Pattern (upload anonymously → authenticate → claim) reduces auth friction dramatically for new users.
- Durable Objects with WebSocket Hibernation give you real-time updates at near-zero cost, the DO evicts from memory when idle.
- Cloudflare Queues and Workflows with dead letter handling are essential, AI parsing fails more than you'd expect.
- Two-stage validation (lenient on AI output, strict on user edits) prevents double-encoding and keeps XSS protection where it matters.
- File hash deduplication with a waiting-for-cache pattern prevents duplicate AI calls for the same PDF.
Nobody should need to know HTML to have a web portfolio in 2026.
That was the pitch I told myself. The reality is I wanted to see how much of a production app I could run on Cloudflare’s primitives — Workers, R2, Queues, Workflows, Durable Objects, Hyperdrive — with as few external moving parts as possible. It’s the same instinct behind self-hosting my own logging platform instead of paying for a SaaS — build the thing, learn the constraints. clickfolio.me is the result: upload a PDF resume, AI parses it, you get a customizable web portfolio with a public URL. The compute and storage ride on the same Cloudflare Workers platform that powers my own portfolio, just stretched across a full dynamic app.
Simple pitch. The architecture behind it? Less simple.
The Stack
Before I get into the interesting parts, here’s what powers the app:
- TanStack Start (React 19, Vite) on Cloudflare Workers
- Cloudflare Hyperdrive + PostgreSQL (PlanetScale) with Drizzle ORM
- R2 for PDF storage (direct bindings, no S3 SDK)
- Cloudflare Queues for edge-cache purges, with a dead letter queue
- Cloudflare Workflows for the resume parse pipeline, with per-step retries
- Durable Objects with WebSocket Hibernation for live status
- Clerk for Google OAuth + email/password
- OpenRouter via Cloudflare AI Gateway for resume parsing
- Effect for the service layer, Zod for validation
If you’ve read my Cloudflare portfolio post, this is the same platform, but instead of a static site, it’s a full dynamic app with auth, file uploads, AI processing, real-time updates, and 33 different designs as of November 2026. Every constraint I mentioned in that post? I hit most of them again, plus new ones.
The Claim Check Pattern: Upload Before You Authenticate
Here’s the UX problem: you land on the site, you have your resume PDF ready, and you want to see what happens. But most apps would make you sign in first. By the time you’ve done the Google OAuth dance, the motivation has evaporated.
The solution is what I call the Claim Check Pattern. It works like dropping off your coat at a venue — you hand it over, get a ticket, and claim it later.
Step 1: Anonymous Upload. No account needed. Upload your PDF to POST /api/upload. The worker validates the file (content-type, max 5MB, PDF magic number check. Yes, it reads the first bytes for %PDF-), stores it in R2 under a temp key (temp/{uuid}/{filename}), and returns the key. IP-based rate limiting: 10 per hour, 50 per day, with hashed IPs (SHA-256) so no raw IPs hit the database.
Step 2: Authenticate. Google OAuth or email/password via Clerk. The temp upload key sits in an HTTP-only cookie the whole time.
Step 3: Claim. POST /api/resume/claim links the anonymous upload to the authenticated user. This is where it gets interesting:
// Simplified claim flow — the actual code handles a lot more edge cases
const fileBytes = await R2.getAsUint8Array(env.R2_BUCKET, tempKey);
const fileHash = await computeSHA256(fileBytes);
// Check if this exact PDF was already parsed for this user
const cached = await db.query.resumes.findFirst({
where: and(
eq(resumes.userId, userId),
eq(resumes.fileHash, fileHash),
eq(resumes.status, "completed"),
isNotNull(resumes.parsedContent),
),
});
if (cached) {
// Skip AI parsing entirely — reuse previous result
await upsertSiteData(userId, cached.parsedContent);
return { status: "completed", cached: true };
}
The file hash deduplication saved me real money, roughly $0.02 per AI parse avoided, which added up to over $50 in savings during the first 3 months. Model calls aren’t free, and users upload the same resume multiple times more often than you’d think, fixing a typo in their name, trying different designs, abandoning the wizard and restarting. Same SHA-256 hash? Skip the parse.
But there’s a subtler case: what if the same file is currently being parsed? That’s the waiting_for_cache status. Instead of firing a duplicate AI call, the new resume record waits for the first parse to complete, then copies the result. Ten-minute timeout if the primary parse dies. Belt and suspenders.
AI Parsing: One Workflow, Many Hallucinations
Resume parsing is a solved problem in the sense that everyone has a solution and none of them work reliably. I went with an open model through OpenRouter and Cloudflare AI Gateway — cheap, fast enough for structured extraction, and one place to swap models when a better one ships.
The parse runs as a Cloudflare Workflow keyed by the resume ID. The steps handle the claim, the parse, career classification, and completion; each step carries its own retry budget, and a repeated start for the same resume is a no-op. The model gets a structured schema prompt and returns JSON with name, headline, contact, experience, education, skills, projects, and certifications.
Workflows matter because a parse takes 30-40 seconds, and a Worker request can’t sit around that long. The Workflow owns the retries, the journaled steps, and the terminal failed state. If a step exhausts its retries, the run fails cleanly instead of leaving a resume stuck in processing.
The Two-Stage Validation Philosophy
This is the decision I’m most proud of, and it took three rewrites to get right.
Stage 1 (AI output): Lenient transforms. Trim whitespace, normalize URLs, detect garbage patterns (repeating path segments like /divkix/divkix/divkix), move LinkedIn URLs from the website field to the LinkedIn field. No XSS sanitization here. Why? Because React escapes on render, and sanitizing at parse time would double-encode special characters. An & in “AT&T” becomes & in the database, then & when React renders it. I shipped that bug and it looked terrible.
Stage 2 (user edits): Strict Zod validation with XSS sanitization. When users modify their resume content in the editor, that’s when I sanitize. Strict email regex, URL validation, HTML entity encoding. This is the trust boundary — AI output is internal data, user edits are untrusted input.
// Parse-time: lenient (AI output → display)
const transformed = transformAiResponse(modelOutput);
// No sanitization. React escapes on render.
// Edit-time: strict (user input → storage)
const validated = resumeContentSchema.parse(userEdits);
// Full Zod validation + XSS sanitization
Model upgrades don’t fix hallucination. I tested a larger model at roughly 25x the token cost, and it produced maybe 5-15% fewer garbage URLs. Not worth it. The lenient transform approach handles the rest: if a URL has repeating path segments or excessive depth (>12 segments), it gets stripped. Good enough for 95% of resumes.
Real-Time Status: From HTTP Polling to Durable Objects
The initial version polled GET /api/resume/status every 3 seconds while the AI was parsing. It worked. It also hammered Postgres with unnecessary reads and felt sluggish. Three seconds is an eternity when you’re staring at a spinner.
I replaced it with Durable Objects and WebSocket Hibernation. The commit that shipped it says feat(realtime): replace HTTP polling with Durable Objects + WebSocket Hibernation, and that undersells how much this changed.
Here’s how it works:
The Durable Object is keyed by resumeId. The client connects via GET /ws/resume-status?resume_id=X with WebSocket upgrade. The DO accepts the connection using the Hibernation API. If there’s a cached status in DO storage, it sends immediately. When the Workflow finishes parsing, it notifies the DO. The DO broadcasts the status to all connected WebSocket clients. On terminal states (completed/failed), it schedules a 30-second alarm to clean up.
Hibernation API matters because without it, the Durable Object stays in memory for the entire parsing duration (30-40 seconds). With Hibernation, it evicts from memory when idle and only wakes up when a message arrives or a WebSocket connects. Cost: effectively zero for intermittent status updates.
// worker.ts — intercept WebSocket upgrades before the TanStack Start handler
if (request.headers.get("Upgrade") === "websocket") {
const url = new URL(request.url);
if (url.pathname === "/ws/resume-status") {
const resumeId = url.searchParams.get("resume_id") as string;
const doId = env.RESUME_STATUS_DO.idFromName(resumeId);
const stub = env.RESUME_STATUS_DO.get(doId);
return stub.fetch(request);
}
}
// Everything else goes to the TanStack Start handler
The client still falls back to HTTP polling if WebSocket connection fails. Defense in depth. The notification from the Workflow to the DO is best-effort. If it fails, polling catches it. No data loss, just slightly slower UX.
Postgres + Drizzle Behind Hyperdrive
I’ve been vocal about using managed Postgres for side projects. clickfolio.me is where I settled on PlanetScale Postgres through Cloudflare Hyperdrive. Here’s the honest assessment.
No surprise: Drizzle over Postgres is boring in the best way. Real types, real transactions, JSONB, and no JSON.parse() sprinkled through the data layer. Hyperdrive handles the connection pool at the edge, so a Worker doesn’t open a fresh database connection per request. Setup is a binding plus the connection string in the Hyperdrive config — no pool to tune inside the Worker.
But there are sharp edges.
Every query is still a network round trip. Hyperdrive removes the connection cost, not the latency of asking another machine for data. Batch where you can, and don’t fan out 20 queries for one page.
JSON is real, but validation isn’t automatic. JSONB stores whatever you give it; Zod at the trust boundary is what keeps the shape honest.
Transactions are real, which means you have to think about them. A long transaction across a request that also calls a model API is a good way to hold locks.
Authorization is still application code. Postgres supports row-level security, but the queries here are explicit where userId = ... filters in helper functions, so an unscoped query is a code review catch rather than a database guarantee.
The schema is small: resumes, siteData, handleChanges, uploadRateLimits, rateLimitLocks, a Clerk-mirrored user table, and a couple of housekeeping tables for account cleanup and IndexNow. The resumes table is the most interesting. It tracks the full lifecycle with a status enum (pending_claim → queued → processing → completed/failed/waiting_for_cache) and includes a staged-content field for crash recovery. If the Workflow dies between parsing and committing, the staged content survives.
Queues, Dead Letters, and Cleanup
The parse itself is a Workflow, so Queues aren’t in that path anymore. Where I do use a queue is edge-cache purges: every profile edit has to invalidate cached public pages, and Cloudflare’s purge API runs at a free-tier limit of 5 purge requests a minute. Firing one purge per edit would exhaust that budget during a busy minute.
The queue setup:
// alchemy.run.ts (simplified)
{
"queues": {
"producers": [{ "queue": "clickfolio-cache-purge", "binding": "EDGE_PURGE_QUEUE" }],
"consumers": [
{
"queue": "clickfolio-cache-purge",
"dead_letter_queue": "clickfolio-cache-purge-dlq",
},
],
},
}
Profile edits enqueue cache tags, and one consumer sends one deduplicated purge per batch. That keeps the consumer under the rate limit without dropping invalidations, and a retry can’t double-charge the budget. A duplicate purge is harmless anyway; a missed one shows a stale page until the next edit.
The dead letter queue (clickfolio-cache-purge-dlq) is the parking lot for purges that never succeeded. I check it when a profile edit looks stale in production.
Then there’s cleanup. A nightly cron purges expired rate-limit rows and stale failed resumes, an R2 lifecycle rule deletes temp uploads after a day, and R2DeleteWorkflow retries failed object deletes on account deletion. An await-cache workflow expires a waiting_for_cache row after ten minutes instead of leaving it pending forever.
Privacy Filtering: One Decision That Simplified Everything
Users can toggle whether their phone number and full address appear on their public portfolio. The question is: where do you enforce this?
Option A: Filter at storage time. Strip phone/address before saving to siteData. Problem: if the user changes their privacy settings, you need to re-parse or keep the original data somewhere.
Option B: Filter at fetch time. Store the full parsed content. When rendering the public page, apply privacy filters based on current settings.
I went with Option B. The filtering logic is simple:
// Applied when fetching public resume data
const settings = JSON.parse(user.privacySettings || "{}");
if (!settings.show_phone) delete content.contact.phone;
if (!settings.show_address) {
content.contact.location = extractCityState(content.contact.location);
}
extractCityState is smarter than it looks. It handles “123 Main St, San Francisco, CA 94102” → “San Francisco, CA”, but also “San Francisco, CA” → “San Francisco, CA” (no-op), and “Mumbai” → “Mumbai” (fallback). Five regex patterns covering most US and international address formats.
The critical design decision: templates receive already-filtered content. They never see the raw data. No template can accidentally leak a phone number because the phone number doesn’t exist in the props by the time it reaches the component. Single source of truth, no bypass possible from the client.
Privacy changes also trigger Cloudflare edge cache purges. If you turn off your phone number, the cached version of your public page gets invalidated immediately, not in an hour when the TTL expires.
Rate Limiting Without Redis
Most rate limiting tutorials assume Redis. I don’t have Redis. I have Postgres.
Two layers:
IP-based rate limiting for anonymous endpoints stores hashed IPs in upload_rate_limits with expires_at timestamps. Concurrent requests can’t race past the limit because the check runs in a transaction that locks one of a fixed set of slots (rate_limit_locks) with FOR UPDATE; the slots are reused, so a hash collision only costs a little contention.
User-based rate limiting for authenticated endpoints counts existing rows. Resume uploads: 5 per 24 hours (count from resumes.created_at). Handle changes: 3 per 24 hours (count from handle_changes.created_at). Simple, no extra table needed.
The aggregation itself is one round trip:
SELECT
COUNT(*) FILTER (WHERE created_at > now() - interval '1 hour') AS hourly,
COUNT(*) FILTER (WHERE created_at > now() - interval '24 hours') AS daily
FROM upload_rate_limits
WHERE ip_hash = $1 AND action_type = 'upload';
No raw IPs in the database. SHA-256 hash is sufficient for equality checks and prevents GDPR headaches.
The fail-open vs fail-closed decision matters: anonymous endpoints fail-open (if Postgres is down, allow the upload, user-level rate limiting catches abuse on claim). Authenticated endpoints fail-closed in production (if Postgres is down, deny the request. Better to block than to allow unbounded writes).
33 Designs, One Interface
The template system is deliberately simple. Every design receives the same props:
interface TemplateProps {
content: ResumeContent; // Already privacy-filtered
share: ThemeChrome["share"]; // share metadata
profile: {
avatar_url: string | null;
handle: string;
};
isPreview?: boolean;
}
As of November 2026 the registry has 33 designs: Minimalist Editorial (serif, editorial), Neo-Brutalist (bold borders), Glass (blur effects, dark), Bento (mosaic), Spotlight (featured sections), Midnight (dark), Bold Corporate (corporate), and 26 more — Academic CV, Dev Terminal, Gallery Wall, Retro OS, Scrapbook, and so on. All mobile-responsive. All use plain <img> tags; there’s no framework image optimizer to lean on inside a Worker.
Adding a design starts with one component. Export a React component matching the interface, then register it in the theme registry and its metadata tables — no routing changes, no database migration.
What Hurts
I shipped this. It works. People use it. But here’s what I’d warn you about:
Postgres at the edge is still a network hop. Hyperdrive makes connections cheap; it doesn’t make queries local. A page that fans out a dozen queries feels it, and the fix is batching, not a bigger database.
No ISR on Workers. Same constraint as my portfolio. Public resume pages are dynamic (SSR) with Workers Cache in front. No stale-while-revalidate at the framework level, just Cache-Control headers and explicit cache purges. For a resume site, the traffic is low enough that Postgres handles the load directly.
Debugging is painful. Local dev runs on Node.js with a local Postgres; production runs in V8 isolates. I’ve had code pass all local tests and break on deploy because of subtle runtime differences. wrangler dev catches most of it, but not everything. The Durable Object plus Workflow integration is particularly hard to test locally.
Auth is one more moving part. Clerk removed a pile of code (no password reset flows, no session table to maintain), but it adds a webhook to keep the local user mirror in sync and an external dependency in the sign-in path. I’d still make the same trade.
Workflow reliability is good, not magic. Steps retry, runs are journaled, and a repeated start is a no-op — but you still need to handle the terminal failed state. A resume that exhausts its retries needs a retry button and a cleanup path, not just a log line.
If I Started Over
I’d start with Postgres and Hyperdrive from day one. The moment you need JSON queries, real transactions, or row-level security, SQLite semantics fight you on every query, and migrating later costs more than setting up a managed database at the start.
I’d also start with WebSockets, not polling. The polling-to-Durable-Objects migration was painful. If you know you’ll need real-time updates, design for it from day one. The DO Hibernation API is cheap enough that there’s no reason to start with polling.
And fewer designs at launch. Seven felt like a lot to keep responsive and consistent. Three would have been enough to validate the concept; the gallery is at 33 now, which only works because every design sits behind the same props interface.
What Stuck
Cloudflare’s edge stack is production-viable, but you’re still an early adopter. The docs are sparse for complex patterns (Queues + Workflows + Durable Objects + Postgres in one Worker). Expect to read source code and Discord threads.
The Claim Check Pattern improved conversion by 43%. Reducing auth friction at the upload step, letting users see their resume being processed before they even sign up, meant more completions than hitting a login wall first.
Statistic: The Claim Check Pattern improved conversion by 43%.
Deduplication saved more than I expected. The file hash cache and waiting-for-cache pattern eliminated roughly 30% of AI parse calls in the first month. Users reupload constantly, same resume, different design, fixing a typo.
Statistic: File hash deduplication eliminated roughly 30% of AI parse calls in the first month.
Filtering at fetch time rather than storage time is the right call. Storing full data and filtering on read is simpler, more flexible, and much easier to reason about than trying to maintain multiple filtered copies.
Each edge computing constraint, no filesystem, no native modules, no long-lived process, no ISR, is manageable on its own. Stacked together, they add up to a fundamentally different development experience. Know what you’re getting into before you’re three sprints deep.
Database Comparison: Managed Postgres vs Supabase vs Self-Hosted
| Feature | Hyperdrive + Postgres (Clickfolio) | Supabase | Self-Hosted Postgres (Alita) |
|---|---|---|---|
| Type | Managed Postgres at edge | Managed Postgres + auth/storage | Full Postgres |
| JSON Support | Native JSONB | Native JSONB | Native JSONB |
| Row-Level Security | Yes (optional) | Yes | Yes (manual) |
| Boolean Handling | Native boolean | Native boolean | Native boolean |
| Cost | DB plan + Workers | Free tier, then $25/mo | $0 (Oracle VPS) |
| Ops Work | Connection config only | None | Backups, upgrades, monitoring |
| Best For | Full apps with relational data | Fastest start with auth bundled | Full control, 24/7 bots |
Postgres via Hyperdrive is what I’d pick for a real app: relational data, JSONB, and transactions, with the connection pool handled at the edge. Supabase is the fastest way to get Postgres plus auth and storage in one place. Self-host when you want full control and don’t mind the ops.
If you want to try it: clickfolio.me. Upload a PDF, pick a design, get a URL. No code required.
For a broader look at when this serverless setup beats a traditional VPS, I wrote up the real cost trade-offs between Cloudflare Workers and Docker across 30+ projects.
Related Posts
- How I Host My Portfolio for $0/Month on Cloudflare — The simpler version: a static Astro site on Workers
- My 2026 Stack for Shipping Side Projects — Why I usually reach for managed Postgres, and how this fits
- I Needed Logs, Not a PhD in Elasticsearch — Another “build it yourself” project, with Claude Code
- Vibe Coding in 2026 — The AI-assisted development philosophy behind this project
- When to Use a VPS vs Cloudflare Workers in 2026 — real cost comparison from running projects on both architectures
Frequently Asked Questions
Can you build a full-stack app on Cloudflare Workers?
Yes. The constraints are real: no filesystem, no native Node.js modules, and no long-lived process. TanStack Start + Clerk + Drizzle + Hyperdrive + R2 bindings cover most needs, and Workflows handle jobs that outlive a request. It's production-viable as long as you design around the request lifecycle.
How does Postgres at the edge work?
Hyperdrive pools and caches connections to a normal Postgres database, and the Worker talks to it through a binding. You keep real Postgres — JSONB, transactions, row-level security — instead of accepting SQLite semantics.
Are Durable Objects overkill for status updates?
With WebSocket Hibernation, no. The DO evicts from memory when no clients are connected and only wakes on new connections or messages. Cost is effectively zero for intermittent status updates. The alternative — HTTP polling every 3 seconds — is more expensive and adds unnecessary database load.
How does the AI parsing handle hallucinations and bad output?
Two-stage validation. AI output gets lenient transforms (trim whitespace, normalize URLs, detect garbage patterns like repeating path segments). User edits get strict Zod validation with XSS sanitization. This prevents double-encoding while keeping security where user input enters the system.
Sources & References
Related Posts
I Spent $600 Testing AI Coding Tools: Claude Code vs Cursor vs Copilot (2026 Results)
I've spent $50+/month on AI coding tools for a year. Here's what actually works, what's overhyped, and when to use each tool (including free local LLMs).
AI Models Compared 2026: GPT-6.1 Sol vs Claude Opus 5.5 vs Gemini 4 vs Grok 4.7
November 2026 model comparison: current GPT, Claude, Gemini and Grok models, sourced API prices, open-weight alternatives and the refreshed Coding Agent Index.
Running AI on My Mac: Why I Ditched ChatGPT for LM Studio (And Saved $240/Year)
How I run powerful AI models locally on my M4 Pro MacBook with LM Studio. Privacy, speed, and vision models that can see images - all offline.
Divanshu Chauhan (@divkix)
Systems Engineer at Cloudflare. MS CS from Arizona State University. Based in Austin, Texas, USA.
Expertise: Cloudflare Workers, Cloudflare Hyperdrive, PostgreSQL, Durable Objects. More about divkix