Redis Command-Line—Comprehensive Explanation
1. Basic Key-Value Commands
- SET key value: Stores any string value at the given key, creating or overwriting it. The key can be nearly any text (like "greeting" or "user:1:email"). Example:
SET greeting "Hello Redis" creates a key-value pair. Redis makes this extremely fast and atomic, meaning even hundreds of simultaneous SETs will not overlap or corrupt.
- GET key: Fetches the value for a key, or returns (nil) if not found. E.g.,
GET greeting returns Hello Redis.
- DEL key: Deletes the key and its associated value—instantly freeing up that slot. Example:
DEL greeting.
- EXISTS key: Checks if the key exists; returns
1 if so, 0 if not. You can use this as a gating check before running further commands.
2. Atomic Counters
- INCR key: If the value at
key is a number (or doesn't exist), INCR increases it by one as a single, atomic operation—no matter how many clients hit this at once, each increment is perfectly tracked.
- INCRBY key num: Increments by a given amount.
- DECR key: Decreases (subtracts) by one.
- GET key: Check the updated counter's value.
Atomicity guarantee: Redis ensures operations like INCR/DECR are indivisible; even under massive concurrency, the counter values are perfectly reliable (crucial for rate limiting, page views, etc).[9]
3. Expiration / Time to Live (TTL)
- EXPIRE key seconds: Sets a lifetime for the key. When the time elapses, Redis erases it automatically—great for caching or temporary states.
EXPIRE tempkey 5 deletes tempkey after 5 seconds.
- TTL key: Shows how many seconds remain until a key expires. After expiry,
GET key returns nil.
4. Lists (Queues / Stacks)
- LPUSH list value: Inserts a value at the left end (start) of the list. Unlike arrays, a Redis list is a linked sequence where you can add and remove entries from both ends.
- LRANGE list 0 -1: Lists all elements from the leftmost to rightmost.
- RPOP list: Removes and returns the value from the right end (oldest).
Use LPUSH + RPOP for a queue (FIFO: first in, first out). Use LPUSH + LPOP for a stack (LIFO: last in, first out).[5][9]
5. Sets (Unique Members)
- SADD set value: Adds a member to the set—ensures uniqueness automatically. Sets are unordered, so you don’t know the order, but duplicates are ignored.
SADD users "sree" creates a set "users" containing "sree".
- SMEMBERS set: Lists every member.
- SCARD set: Number of unique members.
- SISMEMBER set value: Checks if a value exists.
Use cases: unique tags, IDs, feature flags, etc.[9]
6. Sorted Sets (ZSET) — Sliding Window Demo
What’s a score? Each member in a sorted set is paired with a number called its score. Redis automatically organizes the set so the member with the smallest score comes first and the largest last. The set is always sorted by score—not the value itself. Members are unique; scores can repeat, but if you ZADD a member with a new score, its score is updated.
Why use scores? The score represents rank, priority, or timestamp.
- ZADD set score member: Adds/updates member with the given score.
- ZRANGE set 0 -1 WITHSCORES: Lists all members, left to right (lowest to highest score), showing scores.
- ZREMRANGEBYSCORE set min max: Removes all members with scores in the specified range (efficient for cleaning up old/time-bound data).
Use case: leaderboards, logs sorted by time, rate-limiting with timestamps.[9]
7. Hashes (Structured Objects)
- HSET hash field value [field value ...]: Creates (or updates) multiple fields for a given object. E.g.,
HSET user:100 name "Sree" age 68 plan "Gold" creates three fields for user:100.
- HGETALL hash: Lists every field and its value.
- HGET hash field: Fetches an individual field.
- HINCRBY hash field num: Atomically increases field’s value (must be a number).
Use case: storing user/session profiles, structured data with named properties.[5][9]
8. Transactions (WATCH / MULTI / EXEC)
- WATCH key [key ...]: Marks one or more keys so Redis watches for changes. If any watched key changes before EXEC, your transaction aborts, preserving atomicity—very useful for things like account transfers.
- MULTI: Begins transaction; commands are queued.
- EXEC: Executes all queued commands atomically (all succeed or all fail).
Practical example: Deduct stock from one product, add to another; if someone else modifies stock in the middle, your transfer fails safely.
9. Pipelining (Batch Commands)
- MULTI ... EXEC: Redis won’t run each command until EXEC; ships all at once—reducing round-trips and boosting speed when you have several changes.
- MGET key1 key2 ...: Gets multiple values at once; improves performance.
10. Pub/Sub (Publish/Subscribe Messaging)
- SUBSCRIBE channel: Listens for messages; instantly receives anything published to that channel.
- PUBLISH channel message: Sends message to the channel; all subscribers receive it right away. No polling—ideal for real-time notifications between services or for chat/messaging.
11. Lua Scripting (Atomic Server-Side Logic)
- EVAL script numkeys [key ...] [arg ...]: Runs logic on the server side in one atomic operation. Can inspect multiple keys, perform calculations, and update—all at once, no interruptions. Return values let you know if logic succeeded/failed.
E.g.: Atomically debit an account if it has enough funds, else return -1—prevents race conditions.
12. Scan / Key Exploration
- SCAN cursor MATCH pattern COUNT n: Iterates over keys—with cursor-based pagination, avoiding large blocking queries. Safer and more efficient than KEYS * in production. Use SCAN to browse keys without hurting server performance.
- TYPE key: Shows what kind of value the key holds (string, list, set, etc).
- KEYS pattern: Returns all keys matching a pattern. Caution: Can block server—don’t use in high-volume production.
13. Memory & Performance Insights
- INFO memory / stats / commandstats: Shows current memory usage, operation statistics, per-command counters—great for monitoring and diagnosis.
- MONITOR: Streams every command, live. Helps you watch how your API interacts with Redis in real time.
14. Manual Transaction Retry
Try editing the same keys from two terminals using WATCH. If one changes before EXEC, the transaction aborts—forcing you to retry and thus implementing optimistic locking (ensures correctness without always locking the entire key set).
15. Flush / Reset
- FLUSHALL: Erases all keys and data from the current database instantly—use only for test/dev or when you truly want to reset.
16. Rate Limiting Demo (Fixed Window)
- SETEX rl:fixed:demo 10 0: Sets key with expiry (10s window, value 0).
- INCR rl:fixed:demo: Increments count (each request increases counter for this window).
- TTL rl:fixed:demo: See seconds left in window.
- GET rl:fixed:demo: See how many requests so far.
You now have a sliding window rate limiter: keys "decay" as windows expire.
Summary Table
| Feature |
Command(s) |
Use Case/Goal |
| Atomic Counter |
INCR, DECR |
Page views, counters, rate limiting |
| TTL |
EXPIRE, TTL |
Auto-expiring cache/session |
| Hash |
HSET, HGET, HGETALL |
Structured objects—users, sessions |
| Sorted Set |
ZADD, ZRANGE |
Ordered logs, leaderboards, sliding windows |
| Lua |
EVAL |
Custom atomic workflows (logic) |
| Transactions |
WATCH/MULTI/EXEC |
Safe multi-key updates |
| Pub/Sub |
PUBLISH/SUBSCRIBE |
Real-time messaging, notifications |
| Introspection |
INFO, MONITOR |
Debugging, monitoring |
| Flush |
FLUSHALL |
Reset for test/dev |
*