Pull-Style Transfers with Hold/Accept/Cancel
Context
You are building a wallet service that supports pull-style transfers. A transfer is initiated by the source account to place a hold on funds; the target account may accept to capture the held funds, or either party may cancel to release the hold back to the source. You will maintain transfer indices in hash maps for O(1) access.
Assume calls are made in an authenticated context where the caller's accountId is available. The provided method signatures intentionally omit an explicit source account for transfer(), implying the caller is the source. The accept() and cancel() methods include an accountId so you can authorize which party is acting.
Requirements
-
Implement the following APIs:
-
transfer(long timestamp, String targetAccountId, int amount) -> String transferId
-
accept(long timestamp, String accountId, String transferId) -> boolean
-
cancel(long timestamp, String accountId, String transferId) -> boolean
-
Semantics:
-
On transfer(), place a hold on the source account’s funds for the amount and create a PENDING transfer.
-
On accept(), move the held funds from source to target and mark the transfer ACCEPTED.
-
On cancel(), fully reset the source account’s funds (release hold) and mark the transfer CANCELED.
-
Data structures:
-
Maintain allTransfers and pendingTransfers in hash maps (O(1) average-time lookups) keyed by transferId. Use an accounts map for account lookup.
-
Describe and implement:
-
State transitions for a transfer.
-
Idempotency rules for each API.
-
Failure recovery approach (atomicity, crash safety).
-
Time/space complexity.
Assumptions
-
Amounts are non-negative integers (e.g., cents). No overdrafts.
-
The timestamp is provided by the caller and may be used for ordering/auditing and optional expiration checks.
-
Only the target account can accept; either source or target may cancel while pending.
-
A transfer may optionally expire after a TTL (if you choose to implement expiry); otherwise ignore timestamp except for audit.
-
In-memory solution is acceptable for this exercise; describe how you would make it durable in production.