Polling With Examples

Polling With Examples

·

7 min read

Table of contents

Request polling, often referred to simply as polling, is a client-server communication technique where a client repeatedly sends requests to a server at fixed intervals to check for updates or new data. The server responds to each request with the current information or status. This process continues indefinitely as the client continues to poll the server at regular intervals.

Here's how to request polling works:

  • Client Request: The client sends a request to the server, typically using a standard request-response protocol such as HTTP. The request asks for specific information, data, or updates.

  • Server Response: The server processes the client's request and responds with the requested data or information. If there are no updates, the response may indicate that there is no new information.

  • Client Wait: After receiving a response from the server, the client waits for a predetermined interval before sending the next request. This waiting period is often fixed and can range from milliseconds to minutes, depending on the application's requirements.

  • Repeat: The client repeats this process continuously, sending requests at regular intervals and receiving responses from the server. This continues as long as the client needs to monitor for updates or new data.

Request polling is commonly used in various scenarios, including:

  • Real-Time Updates: Polling can be used to implement real-time updates in web applications, where clients periodically check for new messages, notifications, or changes in data, such as in social media feeds or chat applications.

  • Data Synchronization: In mobile applications and synchronization tasks, polling can be used to check for changes in remote data sources and keep local data up to date.

  • Monitoring and Alerts: Polling can be used in monitoring systems to check the status of servers, network devices, or sensors and generate alerts when specific conditions are met.

  • Resource Availability: Polling can be used to check the availability of resources, such as checking for available appointment slots, rental availability, or stock availability on an e-commerce website.

While request polling is a straightforward method, it has some drawbacks:

  • Latency: Polling introduces latency because the client must wait for the next polling interval before receiving updates. If the polling interval is long, there may be a delay in receiving real-time information.

  • Server Load: Frequent polling can generate a significant load on the server, especially when many clients are polling simultaneously. This may require the server to handle a large number of requests, potentially affecting its performance.

  • Inefficiency: Polling can be inefficient, as clients may send requests even when there are no updates. This can waste network bandwidth and server resources.

To address these limitations, more advanced communication techniques like long polling, Server-Sent Events (SSE), and WebSockets have been developed to provide real-time updates with lower latency and reduced server load compared to traditional request polling. These alternatives are often preferred for building responsive and efficient real-time applications.

Short Pooling

Short polling, also known as regular or standard polling, is a client-server communication technique where a client sends periodic requests to a server to check for updates or new data at fixed intervals. In short polling, the client sends a request, waits for a response, and then immediately sends another request, regardless of whether there are updates available. This process repeats continuously.

Here's how short polling works:

  • Client Request: The client sends a request to the server at regular intervals, typically using a standard request-response protocol such as HTTP.

  • Server Response: The server processes the client's request and responds with the current information or status. If there are no updates, the response may indicate that there is no new information.

  • Client Wait and Repeat: After receiving a response from the server, the client immediately sends another request, starting the process over. This continuous cycle of sending requests and waiting for responses continues indefinitely.

Short polling is straightforward to implement and is commonly used in various applications where real-time updates are not critical, and a slight delay in receiving information is acceptable. However, it has some limitations:

  • Latency: Short polling introduces latency because the client must wait for the next polling interval before receiving updates. This can result in delays in receiving real-time information

  • Network and Server Load: Frequent short polling can generate significant network traffic and server load, especially when many clients are polling simultaneously. The server has to handle a constant stream of requests, even if there are no updates.

  • Inefficiency: Short polling can be inefficient, as clients send requests even when there are no updates available, leading to unnecessary use of network bandwidth and server resources

Due to these limitations, more advanced communication techniques, such as long polling, Server-Sent Events (SSE), and WebSockets, have become popular choices for building real-time applications, as they offer lower latency and reduced server load compared to traditional short polling.

Here goes the example of short polling

const app = require("express")();
const jobs = {};

