Scrivio Interview library
DebuggingIntermediate7 min read · updated 13 November 2026

Asynchronous export jobs run on worker pods that take work from a jobs table. After each deployment, about 3 percent of jobs stay in RUNNING forever, and clients poll them indefinitely.

Explain why jobs get stuck and how to make job execution robust to workers dying.

A worker killed during a deployment, for example by SIGKILL after the grace period, leaves its job marked RUNNING, and nothing ever looks at it again. Make execution robust with leases: a worker claims a job by setting an owner and lease_expires_at, renews the lease with a heartbeat, and a reaper or any other worker reclaims jobs whose lease expired. Steps must be idempotent or checkpointed, an attempt counter moves repeatedly failing jobs to FAILED, workers stop claiming and release their jobs on SIGTERM, and alerts plus a hard timeout make sure no job runs forever.

Why this question is asked

Job tables are a common way to run background work: workers pick rows, mark them RUNNING, do the work, and mark them done. The design has a hidden assumption, that a worker which marks a job RUNNING will always live to update it again. Deployments break that assumption on a schedule, which is why the 3 percent of stuck jobs line up with releases. Interviewers ask this to see whether we know the lease pattern and its subtle edge cases. In this answer, we will see exactly how jobs get stuck, add leases and heartbeats, make reclaimed jobs safe to rerun, handle graceful shutdown in Kubernetes, and finish with timeouts and alerts that turn stuck jobs into visible failures.

1How Jobs Get Stuck

During a rolling update, Kubernetes sends SIGTERM to the old pod, waits for terminationGracePeriodSeconds (30 seconds by default), and then sends SIGKILL. An export that takes ten minutes is still running when SIGKILL arrives. The process dies immediately, with no chance to run any cleanup code, and the job's row still says RUNNING.

The rest of the system trusts that status. Other workers only claim QUEUED jobs, so nobody picks it up. The API reports RUNNING to the client, so the client keeps polling. Nothing in the design ever revisits a RUNNING job, so it stays that way forever. Out-of-memory kills and node failures do the same thing at random times; deployments just make it frequent and predictable.

Step throughA job stranded by a deployment
Worker podJobs tableKubernetesClient
claim job 17: RUNNING
SIGTERM (rolling update)
SIGKILL after 30 s
job 17 still RUNNING, no owner alive
GET status: RUNNING
GET status: RUNNING, forever

6 messages in order. Play them, or step through them one at a time.

2Leases and Heartbeats

A lease is a claim that expires unless it is renewed. When a worker claims a job, it sets owner to its pod name and lease_expires_at to now plus 60 seconds, in one atomic statement that also picks the job, so two workers cannot claim the same row. While working, a background heartbeat renews the lease every 20 seconds. If the worker dies, the heartbeats stop, and a minute later the lease has expired.

A reaper, which can simply be part of the claim query, then treats jobs whose lease expired as available again. PostgreSQL's FOR UPDATE SKIP LOCKED lets many workers claim jobs concurrently without blocking each other.

SQL
-- Claim: a queued job, or a running job whose lease expired
UPDATE jobs SET state = 'RUNNING', owner = :pod, attempts = attempts + 1,
lease_expires_at = now() + interval '60 seconds'
WHERE id = (
SELECT id FROM jobs
WHERE state = 'QUEUED' OR (state = 'RUNNING' AND lease_expires_at < now())
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 1)
RETURNING id, attempts; -- 17, 2: second attempt after the pod died
-- Heartbeat every 20 s: only succeeds while we still own the job
UPDATE jobs SET lease_expires_at = now() + interval '60 seconds'
WHERE id = :id AND owner = :pod; -- 1 row: still ours; 0 rows: lost it, stop working

Notice that the heartbeat checks the owner. If it updates zero rows, the lease has passed to another worker, and this worker must stop, which matters for the paused-worker case in the FAQ.

3Making Reclaimed Jobs Safe to Rerun

Reclaiming means a job may run more than once, so the work must tolerate that. The simplest way is to make each step idempotent: writing export part 3 to the same object storage key twice gives the same result, and upserts instead of inserts avoid duplicate rows. For long jobs, checkpointing avoids redoing everything: the worker records completed parts in the job row or a side table, for example parts_done = 7 of 20, and a reclaimed job resumes at part 8.

Some jobs fail every time, because of bad input or a bug that crashes the worker. Without a limit, such a job would be reclaimed and crash workers forever, a poison job. The attempts counter in the claim statement handles it: when attempts reaches a limit, say 3, the job moves to FAILED with an error the client can see, and an alert fires.

4Graceful Shutdown on SIGTERM

