Designing a Zero-Drift Cashback Wallet with PostgreSQL Ledger-First RPCs and RLS
When building real-money features — like the Vietnamese e-commerce cashback web platform Hoàn Tiền (nhanhoantien.vn) for Shopee, TikTok Shop, Lazada, and Tiki — the quickest MVP shortcut is storing a single balance colum
When building real-money features — like the Vietnamese e-commerce cashback web platform Hoàn Tiền (nhanhoantien.vn) for Shopee, TikTok Shop, Lazada, and Tiki — the quickest MVP shortcut is storing a single balance column on users and running UPDATE users SET balance = balance + $1 from backend handlers.
In production, that shortcut breaks down fast under four real-world failure modes:
-
Concurrent withdrawal race conditions: Two simultaneous payout requests both pass
balance >= 10000and double-spend. - Duplicate or out-of-order affiliate webhooks: Networks frequently retry callbacks or send cancellation events before creation events.
-
Floating-point rounding drift: Storing money as
FLOAT/DOUBLEintroduces penny/dong discrepancies over thousands of rows. - Zero audit trail: A single mutable number cannot explain why a user's balance changed yesterday.
Here is the architecture I implemented using Next.js 15 (App Router), TypeScript, PostgreSQL 17 with Row Level Security (RLS), and Drizzle.
1. Ledger-First: Never UPDATE Balance Columns Directly from App Code
Every monetary change goes through a SECURITY DEFINER PostgreSQL RPC:
- Every mutation appends an immutable row to an append-only
transactionstable (INSERTonly — noUPDATEorDELETE). - Updating aggregate balance columns on
profileshappens inside the same database transaction, protected by row-level locking (SELECT ... FOR UPDATE) for withdrawals. - Application code (Server Actions / API routes) never runs raw
UPDATE profiles SET payable_total = ....
// Calling the withdrawal ledger RPC under the authenticated user's RLS context
const result = await withUserContext(user.id, 'authenticated', async (tx) => {
const res = await tx.execute(
sql`SELECT public.request_withdrawal(${amount}) AS request_withdrawal`
)
return res[0]?.request_withdrawal
})
2. Three Explicit Integer Buckets (VND)
E-commerce cashback requires a reconciliation window while return/refund windows close. Mixing pending and withdrawable money in one column confuses users and creates liquidity risk.
We store all currency as INTEGER (1 unit = 1 VND) across three distinct columns:
-
pending_total: Estimated cashback awaiting marketplace confirmation (never withdrawable). -
payable_total: Reconciled cashback eligible for instant bank/e-wallet withdrawal (on nhanhoantien.vn's fee & policy page, withdrawals start at 10,000 VND with 0 VND fee). -
paid_total: Cumulative amount successfully disbursed.
Our core invariant check is trivial to assert in automated SQL tests: for every user and bucket, profiles.<bucket>_total MUST equal SUM(transactions.amount) for that bucket.
3. Enforcing RLS Across User vs. Background Contexts
Every table has PostgreSQL RLS enabled:
- User-initiated requests execute through
withUserContext(userId, 'authenticated', ...)soauth.uid()is scoped strictly to the requesting user inside the transaction. - Only background cron workers and audited admin routes use an isolated service client — and
DATABASE_URLnever touches client bundles.
Takeaways
Investing two extra days upfront in append-only ledger RPCs and SQL invariant tests eliminated an entire class of financial bugs before our first withdrawal ever went live. If you're building a wallet, credits system, or loyalty ledger in PostgreSQL, enforce the invariant at the database boundary — not in application memory.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.