Concurrency Challenges in Financial ERP Systems
In manufacturing and multi-tenant financial systems, duplicate execution is catastrophic. When two webhooks or double-clicking users trigger a payment capture or invoice reconciliation simultaneously, standard row-level locks often fail because the row record does not yet exist.
Standard solutions often reach for Redis distributed locks (Redlock). However, in high-stakes financial ledgers, introducing Redis distributed locks adds network partitions, clock-drift failure modes, and distributed split-brain scenarios.
The Core Principle
Keep the lock mechanism inside the primary transactional boundary. By leveraging PostgreSQL transaction-level advisory locks (pg_advisory_xact_lock), you get zero-dependency, crash-safe, deadlock-preventing serialization.
Why Postgres Advisory Locks Beat Redis Mutexes
PostgreSQL advisory locks have application-defined semantics. They do not lock actual rows or tables. Instead, you lock an arbitrary 64-bit integer (like an invoice hash or tenant ID).
✕ Redis Distributed Locks (Redlock)
- Vulnerable to clock drift and GC pause lease expirations.
- Requires separate Redis connection & timeout recovery code.
- Lock release does not align with database commit time.
✓ Postgres pg_advisory_xact_lock
- Bound strictly to the lifetime of the DB transaction.
- Releases automatically on commit OR unexpected crash rollback.
- Zero extra network hops outside standard Postgres client pool.
Handling QuickBooks Sync Safely
Syncing with external accounting APIs (like QuickBooks or Stripe) requires two-phase atomicity. If QuickBooks responds successfully but your database fails to commit, your ledger becomes out of sync.
We employ the Transactional Outbox Pattern combined with an advisory lock key derived from the invoice idempotency key:
import { PoolClient } from 'pg';
import crypto from 'crypto';
export async function processInvoiceSync(
client: PoolClient,
invoiceId: string,
handler: () => Promise<void>
) {
// Hash invoiceId into a signed 64-bit integer
const lockKey = crypto.createHash('sha256')
.update(invoiceId)
.digest()
.readBigInt64BE(0);
await client.query('BEGIN');
try {
// Acquire transaction-scoped exclusive lock
await client.query('SELECT pg_advisory_xact_lock($1)', [lockKey.toString()]);
// Check current state & execute external sync
await handler();
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
}
}Reconciliation and Rollback Strategies
When an external API call times out or returns a network error, assume it succeeded on the remote host until proven otherwise. Every transaction log payload retains the QuickBooks SyncToken and transaction ID so automatic reconciliation jobs can safely retry without creating duplicate ledger records.

