← All topics
Start ▶
Redis and caching
Caching strategies, TTL, eviction and Redis data structures.
100 questions
Level:
No questions match — try other words or turn a level back on.
1
What is Redis, and what do you typically use it for on the backend?
Redis is an in-memory key-value store. It's mostly used for caches, sessions, counters, queues and rate limiting, because replies come back in microseconds.
2
If Redis keeps data in memory, does everything disappear when the server goes down?
Yes, if persistence is not enabled. With an RDB snapshot or an AOF log enabled, Redis restores the data from disk on restart, but the last few seconds may be lost.
3
List the main data types in Redis and give one example for each.
What it holds / Example — String: text, a number or bytes / SET user:1:name "Ali", INCR views; List: an ordered list / the last 10 notifications; Hash: field → value / HSET user:1 name Ali age 25; Set: a collection without duplicates / users who liked an article; Sorted Set: a set ordered by score / a game…
4
How do you count page views in Redis, and why not GET + SET?
With INCR page:42:views. It is atomic: even if a hundred requests arrive at once, each one adds exactly one. With GET followed by SET, the values overwrite each other and updates are lost.
5
Is it better to store a user profile in Redis as a String (JSON) or as a Hash?
If the object is always read and written as a whole, a JSON String is convenient. If individual fields change often or you only need part of the object, a Hash is better: you work with a single field using HGET, HSET, HINCRBY.
6
How do you build a simple job queue out of a Redis List?
The producer adds to the head of the list with LPUSH, the worker takes from the tail with BRPOP. BRPOP is blocking: if the queue is empty, it waits until an element arrives or the timeout expires.
7
What is the difference between a Set and a Sorted Set, and when do you need each?
A Set is an unordered collection without duplicates. In a Sorted Set every element has a score and the elements are kept ordered by it, so "top 10" and range queries are fast.
8
What is TTL, and how do you give a Redis key a lifetime?
TTL is the time left until the key is removed automatically. You set it at write time with SET key value EX 300, or later with EXPIRE key 300, and TTL key shows the remaining time.
9
Why do you need a cache, and what data should you not cache?
A cache keeps data that is read a lot and changes rarely in a fast place, which cuts DB load and response time. Data that must always be exact, such as an account balance or a payment status, is usually not read from a cache.
10
What are a cache hit and a cache miss, and how do you find out the hit ratio?
A hit means the requested value was found in the cache; a miss means it wasn't and you had to go to the original source. Hit ratio = hit / (hit + miss); in Redis you compute it from keyspace_hits and keyspace_misses in INFO stats.
11
People say Redis is single-threaded. What does that mean, and why is it still fast?
Commands run one after another on a single main thread. The data is in RAM, commands are very short and no locks are needed, so one thread handles hundreds of thousands of operations per second.
12
Why shouldn't you use KEYS * on a production Redis, and what do you use instead?
KEYS walks through all the keys in one go, and during that time Redis answers nobody else. Use SCAN instead: it returns keys in small batches, using a cursor.
13
What do you do to connect a Spring Boot application to Redis?
You add spring-boot-starter-data-redis and set the host/port in application.yml. After that Boot creates a Lettuce connection factory and a StringRedisTemplate on its own, and you just inject and use them.
14
How does the @Cacheable annotation in Spring work?
Before the method is called, Spring looks in the cache for a key built from the arguments. If it finds one, it returns the value without calling the method at all; if not, it runs the method and writes the result to the cache.
15
What is the difference between @CachePut and @CacheEvict?
@CachePut always runs the method and writes the result into the cache, for updates. @CacheEvict removes the entry from the cache, so the value gets reloaded on the next read.
16
How should you structure key names in Redis?
Use a readable namespace separated by colons: app:entity:id:field. It helps you group keys, find them with SCAN, and avoid collisions when several applications share one Redis.
17
Can you use Redis as the main database instead of PostgreSQL?
In some cases yes, but usually no. Redis has no SQL queries, JOINs, secondary indexes or full ACID transactions, all the data has to fit in RAM, and persistence may lose the last seconds.
18
What do the NX, XX, EX and PX options of the SET command do?
NX means write only if the key doesn't exist, XX means write only if it does. EX sets a TTL in seconds, PX in milliseconds. They combine in one atomic command.
19
Which commands do you use in redis-cli to quickly check a running Redis?
PING shows it's alive, INFO shows memory, clients and stats, DBSIZE shows the number of keys, and TTL/TYPE show the state of a single key. MONITOR shows all commands in real time, but in prod it should only be turned on briefly.
20
Why do people move the HTTP session to Redis when the application runs on several instances?
By default the session lives in each instance's own memory: if the next request lands on a different instance, the user gets "logged out". Spring Session writes the session to Redis, and any instance can read it.
21
Does Redis remove a key from memory the moment its TTL runs out?
Not always. Redis removes keys in two ways: when a key is accessed and found expired, it deletes it (lazy), and in the background it periodically checks random keys (active). So a dead key can sit in RAM for a while.
22
Caching isn't working in this code. What's the cause?
Inside findAll, findById is called through this. @Cacheable works through a Spring proxy, and an internal call bypasses the proxy, so every call goes to the DB.
23
What happens when Redis memory reaches the maxmemory limit?
It depends on maxmemory-policy. The default is noeviction: new writes are rejected with an OOM error. For a cache you usually set allkeys-lru or allkeys-lfu, so Redis evicts the least-used keys itself.
24
What is the difference between LRU and LFU eviction, and which one fits a cache better?
LRU evicts the key that hasn't been accessed for the longest time, LFU evicts the one accessed least often. LFU keeps one-off bulk reads from pushing out popular keys, so under a mixed load it's often better.
25
How does @Cacheable build its key, and when do two different calls end up on the same key?
By default SimpleKeyGenerator builds the key from the method arguments and does not include the method name. So if two methods use the same cache name and are called with the same argument, they can return each other's values.
26
Which serializer should you use to write objects to a Redis cache in Spring, and what is wrong with the default?
The default JdkSerializationRedisSerializer uses Java serialization: the class must be Serializable, Redis holds bytes you can't read, and if the class changes, old entries become unreadable. In practice you switch to a JSON serializer.
27
What is the difference between the DEL and UNLINK commands?
Both delete a key, but DEL frees the memory immediately on the main thread, while UNLINK makes the key invisible right away and frees the memory in a background thread. For big keys, UNLINK doesn't block Redis.
28
Does a MULTI/EXEC transaction in Redis roll back when something fails?
No. MULTI/EXEC runs the commands one after another with no other client interleaving, but if one of them fails at runtime, the rest still run and the earlier ones are not undone.
29
What is Redis pipelining, and when does it give a noticeable speedup?
Pipelining means sending several commands back to back without waiting for each reply, then reading the replies together. It removes the network round trip per command, especially when you send thousands of small commands.
30
What happens when a @Cacheable method returns null, and when does that cause problems?
By default RedisCacheManager caches null using a special marker, so a "not found" answer gets cached too. With disableCachingNullValues(), null is not cached and every such request goes to the DB.
31
Explain the cache-aside pattern with code.
The application reads from the cache first; on a miss it loads from the DB, writes to the cache with a TTL and returns the value. On a write it updates the DB and removes the cache entry. All the cache handling lives in application code.
32
What is the difference between write-through and write-behind caching?
With write-through, the write goes to the cache and the DB synchronously, and the reply returns after both are written. With write-behind, the write goes only to the cache, and the DB gets it later in batches in the background: fast, but data can be lost if the cache goes down.
33
When data changes, do you update the DB first and then delete the cache entry, or the other way around? Why?
Usually you write to the DB first, then delete the cache entry (not update it). In the opposite order, another request can put the old value back into the cache between the delete and the DB write, and it stays until the TTL runs out.
34
What is a cache stampede (dogpile), and how do you protect against it?
When a popular key expires, hundreds of requests miss at once and send the same heavy query to the DB. Protection: let a single request do the reload (a lock or sync = true), refresh in the background before expiry, and add random extra time to the TTL.
35
Requests for IDs that don't exist in the database bypass the cache and overload the DB. What do you do?
This is cache penetration. It helps to cache the "not found" result with a short TTL, validate the ID format on input, and, at large scale, add a Bloom filter: if the filter says "no", you don't go to the DB at all.
36
How do you write a simple distributed lock on top of Redis, and what is an easy mistake to make when releasing it?
You acquire it with SET lock:key <unique-token> NX PX 30000. On release you may delete only if the token is yours, and the check plus the delete must be atomic in one Lua script. A plain DEL can remove someone else's lock.
37
How does Redis Pub/Sub work, and what is the risk of using it as a message queue?
A publisher sends a message to a channel, and Redis immediately fans it out to every client subscribed at that moment. The message is not stored anywhere: if a subscriber is disconnected or hasn't connected yet, it never receives it.
38
How do you choose between RDB and AOF persistence?
RDB / AOF — What is stored: the full state at a point in time / the sequence of write commands; Data loss: back to the last snapshot (minutes) / about 1 s with everysec, nearly none with always; File size: small, compressed / large, rewritten periodically; Restart time: fast / slower; Backup: easy: copy one file /…
39
How do you give each cache its own TTL in Spring Boot?
In a RedisCacheManagerBuilderCustomizer or your own RedisCacheManager bean, you give each cache name its own RedisCacheConfiguration. If you only need one shared TTL, the spring.cache.redis.time-to-live setting is enough.
40
How do you build an API rate limiter with Redis?
The simplest is a fixed window: INCR rl:{user}:{minute}, set EXPIRE on the first INCR, and return 429 when the count goes over the limit. For more accuracy, use a sliding window with a Sorted Set, or a token bucket in Lua.
41
How does a consumer group work in Redis Streams, and what happens to a message if the worker takes it and crashes?
Within a group each message goes to one consumer, and it sits in the Pending Entries List (PEL) until that consumer calls XACK. If the worker crashes, the message stays in the PEL; another consumer takes it over with XAUTOCLAIM and processes it.
42
What does it mean in practice that Redis replication is asynchronous, and which writes can be lost when the master goes down?
The master returns OK to the client without waiting for the replicas to receive the write. If the master crashes in the meantime and a replica is promoted, the latest writes that hadn't reached it are lost for good. WAIT reduces this but doesn't fully guarantee it.
43
What does Redis Sentinel do, and how does a Spring application find out the master has changed?
Sentinels watch the master, agree by quorum that it is "dead", promote one of the replicas to master and point the others at it. The application doesn't know the Redis address, only the list of Sentinels, and asks them for the current master.
44
The lock has expired, but the process that took it is still working. How do you handle this?
There are two directions: keep extending the lock while the work runs (the Redisson watchdog does this), and check a fencing token on the protected resource's side. The watchdog covers many cases, but with a long GC pause or a network cut only a fencing token gives real protection.
45
What is the difference between the Lettuce and Jedis clients, and does Lettuce need a connection pool?
Jedis is blocking: one connection serves one thread at a time, so a pool is a must. Lettuce is built on Netty and is thread-safe, so many threads share one connection. Spring Boot uses Lettuce by default with a single shared connection, and a pool is usually not needed.
46
This code oversells tickets under load. Where is the bug, and how do you fix it?
Checking with GET and then DECR are separate commands, and in between other requests also see "1 left". The check and the decrement must be a single atomic operation: check the result of DECR, a Lua script, or WATCH.
47
When do you need a two-level cache (local Caffeine + Redis), and how do you clear stale data across instances?
When even a trip to Redis on every request is too expensive: for very hot data that rarely changes. L1 lives inside the JVM with a short TTL, and L2 is Redis. On a change, the Redis entry is deleted and a message goes out over Pub/Sub telling all instances to "remove it from L1".
48
Redis response time suddenly went up in prod. How do you track down the cause?
First I find out whether the problem is inside Redis or in the network/client: SLOWLOG, LATENCY DOCTOR, INFO (CPU, memory, fork time, connections), --bigkeys/--hotkeys. Common causes are an O(N) command on a big key, a fork, swapping and a single hot key.
49
Why is AOF rewrite needed, and how does the appendfsync setting affect data safety and speed?
AOF appends every write and grows without limit; a rewrite writes the current state as a minimal set of commands to a new file and replaces the old one. appendfsync always is the safest and slowest, everysec is the practical balance with about 1 s of loss, and no leaves fsync to the OS.
50
How does a cache avalanche happen, and how do you prepare the system against it?
Many keys expire at the same time or Redis goes down completely, so the whole load hits the DB at once and takes it down too. Protection: jitter on the TTL, warming the cache beforehand, a circuit breaker for Redis, and limiting the requests that go to the DB.
51
The Redis log shows "scheduled to be closed ASAP for overcoming of output buffer limits". What is this, and how do you fix it?
Redis accumulates replies for each client in an output buffer. If a client reads slowly or a reply is huge, the buffer goes past the client-output-buffer-limit and Redis drops the connection. The culprit is usually a slow Pub/Sub subscriber or a replica.
52
How do you count how many unique users visited a page per day in Redis, and why HyperLogLog and not a Set?
You add each visiting user with PFADD, and PFCOUNT gives the approximate unique count. A HyperLogLog takes at most about 12 KB per key with an error of about 0.81%, while a Set eats hundreds of MB for millions of IDs.
53
Why is it risky to rely on the `expired` event from Redis keyspace notifications to cancel an unpaid order after 15 minutes?
The expired event isn't emitted at the exact moment the TTL runs out, but when Redis actually deletes the key, and it can be late. It arrives over Pub/Sub, so if the application isn't connected at that moment, the event is lost. And in a cluster, each node only sends its own events.
54
In `INFO memory`, `used_memory` shows 6 GB and `used_memory_rss` shows 11 GB. Where does the difference come from, and what do you do?
This is memory fragmentation: Redis uses 6 GB for data, but the allocator (jemalloc) hasn't returned the 11 GB it took from the OS. mem_fragmentation_ratio is about 1.8. The fixes are activedefrag, MEMORY PURGE, and as a last resort a failover to a replica and a restart.
55
Why is LRU in Redis called "approximate", and what does `maxmemory-samples` affect?
Redis doesn't keep a true LRU list, since that would need extra pointers on every key. It takes a few random keys and evicts the oldest; maxmemory-samples is that sample size, and a larger value is more accurate but costs more CPU.
56
What do you understand by a "big key", how do you find one, and why is it dangerous?
A big key is a single key with a huge value, or a collection with millions of elements. When it is deleted, read or migrated, it keeps Redis's single thread busy for a long time, saturates the network, and overloads one node in a cluster.
57
A large share of traffic is hitting a single key (a hot key). What problem does this cause in a cluster, and what do you do?
In a cluster a key lives in one slot on one node, so adding nodes doesn't help: that node gets saturated on CPU and network. The solutions: a local cache inside the application, multiplying the key into several copies, and spreading reads across the replicas.
58
Is it safe to hand out order numbers with `INCR order:seq` in Redis? When does the same number come out twice?
Within a single node INCR is atomic, and parallel requests won't get the same number. But because replication is asynchronous, the latest increments are lost on failover and the new master hands out numbers that were already given. A restart without persistence resets the counter to zero.
59
When do you need a Lua script in Redis, and what does its atomicity rely on?
When you need to turn a read-check-write sequence of several commands into one atomic step. The script runs inside the server and no other command runs until it finishes. The atomicity comes from that same single thread.
60
What is wrong with this balance withdrawal code, and how do you fix it with `WATCH`?
Between the GET and the SET, another request can change the balance: a lost update. WATCH observes the key, and if it changes before EXEC, the transaction is aborted and you try again.
61
When Redis goes down, the `@Cacheable` methods throw exceptions too and the whole API returns 500. How do you soften this?
Spring's default SimpleCacheErrorHandler rethrows cache errors. If you provide your own CacheErrorHandler that logs the error and treats it as a miss, the method falls through to the DB. You also need a short Redis timeout, otherwise every request waits for seconds.
62
How does a Spring Data Redis repository (`@RedisHash`) store data in Redis, and what unexpected problems come up with `@Indexed` and TTL?
Each object is a separate hash, all the IDs go into a shared Set, and one more Set is stored for every @Indexed value. When a hash expires by TTL, the Sets are not cleaned up automatically. Spring does it through keyspace events and a "phantom" key, and if the application isn't running at that moment, "ghost" IDs remain in the indexes.
63
Which Redis feature do you use to quickly find free couriers nearby (say, within 3 km)?
Redis GEO commands: you write the courier's coordinates with GEOADD and fetch the nearest ones with GEOSEARCH ... BYRADIUS 3 km ASC COUNT 10. Internally it's a plain Sorted Set whose score is a geohash. Cleaning out inactive couriers is something you have to handle yourself.
64
How is a small hash or sorted set stored inside Redis, and how does that affect memory?
Small collections are stored in a compact listpack (ziplist before Redis 7), in consecutive bytes. When the element count or size goes over a threshold, it converts to a real hash table or skiplist, and memory use goes up several times.
65
How do you count daily active users (DAU) and "users who visited both yesterday and today" with a Redis Bitmap, and when does this approach not work?
One Bitmap per day: the user ID is the bit position, you mark it with SETBIT, BITCOUNT gives the DAU, and BITOP AND gives the intersection of two days. It's very cheap when the IDs are dense sequential numbers; with sparse IDs or UUIDs it doesn't work.
66
How do you store a verification code (OTP) sent by SMS in Redis, and how do you protect it from brute force?
I store the code as a hash, together with an attempt counter, under a key with a short TTL. I increment the counter on every wrong attempt and delete the code after the limit. I add separate limit keys for resends and for the daily SMS count.
67
At most 5 heavy export jobs should run at once, and the application runs on 10 pods. How do you build a distributed semaphore in Redis?
A plain INCR/DECR counter "eats" a permit when a pod dies. A better way is a Sorted Set: the member is the permit token, the score is its expiry time. In Lua you clear out the expired ones and ZADD if ZCARD is below the limit, keep updating the score during the work, and ZREM at the end.
68
Why can the memory of a Redis server jump sharply while an RDB snapshot is being taken?
BGSAVE does a fork(), and the child process shares the parent's memory through copy-on-write. During the snapshot, every page the parent writes to gets copied, so with many writes memory can reach almost double.
69
If you route reads to replicas in Lettuce (`ReadFrom.REPLICA_PREFERRED`), what problems do you run into?
Because replication is asynchronous, a replica lags by a few milliseconds, sometimes seconds. As a result read-your-writes breaks: a user doesn't see what they just wrote, and reading locks and counters from a replica leads to wrong decisions.
70
Why is it a bad idea to separate services into databases numbered 0, 1, 2 (`SELECT`) on a single Redis instance?
Numbered DBs are only a separate namespace for keys: the thread, the memory limit, eviction, FLUSHALL and slow commands are all shared. One service's mistake takes down the others as well. And Redis Cluster supports only DB 0 at all.
71
In cache-aside, even "update the DB first, then delete the cache entry" can leave a stale value. In what sequence does this happen, and what do you do?
A reader misses the cache and reads the old value from the DB. Meanwhile the writer updates the DB and deletes the cache entry, and then the reader writes the old value into the cache, where it stays until the TTL runs out. Mitigations: a short TTL, a delayed second delete, versioned writes, or CDC-based invalidation.
72
You're caching the catalog of a large online store. At what granularity do you cache product cards, category pages and search results, and how do you invalidate lists?
I cache each product under its own key and cache lists only as IDs, so when a price changes, a single product key is updated, not the lists. I invalidate lists with a category version, and from search I cache only the most-requested queries, with a short TTL.
73
You need to automatically cancel orders that are unpaid after 30 minutes. How do you build a delayed job queue in Redis, and where do you need to be careful?
A Sorted Set: the member is the order ID, the score is the execution time. A poller atomically takes the due items with Lua and hands them to a worker. Several pods must not take the same job twice, a job must not be lost when a pod dies, and there must be a way to recover if Redis loses data.
74
How are keys distributed across nodes in Redis Cluster, and what limits does that put on multi-key operations?
There are 16384 hash slots, and a key's slot is CRC16(key) mod 16384. Each node owns a subset of slots. All the keys in one command or Lua script must be in the same slot. You force that with a {...} hash tag, but if you overuse it you get a hot shard.
75
How do you test code that depends on Redis: caches, locks, Lua scripts?
Mocking RedisTemplate doesn't verify Redis semantics. I start a real Redis of the same version as prod with Testcontainers and, in an integration test, check cache hit/miss, TTL, key format, concurrent calls, and the behavior when Redis is missing.
76
You need to move a production Redis to another cluster without downtime (say, from standalone to Redis Cluster, or to a different provider). What plan do you make?
First I split the data by type: a cache can start empty in the new place, but sessions, queues and locks can't. Then I prepare the code for the new topology (CROSSSLOT, SELECT, KEYS), move the cache in stages, and move stateful data with replication or dual-write, always with a way back.
77
What do you configure to secure a production Redis? Is setting a password enough?
No. Redis should never be exposed to the internet, each service should have its own ACL user with access only to its own keys and the commands it needs, dangerous commands should be disabled, the network should use TLS, and the version should be kept up to date.
78
How does storing HTTP sessions in Redis with Spring Session work, and what problems do you run into in prod?
The session is stored in Redis as a hash, read on every request, and changed attributes are written back, so any pod can serve any user. The problems: putting large objects in the session, serialization versions, everyone being logged out if Redis goes down, and relying on expiry events.
79
How do you design a real-time leaderboard for millions of players in Redis?
A sorted set: the member is the player ID, the score is the points. ZINCRBY to update, ZREVRANGE for the top N, ZREVRANK for a player's own position, all O(log N). You have to handle tie-breaking, periodic (daily/weekly) leaderboards and splitting a very large set separately.
80
What mistakes are there in this combination of `@CacheEvict` and `@CachePut`, and how do you fix them?
The cache writes happen before the transaction commits, a managed JPA entity ends up in the cache, and allEntries = true scans and deletes the whole prefix in Redis, which is expensive on a big cache. You need to make the cache manager transaction-aware and cache DTOs.
81
In 2024 the Redis license changed and the Valkey fork appeared. How do you make the decision for your organization between Redis, Valkey or a managed service?
Facts first: from Redis 7.4 it moved to RSALv2/SSPLv1, an AGPLv3 option was added from Redis 8, and Valkey is a BSD-licensed fork split from 7.2.4. Then I decide based on which features we use, who operates it (us or a managed provider), the price and the legal requirements.
82
How does the Redlock algorithm work, and which weak point did Martin Kleppmann point out? What does a fencing token give you?
Redlock tries to acquire a lock on a majority of N independent Redis instances within a time limit. The criticism: because of a GC pause, a network delay or a clock jump, the lock holder can keep working without knowing the lock has expired. A fencing token is a number that increases with every lock, and the resource rejects writes with an older number.
83
A team wants to make Redis the primary (only) database in a new service. When do you agree, and when do you object?
I agree if the business can tolerate losing a little data, the volume fits in RAM and access is by key. I object if money, legal records, complex queries or reporting are involved: asynchronous replication, memory cost and query capabilities don't fit that.
84
You need to write a single caching standard for all services in the organization. Which of cache-aside, read-through, write-through and write-behind do you make the default?
The default is cache-aside, with invalidation by deleting the entry on write, and a TTL on every key. Write-through only when the cache and the database are managed inside one component, and write-behind only for cases that can tolerate data loss and have heavy writes, with separate approval.
85
Someone proposes doing cache invalidation through CDC (for example, Debezium) instead of in the application code. What trade-offs do you see?
CDC doesn't skip any write path and delivers committed changes in order, so the application code gets simpler. The price: extra infrastructure (Kafka Connect, Debezium), a delay of around a second, and keeping the mapping between a DB table and a cache key in another place.
86
A service has to run active in two regions (say, Tashkent and Frankfurt). How do you set up the Redis cache, and what consistency problems come up?
Usually a separate, independent cache in each region, with invalidation events distributed through a cross-region queue. An active-active Redis with replication (Redis Enterprise based on CRDTs or similar) allows writes on both sides, but you need to understand the conflict resolution semantics and the cost.
87
Dozens of teams use one shared Redis cluster, and one team's mistake takes everyone down. How do you reorganize the platform?
I strengthen isolation: separate clusters for important or heavy services, ACL users restricted to prefixes on the shared cluster, banning dangerous commands, a memory/ops quota per team, and metrics that make it visible who is using what.
88
The Redis cluster was fully flushed (or a new one came up) and started empty, and the DB is collapsing under the load. How do you prepare the system for such a "cold cache" situation?
You need layers that protect the DB: a concurrency limit and load shedding in front of it, cache pre-warming, merging misses (single-flight), and bringing traffic back gradually. And you test all of this beforehand with an "empty cache" drill.
89
When you add a new node to Redis Cluster and move slots, what do clients see, and how do you carry out this operation safely?
While a slot is moving, keys migrate to the new node one by one; keys that haven't moved yet are on the old node, and for the ones that have moved the client gets an ASK redirect, then MOVED once it's done. The risks: big keys blocking the migration, clients not refreshing their topology, and latency growing under load.
90
Is the cache actually paying off or just adding complexity? How do you measure that, and how do you show it to others?
Hit ratio isn't enough: I compare p99 latency with and without the cache, the cost of the load taken off the DB, the number of bugs caused by staleness, and the cost of Redis. For every cache, the answer to "what happens if it's gone" should be in numbers.
91
You need to pick a cache technology for a new service: Redis, Memcached, Hazelcast, or just in-process Caffeine. What criteria do you decide by?
First I answer whether the data needs to be shared between pods: if not, Caffeine is the fastest and cheapest. If it needs to be shared, Memcached for plain key-value and multi-core scaling; Redis for data structures, persistence, Pub/Sub and a wide ecosystem; Hazelcast if you need embedded distributed computing inside the JVM.
92
How do you ship a deploy where the cached object's class changes (a field name or type changed) without breaking the cache?
During a rolling deploy, the old and new versions read and write the same keys, so the format must be compatible in both directions, or a schema version must go into the key. My default approach is a version in the key like v2: the new code writes to new keys, and the old ones die through the TTL.
93
How do you design storing idempotency keys for a payment API in Redis, and where do you see the risks?
I claim the key with SET NX in an "in progress" state, write the result to that key, and return the saved response for a repeated request. But a write in Redis can be lost on failover, so for money movement the real guarantee must be a unique constraint in the DB, and Redis is a fast filter.
94
How do you choose a persistence strategy for Redis: RDB, AOF, both, or turning it off entirely? Explain it in terms of RPO and RTO.
First I get the RPO (how much data we can afford to lose) and RTO (how fast we must recover) numbers from the business. For a pure cache, persistence is often unnecessary, or just RDB for a fast warm-up; for a Redis that holds state, AOF everysec + RDB and a replica.
95
A team wants to use Redis Streams for an event stream instead of Kafka because Redis is already there. When is that enough, and when is it a mistake?
Streams are good for small and medium volume, short-retention queues between one or two services: low latency, consumer groups, simple operation. If you need long retention, large volume, many independent consumers, replay and strong durability, use Kafka.
96
For a distributed lock, when do you choose Redis, a PostgreSQL advisory lock, or etcd/ZooKeeper?
For short locks used for efficiency, Redis: fast and simple. If the lock is tied to a change in the DB, PostgreSQL (an advisory lock or SELECT ... FOR UPDATE), because it lives together with the transaction. For leader election and coordination where correctness matters, etcd/ZooKeeper, because they provide consensus and fencing.
97
Someone proposes caching user permissions (roles, permissions) in Redis. What security problems do you see, and how do you handle them?
The main risk is that when a permission is removed, the cache still says it exists: a fired employee or a blocked account can get in until the TTL expires. The solution: a short TTL, explicit invalidation when permissions change, rechecking against the source for critical actions, and protecting the cached data.
98
You're paying a lot per month for Redis memory and the dataset keeps growing. What technical decisions do you consider to cut the cost?
First I measure what is taking the space: size by key prefix, keys without a TTL, one-time keys. Then the cheap wins: shorter TTLs, grouping small objects into hashes, making values more compact or compressing them, HyperLogLog or Bloom where an exact count isn't needed; and finally moving part of the data out of Redis.
99
Do you run Redis yourself inside Kubernetes or take a managed service (ElastiCache, Memorystore and others)? How do you justify the decision?
I usually prefer a managed service: failover, patching, backup and monitoring are ready, and there's less on-call load. Running it ourselves on Kubernetes makes sense where there's no managed option (on-prem), when cost is very important, or for a pure cache that's fine to lose, but then you need to know the subtle points of the operator and the StatefulSet.
100
In prod, Redis suddenly starts returning `OOM command not allowed when used memory > 'maxmemory'` and order creation stops working. What do you do during the incident and after it?
First I stop the bleeding: quickly find who is using the memory and free a safe part of it, or temporarily raise maxmemory. Then I find the cause (keys without a TTL, a big key, grown buffers), and to prevent a repeat I separate the cache from critical state and set an early memory alert and a key budget.
Sign up — studied questions get marked and your progress is saved.