Skip to content
Zane Hu

AI Safety · FinTech Architecture

Production-Safe AI Agent Payments: 10-Step PostgreSQL Row-Lock Guardrails

Updated 2026-11 · ~10 min read · Open-source implementation: pg-ai-payment-guardrails

LLMs should interpret user intent and surface recommendations. Deterministic PostgreSQL pessimistic row locks, zero-float integer ledgers, and non-escalating session boundaries must guard real money.

Sequence diagram showing 10-step single-transaction PostgreSQL row-lock AI payment guardrails and fail-closed fallback
Figure 1. Fixed lock ordering inside a single PostgreSQL transaction eliminates TOCTOU races, concurrent balance overdraws, and prompt-injected limit overrides.

1. Why AI agent payment demos collapse in production

Most agent payment prototypes wrap a checkout endpoint in an MCP or function-calling schema and ask the model in a system prompt to "confirm the balance and stay under daily spending limits." Three concrete failure modes break that pattern the moment real wallets are connected:

  • Prompt injection and untrusted arguments: External product titles, order notes, or web snippets can coerce the model into passing forged totals, overriding spending caps, or substituting a payout/shipping destination.
  • Time-of-check vs. time-of-use (TOCTOU) races: If an assistant tool reads wallet balance in Request A, reads it in Request B 40ms later, and then fires two debits, both checks pass while driving the real ledger negative.
  • Recipient swap after human opt-in: A customer authorizes automatic settlement for a home address today; an attacker edits the destination address row milliseconds before an autonomous bill settles tomorrow.

To close every one of these vectors without stripping useful autonomy, the guardrail must live completely inside the database transaction boundary rather than in model instructions.

2. Data model invariants and default-OFF isolation

I published the distilled reference schema and TypeScript engine in pg-ai-payment-guardrails. Five structural decisions define the relational layer before a single transaction executes:

  • Default OFF opt-in: ai_mandate_policies.enabled defaults to FALSE, and keys without an explicit opt-in row in ai_mandate_keys are rejected even if the account envelope is active.
  • Zero floating point: All balances, FIFO cost lots, bills, and risk ceilings use signed/unsigned 64-bit integer minor units (BIGINT) with schema-level CHECK (balance_minor >= 0).
  • Append-only audit and ledger tables: A PostgreSQL BEFORE UPDATE OR DELETE trigger rejects history tampering, reinforced by revoking UPDATE and DELETE from the runtime DB role.
  • Session-only risk configuration: The configuration mutation path rejects autonomous agent bearer tokens with HTTP 403 PRIVILEGE_ESCALATION_DENIED—an agent can never raise its own caps or whitelist new addresses.
  • Partial unique replay index: UNIQUE (tenant_id, key_id, idempotency_key) WHERE decision = 'approved' turns retried network requests into deterministic receipts instead of double charges.
