Redis — Interview Q&A Matrix
Parent stack: Persistence & Caching Technology: Redis Levels: Junior · Senior · Architect Questions: 4
Each entry contains a Question, the Expected Depth, an Ideal Answer, and Red Flags.
Junior
Q1 — Redis basics and core data types
Question: What is Redis, why is it fast, and which data types would you use for a session store and a leaderboard?
Expected Depth:
- Explains why in-memory access and efficient data structures make Redis fast.
- Knows that command execution is mostly single-threaded, while networking and background work can use other threads.
- Selects suitable data types: string, hash, list, set, sorted set, and stream.
- Uses TTLs and understands active and lazy expiration.
- Knows that one command is atomic but several commands are not automatically atomic together.
- Understands basic memory limits, eviction policies, persistence, and clustering.
Ideal Answer:
- Redis keeps its working data in memory and uses efficient data structures. Most commands run on the main execution thread, which makes each command atomic. Modern Redis can use other threads for network I/O, persistence, and background tasks, so "Redis is fully single-threaded" is too simple.
- Common data types include:
- String for cached values, counters, and simple locks.
- Hash for fields of a small object.
- List for simple ordered collections.
- Set for unique members.
- Sorted Set for rankings and time-ordered scores.
- Stream for an append-only event log with consumer groups.
- A session can use a hash with an expiry. Set the fields and TTL in one transaction so a failure does not leave a session without expiration:
MULTI
HSET session:abc userId 42 role CUSTOMER
EXPIRE session:abc 1800
EXEC
ZADD leaderboard 1500 "player:42"
ZREVRANGE leaderboard 0 9 WITHSCORES- Expired keys may be removed when accessed and by background expiry work. Expiration is not a precise scheduler, so do not depend on deletion at an exact millisecond.
- Configure
maxmemoryand an eviction policy. A cache may use an LRU/LFU policy, while a Redis instance holding important non-cache data should normally reject writes rather than evict arbitrary keys. - Redis Cluster splits keys into hash slots across nodes. Multi-key operations work reliably only when the required keys are on the same node, often by using a hash tag such as
{account:42}.
Red Flags:
- Says that Redis is only a cache and cannot name its data types.
- Says that every part of Redis runs on one thread.
- Never sets TTLs or a memory policy.
- Uses several commands as if they form one atomic operation.
- Treats key expiration as an exact timer.
- Assumes that Redis has relational durability and constraints by default.
Senior
Q2 — Cache-Aside pattern and invalidation pitfalls
Question: Implement caching for a read-heavy product endpoint with Redis. Which pattern do you use, and how do you avoid stale data and stampedes?
Expected Depth:
- Explains Cache-Aside reads and why the database remains the source of truth.
- Invalidates only after a successful database commit.
- Understands stale-fill races between readers and writers.
- Uses TTL jitter, request coalescing, stale-while-revalidate, or a short lease to reduce stampedes.
- Handles cache penetration with negative caching where safe.
- Plans serialization versioning, cache failure behavior, and observability.
Ideal Answer:
- With Cache-Aside, the application first checks Redis. On a miss, it reads the database, stores the result with a TTL, and returns it. The database remains the source of truth.
Product get(long id) {
String key = "product:" + id;
Product cached = redis.get(key);
if (cached != null) {
return cached;
}
Product product = repo.findById(id).orElseThrow();
Duration ttl = Duration.ofMinutes(10)
.plusSeconds(ThreadLocalRandom.current().nextLong(60));
redis.set(key, product, ttl);
return product;
}- On a write, commit the database transaction first and then delete the cache key. Never invalidate before a transaction that may roll back.
- There is still a race: a reader can load old data, a writer can commit and delete the key, and then the reader can cache the old value. Reduce this risk with versioned cache values, change-data-capture invalidation, or a design that checks the database version before storing.
- For a hot key, combine several controls:
- Add random TTL jitter so many keys do not expire together.
- Coalesce concurrent misses so one request loads the value.
- Serve a slightly stale value while one worker refreshes it, when the business allows this.
- If using a Redis lease, give it a unique token, a short expiry, and safe release logic.
- Cache a "not found" result for a short time when repeated missing IDs could overload the database. Do not negative-cache permission failures or temporary errors as permanent absence.
- If Redis is unavailable, decide whether the service should read the database with rate limits or fail fast. Monitor hit rate, miss latency, eviction count, stale reads, and database fallback traffic.
Red Flags:
- Updates the database but never invalidates the cache.
- Deletes the cache entry before the database transaction commits.
- Claims that delete-after-write removes every race.
- Uses no TTL, or gives every key the same expiry time.
- Uses a lock with no token or expiry to prevent stampedes.
- Sends unlimited cache-miss traffic to the database during a Redis outage.
Q3 — Redis persistence, atomicity, and distributed locks
Question: Explain RDB vs AOF persistence, how to do atomic multi-step operations, and the caveats of a Redis distributed lock.
Expected Depth:
- Compares RDB snapshots and AOF, including data-loss windows and restart cost.
- Understands AOF
fsyncpolicies and that replication is not the same as durability. - Uses
MULTI/EXEC, Lua, or Redis Functions for atomic server-side operations. - Knows that Redis transactions do not roll back earlier commands after a runtime error.
- Uses lock ownership tokens and safe release.
- Explains lease expiry, failover risks, and fencing tokens for correctness-critical resources.
Ideal Answer:
- RDB writes point-in-time snapshots. It is compact and useful for backups and faster restart, but a failure can lose changes made after the latest snapshot.
- AOF records write operations. With
appendfsync everysec, a crash can usually lose about one second of writes.alwaysoffers stronger durability at a higher latency cost. AOF files can be larger and need rewrite or replay work. - Many deployments use both. Replicas improve availability, but asynchronous replication can still lose acknowledged writes during failover.
MULTI/EXECqueues commands and executes them without another client interleaving commands. It does not provide relational rollback when one command fails at runtime.- Use a small Lua script or Redis Function when later steps depend on earlier results:
local available = tonumber(redis.call('GET', KEYS[1]) or '0')
local requested = tonumber(ARGV[1])
if available < requested then
return -1
end
return redis.call('DECRBY', KEYS[1], requested)- Scripts block other commands while they run, so keep them short and bounded.
- Acquire a simple lease with a random ownership token and expiry:
SET lock:invoice:42 8f4c... NX PX 30000- Release it only when the stored token still matches:
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0- A lease can expire while its owner is paused, and that owner may continue writing after another owner gets the lock. For a correctness-critical resource, use a monotonically increasing fencing token that the protected database or service rejects when it is older than the latest token.
- Redis failover and network partitions make strong distributed mutual exclusion difficult. Use a consensus-based coordination system or database lock when the business cannot tolerate two owners.
Red Flags:
- Releases a lock with
DELwithout checking the ownership token. - Uses a lock with no expiry, or assumes expiry stops the old owner from writing.
- Claims that a Redis lock is always safe during failover and network partitions.
- Says that
MULTI/EXECrolls back earlier commands after any error. - Runs a long Lua script and blocks the server.
- Confuses RDB, AOF, replication, and backup guarantees.
Architect
Q4 — Distributed cache consistency models
Question: Compare Cache-Aside, Write-Through, and Write-Behind for a distributed cache, and how do you keep caches coherent across many app instances?
Expected Depth:
- Compares Cache-Aside, Write-Through, and Write-Behind with their failure modes.
- Chooses consistency by data type instead of using one pattern for everything.
- Understands local-cache and shared-cache invalidation across instances.
- Knows that Redis Pub/Sub is not durable and disconnected subscribers miss messages.
- Uses versions, durable change events, and TTLs to limit stale data.
- Keeps authoritative financial state in a transactional system of record.
Ideal Answer:
- Cache-Aside: the application reads the cache and loads missing data from the database. It is simple and can fall back to the database, but it allows stale-fill and invalidation races.
- Write-Through: a cache layer writes to the system of record before confirming the cache write. Reads are simple, but every write depends on the cache layer and has extra latency.
- Write-Behind: the cache accepts the write and persists it later. It has low apparent latency but creates ordering, recovery, duplicate, and data-loss risks.
- For several application instances, publish a versioned invalidation after the database commit. Redis Pub/Sub is fast but not durable; a disconnected instance misses the message. Use a durable stream, Kafka topic, or database change stream when missed invalidations are unacceptable.
Database commit -> durable change event -> evict shared and local cache entries- Include an entity version in the event and cached value. An instance should not replace version 12 with a late version 11 event.
- TTLs are a final safety limit, not the main invalidation method. They ensure that a missed message does not leave a value stale forever.
- Product catalogs often accept Cache-Aside with short staleness. An authoritative financial balance should remain in a transactional database or ledger. Redis may hold a non-authoritative view, but a payment decision must verify the system of record.
Red Flags:
- Uses Write-Behind for critical financial state without a recovery and durability design.
- Uses Pub/Sub as if it were a durable event log.
- Has no version, TTL, or cross-instance invalidation plan.
- Treats all data as having the same consistency requirement.
- Uses Redis as the only authoritative financial ledger without explaining durability and reconciliation.
Scoring Rubric
| Level | Pass bar |
|---|---|
| Junior | Selects Redis data types and expiration rules correctly. |
| Senior | Designs cache and atomic-operation behavior for races and failures. |
| Architect | Defines explicit consistency, durability, invalidation, and recovery policies. |