Design a delayed payment system with scheduled execution, retries and cancellation
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a delayed payment system that schedules payments to execute at a future timestamp. Each payment has a unique ID, an amount, and a scheduled execution time. Payments begin in PENDING state.
When payments are processed, they may succeed or fail based on a deterministic rule: a payment succeeds if its amount is strictly less than `10000`. Failed payments are automatically retried by rescheduling them `60` seconds later. If the maximum number of retries is exhausted, the payment permanently moves to FAILED state.
The system should support scheduling new payments, processing all due payments up to a given timestamp, cancelling pending payments, and querying payment status and retry counts.
Processing follows these rules:
- Due payments are processed in order of scheduled time, earliest first. Payments due at the same time are processed in ascending lexicographic order of payment ID.
- Each failed attempt adds one to the payment's retry counter. If the counter is still below `max_retries`, the payment stays PENDING and is rescheduled 60 seconds after the time the failed attempt was due. When the counter reaches `max_retries`, the payment becomes FAILED, so a payment is attempted at most `max_retries` times.
- A rescheduled payment that falls due at or before `current_timestamp` is processed again within the same `process_payments` call.
- The list returned by `process_payments` has one entry per attempt, so a payment attempted twice in one call appears twice. Cancelled payments are skipped and do not appear.
Implement the following methods:
- `DelayedPaymentSystem(max_retries: int)`: Create the system with the retry limit that applies to every payment.
- `schedule_payment(payment_id: str, amount: float, timestamp: int) -> bool`: Schedule a new payment with the given ID, amount, and execution timestamp. Returns True if scheduled successfully, False if the payment ID already exists in any state.
- `process_payments(current_timestamp: int) -> List[str]`: Process all payments due at or before the given timestamp. A payment succeeds if its amount is strictly less than 10000; otherwise it fails. Failed payments are retried as described above until max retries are exhausted, at which point they become FAILED. Returns the list of payment IDs processed in order.
- `get_status(payment_id: str) -> str`: Return the current status of the payment: PENDING, COMPLETED, FAILED, CANCELLED, or NOT_FOUND if the payment does not exist.
- `cancel_payment(payment_id: str) -> bool`: Cancel a payment that is currently PENDING. Returns True if successfully cancelled, False if the payment does not exist or is not in PENDING state.
- `get_pending_amount() -> float`: Return the total amount of all payments currently in PENDING state, rounded to 2 decimal places.
- `get_payment_retries(payment_id: str) -> int`: Return the payment's retry counter as defined above. Returns -1 if the payment does not exist.
Example 1, retries:
```text
Input:
["DelayedPaymentSystem", "schedule_payment", "schedule_payment", "schedule_payment", "get_pending_amount", "process_payments", "get_payment_retries", "get_status", "process_payments", "get_status", "get_payment_retries", "get_pending_amount"]
[[3], ["a", 50.5, 100], ["b", 15000, 100], ["c", 20.25, 130], [], [100], ["b"], ["b"], [250], ["b"], ["b"], []]
Output: [null, true, true, true, 15070.75, ["a", "b"], 1, "PENDING", ["c", "b", "b"], "FAILED", 3, 0]
Explanation:
sys = DelayedPaymentSystem(3) # max_retries = 3
sys.schedule_payment("a", 50.5, 100) # -> True
sys.schedule_payment("b", 15000.0, 100) # -> True
sys.schedule_payment("c", 20.25, 130) # -> True
sys.get_pending_amount() # -> 15070.75 (50.5 + 15000 + 20.25)
sys.process_payments(100) # -> ["a", "b"] (both due at 100, a first by ID;
# a completes, b fails and is rescheduled to 160)
sys.get_payment_retries("b") # -> 1
sys.get_status("b") # -> "PENDING" (waiting for its retry)
sys.process_payments(250) # -> ["c", "b", "b"] (c completes at 130; b fails at 160,
# is rescheduled to 220, and fails again at 220)
sys.get_status("b") # -> "FAILED" (third failed attempt reached max_retries)
sys.get_payment_retries("b") # -> 3
sys.get_pending_amount() # -> 0.0
```
Example 2, cancellation:
```text
Input:
["DelayedPaymentSystem", "schedule_payment", "cancel_payment", "get_status", "process_payments", "schedule_payment", "get_pending_amount"]
[[3], ["pay1", 100, 50], ["pay1"], ["pay1"], [50], ["pay1", 200, 60], []]
Output: [null, true, true, "CANCELLED", [], false, 0]
Explanation:
sys = DelayedPaymentSystem(3) # max_retries = 3
sys.schedule_payment("pay1", 100.0, 50) # -> True (pay1 scheduled at t=50)
sys.cancel_payment("pay1") # -> True (pay1 cancelled)
sys.get_status("pay1") # -> "CANCELLED"
sys.process_payments(50) # -> [] (pay1 is cancelled, skipped)
sys.schedule_payment("pay1", 200.0, 60) # -> False (pay1 ID already exists)
sys.get_pending_amount() # -> 0.0 (no pending payments)
```
```hint Finding due payments
You need the earliest scheduled payment again and again while new payments and retries keep arriving. Pick a structure that hands you the minimum cheaply, and make its ordering match the tie rule.
```
```hint Cancelling without searching
Removing an arbitrary entry from the middle of that structure is slow. Consider leaving the entry in place and deciding what to do with it when it comes out.
```
### Constraints & Assumptions
- `1 <= len(payment_id) <= 20`
- `0.01 <= amount <= 10^6`
- `0 <= timestamp <= 10^9`
- `1 <= max_retries <= 10`
- Each payment has a unique string ID; scheduling an ID that already exists returns False.
- A payment succeeds if `amount < 10000`, otherwise it fails.
- Failed payments are rescheduled 60 seconds later until retries are exhausted.
### Clarifying Questions to Ask
- Can a payment that is waiting for a retry be cancelled, and does it keep its retry counter if so?
- May I store amounts as integer cents internally, or must they stay floating point?
- Will `process_payments` ever run concurrently with `schedule_payment` or `cancel_payment`, or is the class used from one thread?
- Can `schedule_payment` receive a timestamp earlier than one already passed to `process_payments`, and should that payment run on the next call?
### What a Strong Answer Covers
- A data layout that gives fast lookup by payment ID and fast access to the earliest due payment, with ties ordered as the rules require.
- How cancellation works without searching the queue, and how processing recognizes entries that no longer apply.
- The retry flow: when the counter changes, how the next due time is computed, and why a retry can run inside the same `process_payments` call.
- Edge cases such as reused IDs, cancelling a finished or unknown payment, pending totals that include payments waiting for a retry, and rounding.
- The time and space cost of each method, and what to change if `get_pending_amount` must be fast.
### Follow-up Questions
- `process_payments` now runs on a background timer while other threads schedule and cancel payments. What do you lock, and where can races appear?
- Replace the fixed 60-second delay with exponential backoff and jitter. What changes in the data model and in the tests?
- The process crashes after a payment is charged but before it is marked COMPLETED. How do you avoid charging it twice after a restart?
- How would you make `get_pending_amount` constant time without accumulating floating-point error?
Overview: Design an in-memory delayed payment system that runs payments at scheduled timestamps, retries failures 60 seconds later up to a limit, and supports cancellation and status queries. It tests priority queue scheduling, lazy deletion, retry state and edge cases around time ordering and money totals.