Bỏ qua, tới nội dung chính

Kiến trúc · ADR 0041

Points wallet: one writer, a locked balance row and an idempotent ledger

Trạng thái
accepted
Ngày
2026-11-21
Người quyết định
Tín (#124)

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.record is the only writer of UserStreak.pointsBalance and PointLedger. credit/debit wrap it; callers that must commit atomically with their own writes pass their Prisma.TransactionClient.
  • In one transaction: INSERT … ON CONFLICT DO NOTHING the wallet row, SELECT … FOR UPDATE it, check the idempotency key under the lock, move the balance with one conditional UPDATE (pointsBalance >= -delta), then append the ledger row with balanceAfter. Writers to one wallet queue on the row lock, so the balanceAfter chain 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 is 409 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 key admin:<clientRequestId>, a mandatory 5–200 character reason stored as the ledger note, and audit action user.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).