Real-Time Magic: Harnessing Server-Sent Events (SSE) with Redis for Instant Updates

Anjana K V
Team Lead, Zerone Consulting Pvt Ltd.

In today’s fast-paced digital world, delivering real-time updates to users is no longer optional but a necessity. Real-time updates have become a critical feature in modern applications, enabling users to receive instant updates without refreshing their browsers. Technologies like Server-Sent Events (SSE) and Redis provide powerful tools to implement real-time communication in web applications effectively. This blog focuses on implementing real-time updates using Server-Sent Events (SSE) and Redis, leveraging Azure Platform as a Service (PaaS) offering.

Real-Time Magic: Harnessing Server-Sent Events (SSE) with Redis for Instant Updates

Overview of the Architecture

In this solution:

  1. SSE is used to establish a persistent connection between the server and the client for one-way communication.
  2. Azure Cache for Redis acts as the message broker for distributing real-time updates.

This architecture can be extended to other cloud platforms, such as AWS, using tools like Amazon ElastiCache for Redis.

What is Server-Sent Events (SSE)?

SSE is a standard mechanism for sending updates from the server to the client over a single, persistent HTTP connection. Unlike WebSocket, which enables two-way communication, SSE is designed for unidirectional communication from server to client. It is easy to implement and well-suited for use cases like notifications, live feeds, and real-time dashboards.

Why Redis?

Redis is an in-memory data structure store that serves as a high-performance messaging broker when used with its Pub/Sub feature. It allows different parts of your application to communicate with each other efficiently. By combining SSE and Redis, you can build scalable and reliable real-time systems.

Workflow

flow chart

1. React.js Client
  • Role: Subscribes to the Server-Sent Events (SSE) endpoint provided by the Express.js server.
  • Process:
    1. Uses the EventSource API to establish a persistent connection with the SSE endpoint.
    2. Listens for incoming updates and renders them in real-time on the UI.
2. Express.js Server
  • Role: Acts as the intermediary between the Redis message broker and the React.js client.
  • Process:
    1. Provides an /events endpoint for clients to establish an SSE connection.
    2. Subscribes to the Redis channel to listen for updates.
    3. Forwards the updates received from Redis to the connected clients via SSE.
3. Azure Redis Server
  • Role: Functions as the message broker for real-time data.
  • Process:
    1. Listens for PUBLISH commands from any part of the system.
    2. Broadcasts messages to all subscribers of a specific channel.
    3. Ensures high performance and low latency in delivering messages to the Express.js server

Use Case

For an e-commerce platform, consider implementing a real-time notification system that provides real-time updates on bill processing and its completion.

Setting Up the Environment

  1. Install/Connect Redis:
    • Here, we are using Azure Redis, so you need to obtain the Redis host, password, port, and database index. Alternatively, you can install a Redis server on your system and modify the configuration accordingly
  2. Backend Setup (Node.js):
    • Use Express for routing and Redis’s Node.js client for Publish/Subscribe.
  3. Frontend Setup:
    • Use React.js to establish an SSE connection.

Step-by-Step Implementation

1.Setting Up Redis Pub/Sub

sseHelper.js blog2.jpg

This code initializes a Redis client using the redis Node.js library. It establishes secure connections to a Redis server and creates separate instances for publishing and subscribing to messages on specific channels.

2.Creating an SSE Endpoint

SSE endpoints use the Content-Type: text/event-stream header to establish a persistent connection, where each update is transmitted as an event.

app.js

blog3.jpg

The above code sets up a simple Express.js application to provide Server-Sent Events (SSE) functionality through a dedicated router module.

sse.router.js router The above code defines a router to handle a specific Server-Sent Events (SSE) endpoint in an Express.js application

sse.controller.js controller The above code specifies the following functionality

  • The client connects to the /getBillStatus endpoint and keeps the connection open.
  • The server sends the initial status, either from Redis or a default state
  • Periodic heartbeats keep the connection alive
  • Real-time updates are sent to the client as they are received in the Redis billStatusChannel
  • Resources are properly cleaned up when the client disconnects

3.Publishing Events

blog7.jpg

The above code notifies all subscribers (e.g., SSE clients) about the updated bill status, and the subscribers handle the message by forwarding it to their connected clients.

4.Frontend Integration

The front-end listens to the SSE endpoint to receive real-time updates.

frontend

Benefits of Using SSE and Redis

  • Redis Publish/Subscribe ensures efficient message delivery across distributed systems
  • SSE is easier to implement, and debug compared to WebSocket
  • Persistent HTTP connections reduce overhead
  • Simple implementation for unidirectional data flow

Considerations

  • Browsers limit the number of open SSE connections per domain
  • Implement reconnection logic for disconnected clients
  • Use HTTPS and authentication to protect the endpoint
  • Not suitable for bi-directional communication

Conclusion

By combining the power of SSE and Redis, you can build robust real-time systems with minimal effort. This approach is perfect for scenarios where real-time updates are critical, such as notifications, live score updates, or collaborative applications. While SSE is perfect for unidirectional updates, alternatives like Amazon ElastiCache and, for intranet environments, leveraging tools like Apache Kafka ensures seamless communication. Choosing the right technology depends on your application’s requirements, hosting environment, and scalability needs. Start integrating SSE and Redis into your project today and deliver an exceptional user experience!

Want to discuss your project?
We can help!
Follow us on LinkedIn for future updates
Never Miss a Beat

Join our LinkedIn community for the latest industry trends, expert insights, job opportunities, and more!

close icon

We’re glad you’re here. Tell us a little about your requirement.

  • We're committed to your privacy. Zerone uses the information you provide us to contact you about our products and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy