{
    "slug": "long_polling",
    "term": "Long Polling & Server-Sent Events (SSE)",
    "category": "architecture",
    "difficulty": "intermediate",
    "short": "Server-side push techniques for PHP — long polling holds HTTP connections open until data is ready; SSE streams events over a persistent HTTP response.",
    "long": "Long polling: the client makes a request, the server holds it open (sleeping/waiting) until new data is available or a timeout occurs, then responds and the client immediately reconnects. Simple to implement in PHP but holds a PHP-FPM worker for the duration — inefficient under load. Server-Sent Events (SSE): the server sends a text/event-stream response and pushes data: payloads down over a persistent connection using ob_flush() and flush(). SSE is one-directional (server to client) and reconnects automatically. Both approaches consume a PHP worker per open connection — for high concurrency, a Node.js/Go push service with Redis Pub/Sub as the backend is more scalable.",
    "aliases": [
        "long poll",
        "HTTP long polling",
        "Comet"
    ],
    "tags": [
        "architecture",
        "realtime",
        "http",
        "websockets"
    ],
    "misconception": "Long polling and WebSockets are equivalent for real-time data. Long polling holds an HTTP connection open until data is available then the client reconnects — each message incurs connection overhead. WebSockets maintain a persistent bidirectional connection with far lower per-message latency.",
    "why_it_matters": "Long polling holds an HTTP connection open until data is available, giving near-real-time updates without WebSockets — but ties up server connections and requires careful timeout handling.",
    "common_mistakes": [
        "Not setting a server-side timeout — a connection held indefinitely exhausts worker threads.",
        "Not handling the client reconnect loop — when the server responds, the client must immediately re-poll.",
        "Using long polling when WebSockets or SSE are available and more efficient for the use case.",
        "Not tracking which clients are waiting and what data they have already seen — sending duplicate events."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "websockets",
        "async_processing",
        "redis_patterns",
        "output_buffering"
    ],
    "prerequisites": [
        "long_polling_sse",
        "websockets",
        "async_processing"
    ],
    "refs": [
        "https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events"
    ],
    "bad_code": "// Long poll without timeout — holds worker indefinitely:\nset_time_limit(0); // Dangerous — worker never freed\nwhile (true) {\n    $events = getNewEvents($lastId);\n    if (!empty($events)) { echo json_encode($events); exit; }\n    sleep(1);\n}\n// Fix: set_time_limit(30); respond with empty after timeout so client reconnects",
    "good_code": "// SSE in PHP\nheader('Content-Type: text/event-stream');\nheader('Cache-Control: no-cache');\nwhile (true) {\n    echo 'data: ' . json_encode(getUpdate()) . \"\\n\\n\";\n    ob_flush(); flush();\n    sleep(1);\n}",
    "quick_fix": "Use Server-Sent Events instead of long polling for PHP — SSE is simpler, uses one connection, and auto-reconnects; long polling creates a new HTTP connection for every update which wastes resources",
    "severity": "info",
    "effort": "medium",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/long_polling",
        "html_url": "https://codeclaritylab.com/glossary/long_polling",
        "json_url": "https://codeclaritylab.com/glossary/long_polling.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": "[Long Polling & Server-Sent Events (SSE)](https://codeclaritylab.com/glossary/long_polling) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/long_polling"
            }
        }
    }
}