🌍 Networking

Long Polling

Long Polling

Long Polling is an HTTP-based real-time communication technique in which the server holds the connection open until it has new data. A technology that predates WebSocket/SSE, where timeout handling is key.

📖 Detailed Explanation

Long Polling is a technique for implementing near real-time communication over the HTTP protocol. When a client sends a request to the server, the server holds the response and keeps the connection open until new data is available. When the data is ready, the server sends the response, and the client immediately starts a new request. By repeating this cycle, a real-time communication effect is achieved.

The difference from regular Polling is important. In regular Polling, the client sends requests to the server periodically (e.g., every second) to check whether there is new data. In contrast, Long Polling keeps the connection open until the server has data, which reduces unnecessary requests and minimizes data delivery latency. It became widely known around 2005 when it was adopted by Gmail, Google Maps, and others.

The key to Long Polling is timeout handling. Since the server cannot keep the connection open forever, it sends an empty response or a heartbeat after a certain period (usually 20–30 seconds) and closes the connection. When the client receives this, it immediately starts a new request. This timeout prevents firewalls and proxy servers from closing the connection and serves to detect dropped connections.

With the emergence of WebSocket and SSE (Server-Sent Events), the use of Long Polling has declined, but it is still used in legacy systems and in environments that support only HTTP (some corporate firewalls, old proxies). Facebook Messenger's use of Long Polling until the early 2010s is a representative example.

📊 Real-Time Communication Method Comparison

Method Connection Persistence Latency Server Load Browser Support
Polling New connection for every request As often as the polling interval High (unnecessary requests) All browsers
Long Polling Maintained until data arrives Near real-time Medium All browsers
SSE Unidirectional persistent connection Real-time Low Most browsers except IE
WebSocket Bidirectional persistent connection Real-time Low Modern browsers

💻 Code Example

// Long Polling 클라이언트 구현
class LongPollingClient {
    constructor(url) {
        this.url = url;
        this.isRunning = false;
        this.retryDelay = 1000;  // 에러 시 재시도 지연
        this.maxRetries = 5;
        this.retryCount = 0;
    }

    // 폴링 시작
    async start() {
        this.isRunning = true;
        this.poll();
    }

    // 폴링 중지
    stop() {
        this.isRunning = false;
    }

    async poll() {
        if (!this.isRunning) return;

        try {
            // 타임아웃 설정 (서버보다 길게)
            const controller = new AbortController();
            const timeout = setTimeout(() => controller.abort(), 35000);

            const response = await fetch(this.url, {
                method: 'GET',
                signal: controller.signal,
                headers: { 'Accept': 'application/json' }
            });

            clearTimeout(timeout);

            if (response.ok) {
                const data = await response.json();
                this.retryCount = 0;  // 성공 시 재시도 카운트 리셋

                if (data.type !== 'timeout') {
                    this.onMessage(data);  // 새 데이터 처리
                }
            }

            // 즉시 다음 폴링 시작
            this.poll();

        } catch (error) {
            if (error.name === 'AbortError') {
                console.log('요청 타임아웃, 재연결...');
                this.poll();
            } else {
                console.error('폴링 에러:', error);
                this.handleError();
            }
        }
    }

    handleError() {
        if (this.retryCount < this.maxRetries) {
            this.retryCount++;
            const delay = this.retryDelay * Math.pow(2, this.retryCount);
            console.log(`${delay}ms 후 재시도 (${this.retryCount}/${this.maxRetries})`);
            setTimeout(() => this.poll(), delay);
        } else {
            console.error('최대 재시도 횟수 초과');
            this.onError('연결 실패');
        }
    }

    onMessage(data) { console.log('새 메시지:', data); }
    onError(error) { console.error('에러:', error); }
}

// 사용 예시
const client = new LongPollingClient('/api/events');
client.onMessage = (data) => {
    document.getElementById('messages').innerHTML += `

${data.message}

`; }; client.start();
const express = require('express');
const app = express();

// 대기 중인 클라이언트들
const waitingClients = new Map();
let clientId = 0;

// Long Polling 엔드포인트
app.get('/api/events', (req, res) => {
    const id = ++clientId;
    const timeout = 30000;  // 30초 타임아웃

    console.log(`클라이언트 ${id} 연결`);

    // 타임아웃 설정
    const timer = setTimeout(() => {
        waitingClients.delete(id);
        res.json({ type: 'timeout', message: 'No new data' });
    }, timeout);

    // 클라이언트 등록
    waitingClients.set(id, { res, timer });

    // 연결 종료 시 정리
    req.on('close', () => {
        clearTimeout(timer);
        waitingClients.delete(id);
        console.log(`클라이언트 ${id} 연결 종료`);
    });
});

