Design an idempotent payment transaction state machine
Quick Overview
Design a class that moves payment transactions through initiated, processing, completed and failed states and treats client retries as idempotent. It tests state machine modeling, rejecting illegal transitions without side effects, and preventing double charges when calls are repeated.
Design an idempotent payment transaction state machine
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Implement a `TransactionStateMachine` class that tracks the lifecycle of payment transactions. Every transaction is in one of four states: `INITIATED`, `PROCESSING`, `COMPLETED` or `FAILED`.
Only three transitions are legal: `INITIATED -> PROCESSING`, `PROCESSING -> COMPLETED` and `PROCESSING -> FAILED`. Any invalid request, such as processing a transaction that does not exist or completing one that has already failed, must return `False` and leave the stored state unchanged.
The class must enforce idempotency. If a client retries `initiate` or `process` with the same `transactionId`, the system must not create a duplicate transaction or charge twice. Each transaction keeps the amount it was created with so a retried `initiate` can be checked against it, and clients poll the current state through `getState`.
Implement these methods:
- `initiate(transactionId: str, amount: int) -> bool` creates a new transaction in the `INITIATED` state and returns `True`. If a transaction with the same `transactionId` and the same `amount` already exists, it returns `True` and changes nothing. If the id exists with a different `amount`, it returns `False`.
- `process(transactionId: str) -> bool` moves the transaction from `INITIATED` to `PROCESSING`. It returns `True` if the move succeeds or the transaction is already `PROCESSING`, and `False` if the transaction does not exist or is in a terminal state.
- `complete(transactionId: str) -> bool` moves the transaction from `PROCESSING` to `COMPLETED`. It returns `True` if the move succeeds or the transaction is already `COMPLETED`, and `False` for invalid transitions or unknown transactions.
- `fail(transactionId: str) -> bool` moves the transaction from `PROCESSING` to `FAILED`. It returns `True` if the move succeeds or the transaction is already `FAILED`, and `False` for invalid transitions or unknown transactions.
- `getState(transactionId: str) -> str` returns the current state of the transaction as a string, or `"UNKNOWN"` if it does not exist.
Example 1 is a successful payment with a retry at each step:
```text
Input:
["TransactionStateMachine", "initiate", "initiate", "process", "process", "complete", "complete", "fail", "getState"]
[[], ["tx1", 100], ["tx1", 100], ["tx1"], ["tx1"], ["tx1"], ["tx1"], ["tx1"], ["tx1"]]
Output: [null, true, true, true, true, true, true, false, "COMPLETED"]
```
```text
sm = TransactionStateMachine() # empty state machine
sm.initiate("tx1", 100) # True new transaction, state INITIATED
sm.initiate("tx1", 100) # True idempotent retry, no double charge
sm.process("tx1") # True state PROCESSING
sm.process("tx1") # True idempotent, still PROCESSING
sm.complete("tx1") # True state COMPLETED
sm.complete("tx1") # True idempotent on the terminal state
sm.fail("tx1") # False a COMPLETED transaction cannot fail
sm.getState("tx1") # "COMPLETED"
```
Example 2 is a failed payment, a lookup of an id that never existed, and a retry with a conflicting amount:
```text
Input:
["TransactionStateMachine", "initiate", "process", "fail", "complete", "getState", "getState", "initiate"]
[[], ["tx2", 250], ["tx2"], ["tx2"], ["tx2"], ["tx2"], ["tx99"], ["tx2", 999]]
Output: [null, true, true, true, false, "FAILED", "UNKNOWN", false]
```
```text
sm = TransactionStateMachine() # empty state machine
sm.initiate("tx2", 250) # True new transaction, state INITIATED
sm.process("tx2") # True state PROCESSING
sm.fail("tx2") # True state FAILED
sm.complete("tx2") # False a FAILED transaction cannot complete
sm.getState("tx2") # "FAILED"
sm.getState("tx99") # "UNKNOWN", never initiated
sm.initiate("tx2", 999) # False the id exists with a different amount
```
```hint Shared shape
Compare `process`, `complete` and `fail` side by side. They differ only in which state they start from and which state they move to.
```
```hint Late retries
Trace a retried `initiate` that arrives after the transaction has already completed. Make sure nothing in your code can move it back to `INITIATED`.
```
### Constraints & Assumptions
- `1 <= len(transactionId) <= 64`, and `transactionId` consists of alphanumeric characters.
- `1 <= amount <= 10^9`.
- At most `10^5` operations are performed.
### Clarifying Questions to Ask
- Can two calls for the same transaction arrive at the same time, or can I assume calls are serialized?
- Does the state need to survive a process restart, or is an in-memory store enough here?
- Should a retried `initiate` compare only the amount, or also fields such as currency or payee?
- Are finished transactions ever removed, or does the machine keep every id forever?
### What a Strong Answer Covers
- A store keyed by `transactionId` that holds both the state and the original amount, with constant-time lookups.
- The correct return value for every method from every possible current state, including unknown ids and the two terminal states.
- Idempotent handling of retries, including a late `initiate` on a transaction that has already moved on.
- Rejected calls that leave the stored record untouched.
- Code that keeps the transition rules in one place, so adding a state is a small change.
### Follow-up Questions
- Two threads call `complete` and `fail` on the same `PROCESSING` transaction at once. How do you guarantee exactly one of them wins?
- How would you back this with a relational database so idempotency still holds across several application servers?
- Product wants a `REFUNDED` state reachable from `COMPLETED`. What changes, and what happens to a late retry of `complete`?
- The idempotency records grow without bound. How would you expire them safely?
Overview: Design a class that moves payment transactions through initiated, processing, completed and failed states and treats client retries as idempotent. It tests state machine modeling, rejecting illegal transitions without side effects, and preventing double charges when calls are repeated.
Implement a TransactionStateMachine class that tracks the lifecycle of payment transactions. Every transaction is in one of four states: INITIATED, PROCESSING, COMPLETED or FAILED.
Only three transitions are legal: INITIATED -> PROCESSING, PROCESSING -> COMPLETED and PROCESSING -> FAILED. Any invalid request, such as processing a transaction that does not exist or completing one that has already failed, must return False and leave the stored state unchanged.
The class must enforce idempotency. If a client retries initiate or process with the same transactionId, the system must not create a duplicate transaction or charge twice. Each transaction keeps the amount it was created with so a retried initiate can be checked against it, and clients poll the current state through getState.
Implement these methods:
initiate(transactionId: str, amount: int) -> bool
creates a new transaction in the
INITIATED
state and returns
True
. If a transaction with the same
transactionId
and the same
amount
already exists, it returns
True
and changes nothing. If the id exists with a different
amount
, it returns
False
.
process(transactionId: str) -> bool
moves the transaction from
INITIATED
to
PROCESSING
. It returns
True
if the move succeeds or the transaction is already
PROCESSING
, and
False
if the transaction does not exist or is in a terminal state.
complete(transactionId: str) -> bool
moves the transaction from
PROCESSING
to
COMPLETED
. It returns
True
if the move succeeds or the transaction is already
COMPLETED
, and
False
for invalid transitions or unknown transactions.
fail(transactionId: str) -> bool
moves the transaction from
PROCESSING
to
FAILED
. It returns
True
if the move succeeds or the transaction is already
FAILED
, and
False
for invalid transitions or unknown transactions.
getState(transactionId: str) -> str
returns the current state of the transaction as a string, or
"UNKNOWN"
if it does not exist.
Example 1 is a successful payment with a retry at each step:
sm = TransactionStateMachine() # empty state machine
sm.initiate("tx1", 100) # True new transaction, state INITIATED
sm.initiate("tx1", 100) # True idempotent retry, no double charge
sm.process("tx1") # True state PROCESSING
sm.process("tx1") # True idempotent, still PROCESSING
sm.complete("tx1") # True state COMPLETED
sm.complete("tx1") # True idempotent on the terminal state
sm.fail("tx1") # False a COMPLETED transaction cannot fail
sm.getState("tx1") # "COMPLETED"
Example 2 is a failed payment, a lookup of an id that never existed, and a retry with a conflicting amount:
sm = TransactionStateMachine() # empty state machine
sm.initiate("tx2", 250) # True new transaction, state INITIATED
sm.process("tx2") # True state PROCESSING
sm.fail("tx2") # True state FAILED
sm.complete("tx2") # False a FAILED transaction cannot complete
sm.getState("tx2") # "FAILED"
sm.getState("tx99") # "UNKNOWN", never initiated
sm.initiate("tx2", 999) # False the id exists with a different amount
Constraints & Assumptions
1 <= len(transactionId) <= 64
, and
transactionId
consists of alphanumeric characters.
1 <= amount <= 10^9
.
At most
10^5
operations are performed.
Clarifying Questions to Ask Guidance
Can two calls for the same transaction arrive at the same time, or can I assume calls are serialized?
Does the state need to survive a process restart, or is an in-memory store enough here?
Should a retried
initiate
compare only the amount, or also fields such as currency or payee?
Are finished transactions ever removed, or does the machine keep every id forever?
What a Strong Answer Covers Guidance
A store keyed by
transactionId
that holds both the state and the original amount, with constant-time lookups.
The correct return value for every method from every possible current state, including unknown ids and the two terminal states.
Idempotent handling of retries, including a late
initiate
on a transaction that has already moved on.
Rejected calls that leave the stored record untouched.
Code that keeps the transition rules in one place, so adding a state is a small change.
Follow-up Questions Guidance
Two threads call
complete
and
fail
on the same
PROCESSING
transaction at once. How do you guarantee exactly one of them wins?
How would you back this with a relational database so idempotency still holds across several application servers?
Product wants a
REFUNDED
state reachable from
COMPLETED
. What changes, and what happens to a late retry of
complete
?
The idempotency records grow without bound. How would you expire them safely?