Adding AI workflows to an existing app without breaking production
How to integrate schema-checked LLM extraction, deterministic validation gates, Wilson lower-bound evals, and atomic spend caps into a Postgres backend.
Most teams trying to add AI to an existing application get stuck between two bad options: a fragile prompt wrapper that silently passes wrong data to customers, or a six-month ML detour that never ships. You do not need either.
Adding an LLM workflow to a working Node, Python, or Postgres backend is mostly a distributed systems and validation problem. Here is the pattern I use to turn messy manual workflows like invoice intake, support triage, and document routing into production features that cannot hallucinate silently or drain your API budget.
Why raw model confidence scores fail in production
When an LLM extracts structured fields from an invoice or support email, asking it to output a confidence: 0.94 field is tempting. The problem is that a classifier's self-reported confidence is poorly calibrated out of the box, and a confident wrong answer still breaks downstream billing or CRM tables.
In AI Triage, an open-source multi-tenant document triage system, we never trust self_confidence on its own. Instead, routing sits behind a deterministic gate pipeline before any automation rule is even checked.
Inbound email / PDF
│
▼
Parse + extract with verbatim source quotes (no DB transaction open)
│
▼
Deterministic gates (gates.ts)
├── Fails JSON Schema or required field empty? ──▶ Human review
├── Quoted evidence missing from source text? ──▶ Human review
├── Domain rule fails (e.g. line items != total)? ─▶ Human review
└── Scanned PDF (unverifiable) or prompt pattern? ─▶ Human review
│
▼ (All gates passed)
Category opted into auto_when_confident + score >= frozen threshold?
├── No ──▶ Human review queue (SKIP LOCKED lease)
└── Yes ──▶ Hold 10% deterministic audit sample; emit signed outbox webhook
Notice what happens here: even when a document passes every deterministic gate and clears the threshold, automation is opt-in per category (review_all by default), and a 10% audit sample still routes to a person so drift cannot hide.
Separate the model call from the database transaction
One of the fastest ways to exhaust a PostgreSQL connection pool is calling OpenAI or Anthropic inside an open transaction. Model calls regularly take 2 to 15 seconds; holding row locks across external HTTP requests stalls unrelated endpoints.
Run ingestion and stage transitions as short transactions instead:
- Commit the incoming document and initial
doc.parsejob in one transaction (deduping onMessage-IDor content hash). - Execute the LLM call outside any transaction, save the raw response immediately when it returns, and reuse it on worker retries so transient failures do not re-bill the same step.
- Commit the extracted fields, status transition, and next job in a second short transaction.
- Freeze approved payloads into an
actionsoutbox table and deliver outbound webhooks with anIdempotency-Keyheader.
For human review, Claim next grabs the oldest unclaimed task using FOR UPDATE SKIP LOCKED with a short lease token, and approval requires both a live lease and a matching extraction revision ID. If two operators or stale tabs race, the second request gets a 409 instead of double-approving.
Proving accuracy before shipping with three-split evals
Without offline evaluation, changing a single line in a system prompt is guessing in production. The catch is that running evals on an internal script that uses different parsing or prompt formatting from your worker creates false confidence.
In ai-triage, evals execute the exact production parsing, prompt builders, gates, and routing code, while a TypeScript type constraint (EvalDeps) and source-scan test prove the eval runner holds no queue, action, or webhook delivery port. Even if someone tried to wire a delivery call into an eval run, eval items have no documents row, so Postgres refuses the actions foreign key anyway.
To avoid overfitting thresholds to your test data:
- Split fixtures into
dev,calib, andtest. Tune prompts ondev, inspect precision-vs-coverage curves oncalib, and freeze thresholds into an immutable config version before touchingtest. - Report Wilson 95% lower bounds alongside raw percentages. If a prototype shows 3 of 5 auto-approvals correct (60%), the 95% Wilson lower bound is closer to 23% (and 1 of 3 is roughly 6%). Showing
k/nplus the lower bound prevents shipping fragile rules on small datasets. - Record HTTP replay cassettes keyed by wire-request hash. CI runs deterministically at $0 API cost, and a missing cassette fails loudly instead of silently hitting paid endpoints.
Capping LLM spend and isolating multi-tenant data
Two production requirements usually come up as soon as real customers touch an AI feature: tenant isolation and budget protection.
For isolation in shared PostgreSQL databases, enable row-level security (RLS) on every tenant table, refuse to boot API or worker processes as a role with BYPASSRLS, and use composite foreign keys (tenant_id, id) on child tables so cross-tenant bugs fail at the constraint layer. When tenants configure outbound webhook URLs, validate HTTPS and resolve DNS both at save time and inside a guarded lookup at delivery time to block SSRF against private or metadata IPs.
For spend control, reserve worst-case token cost atomically before calling the model, then settle to actual cost afterward:
UPDATE tenant_budgets
SET reserved_micros = reserved_micros + $1
WHERE tenant_id = $2
AND usage_date = CURRENT_DATE
AND spent_micros + reserved_micros + $1 <= daily_cap_micros
RETURNING daily_cap_micros - (spent_micros + reserved_micros) AS remaining_micros;
Because the check and increment happen in one conditional update, twenty concurrent workers cannot race past a tenant's daily cap.
Honest limitations to plan around
Deterministic gates catch structural and arithmetic errors, not semantic subtleties. Evidence quote matching proves the quoted sentence exists on the cited PDF page, not that the model interpreted the sentence correctly. Prompt-injection regex lists act as regression checks, not security boundaries against adversarial inputs.
That is why human-in-the-loop review and opt-in thresholds per category remain essential when onboarding a new workflow. Once real traffic builds a clean labeled calibration set, you can widen automation safely where the numbers earn it.
If you are trying to integrate an LLM workflow into an existing application and want help scoping the schema, evals, and guardrails, explore the AI Triage case study or see how I structure AI workflow integration consulting.
Frequently asked questions
Can we add an AI workflow to our existing TypeScript or Python backend without a rewrite?
Yes. The workflow runs as async worker stages alongside your existing PostgreSQL database and API, using an outbox pattern to push approved results back into your core application tables or webhooks.
How do we measure whether a new prompt or model is actually better?
Run the production pipeline against a three-split dataset (dev, calib, test) using recorded replay cassettes and field-level comparators (exact match, amount within a cent, date parsing, set F1) rather than relying on category accuracy alone.
What stops an LLM from leaking data across B2B customer tenants?
Enforce PostgreSQL Row-Level Security on every tenant table, verify the application database role cannot bypass RLS, and key child references on (tenant_id, id) so cross-tenant reads or writes fail at the database layer.
How do you control per-customer OpenAI or Anthropic costs in production?
Use an atomic conditional SQL update to reserve worst-case call cost against a daily tenant cap before firing the model request, then reconcile reserved vs. actual cost once the response settles.