惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
Security Archives - TechRepublic
Security Archives - TechRepublic
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Last Week in AI
Last Week in AI
博客园 - 司徒正美
阮一峰的网络日志
阮一峰的网络日志
WordPress大学
WordPress大学
爱范儿
爱范儿
J
Java Code Geeks
T
Tailwind CSS Blog
Apple Machine Learning Research
Apple Machine Learning Research
人人都是产品经理
人人都是产品经理
宝玉的分享
宝玉的分享
博客园 - 【当耐特】
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Help Net Security
Help Net Security
Hacker News: Ask HN
Hacker News: Ask HN
月光博客
月光博客
S
Secure Thoughts
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 聂微东
Hugging Face - Blog
Hugging Face - Blog
V
Visual Studio Blog
博客园 - 三生石上(FineUI控件)
O
OpenAI News
酷 壳 – CoolShell
酷 壳 – CoolShell
N
News and Events Feed by Topic
腾讯CDC
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Webroot Blog
Webroot Blog
博客园 - Franky
有赞技术团队
有赞技术团队
美团技术团队
Jina AI
Jina AI
S
Security @ Cisco Blogs
博客园 - 叶小钗
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园_首页
C
CERT Recently Published Vulnerability Notes
T
Threat Research - Cisco Blogs
Project Zero
Project Zero
A
Arctic Wolf
大猫的无限游戏
大猫的无限游戏
Latest news
Latest news
小众软件
小众软件
IT之家
IT之家
S
Security Affairs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Laravel Queue Architecture: Designing Background Work That Holds Up
Shakil Alam · 2026-04-25 · via DEV Community

Part 2 of 4 — Laravel Architecture Patterns for Production
~9 min read · Queue design · Job architecture · Background processing


Background jobs are one of those features that feel solved the moment they work. You dispatch, it runs in the background, life is good. The framework handles it.

The illusion holds until scale arrives. Then a password reset email sits behind a 90-second video compression job. A job that hits a flaky external API fails, retries, fails, retries — consuming worker processes while real work waits. A bulk operation dispatches 5,000 jobs at once and the queue system staggers under the spike. A crash halfway through a file operation leaves corrupted data you do not notice for three days.

None of these are framework failures. They are design failures — decisions that were not made explicitly, so they defaulted to the wrong thing.

This article is about the decisions, and the reasoning behind them.


What you will learn

  • Why passing an Eloquent model to a job constructor is wrong — and what to pass instead
  • How to design a queue topology before you are forced to by a problem
  • What retry strategy to use for transient, rate-limited, and permanent failures
  • How to write file operations that leave no corrupted state when a job crashes mid-write

The mental model: a queue is not a to-do list

Most queue problems come from treating a queue as a simple list — things go in, things come out, in order. That model works fine for small volumes. It breaks under pressure.

The more accurate mental model: a queue is a work contract between the part of your system that knows something needs to happen and the part that will do it — separated by time, by process restarts, and by failures. The job payload is a self-contained instruction. It cannot assume anything about the context that created it still exists.

That one shift — from "list of tasks" to "self-contained work contract" — makes the rest of this article's decisions feel obvious rather than arbitrary.


What to put in a job constructor — and what not to

The most frequent queue mistake is passing an Eloquent model to a job constructor:

// This seems fine. It is not.
CompressVideo::dispatch($media);

Enter fullscreen mode Exit fullscreen mode

When a job is dispatched, its constructor arguments are serialized into the queue payload. Laravel's SerializesModels trait handles this by storing the model's class and primary key — and re-fetching the model when the job runs. That sounds correct, but consider: the job might run 30 seconds later. Or three hours later if the queue is backed up. The record may have been updated, soft-deleted, or had its status changed in the time between dispatch and execution.

If the job carries a serialized model, it works with the snapshot from dispatch time. If the job carries an ID, it fetches current data at execution time.

class CompressMediaVideo implements ShouldQueue
{
    public function __construct(private readonly int $mediaId) {}

    public function handle(VideoCompressorService $compressor): void
    {
        // Fetch fresh at execution time, not stale from dispatch time
        $media = Media::findOrFail($this->mediaId);

        if (!str_starts_with($media->mime_type, 'video/')) {
            return; // State may have changed since dispatch — handle gracefully
        }

        $compressor->compress($media);
    }
}

Enter fullscreen mode Exit fullscreen mode

Pass IDs, not models. The job's responsibility is to do a unit of work starting from first principles — not to continue a conversation that started somewhere else.


The single responsibility principle, applied to jobs

A job class should do one thing. This sounds obvious. It is regularly violated.

The problem with jobs that do multiple things: when one part fails, the whole job fails. If a job compresses a video, updates the database, sends a notification, and syncs to an external system, and the external sync times out — the compression was done, but the job retries and runs compression again. The retry was meant to retry the sync. You have wasted CPU, potentially introduced a duplicate notification, and made the job's retry behaviour unpredictable.

