Fault-tolerant payment switch built with Go, PostgreSQL and TypeScript across isolated bank schemas. Preserves deterministic operation IDs across failures, verifies participant evidence before retrying and reconciles account ledgers using Merkle trees.
Handling network ambiguity without duplicate charges
Suppose Alice sends ₹100 from Bank A to Bob at Bank B. Bank A locks ₹100 in its schema and the reply drops before reaching the payment switch. When the switch hits a 2s timeout, naive strategies fail in distinct ways.
SWITCHGo Payment API2s RPC timeout elapsed
POST /hold ₹100 →200 OK dropped on wire
BANK A (bank_a)Source Hold Committed₹100 already locked
Persists operation ID, enters Pending and queries evidence
Authoritative
Before issuing any HTTP call, TransactX saves a deterministic operation_id for the step. On timeout, background workers call GetOperationStatus and OperationPresenceReader with that ID before choosing the next transition.
Bank A (Participant State)Original operation ID enforces single execution
Central PostgreSQL StateMoves to PENDING_RECONCILIATION with leased recovery job
Account EffectNo duplicate debits; state settles from Bank A records
02 / Payment Lifecycle
Six durable saga steps
Because Bank A, Bank B and the central ledger maintain separate schemas across HTTP boundaries, routed payments commit step by step using deterministic UUID operation IDs.
Stage 01 of 06 / Go API & Idempotency Repository
Accept Request & Intent
Step Execution
Verifies HS256 JWT, resolves server-owned source account, converts decimal amount into integer paise and validates user-scoped Idempotency-Key.
Durable State
Inserts payment row (CREATED -> VALIDATING) and idempotency_records entry with SHA-256 request hash inside one PostgreSQL transaction.
Safety Rationale
Duplicate submissions return the original payment identity while key reuse with altered amounts or recipients fails with 409 Conflict.
Recovery paths on missing bank replies
Confirmed SuccessSUCCEEDED / PRESENT
Skip re-execution and continue from the stored saga step
When GetOperationStatus proves Bank A held funds or Bank B finalized credit, Service.Resume advances directly to the next uncommitted leg. Under BANK_SETTLED_CENTRAL_PENDING, only missing central ledger rows are repaired.
Confirmed Failure / AbsentFAILED / ABSENT
Reverse pre-commit steps or replay the exact operation ID
Only an explicit pgx.ErrNoRows presence proof (PresenceAbsent) permits replaying an unreceived call under its original operation ID. Reversals (ReleaseHold, ReverseProvisionalCredit) apply only before ConfirmHold commits; post-confirmation failures move forward cleanly rather than deleting settled entries.
Unknown OutcomePENDING_RECONCILIATION
Retain pending state and reschedule under leased exponential backoff
Timeouts, 5xx responses and unreachable participants never trigger blind failure or compensation. Jobs stay leased up to TX_RECOVERY_MAX_ATTEMPTS (20) before escalating to needs_attention.
7 components, 13 edges
Authenticated payment request and settlement sequence
Synchronous request execution path from submission with integer paise through idempotency recording, Bank A hold, Bank B provisional credit, confirmation, finalization and central settlement.
Scroll horizontally on small viewports or expand for zoom, search (/) and route tracing (R).
Loading diagram...
Source account ownership is resolved on the server from JWT claims
User-scoped idempotency rows commit before outbound bank requests leave the switch
Deterministic UUID operation IDs tie every bank call to its parent transfer
03 / Architecture
Go switch, isolated bank schemas and offline client
Five architectural views generated from source commit 109694c. Switch views below or expand any diagram to search nodes, trace routes and inspect repository file references. In production deployment, API, Bank A, Bank B and background worker run as local loopback processes backed by logical schemas public, bank_a and bank_b inside Neon PostgreSQL.
Synchronous HTTPS REST & private bank HTTP Async lease recovery, outbox relay & SSE hints Logical schemas: public, bank_a and bank_b Optional bounded Google OIDC / Gemini
9 components, 26 edges
System architecture and process boundaries
End-to-end topology spanning role-scoped React applications, the Go API switch, independent Bank A and Bank B HTTP services, PostgreSQL schemas, background recovery/outbox workers and the read-only investigator.
Scroll horizontally on small viewports or expand for zoom, search (/) and route tracing (R).
Loading diagram...
Central Go API coordinates HTTP bank boundaries without sharing database transactions across banks
PostgreSQL stores payments, idempotency records, ledger entries, recovery leases, outbox events and analytics windows
SSE streams send lightweight invalidation hints only; authoritative state is fetched over REST
Optional Gemini report formatting sits behind a read-only boundary with deterministic evidence fallback
04 / Reliability Mechanisms
Core mechanisms under partial failure
Unresolved HTTP calls move into leased background recovery without overwriting participant facts. Expand any subsystem below for implementation contracts and ADR links.
5 components, 11 edges
Unresolved bank outcome and recovery sequence
Asynchronous recovery protocol triggered when a downstream bank response drops: holding PENDING state, claiming leased recovery jobs, verifying participant state and resuming safely.
Normal steady state. M2-3 samples rolling 15-minute windows (up to 500 checks). Timeouts and failures inside CIRCUIT_ROLLING_WINDOW increment error counters.
Transition rule: Trips CLOSED to OPEN when failures reach FailureThreshold (default 5).
Subsystems (9)
Problem
Blocking 2PC locks stall during network partitions, while naive async workers risk double-crediting dropped replies, exhausting DB pools under retry storms or re-executing on another rail mid-flight.
Implementation
Each bank step records a deterministic operation_id prior to HTTP RPC dispatch. Workers claim jobs with SKIP LOCKED, monotonic lease epochs and 15s heartbeats under a non-blocking concurrency semaphore (recording overload_count instead of queuing unbounded goroutines). RoutedAdaptersForPayment pins retries to the persisted ExecutionTargetID (failing closed to ROUTE_UNAVAILABLE_LEAVE_PENDING if removed), while OperationPresenceReader verifies pgx.ErrNoRows absence before any replay.
Outcome
Reversible holds and provisional credits compensate safely pre-commit, while committed steps advance forward via BANK_SETTLED_CENTRAL_PENDING without cross-bank double charges across 20 PG crash scenarios.
FOR UPDATE SKIP LOCKEDLease EpochPresence CheckRoute Pinning
Separate application shells expose customer balance tracking, merchant QR verification and read-only operator evidence analysis over distinct RBAC tokens.
Account overview with explicit payment states
Server-resolved account summary displaying current INR balance and BANK-A binding
Decimal-to-paise amount validation with verified recipient lookup prior to idempotent send
Duplicate-prevention prompts encouraging status inspection instead of blind retries
RBAC Scope Boundary
Customer responses exclude bank operation IDs, circuit breaker states and internal routing details.
Customer Interface
Customer workspace bound to an authenticated BANK-A account.
06 / Benchmarks & Tests
Outage routing, crash recovery and Merkle benchmarks
Measurements captured from Go 1.27 and PostgreSQL 18 test suites across fault injection, process termination and 100K-row reconciliation workloads.
Bank Outage Benchmark (300 Requests)
Adaptive circuit routing vs static baseline
During a 100-request fault window on primary rail RAIL-A (FailureThreshold=3), adaptive routing tripped OPEN within 200ms and routed subsequent payments over RAIL-B, completing 297/300 requests.
Circuit-Aware Adaptive297 / 300 (99.0%)
3 initial probe failures before trip; 0 requests sent while OPEN
Static Routing Baseline200 / 300 (66.7%)
100 consecutive failures hitting an offline endpoint
Circuit-aware adaptive routing tripped OPEN on RAIL-A within 3 failed requests (FailureThreshold=3) during a 100-request outage, keeping 99.0% of payments succeeding over RAIL-B with zero requests sent to an OPEN circuit.
RC1 8e1efb0 fault-injection harness across in-memory bank adapters.
Over 300 requests where RAIL-A degraded to 80% failures in phase 2, SelectRoute ranked RAIL-B higher and handled 225/300 transfers over the healthy rail (vs 300 on RAIL-A under static ordering).
RC1 8e1efb0 deterministic routing harness.
Latency Shift Sensitivity (RC1 Experiment 3)4.33 ms vs 17.71 ms P95
Under injected +15ms latency on RAIL-A, health-scored selection shifted 195 of 300 transfers to RAIL-B, lowering P95 latency from 17.71 ms to 4.33 ms with 100% completion across both configurations.
Live PG 18 Concurrency Stress51 Completed, 19 Replays
20 same-key plus 75 unique-key requests at concurrency 25 against live PostgreSQL produced 70 2xx replies (51 logical payments including 1 from the 20-way contended key + 19 idempotent replays) and 25 expected insufficient-funds errors.
RC1 8e1efb0 live PostgreSQL run (450 paise debits=credits, 0 drift).
50 IndexedDB intents across 65 replay attempts produced 45 synced payments (reusing the exact idempotency key on all 10 transient 503 retries) plus 5 expected 400 rejections.
RC1 8e1efb0 client IndexedDB schema and replay worker suite.
07 / Tech Stack
Technologies by responsibility
Application Core
Go 1.27Payment switch, saga orchestrator, bank processes and background worker
React 19 + TypeScriptRole-scoped SPAs for Customer, Merchant and Operations
ViteFrontend build pipeline and Vitest test runner
Data & Communication
PostgreSQL 18Central ledger (public), bank_a and bank_b isolated schemas
REST / HTTPSAuthoritative state queries and private inter-service RPC
Server-Sent EventsLive UI invalidation hints prompting REST state refetches
IndexedDB (v2)Owner-scoped offline intent queue and lease metadata
Reliability & Verification
Durable SagaDeterministic step UUIDs, presence queries and advisory locks