Pay-After-Keyframe AI Video Rendering on Cloudflare Workers, D1, R2, and Containers

Pay-After-Keyframe AI Video Rendering on Cloudflare Workers, D1, R2, and Containers

当你在边缘运行 AI 视频生成应用时,有两种故障模式会迅速摧毁你的利润率:在用户确认视觉效果是否满意之前就向其收费,以及在 Webhook 或轮询请求超时时意外重复提交昂贵的 GPU 渲染任务。当我们构建 Make Me Rap(一个将用户的照片、主题、服装、场景和语音选择转换为完整的 768p 口型同步说唱音乐视频的浏览器工作室)时,我们选择了拆分的 Cloudflare 架构:一个由 D1 和私有 R2 存储桶支持的 Cloudflare Worker(在 Vite 上运行 React / Next.js App Router),用于处理所有身份验证、结账和状态转换,并配有一个专门的 Cloudflare 容器渲染协调器,负责认领付费任务并编排长时间运行的视频生成。以下是四个具体的架构模式,它们确保了我们的结账、审核和 GPU 渲染流水线具有确定性且无泄漏。

1. Split Edge Control Plane vs. Container Render Plane

Cloudflare Workers excel at fast SSR, OAuth/session validation, D1 transactions, and PayPal checkout webhooks — not holding open long-lived video rendering connections or polling upstream video models for 60+ seconds. Instead of cramming render loops into ctx.waitUntil(), we split responsibilities cleanly:

Cloudflare Workers 擅长快速 SSR、OAuth/会话验证、D1 事务和 PayPal 结账 Webhook,而不是保持长时间的视频渲染连接或轮询上游视频模型超过 60 秒。我们没有将渲染循环塞进 ctx.waitUntil(),而是清晰地拆分了职责:

Browser └──> Cloudflare Worker (SSR, Auth, D1 state machine, R2 presigned/private IO, PayPal Orders v2) ├── D1: users, sessions, jobs, billing_checkouts, payment_events, workers ├── R2 (private): uploaded photos, template masters, finished MP4s └── Worker API (/api/worker/ready, /claim, /jobs) ▲ │ periodic heartbeat + atomic claim Cloudflare Container (render coordinator) └── swaps vocal track -> submits ONCE to upstream video model -> validates output -> uploads to R2

Two small details made the Worker ↔ Container boundary rock solid: Capability-based heartbeats (ready levels): The container continuously reports a ready capability tier into D1’s workers table. Before accepting a checkout for a new template combination, the edge Worker checks for a fresh heartbeat matching the required capability level — preventing users from paying when the render container is restarting or degraded. Strictly single-submit upstream job tracking: When the container submits a render job to an upstream video generation API, it persists the external request ID immediately. If a network read times out, the worker only polls the saved request ID and never re-submits a second billable GPU render.

两个小细节使 Worker 与容器之间的边界坚如磐石: 基于能力的“心跳”(就绪级别):容器持续向 D1 的 workers 表报告就绪能力层级。在接受新模板组合的结账之前,边缘 Worker 会检查是否匹配所需能力级别的最新心跳,从而防止用户在渲染容器重启或降级时付费。 严格的单次提交上游任务跟踪:当容器向外部视频生成 API 提交渲染任务时,它会立即持久化外部请求 ID。如果网络读取超时,Worker 只会轮询已保存的请求 ID,绝不会重新提交第二次可计费的 GPU 渲染。

2. Pay-After-Keyframe: Free Preview Before Checkout

Asking users to pay blind for AI video often leads to refund disputes when the lighting, crop, or outfit doesn’t match expectations. Conversely, running a full 15-second video render for every anonymous visitor destroys unit economics. Our middle ground in Make Me Rap is pay_after_keyframe: The user chooses a rap theme, outfit, scene, and voice, then uploads a photo. Every uploaded image runs through automated safety moderation first (MODERATION_REQUIRED=true in production; any moderation error fails closed rather than silently bypassing). We generate a free visual keyframe preview so the user sees the exact framing and look before spending a dollar. Only after approving the preview does the order page open checkout (Apple Pay, Google Pay, PayPal, and cards — see Make Me Rap Pricing).

要求用户在盲目状态下为 AI 视频付费,往往会在光照、裁剪或服装不符合预期时导致退款纠纷。相反,为每位匿名访问者运行完整的 15 秒视频渲染会摧毁单位经济效益。我们在 Make Me Rap 中的折中方案是 pay_after_keyframe:用户选择说唱主题、服装、场景和语音,然后上传照片。每张上传的图片首先通过自动安全审核(生产环境中 MODERATION_REQUIRED=true;任何审核错误都会导致流程关闭,而不是静默绕过)。我们生成一个免费的视觉关键帧预览,以便用户在花钱之前看到确切的构图和外观。只有在批准预览后,订单页面才会打开结账功能(Apple Pay、Google Pay、PayPal 和信用卡——参见 Make Me Rap 定价)。

