Prevent Deadlock in Concurrent Wallet Transfers With Lock Ordering
Last updated: November 29, 2026
Quick Overview
Two threads may transfer money in opposite directions between the same pair of accounts at once. Write a transfer function that locks both accounts, keeps total balance conserved, and can never deadlock.
0
0
0 solved
Two threads may transfer money in opposite directions between the same pair of accounts at once. Write a transfer function that locks both accounts, keeps total balance conserved, and can never deadlock.
This appears in Google onsite fundamentals rounds framed around Google Pay balances or ad budget pools. The interviewer first lets the candidate write the naive nested lock, then asks what happens when A pays B while B pays A, checking that the candidate can name the circular wait and fix it with a global order.
What the Interviewer Expects
- Identifies the circular-wait deadlock in naive nested locking
- Imposes a total order on locks using a stable account id
- Checks the balance only while holding both locks
- Handles self-transfer without re-acquiring a non-reentrant lock
- Mentions the four Coffman conditions and which one the fix breaks
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 you transfer across three or more accounts atomically?
- What if account ids are not comparable or two objects share an id?
- How does a try-lock with timeout and backoff compare to ordering?
- How would this look when accounts live in different database 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
transfer(src, dst, amount)movesamountatomically, or raises if funds are insufficient.- The sum of all balances never changes, and no balance goes negative.
- Arbitrary concurrent transfers i...
High-Level Design
Naive code locks src then dst. Thread 1 doing A to B holds A and waits for B; thread 2 doing B to A holds B and waits for A: a circular wait. Deadlock needs mutual exclusion, hold-and-wait, no pre...