Redis is famously known as an in-memory data structure store, often used as a database, cache, and message broker. The simplest and most fundamental data type in Redis is the string. This blog walks through everything you need to know about Redis strings with practical examples.
What Are Redis Strings?
In Redis, a string is a binary-safe sequence of bytes. That means it can contain any kind of data text, integers, or even serialized objects.
- Maximum size: 512 MB
- Default behavior: key-value pair storage
Common String Commands
Let’s explore key-value operations you can perform on Redis strings using the redis-cli.
1. SET – Assign a Value to a Key
SET user:1:name "Alice"
This sets the key user:1:name to the value "Alice".
2. GET – Retrieve a Value by Key
GET user:1:name
# Output: "Alice"
3. EXISTS – Check if a Key Exists
EXISTS user:1:name
# Output: 1 (true)
4. DEL – Delete a Key
DEL user:1:name
5. SETEX – Set Value with Expiry (TTL)
SETEX session:12345 60 "token_xyz"
This sets session:12345 with value token_xyz that expires in 60 seconds.
6. INCR / DECR – Numeric Operations
SET views:homepage 0
INCR views:homepage
INCR views:homepage
DECR views:homepage
GET views:homepage
# Output: "1"
7. APPEND – Append to Existing String
SET greet "Hello"
APPEND greet ", World!"
GET greet
# Output: "Hello, World!"
8. MSET / MGET – Set or Get Multiple Keys at Once
MSET product:1 "Book" product:2 "Pen"
MGET product:1 product:2
# Output: "Book" "Pen"
Gotchas to Watch Out For
- String size limit: 512 MB per key.
- Atomic operations:
INCR,DECRare atomic – ideal for counters. - Expire keys: Always use TTL for session-like data to avoid memory bloat.
- Binary safety: Strings can hold any binary data, including serialized objects.
Use Redis with Python
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
r.set('user:1:name', 'Alice')
print(r.get('user:1:name').decode())
