Mastering Redis: From Fundamentals to Advanced Features and Real‑World Use Cases
This comprehensive guide walks you through Redis basics, its data structures, commands, installation steps, high‑concurrency principles, persistence mechanisms, replication, caching strategies, Lua scripting, pipelines, distributed locks, and cluster concepts, providing practical examples and best‑practice recommendations for developers and operators.
Redis Introduction
What is Redis?
Redis is an open‑source (BSD‑licensed) in‑memory data‑structure store that can be used as a database, cache, and message broker.
It supports many data types such as strings, hashes, lists, sets, sorted sets, bitmaps, HyperLogLog, and geospatial indexes.
Redis provides replication, Lua scripting, LRU eviction, transactions, and various persistence options.
High availability is achieved via Sentinel and automatic sharding (Cluster).
Key Features
Very fast: ~110 000 reads/s and ~81 000 writes/s per node because data resides in memory and the server is written in C.
Single‑threaded core (multi‑threaded I/O support since 6.0).
Persistence via RDB snapshots and AOF logs.
Rich data structures and commands (e.g., HyperLogLog, GEO, Pub/Sub).
Replication and high‑availability with Sentinel.
All operations are atomic.
Typical Use Cases
Cache: Store frequently accessed data to accelerate reads.
Counter: Implement rate limiting, visit counters, etc.
Message Queue: Use lists as simple queues.
Leaderboard: Sorted sets for ranking.
Social Network: Store relationships, feeds, etc.
High‑Concurrency Principles
Redis is pure in‑memory; most operations are simple memory accesses.
It uses non‑blocking I/O with an event loop, avoiding thread context switches.
Data structures are optimized (e.g., ziplist, quicklist) for fast access.
Custom event dispatcher provides high throughput.
Installation (Linux)
Download the source:
wget https://download.redis.io/releases/redis-6.2.4.tar.gzExtract and compile:
tar -zvxf redis-6.2.4.tar.gz
cd redis-6.2.4
makeInstall to a custom prefix:
make PREFIX=/usr/local/redis installStarting Redis
Run the server with a configuration file: ./bin/redis-server & ./redis.conf Or start in the foreground:
./bin/redis-server ./redis.confConfiguration (redis.conf)
Parameter
Values
Description
daemonize
yes|no
Run as a daemon (default no).
port
integer
Listening port (default 6379).
bind
IP address
Network interface to bind; use * for all.
protected-mode
yes|no
Enable/disable external access (default yes).
loglevel
debug|verbose|notice|warning
Logging verbosity.
databases
integer
Number of logical databases (default 16).
rdbcompression
yes|no
Compress RDB snapshots with LZF.
dbfilename
string
Name of the RDB file (default dump.rdb).
dir
path
Directory for persistence files.
requirepass
string
Password for client authentication.
maxclients
integer
Maximum simultaneous client connections.
maxmemory
bytes
Memory limit for the instance.
Data Structures & Commands
Global Commands
keys– List all keys. dbsize – Number of keys. exists key – Test key existence. del key [key ...] – Delete keys. expire key seconds – Set TTL. ttl key – Remaining TTL. type key – Data type of a key.
String
set key value [ex seconds] [px ms] [nx|xx]– Set value with optional expiration and existence flags. get key – Get value. mset key value ... – Set multiple keys. mget key ... – Get multiple keys. incr key, decr key, incrby key increment, decrby key decrement – Integer increment/decrement.
Hash
hset key field value hget key field hdel key field [field ...] hlen key hmset key field value ... hmget key field ... hexists key field hkeys key, hvals key,
hgetall key hincrbyfloat key field incrementList
rpush key value ...,
lpush key value ... linsert key BEFORE|AFTER pivot value lrange key start stop lindex key index llen key lpop key,
rpop key lrem key count value ltrim key start stop lset key index newValue blpop key ... timeout,
brpop key ... timeoutSet & Sorted Set
sadd key member ..., srem key member ..., smembers key, sismember key member, scard key, spop key [count], srandmember key [count], sinter key ..., sunion key ...,
sdiff key ... zadd key score member ...(options nx, xx, ch, incr), zcard key, zscore key member, zrank / zrevrank, zrem key member ..., zincrby key increment member, zrange / zrevrange, zrangebyscore / zrevrangebyscore, zcount key min max, zremrangebyrank, zremrangebyscore,
zinterstore / zunionstoreBitmap
setbit key offset value– Set a bit. getbit key offset – Get a bit. bitcount key [start end] – Count bits set to 1.
HyperLogLog
pfadd key element ...– Add elements. pfcount key – Approximate cardinality. pfmerge destkey key1 ... – Merge HLLs.
Publish/Subscribe
subscribe channel ... unsubscribe channel publish channel message psubscribe pattern,
punsubscribe patternGEO
geoadd key longitude latitude member ... geopos key member ... geodist key member1 member2 [unit] georadius key longitude latitude radius [options] georadiusbymember key member radius [options] geohash key member ...Small but Powerful Features
Slow Query Log
Configure with slowlog-log-slower-than (microseconds) and slowlog-max-len. Retrieve with slowlog get, length with slowlog len, and clear with slowlog reset.
Pipeline
Batch multiple commands to reduce RTT. Example using Jedis:
JedisPool pool = new JedisPool(...);
Jedis jedis = pool.getResource();
Pipeline p = jedis.pipelined();
for (int i = 0; i < 100000; i++) {
p.set("key"+i, "value"+i);
p.get("key"+i);
}
List<Object> results = p.syncAndReturnAll();Transactions & Lua
Simple transactions with MULTI / EXEC are atomic but lack rollback and conditional logic.
Lua scripts provide atomic execution with full Redis command support via redis.call() or redis.pcall(). Load scripts with SCRIPT LOAD and execute with EVALSHA.
eval "return {KEYS[1],ARGV[1]}" 1 mykey helloClients
Popular language bindings:
Java – Jedis
Python – redis‑py
Node.js – ioredis
Persistence, Replication & Cache Design
Persistence
Redis supports RDB snapshots and AOF logs.
RDB – Forks a child process to write a compact binary snapshot without blocking the main thread.
AOF – Appends every write command to a log; can be rewritten (bgrewriteaof) to shrink size.
Redis 4.0 introduced mixed persistence (RDB + incremental AOF) for faster restarts.
Replication
Master‑slave asynchronous replication. Full sync creates an RDB snapshot on the slave; incremental sync transfers only new commands.
Sentinel monitors masters, performs automatic failover, and provides the current master address to clients.
Message Loss
Configure min-slaves-to-write 1 and min-slaves-max-lag 10 to avoid writes when replication lag is high.
Eventual Consistency
Writes are acknowledged immediately; slaves catch up asynchronously, guaranteeing eventual consistency.
Cache Strategies
Algorithmic eviction – LRU, LFU, FIFO via maxmemory-policy.
Timeout eviction – Set TTL with EXPIRE.
Active update – Application updates cache after DB write.
Combine strategies for different consistency requirements.
Cache Problems
Cache penetration – Use Bloom filters or cache empty results with short TTL.
Cache avalanche – Stagger TTLs with random offsets.
Cache breakdown – Protect hot keys with mutexes or pre‑warming.
Cache “no‑bottom‑hole” – Avoid excessive parallel MGET on many nodes.
Knowledge Expansion
Cache‑Database Synchronization
Four basic patterns:
Update DB → Update cache.
Update cache → Update DB.
Delete cache → Update DB.
Update DB → Delete cache.
Choosing between "update cache" and "delete cache" depends on the cost of updating the cache. For cheap updates, refresh the cache; for expensive updates, delete it.
To avoid stale data, the "Cache‑Aside" pattern (write DB then delete cache) is widely used. Add a short sleep and a second delete (delayed double‑delete) to mitigate race conditions.
Distributed Lock
Basic lock using SET key value NX PX ttl. Release only if the value matches to avoid unlocking another client’s lock:
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
else
return 0
endRedlock algorithm (Antirez) obtains the lock on a majority of independent Redis nodes, uses a unique value, and validates the acquisition time.
Cluster
Redis Cluster provides automatic sharding and high availability. Alternatives include Sentinel‑based master‑slave setups, Codis, and custom proxy solutions.
References
Redis Development and Operations – https://book.douban.com/subject/26971561
Transactions and Lua – https://whiteccinn.github.io/2020/06/02/Redis/redis事务与Lua
Redis GEO use cases – https://www.cnblogs.com/54chensongxia/p/13813533.html
Cache‑Database consistency – https://note.dolyw.com/cache/00-DataBaseConsistency.html
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
