CodePark/ questions / Pub/Sub & Streams
START PRACTICINGPRACTICE
Backend question · Redis & caching › Pub/Sub & Streams

Compare Redis Pub/Sub and Redis Streams. When would you use each?

Use Pub/Sub when only live listeners matter. Use Streams when no message may be lost.

Pub/Sub is fire-and-forget: Redis sends the message once and then forgets it. PUBLISH delivers a message only to the clients that are subscribed to that channel at that moment. Redis stores nothing. So a subscriber that is offline, or that disconnects, misses the messages. There are no acknowledgements (no "I got it" reply) and no replay. Pub/Sub is good when losing a message is acceptable, for example:

  • live notifications
  • cache invalidation broadcasts (telling all servers "this cached value is old")
  • chat presence (who is online)

Streams are an append-only log stored in a key. New entries are only added at the end, like lines in a log file. Streams give you:

  • Entries that persist. They are saved to disk if RDB or AOF persistence is on.
  • Replay: a consumer can read from any entry ID and replay the history.
  • Consumer groups: XREADGROUP splits entries between several workers.
  • Tracking: the group remembers which entries are not yet acknowledged, and each worker must confirm an entry with XACK.

Use Streams for event processing, job pipelines and audit-like feeds. In these cases every message must be handled at least once.

In short: Pub/Sub when only live listeners matter, Streams when messages must not be lost.

  • Pub/Sub stores nothing, so offline subscribers miss messages.
  • Pub/Sub suits live broadcasts and cache invalidation.
  • Streams are a persistent log that you can replay by entry ID.
  • Streams have consumer groups, a list of pending entries, and XACK to confirm each entry.
  • Use Streams for at-least-once processing.