Context
Points are earned, spent, refunded and adjusted by several features (#124 admin adjust, #125 course unlock, #126 purchase, #134 community rewards). The balance must never go negative, every change must be explainable from the ledger, and a retried request must never count twice.
Decision
PointsService.recordis the only writer ofUserStreak.pointsBalanceandPointLedger.credit/debitwrap it; callers that must commit atomically with their own writes pass theirPrisma.TransactionClient.- In one transaction:
INSERT … ON CONFLICT DO NOTHINGthe wallet row,SELECT … FOR UPDATEit, check the idempotency key under the lock, move the balance with one conditional UPDATE (pointsBalance >= -delta), then append the ledger row withbalanceAfter. Writers to one wallet queue on the row lock, so thebalanceAfterchain is gapless. - A replayed key returns the original entry (
replayed: true) and changes nothing. The same key with a different user, kind, source or amount is409 IDEMPOTENCY_KEY_REUSED; a cross-wallet race on one key is caught by the unique index (P2002) and answered the same way. - Overdraw is
409 INSUFFICIENT_POINTS. Admin adjustments use keyadmin:<clientRequestId>, a mandatory 5–200 character reason stored as the ledgernote, and audit actionuser.points_adjusted.
Consequences
The balance is a cache of the ledger sum and can be rebuilt from it. Proven on real Postgres by apps/api/test/integration/points.int-spec.ts (20 concurrent debits, 10 concurrent replays).