Appearance
Redis Data Structure Selection
Use Case → Data Structure Mapping
text
Use Case Data Structure Why
──────────────────────────────────────────────────────────────────────────────────────
Simple cache (user profile) String Fastest, simplest
Object cache (user fields) Hash Memory efficient for objects
Counters (page views) String (INCR) Atomic increment
Rate limiting (API quota) String (INCR) INCR + EXPIRE NX trong MULTI
Session storage Hash Store session fields
Recent items (activity feed) List LPUSH + LTRIM for bounded list
Message queue List LPUSH + BRPOP (blocking)
Unique visitors Set Automatic deduplication
Tags (article tags) Set Set operations (union, intersection)
Leaderboard (game scores) Sorted Set Range queries by score
Priority queue Sorted Set Score = priority
Time-series (recent events) Sorted Set Score = timestamp
Real-time analytics Sorted Set Score = timestamp, ZREMRANGEBYSCORE
Pub/Sub (chat, notifications) Pub/Sub Broadcast messages
Event stream (audit log) Stream Append-only log with consumer groups
Geospatial (nearby locations) Geospatial GEOSEARCH queries
Bloom filter (membership test) Bloom filter (built into Redis 8; RedisBloom module on older versions) Probabilistic set membership
HyperLogLog (unique count) HyperLogLog Memory-efficient cardinalityPattern 1: Cache-Aside (Lazy Loading)
python
# Python (redis-py); minh hoạ: `db` là client SQL giả định, không chạy độc lập
import redis
import json
r = redis.Redis(decode_responses=True)
def get_user(user_id):
cache_key = f"user:{user_id}"
# Try cache first
cached = r.get(cache_key)
if cached:
return json.loads(cached)
# Cache miss - fetch from DB
user = db.query("SELECT * FROM users WHERE id = ?", user_id)
# Store in cache (1 hour TTL)
r.set(cache_key, json.dumps(user), ex=3600)
return userPattern 2: Write-Through Cache
python
# Python (redis-py); minh hoạ, không chạy độc lập: dùng r, json, db từ khối Cache-Aside
def update_user(user_id, data):
# Update DB first
db.execute("UPDATE users SET name = ? WHERE id = ?", data['name'], user_id)
# Update cache
cache_key = f"user:{user_id}"
r.set(cache_key, json.dumps(data), ex=3600)Pattern 3: Rate Limiting (Fixed Window)
python
# Python (redis-py), chạy sau khối Cache-Aside (dùng r)
import time
def rate_limit(user_id, limit=100, window=60):
key = f"ratelimit:{user_id}:{int(time.time() / window)}"
pipe = r.pipeline() # MULTI/EXEC: hai lệnh chạy liền nhau
pipe.incr(key)
pipe.expire(key, window, nx=True) # đặt TTL khi key chưa có TTL (Redis 7.0+)
count, _ = pipe.execute()
return count <= limit # True if allowed, False if rate-limitedPattern 4: Rate Limiting (Sliding Window Log)
python
# Python (redis-py), chạy sau khối Cache-Aside (dùng r)
import time
import uuid
def rate_limit_sliding(user_id, limit=100, window=60):
key = f"ratelimit:{user_id}"
now = time.time()
member = f"{now}:{uuid.uuid4()}" # member duy nhất: hai request cùng lúc không ghi đè nhau
pipe = r.pipeline() # MULTI/EXEC: bốn lệnh chạy liền nhau
pipe.zremrangebyscore(key, 0, now - window) # bỏ request ngoài cửa sổ
pipe.zadd(key, {member: now}) # ghi request hiện tại
pipe.zcard(key) # đếm trong cửa sổ (đã gồm request này)
pipe.expire(key, window)
_, _, count, _ = pipe.execute()
if count > limit:
r.zrem(key, member) # bị chặn thì không tính request này
return False # Rate-limited
return True # AllowedPattern 5: Leaderboard (Sorted Set)
python
# Python (redis-py), chạy sau khối Cache-Aside (dùng r)
# Add player score
r.zadd("leaderboard:global", {"player1": 100, "player2": 200})
# Increment score
r.zincrby("leaderboard:global", 50, "player1") # player1 = 150
# Top 10 players
top10 = r.zrange("leaderboard:global", 0, 9, desc=True, withscores=True)
# [('player2', 200.0), ('player1', 150.0)]
# Player rank (0-indexed)
rank = r.zrevrank("leaderboard:global", "player1")
# 1 (second place)
# Player score
score = r.zscore("leaderboard:global", "player1")
# 150.0Pattern 6: Distributed Lock
python
# Python (redis-py), chạy sau khối Cache-Aside (dùng r)
import uuid
def acquire_lock(lock_name, timeout=10):
identifier = str(uuid.uuid4())
lock_key = f"lock:{lock_name}"
# Try to acquire lock (SET if not exists, with TTL)
acquired = r.set(lock_key, identifier, nx=True, ex=timeout)
return identifier if acquired else None
def release_lock(lock_name, identifier):
lock_key = f"lock:{lock_name}"
# Only release if we own the lock (Lua script for atomicity)
script = """
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
"""
return r.eval(script, 1, lock_key, identifier)Đo bộ nhớ từng kiểu
bash
# redis-cli (redis:8): đo bộ nhớ cùng 100 phần tử trong từng kiểu
redis-cli EVAL "for i=1,100 do redis.call('HSET','h100','f'..i,'v'..i); redis.call('SET','s'..i,'v'..i); redis.call('SADD','set100','m'..i); redis.call('ZADD','z100',i,'m'..i) end for i=1,600 do redis.call('HSET','h600','f'..i,'v'..i) end return 1" 0
redis-cli OBJECT ENCODING h100
redis-cli MEMORY USAGE h100
redis-cli EVAL "local t=0 for i=1,100 do t=t+redis.call('MEMORY','USAGE','s'..i) end return t" 0
redis-cli MEMORY USAGE set100
redis-cli MEMORY USAGE z100
redis-cli OBJECT ENCODING h600
redis-cli CONFIG GET hash-max-listpack-entriesKết quả đo (redis:8.10.3, 100 phần tử mỗi kiểu, byte, đổi theo máy và phiên bản):
text
hash 100 field (listpack) 1014
100 key String 3200 tổng MEMORY USAGE của 100 key
set 100 member (listpack) 524
sorted set 100 (listpack) 722
hash 600 field: hashtable vượt hash-max-listpack-entries = 512Phải nhớ:
- Chọn kiểu theo thao tác cần (INCR, ZRANGE, SADD...) trước, rồi đo
MEMORY USAGEtrên dữ liệu thật. - Hash, Sorted Set, Set nhỏ dùng mã hoá gọn (hash/zset: tham số
*-listpack-*từ Redis 7.0, trước đó*-ziplist-*; Set chuỗi nhỏ dùng listpack từ 7.2, Set toàn số nguyên dùng intset); vượt ngưỡng tự chuyển sang hashtable/skiplist và tốn bộ nhớ hơn. - Mẫu nhiều lệnh (rate limit, lock) phải chạy trong MULTI hoặc Lua; TTL đi cùng lệnh ghi.