0
0
Redisquery~5 mins

XADD for adding entries in Redis

Choose your learning style9 modes available
Introduction
XADD lets you add new messages to a Redis stream, which is like a list that keeps data in order.
You want to record events like user actions in order.
You need to log messages from devices or sensors over time.
You want to build a chat app where messages are stored in order.
You want to track changes or updates in a system step-by-step.
Syntax
Redis
XADD stream_name [MAXLEN ~ max_length] * field1 value1 [field2 value2 ...]
The * means Redis will generate a unique ID for the new entry based on the current time.
MAXLEN ~ max_length trims the stream to keep it from growing too big, but it does this approximately.
Examples
Adds a new entry with fields 'temperature' and 'humidity' to 'mystream'. Redis creates the ID.
Redis
XADD mystream * temperature 22 humidity 60
Adds a new entry with fields 'event' and 'user' and trims the stream to about 1000 entries.
Redis
XADD mystream MAXLEN ~ 1000 * event login user alice
Adds a single field 'message' with a text value to the stream.
Redis
XADD mystream * message "Hello, world!"
Sample Program
Adds two order entries to the 'orders' stream and then reads all entries from it.
Redis
XADD orders * product_id 123 quantity 2
XADD orders * product_id 456 quantity 1
XRANGE orders - +
OutputSuccess
Important Notes
XADD runs in O(1) time, so adding entries is very fast even for large streams.
Each entry uses space proportional to the number of fields and their values.
A common mistake is forgetting the * for the ID, which causes an error.
Use XADD when you want ordered, append-only logs; use SET for single key-value pairs.
Summary
XADD adds new entries to a Redis stream with a unique ID.
You can limit stream size with MAXLEN to save memory.
Entries are stored in order and can have multiple fields.