Key points
- Anything slow, dependent on an outside service, or liable to fail temporarily doesn’t belong in the user’s request.
- A jobs table and a PHP worker are enough to start with, thanks to SELECT … FOR UPDATE SKIP LOCKED, with increasing back-off on failure.
- In production the worker runs under a supervisor, restarts after every deploy, and every job must be safe to run twice.
As a SaaS grows, the same complaints start to arrive: the month-end export errors out after thirty seconds, sign-up takes several seconds because it sends three emails, importing a customer file freezes the browser tab. The cause is nearly always slow work done inside the HTTP request. Exports, reports, emails, imports, third-party API calls, incoming webhook processing: anything slow or dependent on an outside service belongs in a job queue processed in the background by workers, while the user sees “Your export is being prepared”. Frameworks ship ready-made tools for this, but the principle fits in a few dozen lines of PHP, and understanding it prevents most incidents. Here’s the implementation we use as a starting point on applications that don’t have a queue yet.
A queue in your existing database
To get started you don’t need Redis or RabbitMQ: MySQL 8 or PostgreSQL does the job well, and it’s already backed up and monitored. One table is enough:
CREATE TABLE jobs (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
tenant_id BIGINT UNSIGNED NOT NULL,
type VARCHAR(100) NOT NULL,
payload JSON NOT NULL,
status ENUM('pending', 'running', 'done', 'failed') NOT NULL DEFAULT 'pending',
attempts TINYINT UNSIGNED NOT NULL DEFAULT 0,
available_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
reserved_at DATETIME NULL,
last_error TEXT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
KEY idx_pick (status, available_at, id)
);
Each row is a job: a type (which decides the code to run), JSON parameters, a status, an attempt counter and a time from which it can be processed, which also lets you schedule a job for later. The tenant_id column ties every job to a customer, which is essential in a multi-tenant app for logging, throttling or troubleshooting per customer. To add a job:
function dispatch(PDO $db, int $tenantId, string $type, array $payload, int $delay = 0): int
{
$stmt = $db->prepare(
'INSERT INTO jobs (tenant_id, type, payload, available_at)
VALUES (?, ?, ?, NOW() + INTERVAL ? SECOND)'
);
$stmt->execute([$tenantId, $type, json_encode($payload, JSON_THROW_ON_ERROR), $delay]);
return (int) $db->lastInsertId();
}
Call dispatch() inside the same transaction as the business record (the export request, say): if anything fails before commit, neither row exists. That’s a real advantage of a database queue. And keep only IDs in the payload, never serialised objects: the worker reloads fresh data when it runs.
The worker: reserve, run, retry
The worker is a command-line PHP script running in a loop. The tricky part is reservation: with several workers in parallel, two of them must never pick the same job. FOR UPDATE SKIP LOCKED (MySQL 8 and PostgreSQL 9.5+) handles this cleanly: each worker locks one row and skips rows already locked by others, without waiting.
function reserve(PDO $db): ?array
{
$db->beginTransaction();
$job = $db->query(
"SELECT * FROM jobs
WHERE status = 'pending' AND available_at <= NOW()
ORDER BY id
LIMIT 1
FOR UPDATE SKIP LOCKED"
)->fetch(PDO::FETCH_ASSOC);
if ($job === false) {
$db->commit();
return null;
}
$db->prepare(
"UPDATE jobs SET status = 'running', attempts = attempts + 1, reserved_at = NOW()
WHERE id = ?"
)->execute([$job['id']]);
$db->commit();
$job['attempts']++;
return $job;
}
The main loop exits on its own after a number of jobs or above a memory threshold: that regular restart prevents memory leaks and database connections dropped after a long idle period, two classic problems with PHP processes that run for days.
$handlers = [
'export.csv' => new ExportCsvHandler($db, $storage),
'mail.welcome' => new WelcomeMailHandler($mailer),
];
pcntl_async_signals(true);
$stop = false;
pcntl_signal(SIGTERM, function () use (&$stop) { $stop = true; });
$processed = 0;
while (!$stop && $processed < 500 && memory_get_usage(true) < 128 * 1024 * 1024) {
$job = reserve($db);
if ($job === null) {
sleep(2); // empty queue: wait a little before asking again
continue;
}
try {
$handler = $handlers[$job['type']]
?? throw new RuntimeException("Unknown job type: {$job['type']}");
$payload = json_decode($job['payload'], true, 512, JSON_THROW_ON_ERROR);
$handler->handle($payload, (int) $job['tenant_id']);
$db->prepare("UPDATE jobs SET status = 'done' WHERE id = ?")->execute([$job['id']]);
} catch (Throwable $e) {
fail($db, $job, $e);
}
$processed++;
}
// Exit cleanly: the supervisor starts a fresh process
On failure, don’t retry straight away: an external service that’s down will probably still be down a second later. Push the job back with an increasing delay, and mark it permanently failed after a few attempts, keeping the error message. A catch-up query also requeues jobs left in “running” because a worker was killed mid-task:
function fail(PDO $db, array $job, Throwable $e, int $maxAttempts = 5): void
{
$final = $job['attempts'] >= $maxAttempts;
$delay = min(3600, 30 * 2 ** ($job['attempts'] - 1)); // 30 s, 1 min, 2 min, 4 min…
$db->prepare(
"UPDATE jobs
SET status = ?, available_at = NOW() + INTERVAL ? SECOND, last_error = ?
WHERE id = ?"
)->execute([$final ? 'failed' : 'pending', $delay, mb_substr($e->getMessage(), 0, 2000), $job['id']]);
}
// Jobs stuck in 'running' after a worker crash: put them back in the queue
$db->exec(
"UPDATE jobs SET status = 'pending', available_at = NOW()
WHERE status = 'running' AND reserved_at < NOW() - INTERVAL 15 MINUTE"
);
The 15-minute window must be longer than your longest job, otherwise a job still in progress would be started again in parallel. Run that query when each worker starts, or from a scheduled task.
Running workers in production
A worker started by hand in a terminal stops when you log out. In production it needs a supervisor that starts it at boot, restarts it when it exits and keeps its logs. Supervisor is the most common; systemd works just as well if you already know it.
; /etc/supervisor/conf.d/app-worker.conf
[program:app-worker]
command=php /var/www/app/bin/worker.php
process_name=%(program_name)s_%(process_num)02d
numprocs=2
user=www-data
autostart=true
autorestart=true
stopsignal=TERM
stopwaitsecs=120
redirect_stderr=true
stdout_logfile=/var/log/app/worker.log
; At the end of every deployment:
; supervisorctl restart app-worker:*
Three points that have already cost us hours of debugging:
- Restart after every deployment. A worker keeps the code it loaded at start-up in memory: without a restart it keeps running the old version, sometimes for days.
- Stop gracefully. Catching
SIGTERMas above lets the worker finish its current job before exiting;stopwaitsecsmust cover a long job, otherwise Supervisor kills it halfway through. - Monitor the queue. A simple alert on the number of jobs pending for more than a few minutes, and on the number of
failedjobs, spots a dead worker long before customers report it.
Pitfalls, and when to move to a real broker
The main pitfall is conceptual: a job can run more than once. A worker killed right after sending an email but before marking the job done will see it retried. So every handler must be idempotent: check whether the export already exists, record that an email was sent and check before sending, use the idempotency keys payment APIs provide. It’s the same discipline as for webhooks.
This database queue comfortably handles a mid-sized application. When the jobs table starts weighing on your main database, or you need fine-grained priorities or very high throughput, move to Redis, RabbitMQ or a managed service. Laravel Queues and Symfony Messenger follow exactly these principles, with a database transport to begin with.
FAQ
Why not just use a cron job?
Cron suits periodic work (a nightly report). For a job triggered by a user it adds up to a minute of waiting, and two overlapping runs can process the same data. A queue with workers handles each job as soon as it arrives, with one worker at a time.
My shared hosting doesn’t allow long-running processes. What can I do?
Run the worker from cron every minute with a time limit (say 55 seconds or a fixed number of jobs), plus a lock to prevent two runs at once. It’s less responsive, but the rest of the mechanism is identical, and moving to a dedicated server later won’t require code changes.
Timing-out exports, slow emails, imports that freeze: we audit and evolve your SaaS architecture so it handles the load without a full rewrite. Let’s talk.



