0
0
Redisquery~5 mins

Pub/sub vs streams comparison in Redis

Choose your learning style9 modes available
Introduction
Pub/sub and streams help different parts of a program talk to each other by sending messages. They do this in different ways to fit different needs.
You want to send a quick message to many listeners without saving the message.
You need to keep a history of messages so new listeners can see old messages.
You want to make sure every listener gets every message, even if they were offline.
You want a simple way to broadcast updates that don't need to be stored.
You want to process messages in order and keep track of what was read.
Syntax
Redis
Pub/Sub:
PUBLISH channel message
SUBSCRIBE channel

Streams:
XADD stream_name * field value [field value ...]
XREAD [COUNT count] [BLOCK milliseconds] STREAMS stream_name last_id
XGROUP CREATE stream_name group_name last_id
XREADGROUP GROUP group_name consumer_name STREAMS stream_name last_id
Pub/Sub messages are sent live and not saved; listeners only get messages while subscribed.
Streams save messages so consumers can read them later and track progress.
Examples
Send a message "Hello everyone!" to all subscribers of the 'news' channel.
Redis
PUBLISH news "Hello everyone!"
Listen to messages published on the 'news' channel.
Redis
SUBSCRIBE news
Add a message to 'mystream' with fields 'user' and 'action'.
Redis
XADD mystream * user Alice action login
Read up to 2 messages from 'mystream' starting from the beginning.
Redis
XREAD COUNT 2 STREAMS mystream 0
Sample Program
This adds two events to a stream and then reads them back.
Redis
XADD mystream * event "user_login" user "Alice"
XADD mystream * event "user_logout" user "Bob"
XREAD COUNT 2 STREAMS mystream 0
OutputSuccess
Important Notes
Pub/Sub is good for live, temporary messages but does not keep history.
Streams keep messages and let consumers read at their own pace.
Streams support groups so multiple consumers can share the work.
Summary
Pub/Sub sends live messages to all current listeners without saving them.
Streams save messages so consumers can read them later and track what they read.
Use Pub/Sub for simple broadcasts; use streams for reliable, ordered message processing.