{
    "slug": "pub_sub_pattern",
    "term": "Pub/Sub Pattern",
    "category": "messaging",
    "difficulty": "beginner",
    "short": "Pub/Sub (Publish-Subscribe) decouples senders from receivers — publishers emit events to topics, all interested subscribers receive them without knowing each other.",
    "long": "Publisher sends to a Topic/Channel — it doesn't know who's listening. Subscribers declare interest in topics. Broker delivers to all active subscribers. Implementations: Redis PUBLISH/SUBSCRIBE, Kafka topics, RabbitMQ fanout exchange, SNS+SQS (AWS), Google Pub/Sub. Difference from point-to-point queue: queue delivers to ONE consumer; pub/sub delivers to ALL subscribers. Use cases: event broadcasting (user registered → email + analytics + audit + recommendation all receive it), real-time feeds (dashboard updates). Fan-out: one event → many independent handlers. Redis pub/sub doesn't persist — subscribers miss messages while offline; use Redis Streams for durability.",
    "aliases": [],
    "tags": [
        "messaging",
        "pub-sub",
        "events",
        "decoupling"
    ],
    "misconception": "Pub/Sub and message queues are the same — pub/sub broadcasts to all subscribers; queues deliver to one consumer. Redis SUBSCRIBE delivers to active subscribers only; Kafka delivers to all consumer groups including future ones.",
    "why_it_matters": "Pub/Sub enables truly decoupled event-driven architecture — a new subscriber can be added without changing the publisher, enabling independent feature development.",
    "common_mistakes": [
        "Using Redis SUBSCRIBE for durable events — messages are lost if subscriber is offline.",
        "Publishing events that are too granular — hundreds of tiny events create consumer overhead.",
        "Not considering message ordering when multiple publishers write to the same topic."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "message_broker",
        "kafka_concepts",
        "rabbitmq_concepts",
        "event_driven_concurrency"
    ],
    "prerequisites": [
        "message_broker"
    ],
    "refs": [
        "https://redis.io/docs/manual/pubsub/"
    ],
    "bad_code": "// Redis SUBSCRIBE — volatile, lost if offline:\n$redis->subscribe(['user.registered'], function($redis, $channel, $msg) {\n    sendWelcomeEmail($msg); // Missed if worker was down during publish\n});",
    "good_code": "// Redis Streams — durable pub/sub:\n$redis->xadd('user.events', '*', ['event' => 'registered', 'user_id' => $id]);\n\n// Consumer group reads with acknowledgement:\n$msgs = $redis->xreadgroup('email-group', 'worker-1', ['user.events' => '>']);\nforeach ($msgs['user.events'] as $id => $fields) {\n    sendWelcomeEmail($fields['user_id']);\n    $redis->xack('user.events', 'email-group', $id);\n}",
    "quick_fix": "Use Redis Streams (not SUBSCRIBE) for durable pub/sub. Use Kafka for high-throughput multi-subscriber events. Design events to be self-contained and idempotent.",
    "severity": "info",
    "effort": "medium",
    "created": "2026-03-23",
    "updated": "2026-03-23",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/pub_sub_pattern",
        "html_url": "https://codeclaritylab.com/glossary/pub_sub_pattern",
        "json_url": "https://codeclaritylab.com/glossary/pub_sub_pattern.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": "[Pub/Sub Pattern](https://codeclaritylab.com/glossary/pub_sub_pattern) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/pub_sub_pattern"
            }
        }
    }
}