3. Server-Authoritative Checkout & Capture Idempotency

Never trust client-supplied prices or treat a front-end onApprove callback as the sole source of truth: Server-side pricing table: When /api/billing/checkout creates a PayPal Orders v2 checkout, it reads the price solely from server-side configuration (PRICING_JSON), binds the checkout row to the authenticated user_id and job_id, and stores the order state in billing_checkouts. Ownership + amount verification before capture: Before /api/billing/capture captures funds, it verifies both job ownership and exact order amount against D1, incrementing capture_attempts and recording structured refusal diagnostics (failure_issue, failure_debug_id) if an issuer declines the transaction. Webhook deduplication: Incoming PayPal webhooks are deduplicated by event ID in payment_events so duplicate retries never double-queue a render job. Client-side checkout telemetry: Browser wallet popups (Apple Pay / Google Pay / PayPal) can fail before ever hitting /capture. Logging lightweight interrupted-checkout events (method, stage, code) to a 90-day payment_client_events table made diagnosing wallet friction dramatically easier than guessing from server logs alone.

永远不要信任客户端提供的价格,也不要将前端的 onApprove 回调视为唯一的真理来源: 服务器端价格表:当 /api/billing/checkout 创建 PayPal Orders v2 结账时,它仅从服务器端配置 (PRICING_JSON) 读取价格,将结账行绑定到经过身份验证的 user_id 和 job_id,并将订单状态存储在 billing_checkouts 中。 捕获前的所有权和金额验证:在 /api/billing/capture 捕获资金之前,它会根据 D1 验证任务所有权和确切订单金额,增加 capture_attempts,并在发卡机构拒绝交易时记录结构化的拒绝诊断信息 (failure_issue, failure_debug_id)。 Webhook 去重:传入的 PayPal Webhook 通过 payment_events 中的事件 ID 进行去重,因此重复的重试永远不会导致渲染任务被排队两次。 客户端结账遥测:浏览器钱包弹窗(Apple Pay / Google Pay / PayPal)可能在到达 /capture 之前就失败了。将轻量级的结账中断事件(方法、阶段、代码)记录到 90 天的 payment_client_events 表中,使得诊断钱包摩擦比仅从服务器日志中猜测要容易得多。

4. Fail-Closed Post-Render Checks & Automatic Refunds

Once the render container produces an MP4: It runs frame-sampled safety checks plus technical media validation (codec, duration, audio stream integrity) before marking the job deliverable in private R2 storage. If an external moderation check hits a transient upstream outage, the job enters a 15-minute recovery window so temporary blips self-heal instead of killing a completed render. If a job permanently fails (or exceeds the recovery window), the billing layer triggers an automatic refund rather than leaving a paid user stuck in a “Processing…” spinner.

一旦渲染容器生成 MP4:它会运行帧采样安全检查以及技术媒体验证(编解码器、时长、音频流完整性),然后才在私有 R2 存储中将任务标记为可交付。如果外部审核检查遇到暂时的上游中断,任务将进入 15 分钟的恢复窗口,以便临时故障能够自愈,而不是终止已完成的渲染。如果任务永久失败(或超过恢复窗口),计费层会触发自动退款,而不是让付费用户卡在“处理中……”的加载动画里。

Takeaways for Edge + AI Video Builders

Keep state, pricing, auth, and idempotency keys in your relational edge database (D1) — never in memory inside a container or browser callback. Persist every external GPU request ID before waiting on completion so timeouts always resolve via polling, never duplicate billing. Separate cheap visual verification (keyframe) from expensive full-motion rendering, and let users see the keyframe before paying. If you want to see the end-to-end flow live in the browser, you can try a free preview on Make Me Rap.

给边缘 + AI 视频构建者的建议: 将状态、定价、身份验证和幂等性密钥保存在关系型边缘数据库 (D1) 中,永远不要保存在容器或浏览器回调的内存中。在等待完成之前持久化每个外部 GPU 请求 ID,以便超时总是通过轮询解决,绝不会导致重复计费。将廉价的视觉验证(关键帧)与昂贵的全动态渲染分开,并让用户在付费前看到关键帧。如果你想在浏览器中实时查看端到端的流程,可以在 Make Me Rap 上尝试免费预览。