Background job

Also known as: background task

On this page 7

A background job is a unit of work that a server application hands off to run outside the request-response cycle, so that the caller receives an answer immediately while the work completes later. In the field of servers, and specifically in services & processes, background jobs (also called background tasks) cover sending email, resizing images, generating reports, calling slow external APIs and running scheduled maintenance.

The pattern rests on a simple contract: a producer enqueues a job description, a persistent queue stores it, and one or more worker processes pick it up, execute it and record the result. Separating these roles lets each part scale, fail and restart independently.

How a background job moves through the system

A background job travels through a defined lifecycle of states, from the moment the application creates it to the moment a worker acknowledges completion. The job itself is usually a small serialized message containing a job type, arguments and metadata such as an identifier, a creation time and a retry counter, rather than the data being processed.

The queue backend is typically a message broker, a key-value store with list primitives, or a relational table used with row locking. A worker claims a job atomically, marks it as in progress, and either acknowledges success or returns the job for another attempt. If the worker dies mid-task, a visibility timeout or lease expiry makes the job available again.

The following table lists the states that most job systems track and what each one means for operators.

StateMeaningOperator concern
EnqueuedStored and waiting for a free workerQueue depth and wait time
ScheduledWaiting until a set time or delay passesClock accuracy and backlog at release
RunningClaimed by a worker under a leaseDuration against the timeout
RetryingFailed and waiting for the next attemptBackoff interval and attempt count
SucceededAcknowledged and removed or archivedRetention of results and logs
DeadExhausted retries, moved asideAlerting and manual replay
Common background job states

Types of background jobs on servers

Background jobs differ mainly by what triggers them and how long they run. The trigger determines where the job comes from, and the duration determines how workers, timeouts and shutdown handling must be configured.

TypeTriggerTypical example
Fire-and-forgetApplication event, enqueued onceSend a welcome email after sign-up
DelayedEvent plus a fixed delayRemind a user about an abandoned cart after 24 hours
RecurringCalendar schedule, similar to cronRotate logs or rebuild a search index nightly
BatchParent job that fans out to many childrenRecalculate invoices for 50,000 accounts
ChainedCompletion of a previous jobTranscode a video, then generate thumbnails
Background job types by trigger

Short jobs of a few hundred milliseconds suit high-concurrency workers, while jobs that run for minutes or hours need explicit checkpointing, heartbeats that extend the lease, and a graceful shutdown path so a deployment does not discard partial progress.

A background job is a unit of work, not a process, which distinguishes it from neighboring concepts such as a daemon or a worker process. The worker is the long-running process that executes many jobs; the job is the item it consumes.

ConceptWhat it isRelation to background jobs
DaemonA long-running process detached from a terminalOften hosts the worker loop
Worker processA process that consumes and executes jobsRuns many jobs over its lifetime
Cron entryA schedule that launches a commandCan enqueue recurring jobs
Shell background processA command started with a trailing ampersandNot queued, not retried, lost on logout
Asynchronous requestNon-blocking I/O inside one requestStill tied to the request lifetime
How a background job differs from neighboring concepts

The distinction matters for reliability. A shell background process has no queue, no retry policy and no record of failure, whereas a properly designed background job survives a worker crash because its description is persisted before execution begins.

Designing and operating background jobs

The most important design rule is that every job should be idempotent, meaning that running it twice produces the same outcome as running it once. Most queues provide at-least-once delivery, so duplicates occur after timeouts, network partitions and worker restarts, and exactly-once execution is rarely guaranteed end to end.

Operators tune a small set of worker and queue parameters that control throughput, latency and failure handling. The table summarizes typical starting values; the right figures depend on job duration, external rate limits and available memory.

ParameterTypical rangeWhat it affects
Concurrency per worker1-50 threads or slotsThroughput and memory use
Job timeoutSeconds to several hoursDetection of hung jobs
Maximum retries3-25 attemptsPersistence against transient faults
Backoff strategyExponential with jitterLoad on failing dependencies
Queue prioritySeparate queues per classLatency of urgent work
Key worker and queue parameters
  • Pass identifiers, not large payloads, and load current data when the job runs.
  • Separate critical and bulk queues so a large batch cannot starve password-reset emails.
  • Monitor queue latency, not only queue length, because latency reflects user impact.
  • Handle the termination signal so workers finish or release jobs during a rolling restart.

Failure modes and common mistakes

Background jobs fail quietly, which is their main operational risk. Because no user waits on the result, a broken job can fail silently for days unless dead jobs, retry counts and queue latency are monitored with alerts.

SymptomLikely causeFix
Duplicate emails or chargesNon-idempotent job retriedUse idempotency keys and unique constraints
Queue grows without limitProducers outpace workersAdd workers or apply load shedding
Jobs stuck in running stateWorker crashed without releasing leaseSet visibility timeouts and heartbeats
Retries overload a partner APIFixed short retry intervalExponential backoff with jitter
Work lost during deploysWorkers killed without drainingGraceful shutdown and job re-enqueue
Symptoms, causes and fixes

A further mistake is enqueuing a job inside an uncommitted database transaction. If the worker runs before the commit, it reads data that does not yet exist; if the transaction rolls back, the job acts on data that never existed. The transactional outbox pattern or enqueue-after-commit hooks prevent this race.

The short version

A background job is a task the server agrees to do later instead of making you wait. Imagine you click a button to export a large report. The website writes a note about what needs to be done. It puts the note in a waiting line. Then it tells you right away that the report is on its way.

Separate helper programs then take notes from the line and do the actual work. The key idea is simple: slow work moves out of your way, and if a helper fails, the note is still in the line so another helper can try again.

Where it makes a difference

An online store runs a seasonal sale and receives about 3,000 orders per hour at peak. Each order needs a confirmation email, a PDF invoice, a stock update in the warehouse system and a call to a fraud-scoring API that sometimes takes four seconds to answer. Doing all of this inside the checkout request would make customers wait and would fail whenever the fraud service slowed down.

The engineering team keeps only payment authorization in the request and enqueues four background jobs per order. A critical queue with 20 worker slots handles emails and fraud checks, and a bulk queue with 5 slots generates invoices. Fraud calls retry up to 8 times with exponential backoff, and each job uses the order number as an idempotency key.

During the sale, the fraud provider has a 15-minute outage. Checkout keeps working normally, the fraud jobs accumulate in the retry state, and they drain within ten minutes of recovery. No orders are lost or double-processed, and the only visible effect is a short delay before some confirmation emails arrive.