{
    "slug": "message_queue",
    "term": "Message Queue",
    "category": "messaging",
    "difficulty": "intermediate",
    "short": "A durable buffer that decouples the component producing work (producer) from the component processing it (consumer), enabling async processing, load levelling, and retry logic without direct coupling.",
    "long": "A message queue stores messages durably until a consumer processes and acknowledges them. Producers write messages and continue without waiting for processing to complete. Consumers pull messages at their own pace, process them, and acknowledge success — or reject and requeue on failure. This decoupling provides three key properties: temporal decoupling (producer and consumer do not need to be running simultaneously), rate decoupling (a traffic spike fills the queue rather than overwhelming the consumer), and failure isolation (a crashed consumer does not lose work; messages wait until it recovers). Common implementations used with PHP: Redis (via Predis or phpredis, using LPUSH/BRPOP or Streams), database-backed queues (Laravel Queue with MySQL/PostgreSQL), RabbitMQ (via php-amqplib), and Amazon SQS (via AWS SDK). The choice depends on durability requirements, throughput, and operational complexity tolerance.",
    "aliases": [
        "job queue",
        "task queue",
        "work queue",
        "queue",
        "async queue",
        "background queue"
    ],
    "tags": [
        "message-queue",
        "async",
        "background-jobs",
        "redis",
        "rabbitmq",
        "laravel-queue"
    ],
    "misconception": "A message queue guarantees exactly-once delivery. Almost all message queues guarantee at-least-once delivery — a message may be delivered more than once if the consumer crashes after processing but before acknowledging. Consumers must be idempotent: processing the same message twice must produce the same result as processing it once. Exactly-once delivery is significantly harder and comes with performance trade-offs; most systems are designed around at-least-once with idempotent consumers.",
    "why_it_matters": "Message queues are the standard solution for every PHP task that should not block an HTTP response: sending emails, generating PDFs, processing image uploads, making third-party API calls, and running reports. Without a queue, these operations either block the user waiting for them to complete, or fail silently when a downstream service is slow. With a queue, the HTTP response returns in milliseconds, the work happens asynchronously, failed jobs retry automatically, and traffic spikes absorb into the queue rather than crashing the application.",
    "common_mistakes": [
        "Not making consumers idempotent — at-least-once delivery means duplicate messages are inevitable; always design for it.",
        "Not setting a dead letter queue — messages that fail repeatedly should move to a DLQ for inspection, not be silently dropped or loop forever.",
        "Processing messages inside the HTTP request cycle — the whole point of a queue is to move work out of the request; processing synchronously negates the benefit.",
        "Using a queue for real-time communication — queues add latency; use WebSockets or Server-Sent Events for real-time features."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "pub_sub_pattern",
        "dead_letter_queue",
        "at_least_once_delivery",
        "kafka_concepts"
    ],
    "prerequisites": [],
    "refs": [
        "https://laravel.com/docs/queues",
        "https://redis.io/docs/data-types/streams/"
    ],
    "bad_code": "// Blocking the HTTP response — user waits for email\nclass OrderController {\n    public function store(Request $request) {\n        $order = Order::create($request->all());\n        // User waits 2-3 seconds for this\n        Mail::to($order->user)->send(new OrderConfirmation($order));\n        return response()->json($order, 201);\n    }\n}",
    "good_code": "// Async — response returns immediately\nclass OrderController {\n    public function store(Request $request) {\n        $order = Order::create($request->all());\n        // Dispatched to queue — returns in <10ms\n        SendOrderConfirmation::dispatch($order);\n        return response()->json($order, 201);\n    }\n}\n\n// Idempotent job handler\nclass SendOrderConfirmation implements ShouldQueue {\n    public function handle(): void {\n        // Check if already sent — safe to run twice\n        if ($this->order->confirmation_sent_at) return;\n        Mail::to($this->order->user)->send(new OrderConfirmation($this->order));\n        $this->order->update(['confirmation_sent_at' => now()]);\n    }\n}",
    "quick_fix": "Use Laravel Queue with the database driver to start (zero new infrastructure), switch to Redis for production performance, always implement idempotency checks in job handlers",
    "severity": "info",
    "effort": "medium",
    "created": "2026-03-23",
    "updated": "2026-03-23",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/message_queue",
        "html_url": "https://codeclaritylab.com/glossary/message_queue",
        "json_url": "https://codeclaritylab.com/glossary/message_queue.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Message Queue](https://codeclaritylab.com/glossary/message_queue) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/message_queue"
            }
        }
    }
}