Video in progress
Generating a report takes 2–3 minutes. How do you design the API for a long operation like that?
The request immediately returns 202 Accepted and a job ID, and the work runs in the background. The client polls the status with GET /jobs/{id} or gets a webhook/notification when it's done, and the result is downloaded through a separate link.
📖 Answer
Holding an HTTP request open for 3 minutes is a bad idea: LBs and proxies usually cut the connection at 60 seconds, a mobile network drops, the user refreshes the page and starts another report. A thread also stays busy for that long.
The asynchronous flow:
POST /reports -> 202 Accepted, Location: /reports/jobs/7f3a
GET /reports/jobs/7f3a -> {"status": "RUNNING", "progress": 40}
GET /reports/jobs/7f3a -> {"status": "DONE", "resultUrl": "/reports/files/7f3a.xlsx"}
@PostMapping("/reports")
public ResponseEntity<JobDto> start(@RequestBody ReportRequest req) {
Job job = jobService.create(req); // in the DB with PENDING status
queue.send("report-jobs", job.id()); // a worker picks it up
return ResponseEntity.accepted()
.location(URI.create("/reports/jobs/" + job.id()))
.body(JobDto.of(job));
}
A few more points:
- the job status is stored in the DB, not in memory — so the state survives a pod restart;
- if the same request is sent again, don't create a new job (an idempotency key, or a check for "is there already a running job with these parameters");
- the result file goes in object storage, behind an expiring link;
- tell the client the polling interval (for example,
Retry-After: 5), otherwise the front end will ask every 100 ms.
Sign up to mark studied questions and save your progress.