Summary

EN: A practical guide to designing RESTful APIs for long-running asynchronous operations. The core pattern: accept a task with POST → return 202 Accepted with a Location header pointing to a status resource → client polls that resource for progress → returns completion with result link or embedded result. Also covers task cancellation via HTTP DELETE and alternatives (WebSocket, SSE, Kafka) for push-based notification.

ZH: 本文介紹如何為長時間執行的非同步操作設計 RESTful API:以 POST 建立任務並回傳 202 Accepted(附 Location header 指向狀態資源)→ 客戶端輪詢該資源查詢進度 → 完成後回傳結果連結或內嵌結果。同時涵蓋透過 HTTP DELETE 取消任務,以及 WebSocket/SSE/Kafka 的推播通知替代方案。

Key Points

  • 202 Accepted: the correct status code for accepted-but-not-complete operations (per RFC-9110)
  • Location header: always include in 202 response, pointing to the status polling endpoint
  • Task status resource: GET /api/tasks/{id} returns status (pending/in-progress/completed/failed) + progress percentage
  • Cancellation: HTTP DELETE on the task URL; idempotent operation
  • Result delivery: either embed in final status response or provide a separate result URL
  • Alternative push patterns: WebSocket for browser clients; Kafka for server-to-server; SSE for unidirectional server push
  • Best practice: include Retry-After header to guide polling intervals

Insights

  • The pattern turns a synchronous problem into an asynchronous one without requiring the client to maintain a persistent connection
  • DELETE for cancellation is semantically correct (destroying the in-flight task resource) and idempotent — calling it twice is safe
  • The separation of “task status” from “task result” allows lightweight polling without transmitting large result payloads repeatedly

Connections

  • Directly applicable to any API that wraps ML inference, batch processing, or external service calls (e.g., the analyze-vault pipeline)
  • Connects to rainbow deploys: both separate “starting something” from “knowing it’s done”
  • The Kafka alternative connects to the service mesh vs API gateway article — async messaging vs synchronous HTTP calls is a recurring architectural choice

Raw Excerpt

“Return HTTP 202 Accepted with a Location header pointing to a status endpoint. The client polls that URL for progress. Once the task completes, the status endpoint returns the result or a link to it. Never make the client wait on an open HTTP connection for something that might take minutes.”