The cleaner design — one job per responsibility, chained. Note that the constructor is still required on each class:

class CompressMediaVideo implements ShouldQueue
{
    public function __construct(private readonly int $mediaId) {}

    public function handle(VideoCompressorService $compressor): void
    {
        $media = Media::findOrFail($this->mediaId);
        $compressor->compress($media);

        // Compression done — dispatch the next unit of work independently
        UpdateMediaMetadata::dispatch($this->mediaId)->onQueue('default');
    }
}

Enter fullscreen mode Exit fullscreen mode

Each job is independently retryable. A failure in metadata update does not re-run compression. You can add monitoring per job type and scale workers for specific job types independently.


Queue topology: the decision nobody makes until they have to

A single default queue works until it does not. The moment you have both time-sensitive operations (password resets, OTPs) and long-running operations (report generation, bulk compression) on the same queue, you have a priority problem the queue itself cannot solve.

The topology decision — which queues exist and what runs on each — should be made before the first job is deployed, not when a user complains their OTP never arrived because it was stuck behind a batch export.

A practical topology:

Queue Purpose Acceptable delay
critical Password resets, OTPs, security alerts None — delay means users cannot access the system
default Notifications, status updates, lightweight tasks A few seconds
media Video compression, image processing Minutes — slow and CPU-intensive
sync External API sync jobs Variable — isolate third-party failures
reports Bulk exports, large queries Can take minutes — must never starve other queues

Workers listen to queues in priority order:

# Critical has its own dedicated worker — nothing else competes
php artisan queue:work redis --queue=critical --timeout=30

# This worker handles default first, then media if default is empty
php artisan queue:work redis --queue=default,media --timeout=120

# Sync worker — isolated so third-party failures never affect your own queues
php artisan queue:work redis --queue=sync --timeout=60

# Reports isolated — slow timeouts do not affect other workers
php artisan queue:work redis --queue=reports --timeout=600

Enter fullscreen mode Exit fullscreen mode

Why isolate sync? External API reliability is outside your control. If a third-party goes down and you are retrying aggressively, those retry jobs accumulate in the queue. On a shared queue, they compete for worker processes with your own jobs. An isolated sync queue means a third-party outage only affects sync workers — your application's own background work continues unaffected.

If you are on Redis and can run a dashboard, Laravel Horizon gives you queue depth, throughput, and failed job monitoring out of the box. If you are on a database driver or a locked environment, a php artisan queue:failed count in a scheduled log check covers the essentials.


Retry strategy: not all failures are equal

The default retry behaviour — try N times, then give up — is right for some jobs and wrong for others. Thinking about failure modes before writing the job saves you from the wrong defaults.

Transient failures

Database hiccups, brief network timeouts — things that will probably succeed on retry:

public int $tries  = 3;
public int $backoff = 5; // Wait 5 seconds between retries

Enter fullscreen mode Exit fullscreen mode

Rate-limited or service-down failures

External API unavailable, rate limit hit — back off with increasing delays:

public int $tries = 5;

public function backoff(): array
{
    // 30s, 60s, 120s, 240s, 480s between retries
    return [30, 60, 120, 240, 480];
}

public function retryUntil(): \DateTime
{
    // Regardless of tries, give up after 24 hours
    // Prevents zombie jobs accumulating during prolonged outages
    return now()->addHours(24);
}

Enter fullscreen mode Exit fullscreen mode

Permanent failures

Malformed input, a record that will never exist — do not retry at all:

public int $tries = 1;

public function failed(\Throwable $e): void
{
    // Alert immediately — this needs human attention, not retry
    logger()->critical('Permanent job failure', [
        'job'   => static::class,
        'error' => $e->getMessage(),
    ]);
}

Enter fullscreen mode Exit fullscreen mode

Why timeout and tries are different things, and why it matters: A job that hits $timeout is killed and returns to the queue — it counts as a retry. A job that exhausts $tries goes to failed_jobs. If you set timeout = 120 and tries = 3 on a job that consistently takes 130 seconds, it will time out three times and land in failed_jobs — never completing, consuming three worker-slots in the process.

Common mistake: Setting $timeout lower than the job's typical execution time. Every time the job runs, it gets killed before finishing, counts as a retry, and eventually exhausts $tries without ever succeeding. If a job needs 90 seconds, give it at least 120. The timeout is a safety net, not a target.


Processing large backlogs: the Artisan command pattern

When you need to dispatch jobs for thousands of existing records — a backlog compression, a data migration, a bulk recalculation — the dispatch mechanism is as important as the job itself.

The pattern: an Artisan command that chunks through the database and dispatches jobs incrementally, with a --dry-run option before you commit to anything:

