पाठ 5 / 25
Pattern Subscriptions and Common Uses
Use PSUBSCRIBE patterns and apply Pub/Sub to cache invalidation and live updates.
Subscribing to many channels at once
PSUBSCRIBE subscribes to channels matching a glob-style pattern: orders.* matches orders.updates and orders.cancelled; user:*:notifications matches per-user channels. A client subscribed both by name and by a matching pattern receives the message once for each matching subscription. Typical uses for Pub/Sub: cache invalidation (each application instance keeps a local cache and subscribes to cache.invalidate; a writer publishes the key to drop), live updates to browsers through WebSocket or SSE servers (each server subscribes and forwards to its connected users), configuration reloads across a fleet, and presence or typing indicators in chat. All of these tolerate an occasional lost message, either because data is refreshed anyway (cache TTLs) or because it is ephemeral by nature (typing indicators). Keep messages small and avoid using Pub/Sub for anything that must be processed exactly once.
Cache invalidation across app instances
Every instance drops the key from its local cache when any instance writes.
import threading
from cachetools import TTLCache
local_cache = TTLCache(maxsize=10_000, ttl=60) # TTL bounds staleness if a message is lost
def invalidation_listener():
ps = r.pubsub(ignore_subscribe_messages=True)
ps.subscribe("cache.invalidate")
for msg in ps.listen():
local_cache.pop(msg["data"], None)
threading.Thread(target=invalidation_listener, daemon=True).start()
def update_product(product_id, data):
db.save_product(product_id, data)
r.publish("cache.invalidate", f"product:{product_id}") # tell every instanceA PA announcement in an office
An announcement over the PA reaches everyone at their desks right now. People in a meeting room miss it, so important information also goes on the notice board (a TTL, a database, a stream).
त्वरित जाँच: Why is Pub/Sub acceptable for cache invalidation even though messages can be lost?
- Redis guarantees delivery for invalidation messages
- Local cache entries also expire through a TTL, which bounds staleness if a message is missed
- Caches never become stale
- PSUBSCRIBE stores missed messages
Answer
Local cache entries also expire through a TTL, which bounds staleness if a message is missed — A TTL acts as a safety net, so a lost invalidation only causes bounded staleness.