Redis is fast for three reasons: data sits in RAM avoiding disk I/O, commands run sequentially on one main thread without lock contention or context switching, and an I/O-multiplexing event loop (epoll/kqueue) serves tens of thousands of connections. Strictly speaking, only command execution is single-threaded—optional I/O threads handle socket reads/writes, background threads run fsync and UNLINK, and forked children write RDB snapshots or AOF rewrites. The trade-off is that one slow command stalls every request behind it. In production, avoiding big keys, KEYS *, and long Lua scripts matters most, and scaling across cores requires Cluster sharding.
Key terms:event loop, I/O multiplexing, single-threaded execution, big key
Likely follow-up: "If you enable Redis I/O threads, do commands execute in parallel, and how does that affect atomicity?"
I pick Redis data structures based on access patterns. Strings handle cached payloads, atomic counters, and simple leases; Hashes fit multi-field objects like user profiles or carts where you update individual fields atomically; Lists work for lightweight queues or recent-N timelines; Sets handle deduplication and intersections; and Sorted Sets power score-ordered leaderboards and delayed jobs. Beyond the core five, HyperLogLog gives approximate unique counts like UV in roughly 12 KB per key, and Bitmaps pack dense boolean flags like daily check-ins for contiguous integer IDs. In production, I avoid unbounded collections and O(N) full-read commands like HGETALL or SMEMBERS on large keys, preferring HSCAN or pagination.
底层的话,Sorted Set 数据量大时是跳表加哈希表。跳表是多层的有序链表,上层是下层的索引,查找、插入平均 log N,范围查询找到起点顺着往后走就行;哈希表存 member 到 score 的映射,所以查分数是 O(1)。不用红黑树,主要是范围查询更自然、实现更简单,还能在指针上记跨度来算排名。
English PitchEnglish · ~55s
I build leaderboards on Redis Sorted Set: ZINCRBY updates scores, ZRANGE ... REV fetches top-N, and ZREVRANK returns a user's rank in O(log N). I shard keys by period with TTLs, aggregate via ZUNIONSTORE, and encode timestamps into scores for tie-breaking within double's 53-bit integer precision. Under the hood, small sets use listpack, while larger ones pair a hash table—for O(1)ZSCORE lookups—with a skip list. Redis chose skip lists over red-black trees because range scans simply walk the bottom linked list, the code avoids tree rotations while easily tracking pointer spans for rank queries, and memory overhead stays tunable.
Key terms:Sorted Set, skip list, hash table, span
Likely follow-up: "If a global leaderboard grows to 100 million users, why won't a single Sorted Set scale in Redis Cluster and how would you redesign it?"
Redis offers two persistence mechanisms. RDB forks a child process to write compact point-in-time binary snapshots—fast to recover and ideal for off-box backups, though you lose everything written since the last snapshot. AOF appends every write command to a log and replays it on restart, using appendfsync everysec by default to cap typical data loss at around a second, while periodic rewrites compact the file with an RDB preamble for faster startup. In production, I usually enable both AOF everysec and RDB for durable state—keeping headroom for fork copy-on-write memory—but if Redis is strictly a rebuildable cache, disabling persistence avoids fork latency altogether.
Expiration and eviction solve two separate problems. Expiration removes keys whose TTL has elapsed using a hybrid of lazy deletion on access plus periodic background sampling under a CPU time budget, so expired keys are never returned even if they linger briefly in memory. Eviction kicks in only when writes hit maxmemory: Redis defaults to noeviction—returning OOM errors—so for caches I configure allkeys-lru or allkeys-lfu. Neither uses a costly global linked list; Redis approximates LRU by sampling random keys, while LFU tracks access frequency with a decaying logarithmic counter that resists one-off scan pollution. Always isolate cache data from non-evictable data on separate instances.
Both issues stem from Redis's single-threaded core and per-key sharding. A Big Key is an oversized value or huge collection whose DEL, HGETALL, or migration blocks the main thread and saturates bandwidth; I spot them via offline RDB analysis or --bigkeys on replicas, delete with async UNLINK, split into smaller keys, and paginate via HSCAN. A Hot Key concentrates massive traffic on one shard, so adding nodes won't spread load; I detect them with client-side counters or node skew—noting --hotkeys requires LFU—and mitigate with local app caches, read replicas, or salted key copies, trading off brief staleness.
Key terms:Big Key, Hot Key, UNLINK, local cache
Likely follow-up: "Why can an expiring Big Key still stall Redis, and what happens to cache consistency if you add local caching in front of a Hot Key?"
追问4 个
UNLINK 和 DEL 有什么区别?
DEL 在主线程同步释放内存;UNLINK 只在主线程摘除 key,释放交给后台线程。大对象用 UNLINK,也可以开 lazyfree-lazy-user-del yes 让 DEL 默认异步。
All three failure modes bypass the cache and slam the database. Cache penetration happens when requests query non-existent keys that always miss; I block it with input validation, short-TTL negative caching, or a Bloom Filter in front. A cache stampede—or thundering herd—occurs when a single hot key expires under heavy concurrency; I mitigate it using single-flight or mutex rebuilds, or logical expiration with asynchronous refresh so callers don't stall. Mass expiration—or cache avalanche—happens when many keys expire simultaneously or Redis goes down; adding random TTL jitter spreads expirations out, while Redis HA plus rate limiting and circuit breakers protect the database if the cache tier fails.
I default to Cache-Aside: reads check Redis and backfill on miss, while writes update the database first and then delete—not update—the cache key, because concurrent updates can land out of order whereas deletion is idempotent. With Write-Through, callers write only to the cache layer, which synchronously writes through to the database—simpler for callers at the cost of higher write latency—while Write-Behind writes to cache first and batches async DB flushes for high-throughput counters at the risk of losing unflushed updates on crash. Even Cache-Aside is only eventually consistent because a stalled reader can backfill stale data after a write invalidates the key. In production, I pair reliable async invalidation via Outbox or binlog CDC, version-checked Lua backfills, and finite TTLs as a safety net—and bypass caching entirely when strict consistency is required.
Choosing a rate limiter comes down to traffic shape and burst tolerance. Fixed window counters are O(1) and simple, but can admit nearly double the quota across window boundaries; sliding windows smooth that boundary—either accurately via Sorted Set timestamps or cheaply via weighted window counters. Token bucket is my go-to for public APIs because it enforces an average refill rate while allowing controlled bursts up to bucket capacity, whereas leaky bucket smooths output to a rigid rate to protect fragile downstreams. In Redis, the read-check-update must run atomically inside a Lua script using Redis server TIME to avoid clock skew across app nodes.
A single-instance Redis lock acquires atomically with SET key token NX PX 30000—providing mutual exclusion, a lease TTL to avoid deadlocks on crash, and a unique owner token—and releases via a Lua script that compares the token before deleting so you never unlock someone else's lease. However, Redis locks are not strictly safe for correctness: a long GC pause can let a lease expire while the holder keeps working, and asynchronous replication can lose an acknowledged lock during failover. Even Redlock doesn't eliminate pause-induced overlap. I use Redis locks only for efficiency—avoiding duplicate work—and rely on monotonic fencing tokens, database unique constraints, or optimistic locking whenever correctness is critical.
I choose among Redis's three deployment modes based on automatic failover and single-node capacity. Primary-Replica adds replicas for read scaling and backups, but failover is manual. Sentinel adds automatic failover and primary discovery while keeping one primary—my default whenever data and writes fit on one node, because it stays simple. Redis Cluster shards across 16,384 slots over multiple primaries with replicas, scaling memory and write throughput horizontally—at the cost of Cluster-aware clients, single-slot constraints on multi-key commands, and db 0 only. All three replicate asynchronously by default, so failover preserves availability rather than strong consistency.
Redis 主从复制默认是异步命令流:主库写完就回复客户端,再把写命令异步发给副本重放,同时双方维护同一个复制 ID 和递增的 offset。因为不等副本确认,主从会有短暂延迟,读副本可能读到旧值。
副本首次连接或断线重连时会发 PSYNC,带上自己的复制 ID 和 offset。如果主库的环形复制积压缓冲区(Replication Backlog)里还留着它缺的那段数据,就只补差量,叫部分重同步;如果断线太久数据被覆盖了,或者复制 ID 对不上,就触发全量同步:主库后台生成 RDB 发过去加载,再把期间累积的新写命令补齐。
Redis Cluster partitions the keyspace into 16,384 hash slots using CRC16(key) mod 16384, assigning slot ranges across multiple primary nodes with replicas for failover. Cluster-aware clients cache the slot-to-node map and handle two redirections: -MOVED means a slot permanently belongs to another node so the client updates its routing table, whereas -ASK happens mid-migration when a key has already moved—the client sends ASKING once to the target without modifying its cached map. Because multi-key operations, transactions, and Lua scripts require all keys in one slot, you colocate related keys using {hash tags}, being careful not to create hot slots.
Key terms:hash slot, MOVED vs ASK, hash tag, Gossip protocol
Likely follow-up: "Why did Redis Cluster pick 16,384 hash slots instead of consistent hashing or 65,536 slots?"
Yes—Redis can lose acknowledged writes because replication is asynchronous by default. It happens in two ways: either a primary acknowledges a write and crashes before shipping it to replicas, or a network partition creates a split-brain where an isolated old primary keeps accepting writes while Sentinel or Cluster promotes a replica, and those writes are wiped once the old primary rejoins as a replica. You can shrink that window with min-replicas-to-write and min-replicas-max-lag, plus WAIT on critical writes, at the cost of lower write availability during replica hiccups. Neither makes Redis strongly consistent, so authoritative data that cannot be lost belongs in a database.