Autocoder

Redis Interview Questions and Answers

Last updated 2026-11-19

Redis is the default answer to caching, rate limiting, leaderboards and session storage in backend interviews, so the questions go beyond "what is Redis". Expect data-structure choices, persistence trade-offs, eviction, cache stampede and distributed locks. The commands below are valid redis-cli syntax.

For the surrounding theory see caching interview questions, and for how Redis fits among stores see NoSQL questions. Design rounds often use it too; the plan is in how to crack a system design interview.

ModelIn-memory data structure store
PersistenceRDB snapshots, AOF log, or both
ScalingReplication, Sentinel, Cluster with 16384 hash slots

Choosing the right structure

Most Redis answers become easy once you pick the structure. A string holds a value or a counter. A hash holds an object. A list is a queue or a recent-items feed. A set holds unique members and supports intersections. A sorted set orders members by score and is the right tool for leaderboards and delayed jobs. A stream is an append-only log with consumer groups.

Things that lose marks

Redis Interview Questions and Answers: questions with worked answers

  1. 1

    What is Redis and why is it fast?

    easy

    Redis is an in-memory key-value store with rich data structures, optional persistence and replication. It is fast because data lives in RAM, operations use efficient structures with O(1) or O(log n) cost, command execution is single-threaded so there is no lock contention, and an event loop with I/O multiplexing serves many clients. A single instance commonly handles hundreds of thousands of simple operations per second, though throughput depends on hardware, pipelining and value size.

  2. 2

    List the main Redis data types and one use for each.

    easy

    String: counters and cached values. Hash: user profile fields. List: job queue or activity feed. Set: unique visitors and tag membership. Sorted set: leaderboards and scheduled tasks by timestamp. Bitmap: daily active flags per user id. HyperLogLog: approximate distinct counts using about 12 KB. Stream: durable event log with consumer groups. Geo: nearby-places queries, built on a sorted set.

  3. 3

    Build a leaderboard with Redis commands.

    medium

    A sorted set keeps members ordered by score, with O(log n) insertion. ZADD sets or updates a score, ZINCRBY adds to it, ZREVRANGE with scores lists the top players and ZREVRANK returns a player's zero-based position from the top.

    text
    ZADD board 1500 asha
    ZADD board 1720 ravi
    ZINCRBY board 100 asha        # asha now 1600
    ZREVRANGE board 0 2 WITHSCORES # top 3
    ZREVRANK board asha            # 1 (second place)
  4. 4

    RDB versus AOF persistence: what are the trade-offs?

    medium

    RDB writes point-in-time snapshots at intervals: compact files, fast restarts, but you can lose the writes since the last snapshot. AOF appends every write command to a log, with fsync policies of always, every second or never; it loses at most about a second of data with everysec but produces larger files and slower restarts, mitigated by background rewrite. Many deployments enable both: RDB for backups and AOF for durability. If Redis is purely a cache, you can disable persistence.

  5. 5

    What eviction policies does Redis offer?

    medium

    When memory reaches maxmemory, the policy decides what to remove. noeviction rejects writes. allkeys-lru and allkeys-lfu evict among all keys by least recently or least frequently used; volatile-lru, volatile-lfu, volatile-ttl and volatile-random consider only keys with a TTL; allkeys-random evicts at random. LRU and LFU are approximated by sampling keys. For a pure cache, allkeys-lru or allkeys-lfu is the usual choice.

  6. 6

    Explain the cache-aside pattern and its race conditions.

    medium

    The application reads the cache first; on a miss it reads the database, stores the result in the cache with a TTL and returns it. On writes it updates the database and then deletes the cache entry. A race exists: a slow reader fetches an old row, a writer updates and deletes the key, then the reader stores the stale value. TTLs bound how long staleness lasts. See caching questions for write-through and write-back.

    python
    def get_user(uid):
        key = f"user:{uid}"
        cached = r.get(key)
        if cached:
            return json.loads(cached)
        user = db.fetch_user(uid)
        r.set(key, json.dumps(user), ex=300)   # 5 minute TTL
        return user
  7. 7

    What is a cache stampede and how do you prevent it?

    hard

    When a hot key expires, many requests miss at once and all hit the database. Mitigations: take a short-lived lock so only one request rebuilds the value while others wait or serve stale data; add random jitter to TTLs so keys do not expire together; refresh popular keys early in the background; and cache negative results briefly to stop repeated misses for non-existent keys.

  8. 8

    How do you implement a distributed lock in Redis?

    hard

    Acquire with a single atomic command that sets a unique token only if the key does not exist, with an expiry: SET lock:job42 token123 NX PX 30000. Release only if the stored value still equals your token, using a Lua script so check and delete are atomic. The expiry prevents a crashed holder from locking forever, but if work outlasts the TTL two clients can hold it, so use fencing tokens for correctness-critical work. On one instance this is advisory; Redlock across several nodes is debated for safety-critical use.

    text
    SET lock:job42 token123 NX PX 30000
    -- release (Lua):
    if redis.call("get", KEYS[1]) == ARGV[1] then
      return redis.call("del", KEYS[1])
    else return 0 end
  9. 9

    Implement a fixed-window rate limiter with Redis.

    medium

    Use INCR on a key that includes the client and the time window, and set an expiry on first use. If the count exceeds the limit, reject. The fixed window allows bursts at window edges, up to twice the limit across a boundary; a sliding window log with a sorted set or a token bucket in Lua smooths this.

    python
    def allow(client, limit=100, window=60):
        key = f"rl:{client}:{int(time.time()) // window}"
        count = r.incr(key)
        if count == 1:
            r.expire(key, window)
        return count <= limit
  10. 10

    What do MULTI, EXEC and WATCH do?

    medium

    MULTI starts queuing commands and EXEC runs them as one atomic, isolated block with no other client commands interleaved. Redis does not roll back: syntax errors abort the whole block, but a runtime error in one command leaves the others applied. WATCH key marks keys for optimistic locking: if a watched key changes before EXEC, the transaction is aborted and returns nil, so the client retries. Lua scripts are the other way to get atomic multi-step logic.

  11. 11

    Explain Redis replication, Sentinel and Cluster.

    medium

    Replication is asynchronous: a replica copies the master, so a failover can lose recent writes. Sentinel monitors masters, performs automatic failover by majority agreement and tells clients the new master address; it does not shard. Redis Cluster shards data across masters using 16384 hash slots, where a key's slot is CRC16(key) mod 16384, each master owns a range of slots and has replicas. Multi-key commands need all keys in one slot, which you force with hash tags such as {user42}:cart.

  12. 12

    KEYS versus SCAN, and what is a big key problem?

    medium

    KEYS pattern walks the entire keyspace in one blocking call, which stalls a single-threaded server on large datasets. SCAN iterates in small batches with a cursor and does not block, though it may return a key more than once. Big keys, such as a list with millions of elements, make DEL, replication and rehashing slow; use UNLINK for background deletion and split large collections into buckets.

  13. 13

    How does pub/sub differ from streams?

    medium

    Pub/sub is fire-and-forget: subscribers receive messages published while they are connected, and nothing is stored, so offline consumers miss messages. Streams are an append-only log with IDs, retained until trimmed, supporting consumer groups where each message is delivered to one consumer in the group, with acknowledgements and the ability to claim pending messages. Use pub/sub for ephemeral notifications and streams for reliable processing, as covered in message queue questions.

Frequently asked questions

Is Redis single-threaded?

Command execution runs on one main thread. Since version 6, optional I/O threads handle reading and writing sockets, and background threads handle tasks such as lazy freeing.

Can Redis be the primary database?

It can, with AOF and replication, but memory cost and durability limits make it more common as a cache, session store or secondary store.

What is the difference between Redis and Memcached?

Redis offers rich data structures, persistence, replication and scripting. Memcached is a simpler multithreaded string cache.

How big can a Redis value be?

A string can be up to 512 MB, but values of that size are a bad idea; keep values small for latency.

Related guides

More in CS Fundamentals Interview Questions

See all in this section