Comprehensive Redis Guide: Introduction, Installation, Data Types, Persistence, Transactions, and Caching Strategies
This article provides a detailed overview of Redis, covering its core concepts, high‑performance features, common use cases, installation steps, memory‑management policies, supported data structures, persistence mechanisms, transaction model, and best practices for cache consistency and failure handling.
1. Redis Overview
Redis is an open‑source, BSD‑licensed, in‑memory key‑value store that offers high performance, rich data types, atomic operations, and features such as publish/subscribe, key expiration, and fast read/write.
Key Characteristics
Performance – up to 110,000 reads/s and 81,000 writes/s.
Data Types – String, Hash, List, Set, Sorted Set (ZSet), HyperLogLog, etc.
Atomicity – all commands are atomic; multi‑command transactions are supported via MULTI/EXEC.
Additional Features – pub/sub, notifications, key eviction policies.
2. Common Application Scenarios
Redis can serve as a primary database, a cache for hot data, or a message broker. Typical use cases include:
Cache – improves response time and reduces DB load. Leaderboard – uses Sorted Sets for ranking. Counter – atomic increment/decrement for metrics. Distributed Session – central session store. Distributed Lock – SETNX based lock. Social Network Features – likes, follows, friends. Latest List – LPUSH/LTRIM for recent items. Message Queue – simple queue via List or Pub/Sub.
3. Installation & Startup
Download the binary from redis.io , extract, compile, and start the server.
# Extract
[root@host ~]# tar -zxvf redis-6.2.6.tar.gz
# Compile
[root@host redis-6.2.6]# make MALLOC=libc
# Install
[root@host redis-6.2.6]# make PREFIX=/opt/redis install
# Start server
[root@host bin]# ./redis-server
# Start client
[root@host bin]# ./redis-cli4. Memory Eviction Policies
Redis provides several policies to free memory when the limit is reached: volatile-lru – evict least‑recently used keys with an expiration. allkeys-lru – evict LRU among all keys (most common). volatile-random – random eviction among expiring keys. allkeys-random – random eviction among all keys. volatile-ttl – evict keys with the nearest expiration. noeviction – refuse writes when memory is full. volatile-lfu – evict least‑frequently used expiring keys. allkeys-lfu – evict LFU among all keys.
5. Data Types
5.1 String
Basic type, up to 512 MB per key, binary‑safe, supports GET/SET, INCR/DECR, MGET/MSET, APPEND, etc.
# Set a key with expiration
SETEX mykey 10 "value"
# Increment atomically
INCR counter
# Get a substring
GETRANGE mykey 0 45.2 Hash
Map of fields to values, ideal for storing objects; supports HSET, HGET, HMGET, HGETALL, HDEL, HINCRBY, etc.
# Store a user object
HSET user:100 name "Alice" age 30
# Retrieve a field
HGET user:100 name5.3 List
Doubly‑linked list supporting push/pop from both ends, range queries, and blocking operations.
# Push values to the left
LPUSH mylist "a" "b"
# Get a range
LRANGE mylist 0 -1
# Pop from the right
RPOP mylist5.4 Set
Unordered collection of unique strings; supports SADD, SMEMBERS, SISMEMBER, SINTER, SUNION, SDIFF, etc.
5.5 Sorted Set (ZSet)
Members are ordered by a double score; supports ZADD, ZRANGE, ZRANK, ZREVRANGE, ZREM, ZINCRBY, etc.
# Add a member with score
ZADD leaderboard 100 "user1"
# Get top 10
ZRANGE leaderboard 0 9 WITHSCORES5.6 HyperLogLog
Probabilistic cardinality estimator; commands PFADD, PFCOUNT, PFMERGE.
6. Persistence
6.1 RDB (Snapshot)
Periodically writes the entire dataset to a binary dump file (default dump.rdb). Fast snapshot and restore but may lose recent writes.
6.2 AOF (Append‑Only File)
Logs every write command; on restart Redis replays the file to rebuild state. Configurable fsync policies: appendfsync always, appendfsync everysec, appendfsync no. AOF files can grow large; BGREWRITEAOF rewrites them compactly.
7. Transactions
Redis transactions group commands between MULTI and EXEC. All commands are queued and executed atomically in order; other clients cannot interleave commands. Errors in a command do not abort the whole transaction, but DISCARD can abort manually.
# Example: transfer 50 from A to B
MULTI
DECR account:A 50
INCR account:B 50
EXEC8. Cache Consistency & Failure Patterns
8.1 Cache Avalanche
Mass expiration or Redis outage causes a sudden surge of DB traffic. Mitigation: stagger expirations, use distributed locks, or pre‑warm caches.
8.2 Cache Breakdown
Hot key expires, many requests hit DB simultaneously. Mitigation: mutex lock (SETNX) for single DB fetch, or keep hot keys without expiration and refresh asynchronously.
8.3 Cache Penetration
Requests for non‑existent keys bypass cache and hit DB repeatedly. Mitigation: filter illegal inputs, cache null placeholders, or use a Bloom filter to quickly reject absent keys.
9. References & Further Reading
For a deeper dive, see the linked articles on Redis interview questions, micro‑service architecture, and related technologies.
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.
Architect
Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.
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.
