Redis 7 Cheatsheet
A quick reference guide for Redis 7, covering core concepts, essential commands, and common patterns for developers.
A quick reference guide for Redis 7, covering core concepts, essential commands, and common patterns for developers.
## Quick Overview
Redis (Remote Dictionary Server) is an open-source, in-memory data structure store that can be used as a database, cache, and message broker. It supports various data structures like strings, hashes, lists, sets, sorted sets, streams, and more. Known for its blazing fast performance, Redis is often chosen for high-throughput, low-latency applications like caching, real-time analytics, and session management.
You'd reach for Redis when you need speed, flexibility with data structures, and the ability to handle concurrent operations efficiently.
```bash
# macOS (using Homebrew)
brew install redis
# Linux (Debian/Ubuntu)
sudo apt update && sudo apt install redis-server
This section will guide you through installing Redis and running your first commands.
Install Redis:
brew install redis
sudo apt update
sudo apt install redis-server
Start the Redis Server: After installation, Redis typically starts automatically as a service. You can check its status:
# Check status
redis-cli ping # Should return PONG if server is running
If it’s not running, you can start it manually (or restart if needed):
brew services start redis
sudo systemctl start redis-server
sudo systemctl enable redis-server # Enable to start on boot
Connect to Redis:
Use the redis-cli tool to interact with the server.
redis-cli
You should see a prompt like 127.0.0.1:6379>.
Your First Command: Let’s set and get a simple string.
# Set a key-value pair
SET mykey "Hello, Redis!"
OK
# Get the value for mykey
GET mykey
"Hello, Redis!"
To exit the redis-cli, type exit or press Ctrl+C.
Understanding these fundamental concepts is key to working effectively with Redis.
| Concept | Description |
|---|---|
| Keys | The unique identifier for a piece of data. Always a string. Naming conventions are important (e.g., user:123:name). |
| Data Types | Redis is a data structure server. Each key maps to one of several types (String, Hash, List, Set, Sorted Set, Stream, etc.). |
| In-Memory | Redis primarily stores data in RAM for high performance. |
| Persistence | While in-memory, Redis supports optional disk persistence (RDB snapshots, AOF log) to prevent data loss. |
| TTL (Time To Live) | Keys can have an expiration time, after which they are automatically deleted. Crucial for caching. |
| Transactions | Execute a group of commands atomically. All commands in a MULTI/EXEC block are processed sequentially and exclusively. |
| Pipelining | Send multiple commands to the server at once without waiting for individual replies, reducing RTT latency. |
| Pub/Sub | Publish messages to channels and subscribe to channels to receive messages, enabling real-time communication patterns. |
This section covers the most frequently used Redis commands, organized by data type. All examples use redis-cli.
Commands for interacting with keys regardless of their data type.
# Check if a key exists (returns 1 or 0)
EXISTS mykey
# Delete one or more keys
DEL mykey anotherkey
# Set a Time To Live (TTL) in seconds for a key
EXPIRE mykey 60 # Key will expire in 60 seconds
# Get the remaining TTL in seconds (-2 if key doesn't exist, -1 if no expiry)
TTL mykey
# Get the data type of a key
TYPE mykey # e.g., string, hash, list, set, zset
# Find all keys matching a pattern (use with caution in production, can block server)
KEYS user:*
The simplest data type, useful for caching individual values.
# Set a string value
SET username "alice"
# Set a string value with an expiration (EX in seconds, PX in milliseconds)
SET session:1234 "token_value" EX 3600 # Expires in 1 hour
# Get a string value
GET username
# Increment the integer value of a key by 1
INCR page_views
# Increment the integer value of a key by a specified amount
INCRBY product:100:stock 5
# Get and set a value atomically (returns old value)
GETSET current_status "processing"
Ideal for representing objects with multiple fields, like user profiles.
# Set a field and value in a hash
HSET user:1 id 1 name "Alice" email "[email protected]"
# Get a single field's value from a hash
HGET user:1 name
# Get all fields and values from a hash
HGETALL user:1
# Delete one or more fields from a hash
HDEL user:1 email
# Increment the integer value of a hash field by a specified amount
HINCRBY user:1 karma 10
Ordered collections of strings. Useful for queues, timelines, and recent items.
# Push elements to the left (head) of a list
LPUSH mylist "item1" "item2"
# Push elements to the right (tail) of a list
RPUSH mylist "itemA" "itemB"
# Pop an element from the left (head) of a list
LPOP mylist
# Pop an element from the right (tail) of a list
RPOP mylist
# Get a range of elements from a list (0 is first, -1 is last)
LRANGE mylist 0 -1 # Get all elements
# Get the length of a list
LLEN mylist
Unordered collections of unique strings. Good for tracking unique visitors, tags, or friend lists.
# Add one or more members to a set
SADD unique_users "user:1" "user:2" "user:1" # "user:1" only added once
# Get all members of a set
SMEMBERS unique_users
# Check if a member exists in a set (returns 1 or 0)
SISMEMBER unique_users "user:2"
# Remove one or more members from a set
SREM unique_users "user:1"
# Get the number of members in a set
SCARD unique_users
Collections of unique strings where each member is associated with a score, used for ordering. Perfect for leaderboards.
# Add members with their scores to a sorted set
ZADD leaderboard 100 "player:alice" 150 "player:bob" 75 "player:charlie"
# Get members within a score range (withscores returns scores)
ZRANGE leaderboard 0 -1 WITHSCORES # Get all members by score, ascending
# Get members within a score range (reverse order)
ZREVRANGE leaderboard 0 1 WITHSCORES # Top 2 players
# Get the score of a member
ZSCORE leaderboard "player:bob"
# Remove one or more members from a sorted set
ZREM leaderboard "player:charlie"
# Increment the score of a member
ZINCRBY leaderboard 50 "player:alice"
Execute a block of commands atomically.
# Start a transaction block
MULTI
# Queue commands (no immediate execution)
INCR mycounter
SET mykey "new_value"
# Execute all queued commands atomically
EXEC
For real-time messaging patterns.
# In one client, subscribe to a channel
SUBSCRIBE news_updates
# In another client, publish a message to the channel
PUBLISH news_updates "Breaking news: Redis is awesome!"
Real-world usage examples to solve common problems with Redis.
Store frequently accessed data temporarily to reduce database load.
# Store user data with a 1-hour expiration
# The application fetches user data from the DB, then caches it.
# pseudocode: user_data = fetch_from_db(user_id)
# REDIS_CLI:
SET user:profile:123 '{"name": "Alice", "email": "[email protected]"}' EX 3600
# When reading, try cache first:
# pseudocode: cached_data = redis.get("user:profile:123")
# if cached_data: return cached_data
# else: fetch_from_db, cache, return
GET user:profile:123
Limit the number of requests a user can make within a certain time frame.
# Rate limit a user to 10 requests per minute for a specific API endpoint
# Key: `ratelimit:{user_id}:{api_endpoint}`
# Value: `current_requests`
# TTL: `60` seconds
# Function to check and apply rate limit:
# 1. Increment the counter for the user/endpoint. If it's a new key, it starts at 1.
# 2. If the counter is 1 (first request), set its TTL to 60 seconds.
# 3. Check if the counter exceeds the limit (e.g., 10).
# Example for user:456 on /api/v1/data
# In application logic, combine these:
# 1. increment_result = redis.incr("ratelimit:456:/api/v1/data")
# 2. if increment_result == 1: redis.expire("ratelimit:456:/api/v1/data", 60)
# 3. if increment_result > 10: return "Too Many Requests"
# Simulate the first request
INCR ratelimit:456:/api/v1/data
EXPIRE ratelimit:456:/api/v1/data 60
# Simulate subsequent requests (repeat up to 10 times in 60s)
INCR ratelimit:456:/api/v1/data
# After 10 requests, the 11th request would exceed the limit
Use sorted sets to maintain a real-time sorted list of players or items based on scores.
# Player scores in a game
ZADD game:leaderboard 1200 "player:john" 980 "player:jane" 1500 "player:dave"
# Update a player's score (e.g., Dave gets 200 more points)
ZINCRBY game:leaderboard 200 "player:dave"
# Get the top 5 players (highest score first)
ZREVRANGE game:leaderboard 0 4 WITHSCORES
# Get a player's rank (0-indexed, ascending order)
ZRANK game:leaderboard "player:john"
# Get a player's rank (0-indexed, descending order)
ZREVRANK game:leaderboard "player:dave"
These are common pitfalls and best practices to keep in mind when working with Redis.
KEYS * in Production: Avoid using KEYS * on production instances, especially with large datasets. It’s a blocking operation that scans all keys and can severely degrade performance. Use SCAN for incremental iteration.BLPOP, BRPOP): While useful for reliable queues, ensure your client applications handle potential network issues or server restarts when using blocking operations.maxmemory directive in your redis.conf and choose an appropriate eviction policy (e.g., allkeys-lru for LRU-based eviction across all keys).INCR operation, for example, is guaranteed to complete fully without interference from other commands, even in concurrent environments. Leverage this for safe counters or flags.:) to create logical namespaces for your keys (e.g., app_name:module:id:field). This helps with organization and avoids key collisions.MULTI/EXEC) are not Rollbacks: Redis transactions ensure atomicity (all or nothing) but don’t provide rollback capabilities like relational databases if a command within the transaction fails (e.g., wrong type operation). They simply execute all commands in order.You’ve learned the essentials of Redis 7! To deepen your understanding and explore more advanced features:
Source: z2h.fyi/cheatsheets/redis-cheatsheet — Zero to Hero cheatsheets for developers.