Advanced REST API design: async exports, Idempotency-Key and API documentation
Senior-level REST API design, part 2: exporting a 500 MB file with an async job (polling, signed webhooks, presigned URLs), stopping duplicate payments with an Idempotency-Key, a response envelope with 6-digit error codes, and writing API docs plus an API map.
On this page
1. The problem
An admin clicks "Export to Excel": a 500 MB file that takes 4 minutes. The gateway cuts off at 60 seconds (504) while the server keeps going; the admin clicks again, creating a second job, and the pod runs out of memory. The same week, POST /payments charges the card, the network drops, the client retries, gets "Duplicated!" and reports failure.
2. Key idea
An async job is a laundry: hand in your clothes, get a ticket (202 + Location), come back and ask with the ticket. The Idempotency-Key is the ticket number: hand in the same ticket and you get the same bag back, not a second wash.
| Step | Request | Response |
|---|---|---|
| 1 | POST /v1/exports (never GET) |
202 Accepted, Location: /v1/jobs/001 |
| 2 | GET /v1/jobs/001 |
PROCESSING + progress + Retry-After, then DONE or FAILED |
| 3 | GET /v1/jobs/001/result |
303 to a presigned URL valid 15 minutes; 410 once expired |
Workers read and write as streams and upload multipart straight to object storage: the file never passes through the app server. If a worker dies, a locked_until lease + SKIP LOCKED lets another pick the job up. Cap jobs per user and return 429 beyond it.
| How to signal completion | Use when | Don't use when |
|---|---|---|
Polling (GET + Retry-After) |
the default: imports/exports, any client | thousands of clients need instant progress |
| An HMAC-signed webhook | B2B partners, payments | clients behind firewalls with no public URL |
Webhooks sign HMAC-SHA256(secret, timestamp + "." + rawBody); receivers reject old timestamps and dedupe by event_id.
2.1 Idempotency-Key done right
| Question | Approach |
|---|---|
| What does a retry get? | the original response, unchanged, not "Duplicated!" |
| Same key, different body? | store a body hash; different means 422 |
| Two requests at once? | the second waits on the unique index, or gets 409 |
| Which outcomes are stored? | 400s aren't; settled outcomes (insufficient funds) are; infrastructure errors roll back the key too |
3. In Java
@Transactional
public ResponseEntity<PaymentResponse> pay(String clientId, String key, PaymentRequest req) {
String bodyHash = sha256(canonicalJson(req));
// INSERT ... ON CONFLICT (client_id, key) DO NOTHING: returns 0 if the key exists
if (keys.insertIfAbsent(clientId, key, bodyHash) == 0) {
IdemRecord r = keys.find(clientId, key).orElseThrow();
if (!r.bodyHash().equals(bodyHash)) throw new ApiException(422, "IDEMPOTENCY_KEY_REUSED");
if (r.inProgress()) throw new ApiException(409, "REQUEST_IN_PROGRESS");
return r.storedResponse(); // the original response
}
PaymentResponse res = payments.execute(req); // charge, same transaction
keys.complete(clientId, key, 201, res);
return ResponseEntity.status(201).body(res);
}Two requests with the same key in parallel: the second insert waits on the unique index until the first commits, then returns 0 and reads the stored response. Catching DataIntegrityViolationException instead of using ON CONFLICT leaves the transaction aborted on PostgreSQL, so you can't read afterwards.
Streaming exports, 6-digit error codes and API docs
- Streaming from the DB: PostgreSQL only uses a server-side cursor with
autoCommit=falseandfetchSize > 0; MySQL Connector/J needsuseCursorFetch=true. A Spring DataStream<T>must run in a transaction anddetacheach entity. For Excel useSXSSFWorkbook, or export CSV. - Default timeouts: Nginx
proxy_read_timeout60 seconds, AWS ALB idle timeout 60 seconds, Cloudflare about 100 seconds. - An envelope of
meta+datagives every response the same shape; 6-digit codes only help when the first 3 digits always equal the real HTTP status (422001for insufficient funds). Documenting "Status 401" for code400001makes clients log users out by mistake. New systems can use Problem Details (RFC 9457) for errors. - Who generates the key: the client (a UUID per operation) is the most accurate; the server deriving it from content blocks two legitimate identical transactions; the server issuing one first (
checkout_id) is safest at the cost of a round trip. - Documenting an endpoint: purpose, request (required headers, fields, constraints), response, an error-code table, a runnable cURL.
4. Working with AI
Delegate to AI: OpenAPI for the job API, the export worker, the idempotency_keys table and filter, webhook signing/verification code with tests.
Check yourself:
- Jobs are created with
POST;GEThas no side effects. - Workers don't
findAll(); there's a fetch size and streamed upload. - A retry with the same key gets the original response; a different body gets
422; in progress gets409. - Webhooks are signed over the raw body with a timestamp; receivers dedupe by
event_id.
5. Exercises
Exercise 1: Review an AI-written export endpoint
AI wrote @GetMapping("/products/jobs/export") ResponseEntity<byte[]> export(@RequestParam String name) calling repo.findAll(spec), building an XSSFWorkbook and returning byte[]. Description: "simple, works fine on test data". List the bugs and redesign it.
Solution to Exercise 1
- A
GETwith heavy side effects: crawlers, prefetch, link previews and proxy retries all rerun the export. - Synchronous: beyond 60 seconds it's a
504while the server keeps working; a thread and a DB connection are held for minutes. findAll+XSSFWorkbook+byte[]: results, workbook and file all live in the heap: OOM at 500 MB.- Redesign:
POST /v1/exports(with an Idempotency-Key) →202+Location; the worker streams from the DB (fetch size) throughSXSSFWorkbook/CSV and uploads multipart to object storage;GET /v1/jobs/{id}withRetry-After;GET /result→303presigned URL,410when expired; per-user job limits.
Exercise 2: Read the "payment failed but money was taken" incident
Complaints: the app says "payment failed" yet the bank charged the card. Logs: the first request returned 201 after 9 seconds (the client times out at 8); the retry with the same Idempotency-Key got 409 Duplicated!, which the app treated as an error. Diagnose and fix.
Solution to Exercise 2
- Diagnosis: the server blocks the duplicate correctly but returns an error instead of the result: the retry must get the original response (
201+ the payment). The client reads409as failure. - Server fix: store the response with the key; retries after completion get the same
201; return409only while the first request is still running, withRetry-After. - Client fix: on
409 REQUEST_IN_PROGRESS, wait and retry with the same key rather than reporting failure; raise the client timeout or move slow payments to an async job. - Reconciliation: query keys with a stored
201that the app recorded as failed, and contact those customers.
Summary
- Work longer than the gateway timeout becomes a job:
POST→202+Location→ poll. - Workers read and write as streams; files go through presigned URLs.
- Webhooks are HMAC-signed over raw body + timestamp; keep the status API.
- The Idempotency-Key returns the original response; a different body is
422, in progress is409. - Never create jobs with
GET.
Practice interview questions on this topic
- How do you design an API for long-running work like exporting a file of several hundred MB?
- When do you stream an LLM answer over SSE, and when do you make it an async job?
- When do you use GET, POST, PUT, PATCH and DELETE?
- How do you let clients retry an order-creating POST without creating duplicates (idempotency key)?
- How do you design error responses for a multi-service system, and why not return stack traces to clients?
Comments
Community rules