Design an in-memory banking system with expiring accounts, scheduled transfers and top spenders
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design an in-memory banking system that supports user accounts with deposits, withdrawals and transfers between users.
Every command carries a timestamp. An account can have a time-to-live (TTL): once the TTL has elapsed since the account was created, the account expires and can no longer be used. A TTL of `0` means the account never expires.
The system also supports scheduled transfers, which execute at a given future timestamp, and a ranking that returns the top users by total outgoing transaction volume (withdrawals and outgoing transfers combined). A scheduled transfer that comes due runs with the same checks as `transfer`, evaluated at its execution timestamp; if a check fails, the transfer is dropped.
Implement these methods:
- `add_user(timestamp: int, user_id: str, ttl: int) -> bool` creates a new account with balance 0. `ttl = 0` means the account never expires. Return `True` if the user was created and `False` if the user already exists.
- `deposit(timestamp: int, user_id: str, amount: int) -> int` adds `amount` to the account. Return the new balance, or `-1` if the user does not exist or the account has expired.
- `withdraw(timestamp: int, user_id: str, amount: int) -> int` takes `amount` out of the account. Return the new balance, or `-1` if the user does not exist, the account has expired, or the funds are insufficient.
- `transfer(timestamp: int, from_user: str, to_user: str, amount: int) -> int` moves `amount` from one user to another. Return the sender's new balance, or `-1` if either user does not exist or has expired, both are the same user, or the sender has insufficient funds.
- `schedule_transfer(timestamp: int, exec_timestamp: int, from_user: str, to_user: str, amount: int) -> bool` schedules a transfer to run at `exec_timestamp`. Return `True` if it was scheduled, and `False` if either user is invalid, both are the same user, or `exec_timestamp` is not in the future.
- `top_spenders(timestamp: int, n: int) -> List[str]` returns the top `n` active users ranked by total outgoing volume, highest first, with ties broken by user id in ascending lexicographic order. Format each entry as `userId(volume)`.
For example:
```text
add_user(1, "user1", 50) -> True user1 created with TTL 50, expires at t=51
deposit(10, "user1", 500) -> 500
add_user(20, "user1", 0) -> False user1 already exists
deposit(30, "user1", 100) -> 600
transfer(40, "user1", "user2", 100) -> -1 user2 does not exist
withdraw(45, "user1", 100) -> 500
```
A longer sequence with an expiring account, a scheduled transfer and the ranking:
```text
add_user(1, "alice", 0) -> True
add_user(2, "bob", 0) -> True
add_user(3, "carol", 20) -> True carol expires at t=23
deposit(4, "alice", 300) -> 300
deposit(5, "carol", 100) -> 100
schedule_transfer(6, 15, "alice", "bob", 200) -> True
withdraw(7, "carol", 40) -> 60
withdraw(16, "alice", 50) -> 50 the t=15 transfer ran first: alice 300 -> 100, bob 0 -> 200
top_spenders(20, 3) -> ["alice(250)", "carol(40)", "bob(0)"]
top_spenders(25, 3) -> ["alice(250)", "bob(0)"] carol expired at t=23
deposit(26, "carol", 10) -> -1 carol has expired
```
```hint Time only moves at calls
Nothing happens between calls. Decide what every method must settle about the past before it performs its own operation, and at which timestamp each settled event should be evaluated.
```
```hint Several transfers due at once
More than one scheduled transfer can come due between two calls, and each one changes a balance the next one may check. Work out which order reproduces what a continuously running system would do, and which structure hands you that order cheaply.
```
```hint Expiry without a sweep
Expired accounts do not have to be removed the moment they expire. Think about what you need to store so that any call can tell whether an account is still usable.
```
### Constraints & Assumptions
- `1 <= timestamp <= 10^9`, and timestamps strictly increase from one call to the next.
- User ids are non-empty strings.
- `amount >= 1` and `n >= 1`.
- `0 <= ttl <= 10^9`, where 0 means no expiry.
- At most `10^4` operations in total.
- An account created at time `c` with a nonzero TTL `t` is active for timestamps below `c + t` and expired from `c + t` on, so the first example's account (created at 1, TTL 50) is expired at 51.
- If fewer than `n` users are active, `top_spenders` returns all of them.
### Clarifying Questions to Ask
- When several scheduled transfers come due before the next call, do they run in order of execution timestamp, and what breaks a tie between two due at the same timestamp?
- After an account expires, can `add_user` register the same id again, and does the new account start with zero balance and zero outgoing volume?
- If the sender's account expires and its id is registered again before a pending transfer runs, should the new account pay that transfer?
- Does scheduling a transfer hold the funds, or is the balance only checked when it runs?
### What a Strong Answer Covers
- An account model (balance, expiry time, outgoing volume) with one consistent rule for when an account stops being usable, including the exact boundary.
- Settling every scheduled transfer due by the current timestamp before running the requested operation, in execution-time order, with activity and balance checked as of each transfer's own execution time.
- Correct return values for every failure case: unknown or expired users, self-transfers, insufficient funds, and execution times that are not in the future.
- A deterministic `top_spenders` ordering (volume descending, user id ascending) restricted to active accounts.
- The cost of each operation and which parts would need a different structure as accounts and pending transfers grow.
### Follow-up Questions
- How would you let a caller cancel a scheduled transfer, and what would `schedule_transfer` need to return?
- `top_spenders` sorts every active account on each call. How would you make it cheap when it is called far more often than the balances change?
- How would you add an operation that merges one account into another, carrying over balance, outgoing volume and pending scheduled transfers?
- If requests arrived concurrently from many threads, where would you put locks, and how would you avoid deadlock between two opposite transfers?
Overview: Design an in-memory banking system that handles deposits, withdrawals and transfers, accounts that expire after a TTL, transfers scheduled for a future timestamp, and a ranking of users by outgoing volume. It tests state modeling, processing events in timestamp order and handling every failure case cleanly.