Every rewards app looks simple from the outside. A customer buys something, they earn reward points, and later they redeem rewards for cash or a gift card. Under the hood, the part that decides whether users trust you is the points ledger.
If balances drift, double credit, or go negative, support tickets pile up fast. Here is a practical way to model it.
1. Never store a balance as the source of truth
Store every movement as an immutable ledger entry and derive the balance from it.
CREATE TABLE points_ledger ( id BIGSERIAL PRIMARY KEY , user_id BIGINT NOT NULL , entry_type TEXT NOT NULL , -- EARN, BONUS, REDEEM, EXPIRE, REVERSAL points INTEGER NOT NULL , -- positive for credit, negative for debit source_ref TEXT NOT NULL , -- order id, scan id, campaign id created_at TIMESTAMPTZ NOT NULL DEFAULT now ( ) , UNIQUE ( entry_type , source_ref ) ) ;
Enter fullscreen mode
Exit fullscreen mode
The UNIQUE (entry_type, source_ref) constraint is the cheapest protection you will ever add.…