Backend Engineer Guide: Double-Entry Loyalty Points, Multi-Currency Wallets & FIFO Expiration Ledgers in Go & PostgreSQL
Storing a user's wallet balance or loyalty points as a single mutable `balance` integer column without an immutable ledger is one of the most expensive mistakes in e-commerce and FinTech engineering: concurrent redemptions cause negative-balance race conditions, and customer disputes become impossible to audit. As a Senior Backend Engineer specializing in Go (Golang), Python, and PostgreSQL, I architect append-only double-entry wallet and points engines.
1. Preventing Double-Spend Race Conditions with Deterministic Lock Ordering in Go
When transferring funds or redeeming points across accounts in PostgreSQL, locking rows in a consistent primary-key order (`ORDER BY account_id ASC FOR UPDATE`) eliminates deadlocks while preventing concurrent double-spends:
package ledger
import (
"context"
"database/sql"
"errors"
)
var ErrInsufficientFunds = errors.New("insufficient wallet balance")
func RedeemPointsTx(ctx context.Context, db *sql.DB, idempotencyKey string, accountID int64, amount int64) error {
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
if err != nil {
return err
}
defer tx.Rollback()
var currentBalance int64
err = tx.QueryRowContext(
ctx,
`SELECT balance FROM wallet_accounts WHERE id = $1 FOR UPDATE`,
accountID,
).Scan(¤tBalance)
if err != nil {
return err
}
if currentBalance < amount {
return ErrInsufficientFunds
}
_, err = tx.ExecContext(
ctx,
`INSERT INTO wallet_ledger_entries (idempotency_key, account_id, delta_amount, created_at)
VALUES ($1, $2, $3, NOW())`,
idempotencyKey, accountID, -amount,
)
if err != nil {
return err
}
_, err = tx.ExecContext(
ctx,
`UPDATE wallet_accounts SET balance = balance - $1, updated_at = NOW() WHERE id = $2`,
amount, accountID,
)
if err != nil {
return err
}
return tx.Commit()
}
2. FIFO Point Bucket Expiration Modeling
- Remaining-Balance Grant Buckets: Track each point grant with an `expires_at` timestamp and `remaining_amount` so redemptions consume the soonest-to-expire points first (`ORDER BY expires_at ASC FOR UPDATE`).
3. Related Backend Engineering Guides
- Hire a Senior Backend Engineer: Python, Django, FastAPI, Golang & PostgreSQL Pillar Guide
- Golang Microservices & Cloud FinOps Engineering Hub
⚡ Hire Aldian Fazrihady — Senior Cloud, GCP, Backend, AI Application & Full Stack Engineer
Need production cloud architecture, GCP/AWS infrastructure, high-throughput backend systems, AI agents, or full stack web engineering? Book a 1-Day Programming Sprint for $100 USD (International Card / Apple Pay) or Rp 1,000,000 (Indonesian QRIS / Bank Virtual Account), or hire directly on Upwork:
Book $100 / Rp 1M 1-Day Sprint → Hire on Upwork (100% Job Success) →