Design a Resilient Order Refund Workflow Engine
System DesignModel answerLast updated
Design an idempotent, durable DAG workflow execution system for processing order refunds, handling step dependencies, crash recovery, manual reviews, and financial consistency.
Processing refunds in an e-commerce or food delivery platform involves multiple interdependent steps across different services: verifying balances, executing payment gateway refunds, updating account credits, clawing back partner payouts, re-evaluating driver/worker compensation, updating fraud risk models, and notifying users.
Some tasks can execute in parallel (such as sending customer emails and notifying internal operations teams), while others must run strictly in sequence (such as checking available balances before issuing a gateway refund). Furthermore, step failures may require human manual review or compensation steps.
Design a durable workflow engine that executes refund requests modeled as a Directed Acyclic Graph (DAG).
Requirements
Functional Requirements
- DAG Execution & Dependency Tracking: Execute nodes according to explicit dependencies. Independent steps run concurrently; dependent steps wait for all parent steps to succeed.
- Financial Balance & Idempotency: Support partial line-item refunds while ensuring the total refunded amount never exceeds the original charge. Prevent double-refunding across concurrent API requests.
- Fault Tolerance & Crash Recovery: If worker nodes fail mid-task or orchestrators crash, the system must resume from the last known state without executing duplicate financial operations.
- Human-in-the-Loop: Support pausing workflows when triggered by risk rules (e.g., high fraud scores) and resuming them asynchronously via external events or admin actions.
- Observability: Expose status querying for ongoing, paused, and completed refund requests.
Non-Functional Requirements & System Scale
- Throughput: 10 million completed orders per day with a 3% refund rate (~300,000 refund workflows per day, averaging ~3.5 workflows/second and peaking at ~30 workflows/second).
- Correctness: Zero tolerance for double-payouts, lost state transitions, or invalid financial balances.
- Latency: Fully automated paths should complete execution within 3 seconds (excluding external payment processor latencies).
System Design Deliverables
- Data Architecture & Schema: Define models for workflow definitions, runtime execution states, task dependencies, and financial idempotency tracking.
- System Architecture: Detail the interactions between the orchestrator service, database, task queues, and execution workers.
- Idempotency & Resilience: Explain how the system handles transient worker failures, network timeouts, duplicate messaging, and worker crash recovery.
- Concurrency Control: Explain how race conditions are prevented when multiple refund requests target the same order simultaneously.
Hints
Hint 1
Calculate scale upfront: 30 requests/second at peak means the core challenge is consistency and state resilience, not raw volume.
Hint 2
Consider how step state transitions and event notifications can be made transactional using patterns like the Transactional Outbox.
Hint 3
Distinguish between external API retry keys and logical execution step keys to avoid duplicate chargebacks during network timeouts.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scale & Back-of-the-Envelope Calculations
System Load
- Daily Volume: $300,000$ refund workflows / day.
- Average Rate: $\approx 3.5$ workflows / sec.
- Peak Rate: $\approx 30$ workflows / sec.
- Graph Complexity: Assume an average refund DAG consists of $8$ steps (Validate $\rightarrow$ Reserve Balance $\rightarrow$ Fraud Check $\rightarrow$ Gateway Refund $\rightarrow$ Ledger Credit $\rightarrow$ Merchant Clawback $\rightarrow$ Driver Adjustment $\rightarrow$ Customer Notification).
- Task Throughput at Peak: $30 \text{ workflows/s} \times 8 \text{ tasks/workflow} = 240 \text{ tasks/sec}$.
- Database Load at Peak: Roughly 3–4 state transitions per task (Enqueued, Started, Completed/Failed) yielding $\approx 750 \text{ to } 1,000 \text{ write operations/sec}$.
Takeaway
The system is not bottlenecked by raw throughput or massive storage. A single primary SQL database (or a small sharded cluster) can easily accommodate 1,000 writes/second. The primary engineering challenge lies in strict financial correctness, idempotent side-effects, and fault recovery.
2. API Design
Create Refund Workflow
POST /v1/refunds
Header: X-Idempotency-Key: <client_request_uuid>
Payload:
{
"order_id": "ord_99812",
"reason": "missing_items",
"line_items": [
{ "line_item_id": "item_401", "refund_amount": 12.50 }
]
}
Response (202 Accepted):
{
"workflow_id": "wf_77210",
"status": "RUNNING",
"created_at": "2023-10-25T14:30:00Z"
}
Fetch Workflow Details
GET /v1/refunds/{workflow_id}
Response (200 OK):
{
"workflow_id": "wf_77210",
"order_id": "ord_99812",
"status": "WAITING_FOR_SIGNAL",
"nodes": {
"validate_balance": "SUCCEEDED",
"fraud_eval": "PAUSED_MANUAL_REVIEW",
"gateway_refund": "PENDING"
}
}
Resume Paused Workflow (Human-in-the-Loop)
POST /v1/refunds/{workflow_id}/signal
Payload:
{
"signal_name": "MANUAL_REVIEW_DECISION",
"payload": {
"approved": true,
"reviewer_id": "usr_admin_42"
}
}
Response (200 OK):
{
"workflow_id": "wf_77210",
"status": "RUNNING"
}
3. Data Schema & State Management
A relational store (e.g., PostgreSQL sharded by order_id) provides ACID guarantees essential for financial operations.
-- Represents static DAG step topology and ordering logic
CREATE TABLE workflow_definition (
definition_id VARCHAR(64) PRIMARY KEY,
version INT NOT NULL,
graph_json JSONB NOT NULL, -- Nodes, edges, and dependencies
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
UNIQUE(definition_id, version)
);
-- Tracks execution of an overall workflow instance
CREATE TABLE workflow_instance (
workflow_id VARCHAR(64) PRIMARY KEY,
idempotency_key VARCHAR(128) UNIQUE NOT NULL,
order_id VARCHAR(64) NOT NULL,
definition_id VARCHAR(64) NOT NULL,
definition_version INT NOT NULL,
status VARCHAR(32) NOT NULL, -- RUNNING, WAITING_SIGNAL, SUCCEEDED, FAILED, COMPENSATING
context JSONB NOT NULL, -- Execution inputs and cumulative outputs
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_wf_order ON workflow_instance(order_id);
-- Individual DAG node state
CREATE TABLE node_execution (
workflow_id VARCHAR(64) REFERENCES workflow_instance(workflow_id),
node_id VARCHAR(64) NOT NULL,
state VARCHAR(32) NOT NULL, -- PENDING, READY, RUNNING, SUCCEEDED, FAILED, WAITING_SIGNAL
unmet_dependencies_count INT NOT NULL, -- Incremental counter for fast dependency check
attempt_count INT DEFAULT 0,
worker_lease_id VARCHAR(64),
lease_expires_at TIMESTAMP WITH TIME ZONE,
output JSONB,
PRIMARY KEY (workflow_id, node_id)
);
-- Financial balance tracking table to guarantee balance constraints
CREATE TABLE refund_ledger (
order_id VARCHAR(64) NOT NULL,
line_item_id VARCHAR(64) NOT NULL,
original_charge_cents BIGINT NOT NULL,
refunded_cents BIGINT NOT NULL DEFAULT 0,
reserved_cents BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY (order_id, line_item_id)
);
-- External side-effect idempotency log
CREATE TABLE external_execution_log (
idempotency_key VARCHAR(128) PRIMARY KEY,
workflow_id VARCHAR(64) NOT NULL,
node_id VARCHAR(64) NOT NULL,
request_payload JSONB,
response_payload JSONB,
status VARCHAR(32) NOT NULL -- PENDING, COMPLETED, HARD_DECLINE
);
-- Transactional Outbox table for reliable messaging
CREATE TABLE transactional_outbox (
outbox_id BIGSERIAL PRIMARY KEY,
topic VARCHAR(128) NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
4. System Architecture
┌─────────────────────────────────────────┐
│ Relational DB │
│ (State Store + Ledger + DB Outbox) │
└────────────────────┬────────────────────┘
│ Transactional Read/Write
▼
┌──────────────┐ HTTP POST ┌─────────────────────────────────────────┐
│ API Client ├──────────────►│ Orchestrator Service │
└──────────────┘ └────────────────────┬────────────────────┘
│ Enqueue Outbox Rows
▼
┌─────────────────────────────────────────┐
│ Outbox Publisher │
└────────────────────┬────────────────────┘
│ Publish Message
▼
┌─────────────────────────────────────────┐
│ Task Queue (RabbitMQ / SQS) │
└────────────────────┬────────────────────┘
│ Consume Tasks
▼
┌─────────────────────────────────────────┐
│ Stateless Workers │
│ (Payment GW, Ledger, Email, Risk, etc.) │
└─────────────────────────────────────────┘
Orchestration Execution Flow
- Client Ingestion: Client issues a refund request with a unique
X-Idempotency-Key. - Transaction Initialization: The Orchestrator creates a
workflow_instanceentry. Within the same DB transaction:- Evaluates node dependencies and sets
unmet_dependencies_countfor each node execution row. - Sets root nodes (0 parent dependencies) to status
READY. - Emits messages for
READYtasks into thetransactional_outbox.
- Evaluates node dependencies and sets
- Outbox Publisher Relay: A dedicated process reads from
transactional_outbox, publishes tasks to the Message Queue, and deletes/marks outbox rows as sent. - Worker Execution: Workers pull tasks matching their capability (e.g., Payment Worker pulls Payment tasks).
- State Transition: Upon task completion, the worker calls back the Orchestrator API (
POST /v1/tasks/complete). The Orchestrator processes the completion in a DB transaction:- Marks current node
SUCCEEDED. - Decrements
unmet_dependencies_countfor all child nodes. - Moves child nodes with
unmet_dependencies_count = 0toREADYstate and inserts task execution events intotransactional_outbox.
- Marks current node
5. Reliability, Idempotency & Concurrency
A. Race Conditions & Double Refunding
When multiple requests for the same order arrive concurrently:
- We rely on database row locking at balance reservation time.
- To execute a partial or full refund safely:
BEGIN;
-- Lock ledger rows for the order
SELECT line_item_id, original_charge_cents, refunded_cents, reserved_cents
FROM refund_ledger
WHERE order_id = 'ord_99812'
FOR UPDATE;
-- Validate requested refund against limits:
-- (refunded_cents + reserved_cents + requested_cents) <= original_charge_cents
-- Update reservation
UPDATE refund_ledger
SET reserved_cents = reserved_cents + :requested_cents
WHERE order_id = 'ord_99812' AND line_item_id = 'item_401';
-- Create workflow and initial task outbox items within the exact same transaction
INSERT INTO workflow_instance (...) VALUES (...);
INSERT INTO transactional_outbox (...) VALUES (...);
COMMIT;
If the workflow succeeds, reserved_cents is subtracted and added to refunded_cents. If it fails or is rejected, reserved_cents is subtracted back out.
B. Dynamic Idempotency Keys for External Systems
Retrying external calls (e.g., Stripe, Adyen) after network failures poses a risk of duplicate execution.
- Incorrect Key Strategy:
hash(workflow_id, node_id, attempt_count). If attempt 1 succeeds at the payment gateway but the HTTP response times out, attempt 2 uses a new key, triggering a double chargeback. - Correct Key Strategy:
hash(workflow_id, node_id). The key must remain stable across worker retries for the identical logical execution unit.
Worker Execution Sequence:
1. Check external_execution_log for existing key: hash(workflow_id, node_id).
2. If status == 'COMPLETED', return recorded response output immediately.
3. If status == 'PENDING', query external gateway using the key to verify status.
4. If not executed, initiate external API call passing idempotency_key = hash(workflow_id, node_id).
5. Save response output to external_execution_log and complete task.
C. Worker Crashes & Deadlock Prevention (Fencing Leases)
When a worker claims a task, it acquires a timed lease:
UPDATE node_execution
SET state = 'RUNNING',
worker_lease_id = :worker_id,
lease_expires_at = NOW() + INTERVAL '30 seconds',
attempt_count = attempt_count + 1
WHERE workflow_id = :wf_id
AND node_id = :node_id
AND (state = 'READY' OR (state = 'RUNNING' AND lease_expires_at < NOW()));
- Zombie Worker Protection (Fencing): When a worker finishes, its update specifies its lease token and attempt count:
UPDATE node_execution
SET state = 'SUCCEEDED', output = :output
WHERE workflow_id = :wf_id
AND node_id = :node_id
AND worker_lease_id = :worker_id
AND attempt_count = :attempt_count;
If a worker gets stuck in a Garbage Collection pause and loses its lease, another worker will re-claim the task. When the late worker resumes and attempts to write, the update matches 0 rows and is safely discarded.
6. Human-in-the-Loop & Fraud Workflow Pausing
If a fraud assessment task calculates a high risk score:
- The fraud task node outputs state
WAITING_SIGNAL. - The orchestrator transitions the overall workflow status to
WAITING_FOR_SIGNAL. - Dependent tasks (e.g.,
gateway_refund) remain inPENDINGstate withunmet_dependencies_count > 0. - A signal is sent by an admin or external fraud subsystem via
POST /v1/refunds/{id}/signal. - The orchestrator receives the decision in an ACID transaction:
- If APPROVED: Marks the fraud evaluation step as
SUCCEEDED, decrements downstream node counters, and dispatches downstream tasks. - If REJECTED: Marks the workflow as
FAILED, frees any heldreserved_centsbalance inrefund_ledger, and enqueues any required compensation steps.
- If APPROVED: Marks the fraud evaluation step as
7. Common Pitfalls & Anti-Patterns
- Using In-Memory Orchestration Engines: Holding DAG step states in application memory (e.g., standard Go channels or in-memory queues) leads to lost workflows on pod deployments or crashes.
- Distributed Locks for Balance Checking: Using Redis distributed locks (
Redlock) to protect balance checks instead of transactional row-level SQL locking (FOR UPDATE). Redis lock TTL expiration during network blips can lead to concurrency race conditions. - Non-Transactional Message Publishing: Publishing a message to Kafka/SQS before or after committing state to DB. If the app crashes between the operations, state either drifts or gets lost. The Transactional Outbox pattern guarantees eventual consistency between DB state and task dispatch.