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.
What you will learn
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:
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.
| Form | What it is | Good for | Watch out for |
|---|---|---|---|
| Cron job | a scheduled call, such as every night or every five minutes | regular synchronisation, reports, clean-up | runs must not overlap if one takes longer than the interval; a lock is needed |
| Worker | a long-running CLI process waiting for work | fast reaction, even load | needs process supervision, a restart after a crash and after every deployment |
| Queue | a stored list of individual jobs | decoupling trigger and processing, retries per job | someone 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.
<?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]);
}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:
<?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));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:
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.
-- 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;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
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:
- Users currently wait for something they would not need to wait for.
- An external system determines how long a step takes.
- Failures should be retried automatically, without anyone clicking.
- 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
Further sources
- PHP: Runtime Configuration - Manual max_execution_time, defaults for web and CLI
- MySQL :: MySQL 8.0 Reference Manual :: 17.7.2.4 Locking Reads NOWAIT and SKIP LOCKED, suitability for queues
- SELECT — MariaDB Server Documentation SKIP LOCKED in MariaDB syntax, InnoDB only
- Receive Stripe events in your webhook endpoint vendor recommendation to process incoming events asynchronously
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.