Orchestrating a Durable Multi-Step Refund Process
System DesignModel answerLast updated
Design and implement a crash-resistant orchestrator that coordinates a refund across three HTTP services with idempotency, persistence, and retry logic.
You're building a refund orchestration system that coordinates three separate HTTP services. The orchestrator must ensure correctness even when services fail, time out, or the orchestrator itself crashes mid-execution.
Architecture
Three independent services communicate over HTTP:
Order Management (port 8001)
GET /orders/{order_id}returns{"order_id": string, "total_amount_cents": int, "refunded_amount_cents": int, "status": string}POST /orders/{order_id}/holdswith{"hold_id": string, "amount_cents": int}reserves a refund amount, returning{"hold_id": string, "status": "HELD"}or409if insufficient fundsPOST /orders/{order_id}/commit-holdwith{"hold_id": string}finalizes the reservation
Payment Processor (port 8002)
POST /payments/refundwith{"idempotency_key": string, "order_id": string, "amount_cents": int}processes the actual money movement- Uses the idempotency key to deduplicate: identical keys return the same result without re-executing
- May return
504timeouts or drop connections
Refund Orchestrator (port 8003) — your implementation
POST /refundswith{"refund_id": string, "order_id": string, "amount_cents": int}starts a workflow, returning202with statusGET /refunds/{refund_id}returns workflow state and progress through steps- Must execute: validation → hold funds → process payment → commit hold
All amounts are non-negative integers representing cents.
Requirements
Correctness: Concurrent refund requests must not allow refunded_amount_cents to exceed total_amount_cents. Duplicate refund_id values should return existing workflow state.
Durability: If the orchestrator crashes during execution and restarts, it must resume incomplete workflows from where they stopped, not restart from the beginning.
Retry resilience: When the payment service times out or returns ambiguous errors, the orchestrator must retry using the same idempotency key until receiving a definitive success or failure.
Example Flow
POST /refunds
{"refund_id": "rfnd_456", "order_id": "order_789", "amount_cents": 2500}
→ 202 {"refund_id": "rfnd_456", "status": "PROCESSING"}
// Internally executes:
// 1. GET order_789 to check available balance
// 2. POST hold with hold_id="hold_rfnd_456"
// 3. POST payment with idempotency_key="rfnd_456:payment"
// 4. POST commit for hold_rfnd_456
GET /refunds/rfnd_456
→ 200 {
"refund_id": "rfnd_456",
"status": "SUCCESS",
"steps": {
"validate": "COMPLETED",
"hold": "COMPLETED",
"payment": "COMPLETED",
"commit": "COMPLETED"
}
}
Design the orchestrator's architecture, state management, and error handling. Explain how your design ensures correctness under concurrency, crashes, and transient failures.
Hints
Hint 1
Think about what state must be persisted before making each HTTP call, and what happens if the process dies right after sending a request but before recording the response.
Hint 2
The order service's hold operation is your concurrency control mechanism—it's the only place where the 'check and reserve' happens atomically.
Hint 3
Each external call needs a stable, deterministic identifier derived from refund_id so that retries (including after crashes) use the exact same key and produce idempotent effects.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The orchestrator implements a persistent state machine where each refund moves through four stages, with progress durably recorded before and after each external operation. The core principle: write intent to disk, execute the side effect, then record completion—all with idempotent external calls.
State Management
Use SQLite (or similar) with WAL mode and full synchronous commits to persist:
refund_id(primary key)order_idandamount_cents(workflow parameters)status(PROCESSING, SUCCESS, FAILED)steps(JSON map: step_name → PENDING | IN_PROGRESS | COMPLETED | FAILED)error(failure reason if applicable)
Each workflow is inserted on POST /refunds with all steps initially PENDING. Before making any HTTP call, mark that step IN_PROGRESS. After a definitive response, mark it COMPLETED or FAILED.
Idempotency Strategy
Every external call must be safe to replay:
-
Hold: Use
hold_id = "hold_" + refund_id. If the orchestrator crashes after sending the hold request but before marking it complete, restarting will send the same hold_id again. The order service must treat duplicate hold_ids as idempotent. -
Payment: Use
idempotency_key = refund_id + ":payment". Every attempt—initial, retry after 504, replay after crash—uses the same key. The payment gateway deduplicates and returns the recorded outcome. -
Commit: Use the same hold_id. Committing a hold that's already committed should succeed idempotently.
-
Duplicate POST: Before inserting, try
INSERT OR IGNOREon refund_id. If already exists, verify parameters match; return existing state if so, 409 if parameters differ.
Concurrency Control
The validation step only provides early exit—it checks whether sufficient balance exists, but that balance can change immediately after. The real synchronization point is the hold operation.
The order service must implement holds as an atomic operation:
BEGIN TRANSACTION;
current_held = SUM(holds not yet committed)
IF refunded_amount + current_held + requested_amount > total_amount:
ROLLBACK; return 409
INSERT INTO holds (hold_id, amount) VALUES (...);
COMMIT;
This ensures two concurrent refunds cannot both reserve the same money. If one gets 200 and the other gets 409, the 409 workflow fails permanently—there's nothing to compensate since the hold was rejected.
Crash Recovery
On startup, scan for workflows with status = PROCESSING. For each, resume from the first step that isn't COMPLETED:
- If a step is IN_PROGRESS, we don't know if the HTTP call happened. Replay it—idempotency makes this safe.
- Execute remaining PENDING steps in order.
- Update status to SUCCESS or FAILED when done.
An in-memory set tracks which workflows are currently executing to prevent concurrent execution of the same refund_id.
Retry and Ambiguity Resolution
For each HTTP call, implement retry logic:
- Transient errors (504, 503, 502, 500, 429, 408, connection drops): retry with exponential backoff using the same idempotency key. The external service either didn't execute or will return the same result.
- Definitive failures (4xx other than 429): mark step as FAILED, stop workflow.
- Success (2xx): mark step COMPLETED, continue.
For the payment step specifically: if the gateway returns a "pending" status, poll with the same key until it resolves to success or failure.
The Point of No Return
Once the payment step succeeds, the workflow must complete. If the commit step fails (order service down, network issue), retry indefinitely rather than aborting. Why? The money has left the payment system. Releasing the hold would allow that money to be refunded again.
If you need to give up on commit retries eventually, the fallback is manual reconciliation: flag the workflow for human review and alert operations.
Step-by-Step Execution
-
Validate:
GET /orders/{order_id}. Check that status is refundable andtotal_amount_cents - refunded_amount_cents >= amount_cents. This is advisory only. If it fails, mark workflow FAILED. -
Hold:
POST /orders/{order_id}/holdswith deterministic hold_id. If 409, workflow FAILED (concurrent refund won). If 200, mark COMPLETED. -
Payment:
POST /payments/refundwith deterministic idempotency_key. Retry transient failures forever. If definitive failure, mark workflow FAILED and release the hold (compensating action). If success, mark COMPLETED. -
Commit:
POST /orders/{order_id}/commit-hold. Retry transient failures forever. On success, mark workflow SUCCESS.
Complexity
Time: O(1) database operations per step; wall-clock time dominated by network latency and retry backoff.
Space: O(W) where W is the number of workflows, storing workflow state and step progress.
Edge Cases
- Amount validation: Reject non-positive or non-integer amounts immediately with 400.
- Order not found: Fail at validation step.
- Concurrent holds exceeding balance: One succeeds, others get 409 at hold step and fail.
- Crash after payment sent, before recorded: Replay uses same idempotency_key; gateway returns recorded result.
- Duplicate POST during execution: Return existing workflow state without starting a second execution thread.
- Hold succeeds but payment fails: Release the hold (compensating transaction) before marking workflow FAILED.
Sample Implementation Outline (Python)
import sqlite3, json, time
import requests
from flask import Flask, request, jsonify
app = Flask(__name__)
db = sqlite3.connect("workflows.db", check_same_thread=False)
db.execute("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL")
db.execute("""CREATE TABLE IF NOT EXISTS refunds (
refund_id TEXT PRIMARY KEY,
order_id TEXT, amount_cents INT,
status TEXT, steps TEXT, error TEXT
)""")
def persist_step(refund_id, step, state):
wf = load_workflow(refund_id)
wf["steps"][step] = state
db.execute("UPDATE refunds SET steps=? WHERE refund_id=?",
(json.dumps(wf["steps"]), refund_id))
db.commit()
def retry_call(method, url, **kwargs):
"""Retry with exponential backoff on transient errors."""
delay, max_delay = 0.5, 30
while True:
try:
resp = requests.request(method, url, timeout=10, **kwargs)
if resp.status_code in {500, 502, 503, 504}:
time.sleep(delay)
delay = min(delay * 2, max_delay)
continue
return resp
except requests.RequestException:
time.sleep(delay)
delay = min(delay * 2, max_delay)
def execute_workflow(refund_id):
wf = load_workflow(refund_id)
# Step 1: Validate
if wf["steps"]["validate"] != "COMPLETED":
persist_step(refund_id, "validate", "IN_PROGRESS")
resp = retry_call("GET", f"http://localhost:8001/orders/{wf['order_id']}")
if resp.status_code != 200:
mark_failed(refund_id, "Order not found")
return
order = resp.json()
available = order["total_amount_cents"] - order["refunded_amount_cents"]
if available < wf["amount_cents"]:
mark_failed(refund_id, "Insufficient balance")
return
persist_step(refund_id, "validate", "COMPLETED")
# Step 2: Hold
if wf["steps"]["hold"] != "COMPLETED":
persist_step(refund_id, "hold", "IN_PROGRESS")
hold_id = f"hold_{refund_id}"
resp = retry_call("POST", f"http://localhost:8001/orders/{wf['order_id']}/holds",
json={"hold_id": hold_id, "amount_cents": wf["amount_cents"]})
if resp.status_code == 409:
mark_failed(refund_id, "Hold rejected - concurrent refund")
return
elif resp.status_code != 200:
mark_failed(refund_id, f"Hold failed: {resp.status_code}")
return
persist_step(refund_id, "hold", "COMPLETED")
# Step 3: Payment
if wf["steps"]["payment"] != "COMPLETED":
persist_step(refund_id, "payment", "IN_PROGRESS")
resp = retry_call("POST", "http://localhost:8002/payments/refund",
json={"idempotency_key": f"{refund_id}:payment",
"order_id": wf["order_id"],
"amount_cents": wf["amount_cents"]})
if resp.status_code != 200:
# Release hold before failing
retry_call("POST", f"http://localhost:8001/orders/{wf['order_id']}/release-hold",
json={"hold_id": f"hold_{refund_id}"})
mark_failed(refund_id, "Payment failed")
return
persist_step(refund_id, "payment", "COMPLETED")
# Step 4: Commit (point of no return - retry forever)
if wf["steps"]["commit"] != "COMPLETED":
persist_step(refund_id, "commit", "IN_PROGRESS")
resp = retry_call("POST", f"http://localhost:8001/orders/{wf['order_id']}/commit-hold",
json={"hold_id": f"hold_{refund_id}"})
if resp.status_code != 200:
# Log for manual intervention but keep retrying
pass
else:
persist_step(refund_id, "commit", "COMPLETED")
db.execute("UPDATE refunds SET status='SUCCESS' WHERE refund_id=?", (refund_id,))
db.commit()
@app.route("/refunds", methods=["POST"])
def create_refund():
data = request.json
refund_id = data["refund_id"]
# Idempotency check
existing = load_workflow(refund_id)
if existing:
return jsonify(existing), 200
# Insert new workflow
steps = {"validate": "PENDING", "hold": "PENDING",
"payment": "PENDING", "commit": "PENDING"}
db.execute("INSERT INTO refunds VALUES (?,?,?,?,?,?)",
(refund_id, data["order_id"], data["amount_cents"],
"PROCESSING", json.dumps(steps), None))
db.commit()
# Execute asynchronously
threading.Thread(target=execute_workflow, args=(refund_id,)).start()
return jsonify({"refund_id": refund_id, "status": "PROCESSING"}), 202
This design ensures exactly-once money movement through at-least-once execution with idempotent operations, durable state, and careful placement of the point of no return.