Background Jobs
Workers that run long LLM tasks, embeddings, and batch evals off the request path.
In plain words
A background job is a task the system does on the side, like building a big index of your documents, while you carry on using the app and check on its progress later.
Think of it like…
A print shop with order tickets. The counter takes your order and gives you a ticket number straight away; the presses work through the queue, the ticket shows progress, a supervisor reclaims jobs from a press that jams and a big customer's 5,000-copy order can't block the one-page jobs behind it.
Where you’ve seen it
A knowledge-base product lets customers upload folders. POST /v1/imports writes a row jobs(id, tenant_id, type, state, progress, attempts, lease_until, params, error) and enqueues the ID; the API returns 202 and the UI polls GET /v1/jobs/{id} or listens for a stream. A worker claims a job by atomically setting state = running and lease_until = now() + 90s, renews the lease every 30 seconds while working and writes progress = items_done / items_total. A sweeper moves jobs with an expired lease back to queued (up to 3 attempts) so a crashed worker doesn't leave a job stuck. Embedding 1,000 documents at 0.8 seconds each takes 800 seconds on one worker or 40 seconds across 20. Checkpointing matters for big imports: a 10,000-item job at $0.002 per item fails at item 7,300; without checkpoints, a retry repeats all 10,000 items ($20); with a checkpoint every 100 items it restarts from item 7,300 and repeats at most 100 ($0.20). Steps are idempotent (upsert by (document_id, chunk_index)), so redoing an item is harmless. Retries use backoff of 30 seconds, 2 minutes and 10 minutes for transient failures (rate limit, timeout), while permanent failures (unsupported file) mark the item failed and continue. Fairness: if a tenant submits 5,000 jobs of 6 seconds into a shared FIFO queue served by 20 workers, everyone behind them waits 5,000 × 6 / 20 = 1,500 seconds, 25 minutes; a per-tenant concurrency cap of 5 and round-robin scheduling lets other tenants start within seconds while the big import takes longer. Users can cancel (state = cancelling; the worker checks between items), results expire after 7 days, and dashboards show jobs by state, queue age, retry counts and cost per job.
Words you’ll hear
- Job state machine
- The allowed states and transitions of a job, such as queued to running to succeeded.
- Lease
- A time-limited claim a worker holds on a job, renewed by heartbeats.
- Checkpoint
- Saved progress so a retry resumes instead of restarting.
- Noisy neighbour
- A tenant whose heavy workload degrades service for others.
Visual diagram
Theory & deep dive
Job lifecycle, leases and retries
Model each job as a state machine stored in the database: queued → running → succeeded | failed | cancelled, with attempts, progress, error, started_at, finished_at and a lease_until timestamp. A worker claims a job with an atomic update (UPDATE jobs SET state='running', lease_until=now()+interval '90 seconds' WHERE id=$1 AND state='queued'), and renews the lease on a heartbeat (every 30 seconds). If the worker dies, the lease expires and a sweeper returns the job to queued, up to a maximum number of attempts, after which it becomes failed for human review. Leases are better than locks because a crashed worker can't hold a job forever.
Classify failures. Transient errors (timeouts, 429, 503) get retries with exponential backoff and jitter (for example 30 seconds, 2 minutes, 10 minutes); permanent errors (corrupt file, validation) fail the item fast, with a clear message. Put a timeout on every step and a total budget on the job (maximum attempts, maximum cost) so runaway retries can't burn money. Record attempt history, so support can see what happened. Jobs that must not run twice need idempotency: deterministic job IDs, upserts and idempotency keys on side effects.
t = 0 s: worker claims the job, lease_until = 90 s. t = 30 s and 60 s: heartbeats extend the lease. t = 70 s: worker crashes. t = 150 s: lease expired, sweeper sets state = queued, attempts = 2. A new worker resumes from the last checkpoint.
Checkpoints, progress, fairness and cost control
Long jobs should be resumable. Split work into items or batches, record a checkpoint (the last completed index or a per-item status table) every N items, and make each item idempotent. The economics are stark: a 10,000-item job at $0.002 per item that fails at item 7,300 wastes $20 if it restarts from zero but at most $0.20 (100 items) with checkpoints every 100. For large fan-out, create one child job per item or batch and aggregate; with 20 workers and 0.8 seconds per item, 1,000 items finish in 1,000 × 0.8 / 20 = 40 seconds. Report progress (items_done / items_total) and expose it to the UI; provide cancellation (set cancelling, workers check between items) and result retention (expire after a set number of days).
Fairness: with a shared FIFO queue a single tenant's 5,000-job upload at 6 seconds each across 20 workers delays everyone else by 5,000 × 6 / 20 = 1,500 seconds, about 25 minutes. Use per-tenant concurrency caps (for example 5), round-robin or weighted scheduling and priority lanes for interactive work. Cost and safety: enforce per-job and per-tenant budgets, rate limit provider calls from workers with a shared limiter, and avoid running arbitrary user content with broad credentials. Observability: track jobs by state, queue age, run time, attempts, failures by reason and cost per job; alert on jobs stuck in running past their lease, rising retry rates and queue age beyond the SLO.
10,000 items × $0.002 = $20 per full pass. Failure at item 7,300. No checkpoint: rerun all, +$20. Checkpoint every 100 items: resume at 7,300 and redo at most 100 items = $0.20 and 80 seconds at 0.8 s per item.
How it works, step by step
Step 1 of 41. Model the job
Create a jobs table with state, progress, attempts, lease and params, and expose it through a status endpoint.
- Return
- 202 + job id
When to use it & trade-offs
What it is
A background job is work performed by a worker process outside the web request: embedding a document set, summarising a long transcript, running an evaluation suite, sending a digest, retrying a failed tool call. The web tier creates a job record and a message, returns quickly (202 Accepted) and workers execute the job while updating its state (queued, running, succeeded, failed, cancelled), progress and result. Production-grade jobs need a state machine, retries with backoff, timeouts and leases (so stuck jobs are reclaimed), checkpointing for long runs, idempotent steps, priorities and fairness between tenants, cancellation and observability. Frameworks such as Celery, Sidekiq, BullMQ, Temporal and cloud task services provide these building blocks.
Why it matters: LLM workloads are long, expensive and flaky: a 10,000-document embedding run can take minutes and cost dollars, a provider may fail at item 7,300 and a deploy can kill a worker mid-run. Keeping that work in the request path causes timeouts and lost work; keeping it in background jobs without discipline causes duplicate charges, jobs stuck in running forever and one tenant starving everyone else. The patterns here keep jobs correct, cheap to retry and fair.
When to reach for it
- Bulk embedding and indexing of uploaded documents
- Batch evaluations and scheduled quality checks
- Long agent runs and retries of failed side effects
When to avoid or be careful
- Jobs stuck in running with no lease or timeout
- Restarting multi-thousand-item jobs from zero
- A single shared FIFO queue for all tenants
Ways to run background work
Strengths: Simple; scales with workers.
Watch out: You build state, retries and fairness yourself.
Strengths: Durable state, retries and timers built in.
Watch out: More concepts and infrastructure.
Strengths: Trivial for fixed schedules.
Watch out: Not event-driven; overlap risk.
Interview signals & numbers to know
When this topic comes up
- “How would you build a job system for document imports?”
- Leases, heartbeats and sweepers
- Checkpointing long jobs
- Noisy-neighbour protection
- Retry policy and error classification
Benchmarks & rules of thumb
- $20 vs $0.20
- cost of restarting a 10,000-item job versus resuming with 100-item checkpoints
- 40 s
- 1,000 items at 0.8 s across 20 workers
- 1,500 s
- delay a 5,000-job tenant causes in a shared FIFO queue
Common mistakes & follow-ups
Common interview mistakes
- Marking a job running without any way to detect a dead worker.
- Retrying permanent errors until the budget is exhausted.
- Reporting no progress, leaving users guessing.
Likely interviewer follow-ups
- How do you cancel a running job?
- How would you stop one tenant from monopolising workers?
- How do you make a retried step safe?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Background Jobs with generative AI interview Q&A and hands-on practice.