Design an Automated Order Exception & Dispute Resolution Service
System DesignModel answerLast updated
Design and implement a microservice that handles customer order disputes, applies explicit refund business rules, and prevents duplicate processing.
Design an order dispute microservice responsible for handling customer complaints regarding missing, damaged, or delayed deliveries. The service must determine appropriate resolution actions (such as full or partial refunds) based on explicit policies and guarantee idempotent, auditable operations.
Requirements & Context
- Dispute Types: Handle three main exception types:
- Complete Loss / Non-delivery: Item or entire delivery never arrived.
- Partial Loss / Missing Items: Only a subset of items from an order are damaged or missing.
- Delivery Delay: Order arrived late past an agreed SLA threshold.
- Policy Logic:
- Define explicit, configurable refund rules (e.g., total order cost refund for complete loss, item-level refund for partial loss, fixed percentage credit or shipping cost refund for delays).
- Ensure maximum refund limits: the cumulative refunded amount for any order can never exceed the original total charge.
- Idempotency & Auditing:
- Prevent double-refunding from duplicate or repeated customer dispute submissions.
- Maintain an immutable audit log of decisions made (inputs, applied policies, calculated amounts, and status changes).
- Execution Expectations:
- Structure the API endpoint schemas (JSON).
- Define data models for orders, disputes, and refund ledger entries.
- Detail the operational workflow, edge cases, and transition to a production environment.
Clarifying Questions to Consider
- How should multiple dispute reports for the same order be handled over time?
- What data must be present in the incoming payload versus fetched from upstream services (e.g., Order Service, Delivery Tracking)?
- Is payment gateway integration expected in this design, or just ledger/event emission?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architectural Overview
An effective Order Exception Service handles post-fulfillment customer issues while strictly enforcing financial safeguards and business policies. It sits between client applications (Customer Support UI, Mobile App) and underlying core systems (Order Service, Payment Gateway, Notification Service).
+-------------------+ +-------------------------+ +-------------------+
| Client / Mobile | ---> | Order Exception Service | ---> | Payment Gateway |
+-------------------+ +-------------------------+ +-------------------+
| |
v v
+----------+ +----------------------+
| Database | | Event Bus (Kafka) |
+----------+ +----------------------+
Data Models & Schemas
1. Core Database Entities
-
Order(Cached/Read Model)order_id(UUID, Primary Key)customer_id(UUID)total_amount_cents(Integer)shipping_fee_cents(Integer)status(Enum: DELIVERED, IN_TRANSIT, CANCELLED)delivered_at(Timestamp)
-
OrderItemitem_id(UUID, Primary Key)order_id(UUID, FK -> Order)price_cents(Integer)quantity(Integer)
-
DisputeClaimclaim_id(UUID, Primary Key)order_id(UUID, FK -> Order)idempotency_key(String, Unique Index)claim_type(Enum: COMPLETE_LOSS, PARTIAL_LOSS, DELAY)status(Enum: PENDING, APPROVED, REJECTED, PROCESSED)created_at(Timestamp)
-
RefundLedger(Immutable Audit Trail)refund_id(UUID, Primary Key)claim_id(UUID, FK -> DisputeClaim)order_id(UUID, FK -> Order)item_id(UUID, Nullable, FK -> OrderItem)amount_cents(Integer)reason_code(String)created_at(Timestamp)
API Specifications
Create Dispute Claim
POST /v1/disputes
Request Body:
{
"idempotency_key": "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d",
"order_id": "ord_10293847",
"claim_type": "PARTIAL_LOSS",
"reason": "Missing drink and damaged burger",
"affected_items": [
{ "item_id": "item_991", "quantity": 1 },
{ "item_id": "item_992", "quantity": 1 }
],
"delay_minutes": null
}
Response Body (200 OK / 201 Created):
{
"claim_id": "clm_550e8400",
"status": "APPROVED",
"refund_amount_cents": 1450,
"currency": "USD",
"policy_applied": "PARTIAL_LOSS_ITEMIZED_REFUND",
"breakdown": [
{ "item_id": "item_991", "refund_cents": 450 },
{ "item_id": "item_992", "refund_cents": 1000 }
]
}
Business Logic & Policy Engine Rules
-
Complete Loss Policy (
COMPLETE_LOSS)- Rule: If the order is confirmed lost or never arrived, refund
100%of order total (items + tax + shipping). - Calculation:
max_eligible = order.total_amount_cents - prior_refunds_sum refund_amount = min(order.total_amount_cents, max_eligible)
- Rule: If the order is confirmed lost or never arrived, refund
-
Partial Loss Policy (
PARTIAL_LOSS)- Rule: Refund exact line item costs for missing/damaged items plus proportional tax.
- Calculation: For each item $i$, calculate
item_refund = item_price * quantity. - Cap Check:
total_claim_refund = min(sum(item_refunds), remaining_order_balance)
-
Delay Policy (
DELAY)- Rule: If actual delivery time minus promised delivery time $> 30$ minutes, refund $100%$ of shipping fee + $15%$ credit of order value.
- Calculation: $$\text{Refund} = \text{shipping_fee_cents} + (0.15 \times \text{subtotal_cents})$$
- Cap Check: Must not exceed remaining un-refunded order balance.
Workflow & Invariant Checks
[Incoming Claim Request]
|
v
[ Check Idempotency Key ] ---> (If exists: Return prior response)
|
v
[ Fetch Order & History ] ---> Lock Order Row (DB SELECT FOR UPDATE)
|
v
[ Check System Invariant ] ---> Total Refunded + New Refund <= Original Total
|
v
[ Evaluate Business Rules ]
|
v
+-----------------------------+
| Write Refund Ledger Record |
| Update Order Refund Balance |
| Dispatch Payment API Call |
+-----------------------------+
|
v
[ Return Decision API ]
Production Edge Cases & Mitigation
| Edge Case | Impact | Solution |
|---|---|---|
| Concurrent Submissions | Two identical requests sent simultaneously could bypass total limit checks. | Execute claim evaluation inside a transactional DB block using SELECT FOR UPDATE on the target order row. |
| Partial Gateway Failure | Refund saved in DB but Payment Gateway call fails/times out. | Mark dispute status as PROCESSING. Use an asynchronous worker process (outbox pattern) to retry gateway transactions with guaranteed idempotency. |
| Fraud / Abuse Risk | Customer repeatedly claiming missing items across multiple orders. | Integrate a risk engine check before rule execution. Block auto-refunds if customer_refund_rate_30d > 20% and route to human review. |
| Late Delivery + Missing Item | Multiple dispute types for a single order. | Aggregate existing refunds across all prior claims for that order. Ensure strict enforcement: $\sum \text{Refunds} \le \text{OrderTotal}$. |
Summary of Trade-Offs
- Synchronous vs. Asynchronous Gateway Execution:
- Synchronous: Faster feedback for client, but tight coupling to gateway availability and increased API response latency.
- Asynchronous (Recommended for scale): High reliability and resiliency to third-party downstream outages; immediate response to user with a pending status.
- Deterministic Rules vs. Machine Learning Routing:
- Deterministic logic ensures 100% auditability and straightforward policy modifications, though complex edge cases (e.g., multi-condition fraud) require dedicated risk scoring layers.