Naar de inhoud
Recognized by Laravel Match je project Contact

Wachtrij-jobs correct configureren

Voor het laatst bijgewerkt op:

Beschrijving

Configureer Laravel queue-jobs met veilige timeouts, retries, uniciteit en foutafhandeling voor betrouwbaarheid in productie.

Aanbevolen situatie

Gebruik dit wanneer queue-jobs buiten de sync-driver draaien of belangrijk extern of gebruikersgericht werk uitvoeren.

Menselijke begeleiding

Naast het uitbesteden van businesslogica aan jobs (zie Houd commands klein en besteed uit aan jobs), moeten de jobs zelf goed geconfigureerd worden om betrouwbaar te zijn in productie. Dit omvat het instellen van correcte timeout- en retry-waarden, het toepassen van exponential backoff, het voorkomen van dubbele uitvoering, het expliciet afhandelen van fouten en het rate limiten van externe API-aanroepen.

Waarom

  • Voorkomt dubbele uitvoering: Wanneer retry_after korter is dan timeout, verdeelt de queue-worker de job opnieuw terwijl deze nog draait
  • Beschermt externe services: Exponential backoff en rate limiting voorkomen dat falende API's worden overspoeld
  • Expliciete foutafhandeling: Het implementeren van failed() zorgt ervoor dat fouten worden afgehandeld in plaats van stilzwijgend genegeerd
  • Gecontroleerde concurrency: ShouldBeUnique en WithoutOverlapping voorkomen dubbele en gelijktijdige verwerking van dezelfde data

Geschikt voor

  • Applicaties die queue-jobs in productie gebruiken
  • Jobs die externe API's aanroepen of kritieke data verwerken
  • Queue-deployments met meerdere workers of meerdere servers
  • Jobs die gebruikersgerichte operaties verwerken waarbij duplicaten of fouten zichtbaar zijn

Minder geschikt voor

  • Jobs die de sync-queue-driver gebruiken (alleen development/testing)
  • Eenvoudige fire-and-forget-jobs waarbij fouten acceptabel zijn

Voorbeelden

Stel retry_after hoger in dan timeout

class ProcessReport implements ShouldQueue
{
    public $timeout = 120;
}

// config/queue.php, retry_after must be longer than any job timeout
// retry_after: 180 ← safely longer

Gebruik exponential backoff

class SyncWithStripe implements ShouldQueue
{
    public $tries = 3;
    public $backoff = [1, 5, 10]; // seconds between retries
}

Voorkom dubbele jobverwerking

class GenerateInvoice implements ShouldQueue, ShouldBeUnique
{
    public function uniqueId(): string
    {
        return $this->order->id;
    }

    public $uniqueFor = 3600;
}

Implementeer altijd failed()

public function failed(?Throwable $exception): void
{
    $this->podcast->update(['status' => 'failed']);
    Log::error('Processing failed', [
        'id' => $this->podcast->id,
        'error' => $exception->getMessage(),
    ]);
}

Rate limit externe API-aanroepen

public function middleware(): array
{
    return [new RateLimited('external-api')];
}

Batch gerelateerde jobs

Bus::batch([
    new ImportCsvChunk($chunk1),
    new ImportCsvChunk($chunk2),
])
->then(fn (Batch $batch) => Notification::send($user, new ImportComplete))
->catch(fn (Batch $batch, Throwable $e) => Log::error('Batch failed'))
->dispatch();

Gebruik WithoutOverlapping voor concurrency-controle

public function middleware(): array
{
    return [
        (new WithoutOverlapping($this->product->id))
            ->releaseAfter(60)
            ->expireAfter(180),
    ];
}

Gebruik releaseAfter() om te bepalen hoe lang overlappende jobs moeten wachten voordat ze terug naar de queue worden vrijgegeven, en expireAfter() om ervoor te zorgen dat de lock uiteindelijk verloopt als de worker crasht of de job onverwacht een timeout krijgt.

Meer info

Boost-richtlijn

---
title: Configure Queued Jobs Properly
description: Configure Laravel queued jobs with safe timeouts, retries, uniqueness, and failure handling for production reliability.
recommended_situation: Use when queued jobs run outside the `sync` driver or handle important external or user-facing work.
---

- Set job `timeout`, `tries`, and queue `retry_after` coherently so long-running jobs are not retried while still executing.
- Use exponential backoff, rate limiting middleware, and explicit uniqueness or overlap controls for jobs that hit external services or shared resources.
- Implement `failed()` handling for jobs where failure state, cleanup, or observability matters.
- Use batching and queue middleware deliberately when coordinating related jobs or controlling concurrency.
Skill

Laravel Boost Skill

Gebruik deze skill om de richtlijn rechtstreeks toe te passen met een AI-assistent.

Use this skill when a Laravel task touches this best practice. It is self-contained so it can be installed independently by Laravel Boost or another agent-skill system.

## Core Guidance



## Why It Matters

- Apply the best practice consistently and keep the implementation focused.

## Apply When

- Laravel work that directly overlaps with this practice.

## Be Careful When

- Tasks outside this practice; use a more specific skill instead.

## Canonical Source

- Full best practice: https://github.com/Dutch-Laravel-Foundation/best-practices/blob/main/project-structure-and-code-architecture/configure-queued-jobs-properly/BEST_PRACTICE.md
- Dutch translation: https://github.com/Dutch-Laravel-Foundation/best-practices/blob/main/project-structure-and-code-architecture/configure-queued-jobs-properly/translations/nl.md

## Workflow

1. Inspect the user's Laravel code before recommending changes.
2. Identify the narrow rule from this best practice that applies to the task.
3. Prefer Laravel's built-in conventions and documented APIs over custom abstractions.
4. Keep examples focused on this practice; reference other skills or practices when the task crosses boundaries.
5. Verify code changes with the project's available tests, linters, static analysis, or framework checks.

## Review Checklist

- The recommendation is Laravel-specific and grounded in this practice.
- Code examples use realistic Laravel file names, class names, and method names.
- The advice avoids mixing unrelated architecture, deployment, security, or testing topics.
- Related practices are mentioned when useful, but not re-explained in full.
- Dutch output, when requested, keeps framework and API names intact.