Leases make the system recover from abrupt death; graceful shutdown makes most deaths not abrupt. When a worker receives SIGTERM, it stops claiming new jobs at once. For its current job it has two choices: finish it, if it can do so within terminationGracePeriodSeconds, or reach a checkpoint and release the job explicitly, setting it back to QUEUED and clearing the owner and lease, so another worker can pick it up immediately rather than waiting for the lease to expire.

In Spring Boot, server.shutdown=graceful and spring.lifecycle.timeout-per-shutdown-phase cover the web part; for the worker loop, we implement a SmartLifecycle bean or a shutdown hook that sets a stop flag and waits for the current step. The grace period should be set to the longest step plus a margin, for example 120 seconds, rather than the default 30, and steps should be short enough that a checkpoint is always reachable within it.

Step throughWorker lifecycle with leases
  1. Claim job with leaseowner = pod, lease 60 s
  2. Process next step, heartbeat every 20 scheckpoint after each part
  3. SIGTERM received?
    YesStop claiming; finish or checkpoint and releaseNoContinue
  4. Heartbeat updated 0 rows?
    YesLease lost: stop work at onceNoNext step
  5. All parts donemark SUCCEEDED, clear lease

5 steps in order. Play them, or step through them one at a time.

5Timeouts and Alerts

Even with leases, something can go wrong in a way we did not foresee, so the system needs an outer guard. Every job type has a hard maximum duration, for example 2 hours for exports. A periodic check moves any job older than that to FAILED with a clear error, so clients get an answer they can act on instead of polling forever, and the API documents that maximum.

We alert on jobs running longer than their expected maximum, on leases reclaimed (a few after each deployment is expected; many means workers are dying), and on jobs that reached the attempt limit. The metric of stuck jobs after deployment should drop to zero once leases and graceful shutdown are in place, and the reclaim count tells us whether the grace period is long enough.

6Follow-up questions

How do you prevent two workers from running the same job after a lease expires while the first is only paused?

A worker can freeze, for example during a long garbage collection pause or a network partition, while its lease expires and a second worker claims the job. When the first wakes up, it does not know it lost the job. Two things protect us. The heartbeat's owner check makes the first worker discover the loss on its next heartbeat and stop. And to stop it from writing in the meantime, we use a fencing token: the attempt number (or a lease version) increases with every claim, and every write the worker makes, to the job row or to its outputs, includes it, with the database or storage rejecting writes from an older token. Then even a worker that has not noticed yet cannot corrupt the job's results.

Why not use a message queue instead of a jobs table?

A queue with visibility timeouts, such as SQS, implements leases for us: an unacknowledged message becomes visible again after the timeout. The same rules apply, idempotent steps, heartbeats that extend visibility, an attempt limit with a dead-letter queue, and graceful shutdown. A jobs table is often kept because the API needs to show job status anyway.

7Conclusion

In this answer, we saw that jobs stay RUNNING forever when a worker is killed mid-job, because nothing revisits a RUNNING row. We added leases with an owner and expiry renewed by heartbeats, reclaimed expired leases with an atomic claim using SKIP LOCKED, made steps idempotent or checkpointed, moved poison jobs to FAILED with an attempt counter, handled SIGTERM by stopping claims and releasing jobs within the grace period, and added hard timeouts and alerts so no job runs forever unnoticed.

What to say in the interviewAbout 90 seconds aloud

Open with

During a rolling update Kubernetes sends SIGTERM, waits the grace period, thirty seconds by default, and then SIGKILLs the pod. A worker in the middle of a long export dies without any chance to clean up, its job row still says RUNNING, and since workers only claim QUEUED jobs, nothing ever touches it again.

Then, if they want more

The client polls forever. I would fix it with leases. A worker claims a job atomically, setting owner and lease_expires_at to now plus sixty seconds, and a heartbeat renews the lease every twenty seconds.

If the worker dies, the lease expires, and the claim query treats running jobs with an expired lease as available, using FOR UPDATE SKIP LOCKED so workers do not block each other.

Since a job can now run more than once, steps must be idempotent or checkpointed, so a reclaimed job resumes from the last completed part, and an attempt counter moves jobs that keep failing to FAILED.

Then graceful shutdown: on SIGTERM the worker stops claiming, and either finishes within the grace period or checkpoints and releases its job explicitly, so another worker takes it immediately. I would raise terminationGracePeriodSeconds to fit the longest step.

Finally, every job type gets a hard timeout after which it is marked failed, and we alert on long-running jobs, reclaims and attempt limits. For paused workers, the heartbeat checks ownership and a fencing token stops stale writes.

About this answer

Last updated
13 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 official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
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 "Explain why jobs get stuck and how to make job execution robust to workers dying.": https://scrivio-interview-library.netlify.app/architecture/api-design-at-scale/1e2bb03932/