Video in progress

Staff 🌱 Spring

How do you design an API for an operation that takes several minutes (a big report, a bulk import)?

I don't hold the request synchronously: the endpoint accepts the work and returns 202 Accepted with the address of a job resource, background workers do the work, and the client polls for status or is notified by webhook/SSE. I design idempotency, cancellation, result storage and quotas up front.

📖 Answer

Why the synchronous version is bad: load balancers and proxies often cut the connection at 60 seconds, the request dies during a deploy, a Tomcat thread and a DB connection stay busy for minutes, and the client, getting no response, retries and starts the work twice.

The contract:

POST /api/reports
Idempotency-Key: 7f3c...
{"type":"SALES","from":"2026-01-01","to":"2026-03-31"}

202 Accepted
Location: /api/reports/jobs/8812
{"jobId":8812,"status":"QUEUED"}
GET /api/reports/jobs/8812
200 {"status":"RUNNING","progress":45}
200 {"status":"DONE","resultUrl":"https://files.../8812.csv?signature=..."}

Inside:

  • a job table (id, type, params, status, owner, attempts, created_at, result_ref, error) is the source of truth, not an in-memory @Async;
  • workers take a job from a queue (Kafka/RabbitMQ) or from the table with skip locked; if a pod dies, the job is handed out again using a heartbeat and a timeout so the work isn't orphaned;
  • the result is written to object storage and the client gets a time-limited signed link: the large file doesn't flow through the service;
  • every stage is idempotent: a retry gives the same result.

Decisions to agree on with the team up front:

  • notification: polling (simple, works everywhere, with Retry-After), webhook (for B2B, but needs signatures and redelivery), or SSE/WebSocket (for the UI);
  • cancellation: DELETE /jobs/{id}, and the worker checks it between stages;
  • quotas: how many heavy jobs one user can open at once, otherwise a single customer takes over the whole worker pool;
  • how long the result is kept and when it is cleaned up;
  • monitoring: queue length, job duration p95, failure rate: the alerts come from these.

At the platform level it pays to make this pattern a shared library or a separate "job service" so each team doesn't rewrite it: states, retry, cleanup and metrics will be the same everywhere.