Skip to content

Background jobs and queues: when does an application need them?

Not every task belongs in the time someone spends waiting for a response. This article describes how to recognise work that should run in the background, how cron, workers and queues differ, and what makes a queue something you can actually operate.

  • Who it is forDevelopers and technical decision-makers
  • LevelDecision
  • Reading timeabout 12 minutes
  • Last updated24 October 2026

What you will learn

  • How to recognise that a task does not belong in the request
  • How cron jobs, workers and queues differ and complement each other
  • What a robust queue needs, shown in a runnable example
  • When a database table is enough as a queue and when a separate service is justified

In short

Work belongs in the background when the user does not need its result to carry on, when it takes longer than a request should, when it depends on an external system that may be slow or unavailable, or when it arrives in bursts. Typical examples are sending email, generating PDFs, large imports and transfers to other systems.

A robust queue needs persistently stored jobs, a way of claiming them that never hands the same job to two workers, a time limit for workers that crash, limited retries at increasing intervals, a place for jobs that have failed for good, and monitoring that also reports when nothing is running at all. And the jobs themselves must cope with being run a second time.

The limits of a request

A web request has a person waiting at the other end. For that reason alone it should finish within seconds. On top of that come technical limits: according to the PHP manual, max_execution_time defaults to 30 seconds, and to 0 (unlimited) on the command line (CLI). On non-Windows systems, time spent in system calls and stream operations does not count, so a script waiting for a slow external service can run considerably longer than the setting suggests. Web servers and proxies in front of PHP have their own time limits, which apply independently.

The real problem, though, is not the limit but what happens when it is reached. If a long request is cut off, nobody knows how far it got. The user sees an error page, clicks again, and the first half of the work is done a second time. Why this threatens every retry is explained in preventing duplicate processing.

These questions help identify good candidates for the background:

  • Does the user have to wait for the result, or is “in progress” enough?
  • Does the step depend on an external system whose response time you do not control?
  • Does the duration grow with the amount of data, as with an import or month-end run?
  • Should a failure be retried later without anyone clicking again?

Cron jobs, workers and queues

The three terms are often used interchangeably, but they describe different things: when something starts, who does the work, and where the work waits.

Three building blocks that complement each other
FormWhat it isGood forWatch out for
Cron joba scheduled call, such as every night or every five minutesregular synchronisation, reports, clean-upruns must not overlap if one takes longer than the interval; a lock is needed
Workera long-running CLI process waiting for workfast reaction, even loadneeds process supervision, a restart after a crash and after every deployment
Queuea stored list of individual jobsdecoupling trigger and processing, retries per jobsomeone has to work through it: a worker or a cron job

In practice they are combined. A simple and often sufficient set-up: the application writes jobs into a table, and a cron job starts a processor every minute that works through the jobs that are due and then exits.

What a robust queue needs

The following example is a queue in a database table, shown with SQLite. It contains the parts that make the difference in production: status, attempt counter, earliest next run time, a lock with an expiry time (a lease), and the last error.

PHPPHP 8.4 · tested with PHP 8.3, 8.4 and 8.5 CLI, SQLite
<?php
declare(strict_types=1);

