Prevent Double Spending of Coins With Transactions and Idempotency
Last updated: November 29, 2026
Quick Overview
Users spend coins to send LIVE gifts, and a client may retry the same request after a timeout while another device spends from the same balance. Using a relational database, implement spend(user, amount, idempotency_key) so the balance never goes negative and a retried request is applied exactly once.
TikTok
November 29, 20260
0
0 solved
Users spend coins to send LIVE gifts, and a client may retry the same request after a timeout while another device spends from the same balance. Using a relational database, implement spend(user, amount, idempotency_key) so the balance never goes negative and a retried request is applied exactly once.
TikTok's virtual currency must behave like money even under retries and concurrent devices, which makes it a favorite database fundamentals topic in onsite rounds. The interviewer checks transaction isolation, conditional updates, unique constraints for idempotency, and what happens on failure halfway through.
What the Interviewer Expects
- Explains the lost update and check-then-act races with read-then-write logic
- Uses a single conditional UPDATE ... WHERE balance >= amount, or row locks, inside a transaction
- Records the idempotency key under a unique constraint in the same transaction
- Returns the original result for a repeated key instead of spending again
- Discusses isolation levels and why the conditional update is safe even at READ COMMITTED
Key Topics to Cover
How to Approach This
- Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
- Choose data structures based on access patterns, not familiarity.
- Prefer immutable data and message passing over shared mutable state for concurrency.
- Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
- How would this work if the wallet and the gift ledger live in different services?
- How long should idempotency keys be kept, and what happens after they expire?
- How would you shard wallets and still support transfers between users on different shards?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice System Design ProblemsSample Answer
Requirements
- Tables:
wallets(user, balance),spends(idem_key PRIMARY KEY, user, amount, status). spendreturns"ok","insufficient", or the stored result for a repeated key.- Correct under concurren...
High-Level Design
The naive version reads the balance, checks it in the app, then writes balance - amount. Two concurrent requests can both read 100, both pass, and both write, so one spend is lost or the balance goe...