// 새 메시지 발행 (모든 대기 클라이언트에게 전송)
app.post('/api/broadcast', express.json(), (req, res) => {
    const message = req.body;

    // 모든 대기 클라이언트에게 메시지 전송
    waitingClients.forEach((client, id) => {
        clearTimeout(client.timer);
        client.res.json({
            type: 'message',
            data: message,
            timestamp: Date.now()
        });
    });

    const count = waitingClients.size;
    waitingClients.clear();

    res.json({ success: true, deliveredTo: count });
});

// 서버 상태 확인
app.get('/api/status', (req, res) => {
    res.json({
        waitingClients: waitingClients.size,
        uptime: process.uptime()
    });
});

app.listen(3000, () => {
    console.log('Long Polling 서버 실행 중 (포트 3000)');
});
from flask import Flask, request, jsonify
import time
import threading
from queue import Queue, Empty

app = Flask(__name__)

# 메시지 큐 (실제로는 Redis Pub/Sub 등 사용)
message_queues = {}
lock = threading.Lock()

@app.route('/api/events')
def long_poll():
    """Long Polling 엔드포인트"""
    client_id = request.args.get('client_id', str(time.time()))
    timeout = 30  # 30초 타임아웃

    # 클라이언트별 큐 생성
    with lock:
        if client_id not in message_queues:
            message_queues[client_id] = Queue()

    queue = message_queues[client_id]

    try:
        # 타임아웃까지 메시지 대기
        message = queue.get(timeout=timeout)
        return jsonify({
            'type': 'message',
            'data': message,
            'timestamp': time.time()
        })
    except Empty:
        # 타임아웃 - 빈 응답 반환
        return jsonify({
            'type': 'timeout',
            'message': 'No new data'
        })

@app.route('/api/broadcast', methods=['POST'])
def broadcast():
    """모든 대기 클라이언트에게 메시지 전송"""
    data = request.json

    delivered = 0
    with lock:
        for client_id, queue in message_queues.items():
            queue.put(data)
            delivered += 1

    return jsonify({
        'success': True,
        'delivered_to': delivered
    })

@app.route('/api/status')
def status():
    """서버 상태 확인"""
    with lock:
        return jsonify({
            'active_clients': len(message_queues)
        })

if __name__ == '__main__':
    app.run(port=3000, threaded=True)

🗣️ Say It Like This in Practice

💬 In a Technology Selection Meeting
"It's a real-time notification feature, but the client's firewall is blocking WebSocket. If we implement it with Long Polling, it uses only HTTP, so we can avoid the firewall problem. We just need to set the timeout to 30 seconds and keep it shorter than the proxy timeout."
💬 In an Interview
"Long Polling is one of the Comet techniques in which the server keeps an HTTP connection open until it has data. Back when WebSocket did not exist, Gmail implemented real-time mail notifications this way. The key is timeout handling and reconnection logic, and the client must start a new request as soon as it receives a response."
💬 In a Performance Optimization Discussion
"We're currently handling 10,000 concurrent users with Long Polling, but each connection occupies a server thread, so resource efficiency is low. If we use asynchronous I/O such as Node.js or Python asyncio, or migrate to SSE, we can handle 10 times more connections on the same server."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Ignoring Timeout Settings

If the server keeps connections open forever without a timeout, proxies/firewalls will drop the connection or zombie connections will accumulate. Be sure to set a 20–30 second timeout, and set the client timeout longer than the server's (e.g., 35 seconds).

❌
Missing Reconnection Logic

Polling stops on network errors or server restarts. Be sure to implement reconnection logic with exponential backoff. First retry after 1 second, then 2, 4, 8 seconds... up to a maximum of 30 seconds.

❌
Thread Exhaustion on Synchronous Servers

If you implement Long Polling on a thread-based server such as Apache/PHP, each connection occupies a thread and the server quickly becomes paralyzed. Use an asynchronous I/O-based server such as Node.js, Python asyncio, or Go.

✅
Correct Long Polling Implementation

Set the server timeout to 30 seconds and the client timeout to 35 seconds. Exponential backoff reconnection logic is required. Use an asynchronous server. Connection limits and monitoring are required. If possible, consider migrating to WebSocket or SSE.

🔗 Related Terms

📚 Learn More