1. Why trusting raw LLM JSON on billing PDFs fails

Ask a vision or text LLM to extract line items from a multi-page telecom invoice and return structured JSON, and it will happily invent a plausible number for any missing field or misread a dense German table column. For billing reconciliation, a confidently wrong number is worse than an empty cell.

"Put in guardrails to protect your system and your users. ... Output guardrails have two main functionalities: Evaluate the quality of each generation. Specify the policy to deal with different failure modes."
Chip Huyen, Building A Generative AI Platform

In TiDonna's serverless invoice ingestion pipeline (AWS SES → S3 → Lambda), every incoming provider PDF passes through a layout-preserving page model instead of naive text chunking:

  • Mixed page routing without dropping pages: Pages are classified individually as digital, scanned, or mixed so a single scanned summary page inside a digital statement is never discarded.
  • Coordinate-anchored verification: Every LLM-proposed amount or MSISDN identifier must match printed text in the page model and record its (page, line, section) provenance. Printed text always overrides the model proposal.
  • Prompt-cached shared prefixes: Keeping the instruction prefix stable trimmed monthly parsing cost across ~1,740 invoice emails/month to roughly $55–70/month.

2. Integer minor units, content fingerprints & the duplicate-send gate

When outgoing membership invoices are generated on the 25th of each month from German pricing notes, three safeguards prevent double-billing and data loss:

Duplicate-Charge & Retention Safety Boundary Integer Minor Units + Content Fingerprint
Invoice Duplicate-Charge Gate Diagram Shows invoice lines reconciled in integer minor units, approval bound to HMAC content fingerprint so edits invalidate approval, email service running authorizeDispatch with conditional DynamoDB claim, and ambiguous SES timeouts logged as unknown rather than failed to stop duplicate retries. 1. Minor Units money.js 4-decimal EUR math Umlaut-folded line identity keys 2. Content Hash HMAC approval tied to payload digest Any edit drops prior approval 3. Send Boundary emailService All actions + scripts DynamoDB atomic conditional claim 4. SES Rule Ambiguous network timeout = "unknown" (blocks blind retry)
Placing the gate inside the email service closed three script paths that previously bypassed handler checks, while IaC tests guard against S3 expiry rules.

3. When application filters fail: 191 PostgreSQL RLS policies & SKIP LOCKED

Just as prompt instructions are soft guidance without deterministic tool gates, application-level WHERE tenant_id = ? clauses are soft conventions across a 178-endpoint API. In VitaSetu / CareWell, we moved tenant and patient consent enforcement directly into PostgreSQL 17:

  • Two DB roles, boot-time enforcement: Migrations, audit appends, and outbox workers use DATABASE_OWNER_URL. Every HTTP request runs over DATABASE_URL as a non-bypass app_user role, and NestJS refuses to boot if the connection resolves with BYPASSRLS.
  • Consent inside SQL predicates: app.has_consent_for(patient, org, category) checks consent live inside the row policy, covering pre-consent, active, revoked, and expired states across 191 policies.
  • Brokerless outbox + advisory locks: Double-booking is blocked via pg_advisory_xact_lock (proven under concurrent transaction races), while domain events commit into an outbox table in the same Postgres transaction and drain via SELECT ... FOR UPDATE SKIP LOCKED instead of introducing Kafka split-brain complexity prematurely.

4. Meta-engineering: AST knowledge graphs & adversarial verification

Building large multi-repo systems with AI coding agents creates its own context-engineering problem: blindly grepping thousands of files burns context windows and misses cross-file invariants. Across both TiDonna and Power Dialer, we paired documentation vaults with structural tooling:

  • AST knowledge graphs (graphify): Indexed Power Dialer's codebase (~10k nodes, 24k edges) and doc vault so agents query exact dependencies first. Measured structural-query token spend dropped 7.3x.
  • Mandatory read-only adversarial reviews: Every implementation set ran on its own branch followed by a read-only verification agent checking claims against shipped code. That process downgraded multiple false "done" items and kept engineering logs honest.

5. Actionable Tips & Tricks Checklist

CHECK 01

Never float-round billing arithmetic

Hold intermediate values in integer minor units (1/10,000th EUR) so invoice line totals reconcile cleanly to the cent.

CHECK 02

Test IaC templates for retention regressions

After an unscoped S3 rule deleted 241 PDFs, we added Jest checks over template.yaml failing builds if expiry rules reappear.

CHECK 03

Distinguish "withheld" from "empty" in UI

Clinical safety depends on showing doctors when allergy/medication rows are withheld by consent rather than rendering an empty array.

CHECK 04

Adopt SKIP LOCKED before adding Kafka

A transactional Postgres outbox gives atomic event durability and scheduled reminders with zero extra broker infrastructure.

Read VitaSetu case study Read TiDonna case study Back to Blog Hub