How to Choose the Right Real-Time Communication Approach: Long Polling vs Redis Pub/Sub

Written by ssukhpinder | Published 2023/03/17
Tech Story Tags: web-development | redis | scalability | software-development | coding | programming | application | real-time | web-monetization

TLDRLong Polling is a technique where the client sends a request to the server and waits for a response. The server holds the request open until it has new data to send back or until a timeout occurs. If new data is received before the timeout, the data is returned in the response. Long Polling can be implemented using ASP.NET Core.via the TL;DR App

Choosing the Right Real-Time Communication Approach

Real-time communication is essential for modern web applications that require fast data exchange between clients and servers. Two popular approaches for achieving real-time communication in web applications are as follows:

  • Long Polling
  • Redis Pub/Sub

What Is Long Polling?

Long Polling is a technique where the client sends a request to the server and waits for a response. The server holds the request open until it has new data to send back or until a timeout occurs.

Long Polling is a low-overhead approach suitable for projects with a low volume of clients and a low frequency of updates.

The basic architecture of Long Polling is shown below.

In C#, Long Polling can be implemented using ASP.NET Core. The server waits for a maximum of a specified time for new data from the service. If new data is received before the timeout, the data is returned in the response.

If the timeout is reached before new data is obtained, the action returns a “No Content” response.

Basic C# Code Example

public async Task<ActionResult> LongPolling()
{
    while (true)
    {
        // Wait for new data for a maximum of 30 seconds
        var newData = await GetDataAsync(30);

        if (newData != null)
        {
            // Return the new data to the client
            return Json(newData);
        }

        // No new data received within the timeout, continue polling
    }
}

private async Task<Data> GetDataAsync(int timeoutSeconds)
{
    // Make an asynchronous call to retrieve data from the server
    // This call will be held open until new data is available or until the timeout is reached
    var data = await _dataService.GetDataAsync();

    if (data != null)
    {
        // New data received, return it immediately
        return data;
    }

    // No new data received, wait for the specified timeout period
    await Task.Delay(TimeSpan.FromSeconds(timeoutSeconds));

    // Check again for new data
    return await GetDataAsync(0);
}

The above piece of code is a simple implementation of long polling, a technique where the client waits for new data from the server. If new data is received within 30 seconds, it’s returned to the client. If not, the client continues polling until new data is available.

It’s important to note that this code is just a basic example and may not be suitable for all use cases. Long polling can be resource-intensive and may not scale well for many clients. Alternative techniques like Redis Pub/Sub or other messaging systems may be more appropriate.

Long Polling is a simple and low-overhead approach suitable for small-scale projects. It is a reliable technique that guarantees that the client receives updates in real-time, and it is compatible with most web browsers.

What Is Redis Pub/Sub?

Redis Pub/Sub is a scalable messaging system enabling real-time client and server communication. It involves clients subscribing to channels and receiving updates whenever new data is published to those channels. Redis Pub/Sub suits projects with a high volume of clients and frequent updates.

Redis Pub/Sub can be implemented in C# using the StackExchange — Redis library. The library provides a Redis connection, a Redis subscriber, and a Redis publisher.

The subscriber subscribes to a channel and executes a function when receiving a message. The publisher publishes a message to the specified channel.

Basic C# Code Example

using StackExchange.Redis;

public class RedisPubSubService
{
    private readonly IConnectionMultiplexer _connectionMultiplexer;
    private readonly string _channelName;

    public RedisPubSubService(IConnectionMultiplexer connectionMultiplexer, string channelName)
    {
        _connectionMultiplexer = connectionMultiplexer;
        _channelName = channelName;
    }

    public void Subscribe(Action<string> onMessageReceived)
    {
        var redis = _connectionMultiplexer.GetSubscriber();
        redis.Subscribe(_channelName, (channel, message) =>
        {
            onMessageReceived?.Invoke(message);
        });
    }

    public async Task PublishAsync(string message)
    {
        var redis = _connectionMultiplexer.GetSubscriber();
        await redis.PublishAsync(_channelName, message);
    }
}

The above code defines a class that manages Pub/Sub communication. The Subscribe method takes an argument, which will be called once a message is received on the specified channel. The PublishAsync method sends a message to the channel.

Create a ConnectionMultiplexer instance that connects to the server. Then, it can instantiate a RedisPubSubService object and subscribe to the channel using the Subscribe method. The specified callback function will be executed when a message is received on the channel.

// Create a ConnectionMultiplexer instance
var redis = ConnectionMultiplexer.Connect("localhost");

// Create a RedisPubSubService instance for the "my-channel" channel
var pubSubService = new RedisPubSubService(redis, "my-channel");

// Subscribe to the channel and handle incoming messages
pubSubService.Subscribe(message =>
{
    Console.WriteLine($"Received message: {message}");
});

// Publish a message to the channel
await pubSubService.PublishAsync("Hello, world!");

Redis Pub/Sub is a highly scalable approach suitable for large-scale projects with a high volume of clients and a high frequency of updates. It provides real-time communication between multiple clients and enables them to receive real-time updates without sending requests to the server.

Conclusion

Long Polling and Redis Pub/Sub are two approaches for real-time communication in web applications.

Long Polling is suitable for projects with a low volume of clients, while Redis Pub/Sub is suitable for projects with a high volume of clients and real-time communication between multiple clients.

Implementing Long Polling and Redis Pub/Sub in C# can provide users with an excellent real-time communication experience.


Also published here


Written by ssukhpinder | Programmer by heart | C# | Python | .Net Core | Xamarin | Angular | AWS
Published by HackerNoon on 2023/03/17