Design a Pay Calculation API with Retries and Idempotency
System DesignModel answerLast updated
Design a resilient HTTP API for event ingestion and worker earnings computation, featuring idempotency keys, deterministic windowing, batch partial success, and retries.
You are designing an HTTP API for a gig-economy platform to compute worker earnings based on order event logs (such as order assignment, pickup, delivery, and cancellation).
Your design should fully specify the following requirements:
- API Endpoints: Design routes for ingesting event streams, submitting pay calculation jobs, and retrieving computed earnings.
- Schemas & Data Types: Specify request/response models, exact currency representations, timestamp standards, and rules for evaluating time-range boundaries.
- Idempotency Strategy: Detail how write operations and calculation requests avoid race conditions, handle duplicate client submissions, and process partial batch failures safely.
- Failure Recovery & Retry Behavior: Explain how clients and servers handle transient and permanent failures, backoff policies, HTTP status mappings, and non-retryable error conditions.
- Observability & Auditability: Define the logging, metrics, tracing, and metadata required to verify financial calculations reproducibly.
Assume this service operates in an internal microservices architecture, taking events from order management systems and producing figures consumed by financial reporting and payout backends.
Hints
Hint 1
Financial systems require strict auditability: always represent monetary values as integer minor units combined with explicit currency codes.
Hint 2
Differentiate between event-level idempotency (handled via natural unique event IDs) and operation-level idempotency (handled via header tokens).
Hint 3
Use half-open intervals [start, end) for time windows to avoid double-counting events on exact period boundaries.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements & Core Assumptions
Audience and Throughput Requirements
- Callers: Internal microservices. The Order Lifecycle service submits events; the Financial Settlement and Driver App backends request earnings computations. Authentication relies on mTLS and SPIFFE identity tokens.
- Scale Assumptions:
- ~10 million orders per day with ~6 status events per order = ~60 million events/day.
- Steady-state ingestion: ~700 events/sec; peak load: ~5,000 events/sec.
- ~1 million active gig workers. Pay queries spike significantly at weekly pay period closes.
- SLA Targets:
- Event batch ingestion p99 latency < 100 ms.
- Synchronous pay queries (time window $\le$ 7 days) p99 latency < 800 ms.
Financial & Operational Guarantees
- Datetimes must follow strict ISO 8601 / RFC 3339 formats in UTC.
- Currency amounts must be stored and transmitted using integer minor units (e.g., cents for USD) with ISO 4217 code identifiers to prevent floating-point rounding errors.
- Pay computations must be pure functions of the input events and the effective compensation ruleset version.
2. General Conventions
Datetimes and Time-Window Boundaries
- Format:
YYYY-MM-DDTHH:mm:ss.sssZ(e.g.,2024-11-01T08:15:30.120Z). - Validation Rule: Reject any timestamp string that lacks an explicit timezone designation with an HTTP
400 Bad Request. - Interval Semantics: Time ranges are evaluated over half-open intervals
[window_start, window_end). An event occurring precisely at2024-11-01T00:00:00.000Zfalls within[2024-11-01T00:00:00.000Z, 2024-11-08T00:00:00.000Z)and is excluded from[2024-10-25T00:00:00.000Z, 2024-11-01T00:00:00.000Z).
Monetary Field Representation
{
"amount": 2450,
"currency": "USD"
}
3. API Endpoint Specifications
A. Ingest Event Batch
- Route:
POST /v1/events:batch - Batch Size Limit: Up to 500 events per request payload. Exceeding requests return
413 Payload Too Large. - Request Format:
{
"events": [
{
"event_id": "evt_01JBMX1234567890",
"order_id": "ord_88123",
"worker_id": "wrk_9901",
"type": "PICKED_UP",
"occurred_at": "2024-11-01T08:15:30.120Z",
"attributes": {
"distance_meters": 3400,
"wait_duration_sec": 120
}
}
]
}
- Response Format (
200 OK- Partial Success Model):
{
"results": [
{ "event_id": "evt_01JBMX1234567890", "status": "CREATED" },
{ "event_id": "evt_01JBMX1234567891", "status": "DUPLICATE" },
{
"event_id": "evt_01JBMX1234567892",
"status": "REJECTED",
"error": {
"code": "INVALID_STATE_TRANSITION",
"message": "DELIVERED event received before PICKED_UP event",
"retryable": false
}
}
]
}
B. Request Pay Computation
- Route:
POST /v1/pay-computations - Header Required:
Idempotency-Key: <UUIDv4/ULID> - Request Format:
{
"worker_id": "wrk_9901",
"window_start": "2024-11-01T00:00:00.000Z",
"window_end": "2024-11-08T00:00:00.000Z",
"ruleset_version": "2024-v3"
}
- Responses:
- Synchronous (
201 Created): Short windows ($\le$ 7 days) execute in-flight and return the full calculation schema immediately. - Asynchronous (
202 Accepted): Large batch ranges (> 7 days) return{ "computation_id": "comp_01J...", "status": "PENDING" }and include aLocation: /v1/pay-computations/comp_01J...header.
- Synchronous (
C. Retrieve Pay Computation Result
- Route:
GET /v1/pay-computations/{computation_id} - Response Format (
200 OK):
{
"computation_id": "comp_01J...",
"worker_id": "wrk_9901",
"status": "SUCCEEDED",
"window_start": "2024-11-01T00:00:00.000Z",
"window_end": "2024-11-08T00:00:00.000Z",
"ruleset_version": "2024-v3",
"event_watermark": "2024-11-08T00:01:45.002Z",
"total": { "amount": 38450, "currency": "USD" },
"breakdown": [
{
"order_id": "ord_88123",
"base_pay": { "amount": 500, "currency": "USD" },
"distance_pay": { "amount": 350, "currency": "USD" },
"tip": { "amount": 400, "currency": "USD" }
}
],
"computed_at": "2024-11-08T01:00:00.000Z"
}
4. Idempotency & Data Storage Architecture
Client Service API Gateway / Pay Service Database Store
| | |
|--- POST /v1/pay-computations --------->| |
| (Idempotency-Key: K) |--- Begin Transaction ------------>|
| |--- Lock Key Record (K) --------->|
| |<-- Existing Key Status? ---------|
| | |
| [State: IN_PROGRESS] | |
|<-- 409 Conflict (Retry-After) ---------| |
| | |
| [State: COMPLETED] | |
|<-- Replayed 201/200 Cached Payload ----| |
| | |
| [Key Absent] |--- Insert K (IN_PROGRESS) ------->|
| |--- Compute Payout Logic -------->|
| |--- Commit Result & Update K ---->|
| | to COMPLETED in same TX |
|<-- 201 Created Payload ----------------| |
Event Ingestion Deduplication
Events leverage natural key deduplication on the unique event_id attribute:
INSERT INTO order_events (event_id, order_id, worker_id, type, occurred_at, payload_hash)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (event_id) DO UPDATE
SET received_at = order_events.received_at
RETURNING (order_events.payload_hash = EXCLUDED.payload_hash) AS hash_match;
If hash_match resolves to true, the service returns CREATED/DUPLICATE. If false, it flags an EVENT_ID_PAYLOAD_MISMATCH non-retryable error.
Idempotency Key Tracking Table
Stateful mutation requests use a dedicated tracking table in a relational backend:
| Column | Data Type | Purpose |
|---|---|---|
caller_id | String | Client microservice identity |
idempotency_key | String | Unique token provided in request header |
request_hash | String | SHA-256 fingerprint of payload body and request target |
status | Enum | IN_PROGRESS, COMPLETED |
response_code | Integer | Recorded HTTP status code |
response_body | JSONB | Cached JSON response structure |
expires_at | Timestamp | Expiration timestamp (retention horizon of 72 hours) |
Key State Workflow:
- Open database transaction: attempt to acquire or register
(caller_id, idempotency_key)with statusIN_PROGRESS. - Key Exists + Hash Mismatch: Roll back transaction; respond with
422 Unprocessable Entity(IDEMPOTENCY_KEY_MUTATED). - Key Exists + Status
COMPLETED: Roll back transaction; return storedresponse_codeandresponse_bodyimmediately with headerIdempotency-Replayed: true. - Key Exists + Status
IN_PROGRESS: Roll back transaction; return409 Conflictwith aRetry-After: 2header. - New Key Execution: Compute calculation, write earnings output, set status to
COMPLETED, and commit both record changes inside a single atomic transaction.
5. Retry Handling and Error Schema
Standard Error Body
All HTTP 4xx and 5xx responses must return a uniform structured error body:
{
"error": {
"code": "CONCURRENT_CALCULATION_IN_PROGRESS",
"message": "A pay calculation for worker wrk_9901 is currently running.",
"retryable": true,
"details": []
}
}
HTTP Status Mapping Matrix
| Status Code | Code String | Retryable? | Description |
|---|---|---|---|
400 Bad Request | INVALID_TIMESTAMP | No | Timestamp string lacks explicit UTC timezone marker (Z). |
409 Conflict | REQUEST_IN_PROGRESS | Yes | Matching operation running under the same idempotency key. |
413 Payload Too Large | BATCH_LIMIT_EXCEEDED | No | Submitted batch exceeds maximum allowable limit of 500 events. |
422 Unprocessable | IDEMPOTENCY_MUTATED | No | Idempotency key reused with a different request payload body. |
429 Too Many Requests | RATE_LIMIT_EXCEEDED | Yes | Rate limit reached; respect Retry-After header. |
500 Internal Server Error | INTERNAL_ERROR | Yes | Unexpected backend failure. Safe to retry due to backend idempotency protection. |
503 Service Unavailable | SERVICE_UNAVAILABLE | Yes | Temporary overload or network failure; apply exponential backoff. |
Client Retry Strategy
Clients must implement Full Jitter Exponential Backoff for all retryable operations: $$\text{Sleep Time} = \text{random}(0, , \min(\text{cap}, , \text{base} \times 2^{\text{attempt}}))$$
- Recommended Values: Base delay = 100 ms, Maximum Cap = 5 seconds, Maximum Attempts = 5.
6. Observability & Financial Auditability
- Trace Propagation: Every request must consume standard OpenTelemetry headers (
traceparent,tracestate) to link incoming HTTP requests to database queries and background queue tasks. - Auditability Metadata: Calculation outputs store an
event_watermarktimestamp representing the latestreceived_atevent included in the execution run. Recomputations for audit purposes verify that identical outputs are derived when restricting input events toreceived_at <= event_watermarkunder the specifiedruleset_version. - Core Metrics:
pay_api_events_ingested_total(labels:status=[created|duplicate|rejected]).pay_api_idempotency_hits_total(labels:status=[replayed|in_progress_conflict|mutated]).pay_api_calculation_latency_seconds(histogram by window duration and mode[sync|async]).