Design a thread-safe credit account that handles concurrent deductions
Quick Overview
Design a thread-safe credit account whose deduct, add and balance methods stay correct when many threads call them at once. A deduction must check and subtract in one atomic step and leave the balance unchanged when credits run short. It tests critical sections, locking discipline and check-then-act race conditions.
Design a thread-safe credit account that handles concurrent deductions
Company: Midjourney
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: easy
Interview Round: Other
Design a thread-safe `CreditAccount` that tracks a user's available credits and supports concurrent deductions from multiple threads or callers without race conditions.
Each deduction must be atomic: if the current balance is sufficient, the credits are subtracted and the operation succeeds; otherwise, the balance is left unchanged and the operation fails. The class must also support adding credits and querying the current balance, all safely under concurrent access.
Internally, use a lock to serialize the check-and-update of the balance so that no two operations can observe or modify the balance in an inconsistent intermediate state.
Implement the following methods:
- `CreditAccount(initialBalance: int)`: create an account with the given starting balance.
- `deduct(amount: int) -> bool`: atomically deduct `amount` credits from the balance. Return `True` if the deduction succeeded, or `False` if the balance was insufficient (in which case the balance is unchanged).
- `add(amount: int)`: atomically add `amount` credits to the balance.
- `getBalance() -> int`: return the current credit balance.
Example 1:
```text
Input:
["CreditAccount", "deduct", "deduct", "getBalance", "add", "deduct", "getBalance"]
[[100], [30], [80], [], [50], [40], []]
Output: [null, true, false, 70, null, true, 80]
Explanation:
account = CreditAccount(100) # initial balance = 100
account.deduct(30) # True (balance: 70)
account.deduct(80) # False (insufficient, balance still 70)
account.getBalance() # 70
account.add(50) # balance: 120
account.deduct(40) # True (balance: 80)
account.getBalance() # 80
```
Example 2:
```text
Input:
["CreditAccount", "getBalance", "deduct", "add", "deduct", "getBalance"]
[[0], [], [1], [10], [10], []]
Output: [null, 0, false, null, true, 0]
Explanation:
account = CreditAccount(0) # initial balance = 0
account.getBalance() # 0
account.deduct(1) # False (insufficient, balance still 0)
account.add(10) # balance: 10
account.deduct(10) # True (balance: 0)
account.getBalance() # 0
```
```hint Where the race is
Picture two threads that both read a balance of 50 and both try to deduct 40. Find the smallest stretch of code that has to run without another thread getting in between.
```
### Constraints & Assumptions
- `0 <= initialBalance <= 10^9`
- `1 <= amount <= 10^9` for `deduct` and `add` calls.
- At most `10^4` total operations are performed.
- All operations must be thread-safe.
- A deduction the balance cannot cover fails immediately; it does not wait for credits to be added.
### Clarifying Questions to Ask
- Does the account live in one process, or do several servers deduct from the same balance?
- Can a caller pass a zero or negative amount, and if so, should the call raise an error?
- Is it acceptable for `getBalance` to return a value that may already be out of date when the caller reads it?
### What a Strong Answer Covers
- The interleaving that lets two deductions both succeed or lose an update when the check and the subtraction are separate steps.
- One lock that guards every read and write of the balance and is released on every path, including exceptions.
- Why `getBalance` is only a snapshot and why callers must act on the return value of `deduct`.
- Integer range and amounts outside the stated constraints.
- How the design changes when the balance is shared outside one process.
### Follow-up Questions
- How would you implement `deduct` without a lock, using compare-and-swap?
- The balance now lives in a database shared by many API servers. How do you keep each deduction atomic?
- A client retries a deduction after a timeout. How do you make sure it is not charged twice?
- How would you add `transfer(other, amount)` between two accounts without risking deadlock?
Overview: Design a thread-safe credit account whose deduct, add and balance methods stay correct when many threads call them at once. A deduction must check and subtract in one atomic step and leave the balance unchanged when credits run short. It tests critical sections, locking discipline and check-then-act race conditions.
Design a thread-safe CreditAccount that tracks a user's available credits and supports concurrent deductions from multiple threads or callers without race conditions.
Each deduction must be atomic: if the current balance is sufficient, the credits are subtracted and the operation succeeds; otherwise, the balance is left unchanged and the operation fails. The class must also support adding credits and querying the current balance, all safely under concurrent access.
Internally, use a lock to serialize the check-and-update of the balance so that no two operations can observe or modify the balance in an inconsistent intermediate state.
Implement the following methods:
CreditAccount(initialBalance: int)
: create an account with the given starting balance.
deduct(amount: int) -> bool
: atomically deduct
amount
credits from the balance. Return
True
if the deduction succeeded, or
False
if the balance was insufficient (in which case the balance is unchanged).
add(amount: int)
: atomically add
amount
credits to the balance.
getBalance() -> int
: return the current credit balance.