Case study 02 of 07 · Generative AI · Pipelines · Payments
Genbooks
A live, end-to-end AI product: a visitor describes a non-fiction book, reads a free preview, pays a fixed price and receives a finished EPUB, PDF and cover.
In 20 seconds
- What it is
- Multi-stage Gemini workflows (planning, drafting, editing, cover) on serverless hosting that can’t keep a long process alive. Quality is enforced in code and the real AI cost of every job is recorded.
- My part
- Product owner and system designer. I set the requirements, funnel, pricing and abuse rules, set up and run the accounts, and tested every release. Claude Code wrote much of the code.
- Built with
- Claude Code in VS Code (all 64 commits are co-authored with Claude), git and ESLint
- AI in the product
- Gemini 3.1 Pro plans, drafts, edits and repairs the book. A Gemini image model makes the cover.
- Status
- Live in production. 64 commits over about 6 weeks
Straight answer: It is a young single-developer product: non-fiction only, no back cover yet, no automated tests, and no user, revenue or conversion numbers that I can publish.
- 4 to 6 min total time for a free preview in real runs
- £7 fixed price up to 30,000 words
- 6 attempts per step, with backoff
- ~120,000 disposable email domains blocked
Overview
A visitor fills in a book request: title, subtitle, author name and bio, genre, target reader, promise, tone and a word count from 5,000 to 100,000. They can also supply their own chapter outline. They get a free AI-written preview: a title page, About the Author, an Introduction, a contents list and the real opening of Chapter 1 (about 2,000 words) in a paginated reader capped at 15 pages. If they like it, they pay a fixed price and an automated pipeline writes, edits and typesets the full book, then emails an EPUB, a PDF and a front cover.
The problem. Writing a 5,000 to 100,000 word non-fiction book is slow and expensive. Genbooks removes the commissioning step, and the buyer reads the real opening pages before paying anything.
Who it is for. Individuals who want a non-fiction book written to their brief. The site is UK-oriented, with prices in GBP and a UK GDPR privacy policy.
What makes it different
- A free preview before payment. Real opening pages, not a sample.
- Fixed pricing. £7 up to 30,000 words, plus £2 for each extra 10,000.
- Nothing is generated twice. The paid book reuses the preview’s chapter plan, About the Author and Introduction.
- A quality gate in code rejects AI-sounding text and triggers an automatic repair pass.
- Real AI cost of every preview and book is recorded from token counts.
- The whole journey runs automatically, from submission to the delivery email.
Screens
How it works
From request to delivered book
- AI model
- External service
- Human step
- Service
Read this diagram as a list
The boxes
- Outline: JSON chapter plan
- Front matter: About the Author, Introduction
- Free preview: about 2,000 words, 15-page reader
- Payment: Stripe Checkout unlocks the book
- Customer clicks Continue: payment alone does not start it
- Chapter drafting: spec, running summary, last 120 words
- Line edit: one pass per chapter
- Quality gate: banned phrases, dashes, placeholders
- Repair pass: targeted fix for violations
- Cover: Gemini image model
- EPUB 3 and A5 PDF: jszip and pdfkit
- Delivery email: sent once, link to download
The connections
- Outline → Front matter
- Front matter → Free preview
- Free preview → Payment
- Payment → Customer clicks Continue
- Customer clicks Continue → Chapter drafting
- Chapter drafting → Line edit
- Line edit → Quality gate
- Quality gate → Repair pass
- Repair pass → Cover
- Cover → EPUB 3 and A5 PDF
- EPUB 3 and A5 PDF → Delivery email
How a job survives on serverless hosting
- Scheduled / background
- Data store
- Service
- AI model
- Asynchronous / scheduled
Read this diagram as a list
The boxes
- Three watchdogs: 4-minute loop, GitHub Actions every 30 min, Vercel daily
- Lease: Firestore transaction, 330 s claim
- One step: hard stop at 270 s
- Retry with backoff: up to 6 attempts
- Gemini call: aborts after 150 s of silence
- Save progress: truncated output is never saved
- Trigger next step: the step calls itself
The connections
- Three watchdogs → Lease (restarts stalled jobs)
- Lease → One step (claims job)
- One step ⇄ Gemini call (calls)
- One step → Retry with backoff (on failure)
- Retry with backoff → Lease (tries again)
- One step → Save progress (chapters)
- Save progress → Trigger next step
- Trigger next step → Lease
Everything below runs without me. Only the customer’s choices need a person.
Runs without me
- Preview generation, planning, writing, editing, quality checks and repairs.
- Cover generation, EPUB and PDF building, saving and the delivery email.
- Retries after failures and recovery of stalled jobs.
- Erasing IP addresses after 90 days.
- An admin email alert if a job fails after every retry.
Needs a person
- The customer confirms their email, which starts the free preview.
- The customer presses Continue to start the full book. Payment alone deliberately does not.
- I resolve support tickets from the admin view.
Abuse prevention, all before any AI spend. The captcha is checked on the server, a confirmed email is required, about 120,000 disposable email domains are blocked, email variants are normalised (plus-tags dropped, Gmail dots ignored), and there is one account per internet connection, browser or email per 7 days. One unpaid preview is allowed per account, replaceable once a week. Pasting the same long text into several fields is rejected, and the word count is limited to 5,000 to 100,000.
Stack
AI models and APIs
- Google Gemini 3.1 Protext, over REST with streaming
- Gemini image modelfront cover
AI techniques
- Multi-stage LLM pipeline
- Structured JSON outputchapter plans
- Quality gates in codebanned-phrase gate and repair pass
- Grounding (no invented facts)
- Retries, failover and rate limitinghonours Google's suggested wait
- Cost and token tracking
- Streaming with truncation protection
Languages
- JavaScriptES modules, about 6,300 lines
Backend and APIs
- Next.js route handlersVercel serverless, up to 300 s
- joseFirebase token verification
- jsziphand-built EPUB 3
- pdfkitA5 PDF
- nodemailer
Frontend
- Next.js 16 (App Router)
- React 19
- Tailwind CSS 4
- Hand-built UIpaginated reader, live progress card
Data and storage
- Cloud Firestoreclient writes blocked by rules
- Firestore base64 chunksEPUB, PDF and cover files
Payments and integrations
- Stripe Checkout (GBP)signature-verified webhook
- Cloudflare Turnstileverified on the server
- Firebase Authanonymous users upgraded in place
- Zoho Mail (SMTP)
- Google Search Console
Cloud and infrastructure
- Vercelhosting and a daily cron job
- CloudflareDNS
- GitHub Actions30-minute watchdog
Testing and tooling
- Claude Code
- Git
- ESLint
AI and machine learning
Models and what they do
- Gemini 3.1 ProOutline, front matter, preview, drafting, editing and repair, called over REST with streaming. Temperature differs by stage: drafting 0.9, outline 0.7, front matter 0.8, editing 0.4, repair 0.3.
- Gemini image modelA front cover generated from the title, subtitle, author, genre, tone, reader and promise.
Techniques actually used
- ‘House rules’: five Markdown files (about 1,800 lines) covering craft structure, banned AI-voice tells, engagement patterns and cover design, loaded into the prompts as binding rules.
- A strict JSON chapter plan. If the customer supplied an outline, the model must follow its exact titles and order.
- Prompt rules against invented facts, studies and quotes, and against mentioning chapter numbers or how the book was made. The author bio is rewritten only from the customer’s own bio.
- Each drafting prompt carries the chapter spec, a running continuity summary and the last 120 words of the previous chapter.
- Streaming with live word counts. A stalled connection aborts after 150 seconds and a cut-off response is treated as a failure.
- Token usage recorded on every call, including failed ones.
Not in this project
- RAG
- Embeddings
- Vector database
- Fine-tuning
- Speech to text or text to speech
- Browser automation or scraping
An orchestrated multi-stage LLM workflow with automated quality checks and self-healing. It is not a tool-using autonomous agent.
History. The first books were produced by a human-supervised Claude Code book-writing workflow with sub-agents for writing, editing and cover design. The automated Gemini pipeline is a port of that workflow.
Features
- A request form with a live page estimate, captcha and inline account creation or sign-in.
- An email-confirmation gate that starts the preview automatically.
- A live progress bar that combines real server progress with a time-based curve that never moves backwards and never reaches the end of a stage early.
- A paginated preview reader that measures the real screen frame, fills each page to fit and keeps the reader’s place when resized.
- Stripe payment with server-side price calculation.
- Full-book generation with EPUB 3, A5 PDF and a front cover, downloadable only by the paying owner or an admin.
- A ready-email sent exactly once, with automatic resend if it fails.
- A My Books library, a per-book page, a support ticket system with an admin view, forgot-password, a UK GDPR privacy policy (no analytics are used), robots.txt and a sitemap.
My role
What I decided
- The funnel: free preview first, then register, then pay, then the customer confirms before the full book is written.
- Pricing, moving from tiers to a uniform £7 base plus £2 per 10,000 words. DOCX was removed as an offered format and the free preview was capped at 15 pages.
- The abuse rules: one free preview per connection per week, confirmed email, no disposable emails.
- The privacy policy wording and the choice to use no analytics.
- To automate the original manual Claude-assisted workflow with Gemini.
What I set up and run. The domain and Cloudflare DNS, the Zoho mailbox, Stripe, Cloudflare Turnstile, Firebase, Vercel hosting, Google Search Console and the GitHub Actions watchdog.
Built with AI. All 64 commits are co-authored with Claude (Claude Code in VS Code). I set the requirements and product decisions, tested the results and shipped the product, and Claude wrote much of the code. Problems I worked through with the assistant include stalled generation jobs, duplicate payment handling, AI-voice quality control, mobile layout bugs, a broken My Books page, a captcha bypass and a build-time bundling crash.
Engineering challenges
Jobs stuck at 0%
Generation jobs sat at 0% for three separate reasons.
How it was solvedHide
A function time limit shorter than one AI call (a single call took about 78 seconds), Vercel’s deployment protection blocking the system’s own follow-up calls, and an output-token cap that cut text off mid-sentence because the model’s thinking tokens count against it (one preview came out as 277 of 2,000 words). Fixed with longer limits, a hard step deadline, public-domain self-calls, a larger token cap and rejection of truncated output, plus leases, retries and three watchdog clocks.
Duplicate or lost paid work
Repeated payment webhooks or double clicks could double the AI spend.
How it was solvedHide
A transactional start check and the lease stop it. A bug where a finished preview job blocked the paid job was caught before release.
No human editor
The prompt alone could not guarantee zero-tolerance style rules.
How it was solvedHide
A code-level quality gate plus a targeted repair call rejects machine-sounding text. Words with legitimate literal uses, such as “toolkit”, were deliberately left off the banned list after a false positive.
Token checking crashed the bundler
Firebase’s token verification crashed on Vercel’s bundler.
How it was solvedHide
Solved by verifying tokens directly with the jose library against Google’s public keys.
No file storage service
Finished books needed a home without adding Cloud Storage.
How it was solvedHide
Delivery files are stored as chunked base64 in Firestore, with a fix for old chunks corrupting re-uploads.
Waiting visitors dropping off
The progress number froze for up to two minutes because AI progress arrives in bursts.
How it was solvedHide
A time-based curve now keeps it moving without ever going backwards or finishing a stage early. In a replay against measured timings it never stood still for more than 15 seconds.
A security audit
Four live attacks were tried: writing paid:true directly, continuing an unpaid book, downloading an unpaid book’s files and tampering with the price calculation.
How it was solvedHide
All were blocked or calculated server-side. The audit also found that My Books was broken for every user, and that was fixed.
A captcha bypass
Calling the API directly could skip the captcha.
How it was solvedHide
Verification moved into the protected routes themselves, so it cannot be skipped.
Mobile layout bugs
A missing viewport tag, captcha overflow and scrollbar-driven layout shift.
How it was solvedHide
Diagnosed with measured screenshots and fixed site-wide.
Cost visibility
Every job needed a price tag.
How it was solvedHide
Each job records input, output and thinking tokens, images generated and the estimated cost in USD.
Status
Live at genbooks.uk, deployed from the master branch on Vercel. The product works end to end: request, free preview, payment, full book and delivery email. It is a young single-developer product.
Complete
- Request form with live page estimate, captcha and inline account creation.
- Email-confirmation gate that starts the preview automatically.
- Free paginated preview, Stripe payment with the price calculated on the server.
- Full-book generation with EPUB 3, A5 PDF and a front cover, with protected downloads.
- My Books library, support tickets, forgot-password, UK GDPR privacy policy, robots.txt and sitemap.
Partial or still open
- SEO: one site-wide title and description, no social share tags and a thin homepage.
- Editing: there is one pass, not several.
- The form’s front and back cover description fields are not yet used by the automated cover step.
Not built, and not claimed
- Back cover and paperback wrap.
- Fiction. The pipeline is non-fiction only.
- An automated test suite.
Evidence
- 4 to 6 min total time for a free preview in real runs Planning 110 s, drafting 85 s, editing 88 s, repair 75 s.
- £7 fixed price up to 30,000 words Plus £2 for each extra 10,000 words. A 100,000-word book costs £21.
- 6 attempts per step, with backoff Waits of 0, 0, 30 s, 2 min, 5 min and 15 min, so a Gemini outage is ridden out.
- ~120,000 disposable email domains blocked Checked before any AI spend.
- 62 banned words and phrases enforced in code Plus em dashes and leftover placeholder markers, with an automatic repair pass.
- 64 commits over about 6 weeks
- ~6,300 lines of JavaScript
Code worth reading
Step runnerLease, hard deadline and retries, the core of the reliability design.Quality gateThe rule gate and the targeted repair call.Streaming Gemini clientWith truncation protection and rate-limit handling.Abuse rulesCaptcha, confirmed email, disposable-domain blocking and weekly limits.EPUB builderHand-built EPUB 3 packaging with jszip.Progress curveReal server progress combined with a time-based curve that never goes backwards.Firestore security rulesServer-only writes: clients are read-only.
What I can't verify, so I don't claim
- User counts, revenue and conversion rates. None are published, so none are claimed.
- SEO outcomes beyond the fact that Google reads the sitemap.
Public links
- Open Genbooks A free preview needs an account with a confirmed email, limited to one per connection per week.
verified checked against the code, tests, logs or the live system. reported from my own notes or hands-on use. unverified could not be checked, so it is not claimed.