CREATE TABLE ai_mandate_audit_log (
  audit_id        TEXT        PRIMARY KEY,
  tenant_id       TEXT        NOT NULL,
  customer_id     TEXT        NOT NULL,
  key_id          TEXT        NOT NULL,
  idempotency_key TEXT        NOT NULL,
  bill_id         TEXT        NULL,
  decision        TEXT        NOT NULL CHECK (decision IN ('approved', 'fallback')),
  reason_code     TEXT        NOT NULL,
  amount_minor    BIGINT      NOT NULL CHECK (amount_minor >= 0),
  ledger_entry_id TEXT        NULL REFERENCES ledger_entries (entry_id),
  created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Approved debits are unique per credential and Idempotency-Key; failed fallbacks remain logged.
CREATE UNIQUE INDEX idx_mandate_audit_approved_replay
  ON ai_mandate_audit_log (tenant_id, key_id, idempotency_key)
  WHERE decision = 'approved';

3. The 10-step fixed lock order (and why order prevents deadlocks)

Acquiring row locks in an arbitrary sequence across concurrent HTTP handlers causes PostgreSQL deadlocks under load. Every autonomous debit acquires locks in the exact same monotonic hierarchy inside one transaction:

  1. Customer root (FOR UPDATE): Serializes wallet top-ups, manual checkout actions, address mutations, and agent debits for the same customer.
  2. Agent key credential (FOR SHARE): Verifies existence, ownership under (tenant_id, customer_id), and revoked = false.
  3. Account mandate policy (FOR UPDATE): Ensures enabled = true and strictly positive server-stored caps.
  4. Per-key mandate flag (FOR UPDATE): Confirms this specific credential key has explicit human opt-in.
  5. Bill row + idempotency check (FOR UPDATE): Preceded by approved replay lookup so legitimate retries return the original receipt cleanly; otherwise checks status = 'pending' and server-stored amount_minor > 0. Zero monetary fields are ever read from tool arguments.
  6. Destination whitelist & live address (FOR SHARE): Normalizes live recipient fields and verifies their SHA-256 hash matches recipient_sha256 stored at confirmation time.
  7. Wallet & open FIFO cost lots (FOR UPDATE): Ensures wallet.balance_minor >= amount_minor and open lots ordered by (received_at ASC, lot_id ASC) fully cover the deduction.
  8. Velocity caps inside lock: Validates amount <= single_cap_minor and trailing_24h_approved + amount <= daily_cap_minor across all keys belonging to the customer.
  9. Dual idempotency assertion: Verifies unique ledger operation key alongside the approved audit index.
  10. Atomic debit & audit commit: Depletes oldest FIFO lots, writes the immutable ledger debit, settles the bill, appends the approved audit entry, and commits together.
// Enforced fail-closed wrapper: any guard rejection or step-10 fault rolls back
// all ledger, FIFO, and bill writes before recording a non-PII fallback audit row.
try {
  return await store.inCustomerTransaction(auth.tenantId, auth.customerId, async (tx) => {
    await tx.lockAndVerifyCustomer(auth.tenantId, auth.customerId);
    const key = await tx.getAgentKeyForShare(auth.tenantId, auth.customerId, auth.keyId);
    if (!key || key.revoked) throw new GuardRejection("KEY_REVOKED");
    // Steps 3..9: policies, replay check, bill > 0, SHA-256 address, FIFO balance, 24h cap
    return await commitFifoDebitAndAudit(tx, auth, req);
  });
} catch (err) {
  const reasonCode = err instanceof GuardRejection ? err.reasonCode : "TRANSACTION_FAILED";
  await store.recordFallbackAudit({ decision: "fallback", reasonCode, ...metadata });
  return { ok: false, paidBy: "checkout_url", fallbackReason: reasonCode, checkoutUrl };
}

4. Engineering trade-offs we intentionally made

Decision Dimension Rejected Alternative Chosen Architecture & Trade-off
Concurrency Control Optimistic version retries at app tier Per-customer FOR UPDATE row serialization eliminates TOCTOU windows between balance, cap, and recipient address reads, trading trivial single-customer throughput for zero overdraw risk.
Ledger Isolation Separate mirrored AI wallet table Reuse the single primary wallet ledger & FIFO lots with distinct mandate_debit metadata—zero shadow reconciliation drift between human cashier and agent debits.
Failure Experience Hard 4xx API error aborting user task Full atomic rollback paired with paidBy: "checkout_url" handoff lets the assistant surface a one-click human confirmation link without corrupting accounting state.
Card / Provider Keys Model accesses payment provider tokens Agent mandate only settles pre-funded ledger balances; external card/payment credentials never enter runtime grants or LLM context.

5. Extending least privilege to AI Ops, MCP & Coding Workflows

The exact same transactional distrust of free-form LLM actions governs adjacent infrastructure layers I designed:

  • Zero Shell / SSH AI Diagnostics (x-observe): AI incident responders only execute strongly typed, allowlisted diagnostics and remediation hooks—zero arbitrary shell access or credential visibility.
  • Single-Schema Remote MCP (x-forge): Web forms, HTTP routes, and Remote MCP tools expose one shared validation schema, ensuring permission invariants never drift across clients.
  • MacOS Keychain Read-Only Connector (qq-mail-mcp): IMAP authorization codes stay exclusively inside macOS Keychain, bounded by byte limits and untrusted-input guards.
  • Deterministic AST Coding Gates (agent-arch-guard): Parallel AI coding agents face the same failure mode—taking local shortcuts around shared foundations. AST gates catch drift at commit time.

Verify the full reference implementation and 13 concurrency, recipient-swap, privilege-escalation, and atomic-rollback tests in github.com/zanehu-ai/pg-ai-payment-guardrails.

Back to Writing