Developer Builds NestJS Banking Ledger Using DB-Level Locks to Prevent Overdrafts
A software developer built a NestJS-based banking ledger to demonstrate a real solution to the 'lost update anomaly,' a concurrency bug where two simultaneous withdrawal requests both read the same balance and both get approved, leaving an account overdrawn with no errors logged. The bug arises because a gap exists between when a balance is read and when it is written back, allowing two requests to act on stale data simultaneously. The fix bypasses application-level coordination entirely, instead using PostgreSQL's SELECT FOR UPDATE query via TypeORM's pessimistic write lock to serialize row-level access within a database transaction. Once one transaction holds the lock and commits, any waiting transaction reads the updated balance before proceeding, ensuring no request ever acts on outdated data. The project is publicly available on GitHub and documents not only the solution but also implementation mistakes encountered during the build.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in