Course contentsShow
← Databases & SQL
Lesson 1372 of 1,95312. Key-Value and Caching EnginesFree lesson

Implementing Pub-Sub Patterns for UI Updates

Push real-time notifications to users via websocket integrations.

In this lesson, you will learn how to bridge the gap between database state changes and user interface updates using a Publish-Subscribe (Pub-Sub) pattern integrated with WebSockets.

Bridging the Database-to-UI Gap

In high-scale systems, polling the database every few seconds to check for new data is inefficient and creates unnecessary load. Instead, we use the Pub-Sub pattern. When a data change occurs—such as a new record being written to your primary store—your application acts as a "Publisher" to a message broker (like Redis Pub/Sub). The UI, connected via a persistent WebSocket, acts as the "Subscriber."

The Workflow

  1. The Write Event: Your application performs an operation in your database.
  2. The Notification: Immediately after the write, the application publishes a message to a specific channel (e.g., user_notifications_123) via your caching engine.
  3. The Push: Your WebSocket server listens to this channel and, upon receiving the message, "pushes" the update directly to the client's browser.

Practical Implementation

Imagine a scenario where a user’s order status updates. Instead of the client asking, "Is it done yet?", the server tells the client as soon as the database transaction completes:

// Server-side (Node.js/Redis example)
db.orders.update({ id: 123, status: 'shipped' });

// Publish the change to a Redis channel
redis.publish('order_updates_123', JSON.stringify({ status: 'shipped' }));

// WebSocket server listens to Redis and relays to client
redis.subscribe('order_updates_123', (message) => {
  webSocket.sendToUser(123, message);
});

Why this matters

By decoupling the database write from the UI update, you keep your database clean of "status-polling" queries. This architecture ensures that the UI reflects the state of the database almost instantly without forcing the user's browser to work harder than necessary. You are effectively shifting from a pull-based model (where the UI asks for data) to a push-based model (where the system announces changes).

This pattern is highly effective when paired with your previous knowledge of Data Expiration and Cleanup—you only need to keep relevant state in your cache to facilitate these real-time notifications.

Key Takeaway: Use the Pub-Sub pattern to notify clients of database changes in real-time, eliminating the need for inefficient polling and reducing overall database load.