Backend Engineer Guide: Double-Spend Proof Loyalty Points & FIFO Expiration Ledgers in Go

Loyalty point and promotional credit systems are high-value targets for race-condition exploits: if a user submits ten concurrent checkout redemptions from separate browser tabs and the backend checks if user.points_balance >= 500 without row-level locking, the user redeems 5,000 points from a 500-point balance. Worse, loyalty points typically carry batch-level expiration dates that require First-In, First-Out (FIFO) consumption across grant buckets. As a backend engineer, I architect double-spend-proof FIFO loyalty ledgers in Go and PostgreSQL.

1. Atomic FIFO Bucket Consumption with SELECT ... FOR UPDATE in Go

Instead of mutating a single scalar column, every point grant creates an immutable loyalty_grant_buckets row with remaining_points and expires_at. Redemption locks the wallet row in deterministic order, iterates active buckets ordered by expires_at ASC, and records a double-entry ledger journal:

// loyalty/redeem.go
package loyalty

import (
	"context"
	"database/sql"
	"errors"
)

var ErrInsufficientPoints = errors.New("insufficient non-expired loyalty points")

func RedeemPointsFIFO(ctx context.Context, db *sql.DB, walletID, idempotencyKey string, pointsToRedeem int64) error {
	tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
	if err != nil {
		return err
	}
	defer tx.Rollback()

	// 1. Idempotency guard
	var existingID string
	err = tx.QueryRowContext(ctx,
		`SELECT id FROM loyalty_redemptions WHERE idempotency_key = $1`, idempotencyKey,
	).Scan(&existingID)
	if err == nil {
		return nil // Already redeemed
	} else if !errors.Is(err, sql.ErrNoRows) {
		return err
	}

	// 2. Lock active non-expired grant buckets in FIFO expiration order
	rows, err := tx.QueryContext(ctx, `
		SELECT id, remaining_points
		FROM loyalty_grant_buckets
		WHERE wallet_id = $1 AND remaining_points > 0 AND expires_at > NOW()
		ORDER BY expires_at ASC, id ASC
		FOR UPDATE
	`, walletID)
	if err != nil {
		return err
	}
	defer rows.Close()

	type bucketAllocation struct {
		BucketID string
		Deduct   int64
	}
	var allocations []bucketAllocation
	remainingNeeded := pointsToRedeem

	for rows.Next() && remainingNeeded > 0 {
		var bID string
		var avail int64
		if err := rows.Scan(&bID, &avail); err != nil {
			return err
		}
		take := avail
		if take > remainingNeeded {
			take = remainingNeeded
		}
		allocations = append(allocations, bucketAllocation{BucketID: bID, Deduct: take})
		remainingNeeded -= take
	}
	if err := rows.Close(); err != nil {
		return err
	}
	if remainingNeeded > 0 {
		return ErrInsufficientPoints
	}

	// 3. Apply bucket deductions and insert immutable audit journal
	for _, alloc := range allocations {
		if _, err := tx.ExecContext(ctx,
			`UPDATE loyalty_grant_buckets SET remaining_points = remaining_points - $1 WHERE id = $2`,
			alloc.Deduct, alloc.BucketID,
		); err != nil {
			return err
		}
	}
	if _, err := tx.ExecContext(ctx,
		`INSERT INTO loyalty_redemptions (wallet_id, idempotency_key, points_redeemed) VALUES ($1, $2, $3)`,
		walletID, idempotencyKey, pointsToRedeem,
	); err != nil {
		return err
	}

	return tx.Commit()
}

2. Related Financial Ledger & Go Backend Resources


About the Author — Hire Aldian Fazrihady (Cloud Engineer, GCP Professional Cloud Architect, GCP Professional Data Engineer, Backend, AI & Full Stack Engineer)

Aldian Fazrihady is a Top-Rated Senior Cloud Engineer, GCP Professional Cloud Architect (Google Cloud Certified), GCP Professional Data Engineer (Google Cloud Certified), Backend Engineer (Python, Django, FastAPI, Go, PostgreSQL), AI Application Engineer (LLMs, RAG, MCP, Google ADK, LangGraph), and Full Stack Engineer (React, Next.js, TypeScript) with 25+ years of production software engineering experience.

Hire Aldian Fazrihady on Upwork | Book 1-Day Programming Service ($100 USD / Rp 1.000.000) | View Live AI Portfolio | Send a Direct Message

Related Engineering Articles

Engineering Role Pillar Guides & Category Hubs