Design a Safe, Idempotent Auto-Approval Engine for Order Refunds
Data Structure DesignModel answerLast updated
Design and code a refund decision engine that applies pluggable rules, never refunds more than was paid, and handles retried or concurrent requests without paying twice.
Scenario
An e-commerce company wants refund requests against existing orders to be handled automatically, with no human involved in the normal case. For each request the system must decide:
- Whether to refund.
- How much to refund.
- Why it reached that decision.
It must then record the outcome so that the same money is never paid out twice.
You will work through this in a live, collaborative coding session of about 75 minutes. That includes setting up the project and a closing discussion. The requirements arrive in small increments, and finishing all of them is not expected. What matters is how you model the problem, which edge cases you raise, and how clearly you explain your choices while you write working code.
Given
- A refund request refers to an order and states what the customer wants back.
- Which conditions make a request automatically eligible is open. Part of your job is to ask about and settle them (order status, time since purchase or delivery, requested amount, stated reason, customer refund history, and so on).
- Two rules hold for every version of the system:
- Cap invariant: the total refunded for an order must never exceed the amount paid for it.
- Retry safety: submitting the same request again must not produce a second refund.
What to deliver
- A small domain model and a public API, for example
decide(request) -> Decisionand a way to record or execute the result. An in-memory implementation is fine unless you agree otherwise. - Eligibility logic that can grow as the requirements are extended.
- Every decision must carry an outcome (approved, rejected, or sent to manual review), an amount and a reason.
- A few quick tests for the rules and for the two invariants.
- A short verbal explanation of your trade-offs, including how you would handle concurrent requests for one order and a failing payment call.
State your assumptions before coding. Questions worth asking include:
- Are partial refunds allowed, by amount or by line item?
- Do shipping and tax come back with the items?
- Is a request that does not qualify rejected, or queued for review?
- Is the payout immediate or deferred?
- How is a retry identified?
Hints
Hint 1
Keep money out of floating point: use integer minor units (cents) or a decimal type, and compute the refundable amount as paid minus the sum of already-refunded amounts. Put this check in one function that every path goes through.
Hint 2
Model each eligibility rule as a small object or function that takes the request and order context and returns pass, fail or review plus a reason. A decision engine then runs the list in order, so a new requirement means adding a rule rather than editing existing ones.
Hint 3
For retries, require a client-supplied idempotency key and store the first result under it. Return that stored result for any repeat. For concurrency, make the 'check remaining balance, then write refund' step atomic per order, using a lock or a conditional database update.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify first (2-5 minutes)
Settle these assumptions out loud and write them down:
- Partial refunds by amount are supported. Line-item refunds can come later.
- Amounts are integers in minor units (cents) with a currency code.
- A request carries a client-generated
request_id, which serves as the idempotency key. - Requests that do not qualify automatically go to manual review if they are borderline (for example, over an amount threshold) and are rejected if they are clearly invalid (for example, order never paid).
- In-memory storage behind an interface, so a database can replace it later.
2. Domain model
Order: id, customer id, status (paid, shipped, delivered, cancelled), paid amount, purchase and delivery timestamps.RefundRequest: request id, order id, requested amount, reason, submitted time.Decision: outcome (APPROVED,REJECTED,REVIEW), approved amount, list of reason codes.RefundRecord: the ledger entry created only on approval and execution, holding request id, order id, amount and state (PENDING,COMPLETED,FAILED).
The key design choice is that refunded-so-far is derived from the ledger, not stored as a free-floating counter that can drift.
3. Pluggable rules
Each rule has one job:
class Rule(Protocol):
def evaluate(self, ctx) -> RuleResult: ... # PASS, REJECT(reason), REVIEW(reason), optional amount cap
Example rules: OrderIsRefundableStatus, WithinReturnWindow(days=30), AmountWithinAutoLimit(limit), CustomerRefundHistory(max_recent=3).
The engine combines results with a clear precedence: any REJECT wins, then any REVIEW, otherwise approve. It collects all reasons rather than stopping at the first, which helps support staff and tests. Rules may also lower the approved amount, for example by capping it at the remaining balance.
Adding a follow-on requirement (say, "non-returnable items") is one new class and one line in the rule list. Earlier rules and tests stay untouched.
4. Enforcing the cap in one place
def refundable(order, ledger):
return order.paid - sum(r.amount for r in ledger.for_order(order.id)
if r.state in (PENDING, COMPLETED))
Count PENDING entries too, otherwise two in-flight refunds can together exceed the cap. The engine clamps or rejects a request based on this value. If the request asks for more than is refundable, choose a policy and state it: reject, or approve the remainder. Rejecting is simpler and safer by default.
5. Idempotency
- On arrival, look up
request_id. - If a stored result exists, return it unchanged. Do not re-evaluate, because rules that depend on time or history could give a different answer on a retry.
- Otherwise evaluate, then save the decision and the ledger entry together under the key.
If the same key arrives with a different payload (different amount or order), return an error rather than silently reusing the old result.
If no client key exists, fall back to a derived key such as (order_id, amount, reason) within a time window. State that this is weaker, because two genuine identical refunds would be conflated.
6. Concurrency
Two simultaneous requests could both read the same remaining balance and both be approved. Options:
- In-process: a lock per order id around "compute refundable, then append to ledger".
- Database: a transaction with
SELECT ... FOR UPDATEon the order, or an optimistic version column on the order and a retry on conflict. - A unique constraint on
request_idmakes duplicate inserts fail safely even if the application check races.
7. Payment failures
Write the ledger entry as PENDING before calling the payment provider, and pass the request_id as the provider's own idempotency key. On success, mark it COMPLETED. On a definite failure, mark it FAILED, which frees the balance. On a timeout (unknown outcome), leave it PENDING and reconcile later by asking the provider. Never assume failure on a timeout, since that could cause a double payout on retry.
8. Edge cases to raise
- Zero or negative amounts.
- Orders that are unpaid, cancelled or already fully refunded.
- Currency mismatch.
- Several partial refunds that sum exactly to the paid amount (the last should pass, the next should fail).
- Requests exactly on the time-window boundary (decide inclusive or exclusive and test it).
- Clock source: use an injected clock so tests are deterministic.
9. Tests
- Each rule alone, with pass and fail cases.
- Over-refund: paid 100, refund 60, then request 50, expect rejection (or a 40 cap per policy).
- Retry: same
request_idtwice gives one ledger entry and identical results. - Concurrency: run many threads against one order and assert the total never exceeds the paid amount.
10. Complexity and trade-offs
Each decision costs O(R + L), where R is the number of rules and L is the number of ledger entries for the order, and that is small in practice. An aggregate maintained in a transaction would make it O(R).
The main trade-off is flexibility against simplicity. A rule list is easy to extend but needs explicit precedence. A full rules DSL is overkill for a 75-minute session.
Common mistakes
- Using floats for money.
- Checking the cap in several places, so they drift apart.
- Re-evaluating on retry instead of returning the stored result.
- Ignoring in-flight refunds when computing the remaining balance.
- Returning only "denied" with no reason.
- Building everything at once instead of keeping a working, tested increment at each step.