← All writing

Architecting a real-time multimodal agent SaaS: session state, provider routing, and micro-USD ledgers

Yunseop Im · Software Engineer, AI & Backend Systems · M.S. CS, Georgia Tech

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).

1. System topology: separating perception, cognition, and SDK runtimes

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:

2. Stateful edge sessions: Durable Objects as lease authorities

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:

  1. Prepaid draw + idempotent teardown refund: the API route debits the full session block from a 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.
  2. 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.
  3. Eviction-safe state migrations: running DOs keep their code version, but an evicted DO wakes up on new Worker code reading old persisted storage. Every persisted blob carries v: STATE_VERSION and passes through an explicit migrate() step on cold load.
  4. Storage and socket ceilings: Cloudflare DO values cap at 128 KiB. Storing unbounded per-call usage inside the session state blob will eventually brick active sessions. We cap in-blob records at 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.

3. Persistent agent cognition instead of prompt-stuffing

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:

  1. Appraisal pass: classifies the dominant new stimulus (question | redirect | challenge | feedback | failure | progress | silence) and scores continuous signals (unexpectedness, urgency, uncertainty, confirming_evidence, failing_evidence).
  2. Structured state update: updates a 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.

4. Provider gateway & typed error taxonomy

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);
};

5. Financial correctness: two-table truth and lock-free atomic debits

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 tableQuestion it answersIdempotency & concurrency guarantee
credit_transaction + credit_balanceWhat did we charge or grant the customer?UNIQUE(referenceId) + single-roundtrip 4-statement D1 batch with NOT NULL overdraft abort
usage_eventWhat did upstream models actually consume?UNIQUE(requestId) + turn-scoped TurnMeter staging main and auxiliary calls

Closing the read-then-write balance race without distributed locks

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.

6. Metering pipeline: TurnMeter → OpenMeter + BigQuery

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:

7. Payment webhooks & the 15-minute reconciliation engine

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:

  1. Payment capture ≠ entitlement grant: when a webhook reports upstream payment completion, we transition the row to non-terminal captured — not finished — until fulfillPaidOrder() commits the credit batch. If fulfillment fails mid-flight, the row stays visible to the sweeper.
  2. Terminal refund-lane protection: states like 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.

8. Gray failures and the 12-stage predeploy gate

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:

Honest trade-offs & current limits

Related: Product case study · Per-tenant RAG isolation · Agent harness teardown (devin-harness) · Resume