app.post("/submit", (req, res)=> {
    const jobId = `job:${Date.now()}`;
    jobs[jobId] = 0;
    updateJob(jobId, 0);
    res.send("\n\n"+jobId+"\n\n");
});

app.get("/checkstatus", (req, res)=> {
    console.log(jobs[req.query.jobId]);
    res.end("\n\nJobStatus: " + jobs[req.query.jobId] + "%\n\n");
});

app.listen(3000, ()=> console.log("listening on 3000"));

function updateJob(jobId, prg) {
    jobs[jobId] = prg;
    console.log(`updated ${jobId} to ${prg}`);
    if (prg == 100) return;
    this.setTimeout(()=> updateJob(jobId, prg+10), 3000);
}

Long Polling

Long polling is a client-server communication technique that addresses some of the limitations of traditional short polling, allowing for near-real-time updates and reduced server load. In long polling, the client sends a request to the server, and instead of immediately responding, the server holds the request open until it has new data to send or a certain timeout is reached. This approach enables the server to push data to the client as soon as it becomes available, making it suitable for real-time and event-driven applications

Here's how long polling works:

  • Client Request: The client sends an HTTP request to the server, just like in short polling or regular HTTP communication.

  • Server Processing: Upon receiving the client's request, the server does not respond immediately. Instead, it waits for one of the following conditions to be met:

    • New Data: If new data or updates are available, the server immediately sends a response containing the data to the client.

    • Timeout: If no updates are available within a certain time limit (the "long" in long polling), the server responds with an empty response or a specific message to indicate that no updates are available.

  • Client Response Handling: The client receives the server's response and processes the data or handles the timeout message, if applicable. After handling the response, the client initiates a new request, restarting the long polling process.

  • Repeat: The long polling process repeats continuously, with the client sending new requests after each response is received or after a timeout occurs.

Long polling has several advantages and use cases:

  • Reduced Latency: Long polling reduces latency compared to traditional short polling because updates can be pushed from the server to the client as soon as they are available, rather than waiting for the next polling interval.

  • Efficiency: Long polling is more efficient in terms of network and server resource usage than short polling because the server holds fewer open connections. This makes it more scalable for applications with many clients.

  • Real-Time Updates: Long polling is suitable for building real-time applications, such as chat applications, news feeds, and collaborative tools, where timely updates are essential.

However, long polling also has some limitations:

  • Complexity: Implementing long polling can be more complex than traditional short polling because it requires handling open connections and managing timeouts effectively.

  • Resource Usage: While long polling reduces the number of open connections compared to short polling, it still requires servers to maintain open connections, which can be resource-intensive under heavy loads.

  • Potential for Stale Data: In some cases, long polling may result in slightly stale data because the client may not receive updates immediately, depending on the timing of the server's response.

In summary, long polling is a communication technique that strikes a balance between real-time updates and reduced server load compared to short polling. It is a valuable choice for building responsive and efficient real-time applications but may require careful implementation to handle open connections and timeouts effectively.

Here goes the example of long polling:

const app = require("express")();
const jobs = {};

app.post("/submit", (req, res)=> {
    const jobId = `job:${Date.now()}`;
    jobs[jobId] = 0;
    updateJob(jobId, 0);
    res.send("\n\n"+jobId+"\n\n");
});

app.get("/checkstatus", (req, res)=> {
    console.log(jobs[req.query.jobId]);
    while(await checkJobComplete(req.query.jobId) == false);
    res.end("\n\nJobStatus: " + jobs[req.query.jobId] + "%\n\n");
});

app.listen(3000, ()=> console.log("listening on 3000"));

function checkJobComplete(jobId) {
    return new Promise((resolve, reject)=> {
        if (jobs[jobId] < 100) {
            this.setTimeout(()=> resolve(false), 1000);
        } else {
            resolve(true);
        }
    })
}

function updateJob(jobId, prg) {
    jobs[jobId] = prg;
    console.log(`updated ${jobId} to ${prg}`);
    if (prg == 100) return;
    this.setTimeout(()=> updateJob(jobId, prg+10), 3000);
}