Most "production AI agent" writeups stop at prompt chains and tool schemas. When you run a multi-tenant, real-time multimodal AI product solo — where live video segments stream in every five seconds, agents drive external tools over MCP, and users prepay in fiat, crypto, or agent wallets — the prompt is maybe 10% of the engineering surface.
The other 90% is state authority, provider failure semantics, financial invariants, and catching gray failures before users do. This post tears down the actual backend and AI architecture of an independent multimodal copilot SaaS I designed, built, and operate in production (product name omitted under stealth framing).
A live multimodal session has two conflicting latency and reliability profiles: ingesting rolling audio/video windows (~5s WebM chunks, rolling 20s context) is high-bandwidth and stateless-friendly, while tool dispatch, belief tracking, and credit accounting require single-threaded state authority.
Browser / CLI / MCP Host
│
├─ WebSocket + 5s A/V chunks ──► LiveSessionDO (1 Durable Object per live session)
│ ├─ schema-versioned state (v=2) + migrate()
│ ├─ alarm() hard expiry + early-teardown grant refund
│ └─ bounded in-DO usage ring (MAX_USAGE_EVENTS = 1,000)
│
├─ Hono + zod-openapi (OpenAPI 3.1) on Cloudflare Workers
│ ├─ Agent loop: Appraisal ──► SelfModel (belief DAG) + GoalGraph (JSON in D1)
│ ├─ Provider layer ──► Cloudflare AI Gateway ──► Gemini / OpenAI
│ └─ SDK Sidecar Container ──► Vertex AI / PayPal Node SDKs (workerd bypass, REST fallback)
│
└─ Financial & Telemetry Plane
├─ D1 credit_balance + credit_transaction (integer micro-USD, atomic batch)
├─ D1 usage_event (authoritative per-call cost via vendored LiteLLM rate table)
├─ Async fan-out (ctx.waitUntil) ──► OpenMeter (CloudEvents 1.0) + BigQuery
└─ 15-min Cron Reconciler ──► lost-webhook recovery + Σ delta == balance audit
Two architectural boundaries paid for themselves immediately:
workerd) reject
several official Node SDKs at startup (for example, proxy/auth dependencies throwing deploy
error 10021). Instead of forking vendor SDKs, incompatible clients
(google-auth-library, Vertex AI, PayPal server SDK) run inside an isolated
sidecar container bound over Durable Objects, with a pure REST fallback if the container is cold
or unhealthy.In a prepaid real-time product, the client cannot be trusted to stop the meter. Every live
session maps 1:1 to a Cloudflare Durable Object (LiveSessionDO) that enforces four
server-side contracts:
live_session_grant pool before the socket opens. If
the user ends a 60-minute session at minute 18, teardown returns 42 minutes via a deterministic
idempotency key (restore_<sessionId>) so duplicate close frames can never
double-refund.alarm()-enforced expiry: if every browser tab crashes, the
DO's scheduled alarm fires at expiresAt, flushes final provider usage, and closes
the session without leaking compute.v: STATE_VERSION and passes through an explicit
migrate() step on cold load.MAX_USAGE_EVENTS = 1_000 (~80 bytes/event) and cap
concurrent WebSockets at MAX_SOCKETS = 8 so a reconnect storm or leaked bearer
token cannot pin hundreds of sockets on one actor.Appending raw transcripts until you hit the context window degrades both latency and reasoning consistency. Instead, each turn runs a two-stage cognition cycle whose entire state is plain JSON stored in a single D1 row per conversation:
question | redirect | challenge | feedback | failure | progress | silence) and
scores continuous signals (unexpectedness, urgency,
uncertainty, confirming_evidence, failing_evidence).SelfModel (explicit
beliefs, assumptions, and strategies with justification
links and confidence scores) alongside a dependency-ordered GoalGraph.Because structured-output calls occasionally truncate at max_tokens or emit raw
control bytes inside strings, the provider layer never calls bare JSON.parse on model
output. A deterministic recovery pass escapes raw control characters inside string literals, tracks
the open brace/bracket stack, trims trailing commas or dangling keys, and closes truncated objects
while recording a repaired: string[] audit trail.
Multi-provider routing breaks down when every upstream HTTP failure is treated as "retry another model." A guardrail block retried three times just burns quota and triggers abuse flags.
export class ProviderError extends Error {
status: number;
fatal: boolean;
/** Provider-side content/guardrail refusal — never retry. */
blocked: boolean;
}
// Cloudflare AI Gateway guardrail codes: 2016 (prompt) / 2017 (response)
const GATEWAY_BLOCK_CODES = new Set([2016, 2017]);
const SAFETY_CODE_RE = /^(safety|prohibited_content|spii|blocklist|content_blocked)$/i;
const isBlockedError = (status: number, body: any, message: string) => {
const code = body?.error?.code ?? body?.code;
if (GATEWAY_BLOCK_CODES.has(Number(code))) return true;
if (typeof code === "string" && SAFETY_CODE_RE.test(code)) return true;
return status >= 400 && status < 500 && /\b(safety|blocked|prohibited)\b/i.test(message);
};
text vs input_text) cannot
creep into call sites.blocked = true halts retries
immediately and increments a per-user KV abuse counter; transient 5xx/429 errors remain eligible
for fallback routing.Billing bugs in AI SaaS come from two mistakes: floating-point USD math, and conflating
what you charged the user with what upstream providers billed you. We split them
into two immutable D1 ledgers denominated in integer micro-USD
(1 USD = 1,000,000 micro):
| Ledger table | Question it answers | Idempotency & concurrency guarantee |
|---|---|---|
credit_transaction + credit_balance | What did we charge or grant the customer? | UNIQUE(referenceId) + single-roundtrip 4-statement D1 batch with NOT NULL overdraft abort |
usage_event | What did upstream models actually consume? | UNIQUE(requestId) + turn-scoped TurnMeter staging main and auxiliary calls |
SQLite/D1 executes a db.batch([...]) atomically. Checking a user's balance in
application code before debiting is vulnerable to concurrent requests overdrawing the account. We
close that race inside the SQL update itself: when preventNegative is set, an
overdraft evaluates to NULL on a NOT NULL column, aborting the entire
four-statement batch (including the transaction row insert):
const [, , rows] = await db.batch([
db.insert(creditBalance)
.values({ userId, balanceMicro: 0, createdAt: now, updatedAt: now })
.onConflictDoNothing(),
db.insert(creditTransaction).values({
id: txId, userId, deltaMicro, balanceAfterMicro: 0,
type, referenceId: extra.referenceId ?? null, createdAt: now,
}),
db.update(creditBalance).set({
balanceMicro: extra.preventNegative
? sql`CASE WHEN ${creditBalance.balanceMicro} + ${deltaMicro} >= 0
THEN ${creditBalance.balanceMicro} + ${deltaMicro}
ELSE NULL END`
: sql`${creditBalance.balanceMicro} + ${deltaMicro}`,
updatedAt: now,
}).where(eq(creditBalance.userId, userId))
.returning({ balanceAfterMicro: creditBalance.balanceMicro }),
// 4th statement stamps the exact post-mutation balance onto credit_transaction
]);
A duplicate webhook delivery hits UNIQUE(referenceId) on statement 2 and rolls back
statement 3; a concurrent spend race hits NOT NULL on statement 3 and rolls back
statement 2. Zero ghost transactions, zero negative balances.
A single user turn often triggers multiple billable operations: the primary model response, helper calls (compaction, captioning, judge), and flat per-request fees (search grounding). Passing a bare cost number by reference makes it easy to forget a helper call.
Instead, we implement the LiteLLM cost_calculator pattern via a request-scoped
TurnMeter object injected into every provider helper:
PRICING_VERSION). If a model is missing from the table or an
upstream response omits token counts, TurnMeter still writes a
usage_event row with priced = false or usageMissing = true
so reconciliation flags the anomaly instead of silently charging $0.${requestId}:aux:${seq++}) so retries never double-count sibling operations.ctx.waitUntil() — never blocking user latency and never throwing into
the request path. OpenMeter receives application/cloudevents-batch+json events with
id = requestId (replay-safe) and strictly disjoint token buckets
(input_text_uncached, input_text_cached, output_text,
thinking) so cached prompts are never double-summed. BigQuery receives parallel
streaming rows for margin and cohort analysis.The product accepts fiat (PayPal), crypto invoices (NOWPayments, verified via HMAC-SHA512 over
recursively key-sorted JSON), and programmatic agent payments (x402 USDC top-ups
paired with SIWX Sign-In-With-X per-call wallet debits).
Webhooks are a latency optimization; the reconciliation sweep is the correctness engine.
Every checkout writes a pending purchase row before redirecting the buyer.
Two state-machine rules prevent classic webhook bugs:
captured — not
finished — until fulfillPaidOrder() commits the credit batch. If
fulfillment fails mid-flight, the row stays visible to the sweeper.refund_requested,
refunded, and hold are immune to late or replayed payment webhooks, so
a delayed IPN can never resurrect a refunded order or clobber its audit trail.Every 15 minutes, a scheduled Worker cron runs a go-reconcile-style sweep over
non-terminal rows aged between 10 minutes (giving normal webhooks time to land) and
7 days (bounded batches of 25), queries upstream provider truth via official SDKs/REST,
runs the exact same idempotent fulfillPaidOrder() path, and audits global ledger
invariants (Σ credit_transaction.deltaMicro == credit_balance,
usedMinutes <= grantedMinutes), paging the operator via deduplicated SMS if any
invariant drifts.
The worst outage we suffered in production returned HTTP 200 everywhere: an
upstream cloud project deletion invalidated the OAuth client, breaking every new login while
uptime monitors stayed green. That incident shaped two operational rules:
/api/health. Silent .catch(() => {}) blocks on money, auth, or alert
paths are banned by static check.predeploy.mjs): standalone
wrangler deploy is forbidden. Both PR CI and production deploys must pass a 12-step
pipeline: diff scan for forbidden suppressions/secrets, D1 table & Durable Object migration
monotonicity checks, catalog sync, UI route-wiring verification, typed LLM diff judgment,
tsc --noEmit, full SSR build, local Worker boot with D1 migrations applied, live
route smoke tests, headless DOM/visual render checks, and a sitemap-wide copy audit.workerd solves SDK incompatibility cleanly, but adds cold-start and health-probe
surface area that pure Worker code doesn't have.APP_KV dynamic caps and session wind-down flags), and strict deploy gates substitute
for an ops team — they reduce operational pages near zero, but they don't replace multi-region
provider redundancy when an upstream multimodal model degrades globally.