$pdo = new PDO('sqlite::memory:', options: [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$pdo->exec("CREATE TABLE job (
    id INTEGER PRIMARY KEY, payload TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'pending',  -- pending | running | done | failed
    attempts INTEGER NOT NULL DEFAULT 0,
    available_at INTEGER NOT NULL,           -- not before this time (retry delay)
    locked_until INTEGER, last_error TEXT)");

const MAX_ATTEMPTS = 3;

/** Claims one due job atomically; a crashed worker's job becomes due again. */
function claim(PDO $pdo, int $now): ?array
{
    // A job whose worker died on the last attempt is parked, not claimed again
    $pdo->prepare("UPDATE job SET status = 'failed', last_error = 'lease expired'
        WHERE status = 'running' AND locked_until < ? AND attempts >= ?")
        ->execute([$now, MAX_ATTEMPTS]);
    $stmt = $pdo->prepare("UPDATE job SET status = 'running', attempts = attempts + 1,
            locked_until = :lease
        WHERE id = (SELECT id FROM job
            WHERE (status = 'pending' AND available_at <= :due)
               OR (status = 'running' AND locked_until < :expired)
            ORDER BY id LIMIT 1)
        RETURNING id, payload, attempts");
    $stmt->execute(['due' => $now, 'expired' => $now, 'lease' => $now + 300]);
    return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}

function fail(PDO $pdo, array $job, string $error, int $now): void
{
    $status = $job['attempts'] >= MAX_ATTEMPTS ? 'failed' : 'pending';
    $retryAt = $now + 60 * 2 ** $job['attempts'];      // 2, 4, 8 … minutes
    $pdo->prepare('UPDATE job SET status = :status, available_at = :retry, last_error = :error
        WHERE id = :id')
        ->execute(['id' => $job['id'], 'status' => $status, 'retry' => $retryAt, 'error' => $error]);
}
The actual claim in claim() is a single UPDATE statement. It selects a due job and marks it in the same step, so no second worker can grab it in between. UPDATE … RETURNING requires SQLite 3.35 or later; it was tested with SQLite 3.45.

A run with a fixed clock shows the behaviour:

PHPPHP 8.4 · tested with PHP 8.3, 8.4 and 8.5 CLI, SQLite
<?php
declare(strict_types=1);

require __DIR__ . '/01-queue.php';

$t = 1_800_000_000;   // fixed clock, so the run is reproducible
$pdo->prepare('INSERT INTO job (payload, available_at) VALUES (?, ?)')
    ->execute(['{"mail":"invoice R-1"}', $t]);

// Worker A claims the job and crashes without reporting back
$a = claim($pdo, $t);
echo 'worker A got job ', $a['id'], "\n";
echo 'worker B, same second: ', var_export(claim($pdo, $t + 1), true), "\n";

// After the lease of 300 s has expired, the job is due again
$b = claim($pdo, $t + 301);
echo 'worker B after lease: job ', $b['id'], ', attempt ', $b['attempts'], "\n";
fail($pdo, $b, 'SMTP timeout', $t + 301);

// Third attempt also fails: the job is parked for a human, not retried forever
$c = claim($pdo, $t + 301 + 240);
fail($pdo, $c, 'SMTP timeout', $t + 541);
print_r($pdo->query('SELECT status, attempts, last_error FROM job')->fetch(PDO::FETCH_ASSOC));
Output: worker A got job 1, worker B, same second: NULL, worker B after lease: job 1, attempt 2, and finally status => failed, attempts => 3, last_error => SMTP timeout.

Three points matter here:

  • The lock expires. If a worker crashes, its job does not stay “running” forever but becomes due again once the lease has expired. If that was already the last permitted attempt, claim() parks it as failed instead of handing it out again and again. The lease must be longer than the longest normal processing time.
  • Retries are limited and scheduled at increasing intervals. After the last attempt, the job ends up as failed, with a reason, in a list a person can see: the follow-up work described in our article on failed automations.
  • A job can run twice. If worker A had already sent the email and crashed only afterwards, worker B sends it again. The promise is “at least once”, just as with webhooks. Processing itself therefore has to recognise what has already been done.

A database table or a separate service?

A queue in your existing database has an advantage that is often underestimated: the job can be created in the same transaction as the business record. If the order is saved, the “send confirmation” job exists too, or neither does. On top of that, there is no additional software to run, back up and monitor, and the state can be inspected with an SQL query.

MySQL and MariaDB claim jobs differently from SQLite: with a locking read that skips rows already locked. The MySQL documentation explicitly describes SKIP LOCKED as a way to avoid lock contention when several sessions access a queue-like table, and as unsuitable for general transactional work. The MariaDB documentation lists the option as well, effective only on InnoDB tables.

SQLMySQL 8.0 / MariaDB · syntax example, not executed
-- MySQL 8.0 / MariaDB (InnoDB): claim one job, skip rows other workers hold
START TRANSACTION;
SELECT id, payload FROM job
 WHERE status = 'pending' AND available_at <= UNIX_TIMESTAMP()
 ORDER BY id
 LIMIT 1
 FOR UPDATE SKIP LOCKED;
UPDATE job SET status = 'running', attempts = attempts + 1,
       locked_until = UNIX_TIMESTAMP() + 300
 WHERE id = ?;   -- the id selected above
COMMIT;
This example has not been run against a MySQL or MariaDB server; the tests for this article run on SQLite only. Check your database’s release notes to see from which version SKIP LOCKED is supported.

A separate message broker pays off when volumes are high, when jobs need to be distributed to many consumers, or when several applications in different languages are involved. It does, however, introduce a new boundary: database and broker are two systems, and “order saved, message sent” is no longer a single operation. The usual remedy is to write messages into a table in your own database first and pass them on from there.

In our assessment, a table in the existing database is enough for most business applications with moderate volumes. What usually forces the move is volume and distribution, rarely the retry or locking logic.

A hypothetical example

Month-end at the push of a button

On the first of each month, an application creates around 2,000 invoices at the push of a button and emails them. In the first month this works. In the third, the request is cut off with a timeout after a few minutes. Accounts do not know which invoices have gone out, click again, and some customers receive two invoices.

Rebuilt, the same process looks like this: the button creates one job per invoice in a single transaction and responds immediately. An overview shows how many are done, pending and failed. The worker generates and sends; each invoice records whether it has already been sent. Anything that does not go through after three attempts, for instance because of an invalid address, appears in the list with a reason. A second click creates no new jobs, because jobs for this month already exist.

What a queue must report in production

  • Age of the oldest pending job. More telling than the length: a hundred pending jobs may be normal; one job that has been waiting for two hours is not.
  • Number of failed jobs, with someone responsible for the follow-up.
  • Signs of life from the workers. A worker that has stopped running reports no error. A regular “still alive” entry and a check for its absence do.
  • A restart after every deployment. A long-running PHP process loaded its code at start-up and otherwise carries on with the old version. Stopping workers deliberately after a fixed number of jobs and restarting them is also common practice.

Errors in the background follow the same rules as in the foreground, just without a screen: exceptions with context and job number go into the log, as described in error handling and logging.

Does your application need one?

A queue is additional technology that has to be operated. It is worth it if at least one of these applies:

  1. Users currently wait for something they would not need to wait for.
  2. An external system determines how long a step takes.
  3. Failures should be retried automatically, without anyone clicking.
  4. Operations arrive in bursts that would otherwise block the application.

If none of these applies, direct processing is the simpler and therefore better solution. If you are facing this decision for an application of your own, it is part of our custom PHP development.

Common misconceptions

The response to the user becomes faster; the work itself does not. It is deferred, and therefore needs a way of reporting when it is finished.

A cron job decides when something starts. Without stored individual jobs there is no state, no retry per job and no protection against overlapping runs.

If a worker crashes after finishing the work but before reporting back, the job runs again. Processing has to cope with that.

A table in the existing database is often enough, and it can create jobs in the same transaction as the business data.

Further sources

About the author

Fabian Lücker is managing partner of PHP Schmiede KG in Rheine and has worked in software development since 2007. He is responsible for development and design, and writes here about decisions that come up in real projects.

An application reaching its limits?

Tell us which operations currently take a long time, break off or run twice. Together we will work out which of them belong in the background.