class ProcessBacklogCommand extends Command
{
    protected $signature = 'media:compress-videos
        {--id=      : Process a single record by ID}
        {--dry-run  : Show what would run without dispatching anything}
        {--chunk=200: Records per batch}';

    public function handle(): void
    {
        // If --id is provided, scope the query to that single record
        $query = Media::query()
            ->where('mime_type', 'like', 'video/%')
            ->whereNull('compressed_at')
            ->when($this->option('id'), fn ($q) => $q->where('id', $this->option('id')));

        $total = $query->count();
        $this->info("Found {$total} records to process.");

        if ($this->option('dry-run')) {
            $this->info('Dry run complete — no jobs dispatched.');
            return;
        }

        $dispatched = 0;
        $query->chunkById((int) $this->option('chunk'), function ($batch) use (&$dispatched) {
            foreach ($batch as $record) {
                CompressMediaVideo::dispatch($record->id)->onQueue('media');
                $dispatched++;
            }
            $this->info("Dispatched {$dispatched} jobs so far...");
        });

        $this->info("Done. Total dispatched: {$dispatched}");
    }
}

Enter fullscreen mode Exit fullscreen mode

Why chunkById instead of chunk? Laravel's chunk() uses SQL OFFSET — which means the database must count and skip N rows before returning the next batch. On a table with a million rows, the 500th batch requires skipping 100,000 rows. It gets progressively slower. chunkById uses WHERE id > $lastSeen LIMIT $chunk — a keyset cursor. The query time is constant regardless of position. For large tables, this is the difference between a command that completes in minutes and one that times out.

Why --dry-run as a first-class option? Because the first time you run a bulk dispatch against production data, you want to see what would happen before it happens. --dry-run costs nothing to add and saves numerous "I did not realise it would dispatch 40,000 jobs" moments.


Atomic file operations: designing for crashes

Any job that writes a file must assume it will crash mid-write. At scale, it happens. The question is what state the system is in when it does.

Write directly to the target path: a crash leaves a partial, corrupted file where the original was. The damage is permanent until manual intervention.

Write to a temporary file, then rename:

$inputPath = $media->full_path;
$tempPath  = $inputPath . '.tmp.' . uniqid();

// All writes go here — a crash here leaves the original untouched
$this->runFFmpeg($inputPath, $tempPath);

// Only replace if the output is actually better
if (filesize($tempPath) >= filesize($inputPath)) {
    @unlink($tempPath);
    return; // Original was already optimal — do not replace it
}

// rename() is atomic on POSIX filesystems — this either completes
// or does not happen. There is no in-between state.
rename($tempPath, $inputPath);

Enter fullscreen mode Exit fullscreen mode

Why compare sizes before replacing? Re-encoding an already-compressed file can produce a larger output — the encoding overhead outweighs the savings. Always verify the output is an improvement before discarding the original.

Why is rename() atomic? On Linux and macOS, rename() is a single filesystem syscall. The kernel guarantees it either moves the file or does not — there is no half-way state where the destination file is partially written. The old file remains intact until the new one is fully in place.


The shape of a well-designed job

Bringing it together:

class CompressMediaVideo implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries   = 3;
    public int $timeout = 120;
    public int $backoff = 60;

    // Takes an ID, not a model
    public function __construct(private readonly int $mediaId) {}

    public function handle(VideoCompressorService $compressor): void
    {
        // Fetches fresh at execution time
        $media = Media::findOrFail($this->mediaId);

        // Guards for state changes since dispatch
        if (!str_starts_with($media->mime_type, 'video/')) {
            return;
        }

        $compressor->compress($media);
    }

    // Failure handling is not an afterthought
    public function failed(\Throwable $exception): void
    {
        logger()->error('Video compression failed after all retries', [
            'media_id' => $this->mediaId,
            'error'    => $exception->getMessage(),
        ]);
    }
}

Enter fullscreen mode Exit fullscreen mode

This job takes an ID not a model, fetches fresh data at execution time, guards against state changes since dispatch, has a meaningful failed() handler, and has timeout, retry, and backoff values that reflect actual job characteristics — not framework defaults.


The key insight from this article: Queue failures are almost never framework failures — they are design failures. Passing IDs not models, setting explicit timeout and retry values, and separating work by queue type are decisions that should be made before the first job is deployed, not after the first incident.

Before you ship — checklist

  • [ ] Queue topology is defined — not everything on default
  • [ ] Every job constructor takes an ID, not an Eloquent model
  • [ ] Every job has $tries, $timeout, and $backoff explicitly set — not left to framework defaults
  • [ ] Every job has a failed() method that logs meaningful context
  • [ ] $timeout is comfortably higher than the job's typical execution time
  • [ ] Bulk dispatch commands use chunkById, not chunk
  • [ ] Bulk commands have a --dry-run option
  • [ ] Any job that writes a file writes to .tmp first, then rename() — never directly to the target path

Previous: Part 1 — The Audit Trail