Quick revision
The short answer
We keep every job in a database table, so its state survives a pod restart and any pod can answer GET. The controller inserts the job and returns ResponseEntity.accepted().location(uri).body(jobDto); workers claim pending jobs with SELECT ... FOR UPDATE SKIP LOCKED (or receive a message), update status and a heartbeat as they go, and a sweeper puts jobs stuck in RUNNING back in the queue after a timeout. GET checks that the caller owns the job, and a cancel endpoint lets clients stop work they no longer need.
What to remember
In this answer, we built the long-running job pattern so it survives restarts: jobs in a database table, a controller that inserts and returns 202 with a Location, workers that claim jobs with FOR UPDATE SKIP LOCKED, heartbeats and a sweeper for crashed workers, and ownership checks and cooperative cancellation.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We keep every job in a database table, so its state survives a pod restart and any pod can answer GET. The controller inserts the job and returns ResponseEntity.accepted().location(uri).body(jobDto); workers claim pending jobs with SELECT ... FOR UPDATE SKIP LOCKED (or receive a message), update status and a heartbeat as they go, and a sweeper puts jobs stuck in RUNNING back in the queue after a timeout. GET checks that the caller owns the job, and a cancel endpoint lets clients stop work they no longer need.
Why this question is asked
The 202 pattern is easy to sketch on a whiteboard and easy to get wrong in code. The most common mistake is to start the work with @Async and keep the status in a map: it works on a laptop, and then a deploy restarts the pod and every running job vanishes, or a GET lands on another pod that has never heard of the job. Interviewers ask this to see whether we can build the pattern so it survives real operations. In this answer, we will see why in-memory state fails, then build the job table, the controller, the worker that claims jobs safely across pods, the heartbeat and sweeper that recover from crashes, and the ownership check and cancellation.
1Why @Async Alone Is Not Enough
@Async runs a method on another thread from a Spring executor, so the controller can return at once. That part is fine. The problem is where the job lives: in the memory of one JVM. Kubernetes restarts pods for deploys, scaling and node maintenance, and each restart silently loses every queued and running job. With three replicas behind a load balancer, the GET for a job is answered by a random pod, and two out of three times that pod does not know the job.
So the state must live outside the JVM, in a store all pods share. A database table is the natural choice, because we already have one, it is transactional, and it lets us query jobs for support and cleanup.
2The Job Table
The table holds everything needed to answer GET and to resume work after a crash: who owns the job, what was asked, where it stands, where the result is, and when a worker last showed signs of life.
Notice the unique constraint on owner and idempotency key: a client that retries the POST with the same key cannot create a second job, because the database refuses the duplicate. The partial index keeps the pending-job query fast.
3The Controller: Insert and Return 202
The POST handler validates the request, inserts a PENDING job in a transaction and returns at once. Spring's ResponseEntity builder has exactly the methods we need.
The controller does not start the work itself. That is deliberate: if it called the report code directly in a background thread, we would be back to in-memory state. It only records the job, and the workers find it.
4Workers That Claim Jobs Safely
Each pod runs a small worker loop. It asks the database for the oldest pending job and marks it RUNNING in one statement. FOR UPDATE locks the row, and SKIP LOCKED tells PostgreSQL to skip rows another transaction has already locked instead of waiting, so ten workers on five pods each get a different job and none of them blocks.
9 messages in order. Play them, or step through them one at a time.
Any pod can answer GET, because the state is in the database and not in a worker's memory.
Notice that the claim is a short transaction of its own. We must not hold a database transaction open for the 15 minutes the report takes; the row lock would block cleanup, and a long transaction harms the database. So the claim commits immediately, and the RUNNING status, not a lock, says that the job is taken.
Instead of polling, the controller can publish a message that workers consume, but then the insert and the publish must not get out of step, which usually means a transactional outbox. For a modest volume of jobs, polling with SKIP LOCKED is simpler.
5Heartbeats and a Sweeper for Crashed Workers
A worker can die halfway through a report, for example when its pod is killed by a deploy. The job then stays RUNNING forever, and the client polls forever. To detect this, the worker updates heartbeat_at, together with progress, every 30 seconds while it works. A sweeper, also scheduled, looks for RUNNING jobs whose heartbeat is older than a timeout, a few heartbeat intervals, and puts them back to PENDING, or marks them FAILED once they have used up their attempts.
The sweeper is safe to run on every pod, because each statement is a single conditional update. Two pods running it at once simply find nothing the second time. The attempts limit stops a report that always crashes its worker from being retried forever.
6Ownership Checks and Cancellation
A job id is not a secret, so GET must check that the caller owns the job, and it should return 404 rather than 403 for someone else's job, so the response does not even reveal that the job exists.
Cancellation is cooperative. A pending job can be moved straight to CANCELLED. A running job gets cancel_requested set, and the worker checks that flag between steps, when it writes its heartbeat, then stops and sets CANCELLED. DELETE /report-jobs/{id} is an equally valid design.
7Follow-up questions
Should the workers run in the same pods as the API?
They can at first, which keeps deployment simple. When reports get heavy, a separate worker deployment lets us scale and size them independently, and the API pods stay responsive. The table design does not change.
Why not use Spring Batch or a job scheduler for this?
We can, and for complex multi-step reports Spring Batch gives us restartable steps and its own job repository tables. The pattern is the same: state in the database, workers that claim work, and restart after failure. For a single-step report, a table and SKIP LOCKED are lighter and easier for the team to understand.
8Conclusion
In this answer, we built the long-running job pattern so it survives restarts: jobs in a database table, a controller that inserts and returns 202 with a Location, workers that claim jobs with FOR UPDATE SKIP LOCKED, heartbeats and a sweeper for crashed workers, and ownership checks and cooperative cancellation.
Open with
I would never keep the job state in memory with just @Async, because a pod restart loses it and other replicas cannot answer GET. Instead I create a report_job table with the id, owner, status, the request as JSON, result location, error, attempts, an idempotency key with a unique constraint per owner, timestamps and a heartbeat column.
Then, if they want more
The POST controller validates, inserts a PENDING row, and returns ResponseEntity.accepted().location(uri).header Retry-After .body(jobDto), so the client gets 202 and a Location for /report-jobs/{id}.
Work is picked up by workers on every pod: a scheduled loop runs one UPDATE that selects the oldest pending job with FOR UPDATE SKIP LOCKED and sets it to RUNNING, committed immediately, so several workers never take the same job and no transaction stays open during the long work. Alternatively the controller publishes a message through a transactional outbox.
While a worker runs, it updates progress and heartbeat every thirty seconds, and a sweeper requeues RUNNING jobs whose heartbeat is older than a couple of minutes, failing them after three attempts. GET loads the job and checks the caller is the owner, returning 404 otherwise.
And a cancel endpoint marks pending jobs cancelled and sets a flag that running workers check between steps.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Framework reference, Spring Web MVC
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Implement the long-running job pattern in Spring Boot: POST starts the work...": https://scrivio-interview-library.netlify.app/spring-boot/rest-api-design/2d309d093a/