Lesson 6 of 9 · 23m
Asynchronous PHP: Queues First, Fibers When They Earn Their Keep
The practical async toolbox — background jobs, workers, retries, event loops, fibers — and why moving work is usually better than doing it concurrently in-request.
The most scalable asynchronous PHP technique is not an event loop. It is refusing to do nonessential work inside the web request. Email, image processing, search indexing, webhook fanout, analytics, and cache warming belong in queues. A request that returns after writing the database row and enqueueing a job can survive traffic that destroys a request trying to do everything synchronously.
Queue the work that can wait
$queue->push(ProcessPodcastAudio::class, [
'episode_id' => $episode->id,
], delay: 0);A serious job system needs explicit behavior for retries, idempotency, and dead letters:
public function handle(ProcessPodcastAudio $job): void
{
if ($this->alreadyProcessed($job->episodeId)) {
return; // safe under retry
}
$this->audio->transcode($job->episodeId);
$this->markProcessed($job->episodeId);
}Workers must be idempotent because retries happen after partial failure. A job that creates a charge and then crashes before acknowledging will eventually create two charges unless the operation itself is idempotent.
Tune workers separately from web workers
Queue workers are long-lived PHP processes. They keep memory warm, leak differently, and often perform CPU-heavy work. Do not simply copy FPM settings. Control concurrency per queue:
php artisan queue:work redis --queue=high,default --sleep=1 --tries=3 --timeout=90
symfony console messenger:consume async --time-limit=3600 --memory-limit=256MSeparate urgent and slow queues. Otherwise image transcodes starve password-reset email.
Fibers and event loops have a narrow but real niche
PHP fibers, ReactPHP, AMPHP, Swoole, and OpenSwoole can overlap I/O inside a process. They shine for high-concurrency network clients, websocket servers, and long-running specialized services. They do not make blocking libraries nonblocking, and they demand discipline because accidental blocking stalls the loop.
$first = async(fn() => fetchProfile($id));
$second = async(fn() => fetchRecommendations($id));
[$profile, $recommendations] = await($first, $second);This is valuable when both calls are genuinely concurrent I/O. It is a liability if fetchProfile uses a blocking MySQL driver on the event loop.
Field notes
- A queue without monitoring is a black hole. Track backlog age, failure rate, retries, and dead-letter count.
- Timeouts for jobs should exceed expected runtime but remain finite; 'forever' is not a retry policy.
- Beware exactly-once mythology. Design for at-least-once delivery and idempotent handlers.
- Do not put mutable serialized objects in queues if deploys change their shape; serialize IDs and small explicit payloads.
Was this lesson helpful?