Payment Processor State Machine
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: easy
Interview Round: Other
Design a payment processor that manages the lifecycle of payments using a strict state machine.
Every payment begins in the `INITIATED` state. Allowed transitions are: `INITIATED` → `PROCESSING`, `PROCESSING` → `COMPLETED`, `PROCESSING` → `FAILED`, and `COMPLETED` → `REFUNDED`. The states `FAILED` and `REFUNDED` are terminal.
Any attempt to make an invalid transition (for example `INITIATED` → `COMPLETED`, or transitioning a terminal payment) must be rejected without modifying state. Operations on unknown `paymentId` values must also be rejected.
Implement the following methods:
- `createPayment(paymentId: str, amount: int) -> bool`: Create a new payment in the `INITIATED` state. Returns True on success, or False if a payment with the same id already exists.
- `transition(paymentId: str, toState: str) -> bool`: Attempt to move the payment to `toState`. Returns True if the transition is valid per the state machine, otherwise False (and state is unchanged).
- `getState(paymentId: str) -> str`: Return the current state of the payment, or the string `"UNKNOWN"` if no such payment exists.
- `countInState(state: str) -> int`: Return the number of payments currently in the given state.
Example 1, a payment that completes and is refunded:
```text
Input:
["PaymentProcessor", "createPayment", "transition", "transition", "getState", "transition", "countInState", "countInState"]
[[], ["p1", 100], ["p1", "PROCESSING"], ["p1", "COMPLETED"], ["p1"], ["p1", "REFUNDED"], ["REFUNDED"], ["INITIATED"]]
Output: [null, true, true, true, "COMPLETED", true, 1, 0]
Explanation:
pp = PaymentProcessor() # empty processor
pp.createPayment("p1", 100) # True (p1: INITIATED, amount=100)
pp.transition("p1", "PROCESSING") # True (p1: PROCESSING)
pp.transition("p1", "COMPLETED") # True (p1: COMPLETED)
pp.getState("p1") # "COMPLETED"
pp.transition("p1", "REFUNDED") # True (p1: REFUNDED, terminal)
pp.countInState("REFUNDED") # 1
pp.countInState("INITIATED") # 0
```
Example 2, rejected operations:
```text
Input:
["PaymentProcessor", "createPayment", "createPayment", "transition", "getState", "transition", "transition", "transition", "transition", "getState", "countInState", "countInState"]
[[], ["p1", 50], ["p1", 75], ["p1", "COMPLETED"], ["p1"], ["p1", "PROCESSING"], ["p1", "FAILED"], ["p1", "REFUNDED"], ["p9", "PROCESSING"], ["p9"], ["FAILED"], ["PROCESSING"]]
Output: [null, true, false, false, "INITIATED", true, true, false, false, "UNKNOWN", 1, 0]
Explanation:
pp = PaymentProcessor()
pp.createPayment("p1", 50) # True (p1: INITIATED)
pp.createPayment("p1", 75) # False (p1 already exists, nothing changes)
pp.transition("p1", "COMPLETED") # False (INITIATED cannot go straight to COMPLETED)
pp.getState("p1") # "INITIATED"
pp.transition("p1", "PROCESSING") # True (p1: PROCESSING)
pp.transition("p1", "FAILED") # True (p1: FAILED, terminal)
pp.transition("p1", "REFUNDED") # False (FAILED is terminal)
pp.transition("p9", "PROCESSING") # False (unknown payment)
pp.getState("p9") # "UNKNOWN"
pp.countInState("FAILED") # 1
pp.countInState("PROCESSING") # 0
```
Every rejected call leaves the stored state alone, so `p1` ends in `FAILED` and no payment is left in `PROCESSING`.
```hint Counting by state
Scanning every payment on each `countInState` call costs O(n). Think about which counts change, and by how much, when a payment is created or moves to a new state.
```
### Constraints & Assumptions
- `1 <= len(paymentId) <= 50`
- `1 <= amount <= 10^9`
- At most `10^4` total operations.
- State names are one of: `INITIATED`, `PROCESSING`, `COMPLETED`, `FAILED`, `REFUNDED`.
### Clarifying Questions to Ask
- Is a transition to the state a payment is already in (for example `PROCESSING` to `PROCESSING`) a valid no-op or a rejection?
- Is a refund always for the full amount, or can a payment be partly refunded?
- Can two callers transition the same payment at the same time, or are calls single-threaded?
- Do we only need the current state, or also a history of transitions?
### What a Strong Answer Covers
- How the allowed transitions are represented and checked, including the terminal states.
- Rejecting invalid transitions, unknown ids and duplicate creates with no change to stored state or counts.
- How `countInState` stays O(1) as payments are created and move between states.
- The time and space cost of each operation.
- How the design extends to new states, concurrent callers or an audit history.
### Follow-up Questions
- How would you add partial refunds, where several refunds can be issued until the full amount has been returned?
- Two workers call `transition` on the same payment at the same moment. How do you keep the state and the per-state counts consistent?
- How would you record each payment's transition history so you can answer when it failed or who refunded it?
- If the processor is backed by a database, how would you make `transition` safe for a client that retries a request after a timeout?
Overview: Implement a payment processor that moves each payment through a fixed lifecycle of states, rejects invalid transitions, terminal payments and unknown ids, and reports how many payments sit in each state. It tests modeling a state machine as data and keeping derived counts consistent on every operation.