Mastering Redis: From Basics, Installation to Advanced Features and Real‑World Use Cases
This comprehensive guide explains what Redis is, its core data structures, typical scenarios such as caching, counters, message queues and leaderboards, installation steps on Linux, configuration options, advanced features like pipelines, Lua scripting, persistence mechanisms, replication, caching strategies, consistency challenges, and distributed locking techniques.
What Is Redis?
Redis is an open‑source, in‑memory data‑structure store that can serve as a database, cache, and message broker. It supports strings, hashes, lists, sets, sorted sets, bitmaps, HyperLogLog, GEO, and more, with built‑in replication, Lua scripting, LRU eviction, transactions, and high‑availability via Sentinel and Cluster.
Typical Use Cases
Cache – accelerate data reads (e.g., user sessions, product info).
Counter – rate limiting, IP blocking.
Message Queue – simple pub/sub workflows.
Leaderboard – sorted‑set based ranking.
Social Network – fast set operations for followers.
High‑Concurrency Principles
Redis runs a single‑threaded event loop using non‑blocking I/O, which makes read/write operations extremely fast (hundreds of thousands ops/s) and reduces context‑switch overhead.
Installation on Linux
wget https://download.redis.io/releases/redis-6.2.4.tar.gzExtract, compile, and install:
tar -zvxf redis-6.2.4.tar.gz
cd redis-6.2.4
make
make PREFIX=/usr/local/redis installStart Redis:
./bin/redis-server ./redis.confKey Configuration Options (redis.conf)
daemonize – run as a background daemon (yes/no).
port – listening port (default 6379).
bind – network interface; set to 0.0.0.0 for remote access.
protected-mode – restrict external connections (yes/no).
loglevel – logging verbosity (debug, notice, warning).
databases – number of logical DBs (default 16).
rdbcompression – enable LZF compression for RDB files.
maxmemory – memory limit; choose eviction policy (LRU, LFU, etc.).
Data Structures and Commands
Strings
Simple key‑value pairs; useful for caching user info.
SET key value [EX seconds] [PX ms] [NX|XX]
GET key
INCR key
MSET key1 val1 key2 val2Hashes
HSET user:1 name "Alice"
HGET user:1 name
HGETALL user:1Lists
LPUSH mylist a b c
LRANGE mylist 0 -1
LPOP mylistSets
SADD myset a b c
SMEMBERS myset
SINTER set1 set2Sorted Sets (ZSET)
ZADD scores 100 user1 200 user2
ZRANGE scores 0 -1 WITHSCORES
ZINCRBY scores 10 user1Bitmaps
SETBIT login:2021-04-10 66666 1
BITCOUNT login:2021-04-10HyperLogLog
PFADD uv:user user1 user2
PFCOUNT uv:userGEO
GEOADD locations 117.12 39.08 tianjin
GEORADIUS locations 117 39 100 km WITHDISTAdvanced Features
Slow Log
Record commands that exceed a latency threshold.
CONFIG SET slowlog-log-slower-than 1000
SLOWLOG GET 3Pipeline
Batch multiple commands to reduce round‑trip time.
pipeline.set("key1", "val1");
pipeline.get("key1");
List<Object> results = pipeline.syncAndReturnAll();Transactions & Lua Scripting
MULTI
SET msg "hello"
GET msg
EXECLua scripts run atomically inside Redis:
EVAL "return redis.call('set', KEYS[1], ARGV[1])" 1 mykey myvaluePublish/Subscribe
SUBSCRIBE mychannel
PUBLISH mychannel "hello"
UNSUBSCRIBE mychannelPersistence
Redis offers two main persistence mechanisms:
RDB – snapshot of the dataset (fast loading, but may lose recent writes).
AOF – append‑only log of write commands (more durable, can be rewritten to shrink size).
Since Redis 4.0, mixed persistence combines an RDB snapshot with incremental AOF for faster restarts.
Replication & High Availability
Master‑slave replication provides read scalability and failover. Sentinel monitors instances, automatically promotes a slave to master when the primary fails, and informs clients of the new address.
Cache Consistency Strategies
Common problems and mitigations:
Cache penetration – use Bloom filters or cache empty results briefly.
Cache avalanche – add random jitter to expiration times.
Cache breakdown – protect hot keys with mutexes or always‑on cache.
Cache‑DB Synchronization
Four basic patterns:
Update DB then update cache.
Update cache then update DB.
Delete cache then update DB.
Update DB then delete cache.
For patterns 3 and 4, the double‑delete (or delayed delete) technique reduces stale data:
// Delete cache
DEL key
// Update DB
UPDATE table SET ... WHERE id=...
// Sleep 1 s
sleep(1)
// Delete cache again
DEL keyDistributed Locks
Simple lock using SET key value NX PX ttl ensures atomic acquisition and expiration. SET lock:order 12345 NX PX 5000 Release only if the value matches to avoid deleting another client’s lock:
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
endRedlock algorithm (recommended for multi‑node environments) obtains the lock on a majority of independent Redis instances, uses a unique value, and validates the elapsed time before considering the lock acquired.
Clustering Options
Beyond single‑node setups, Redis can be scaled with:
Sentinel – monitor master‑slave groups and perform failover.
Codis – proxy‑based sharding solution (open‑source, Chinese origin).
Redis Cluster – native sharding and automatic failover built into Redis.
Further Reading
For deeper dives, see the official Redis documentation, the “Scaling Memcache at Facebook” paper (covers cache‑aside pattern), and Antirez’s Redlock design notes.
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.
Tencent Cloud Developer
Official Tencent Cloud community account that brings together developers, shares practical tech insights, and fosters an influential tech exchange community.
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.
