Database / Cache Basics interview questions
Last updated
1. What is a cache?
A cache is a small, fast storage layer that keeps copies of frequently used data so future requests can be served without going back to the slower original source, such as a database, disk or remote API.
The trade is simple: you spend a little memory to save a lot of time. Data in a cache is a copy, so the original source remains the single source of truth.
Caches show up at every level of a system: CPU registers and L1-L3 caches, the operating system page cache, browsers, CDNs, application memory and dedicated servers such as Redis or Memcached.
A cache is limited in size, so it needs rules for what to keep (eviction) and how long to keep it (expiry).
Take quiz
Because caches are always slower than databases
Because caches can only store numbers
Because the cache only holds copies that can be evicted or become stale
The ability to run SQL queries on the database
Extra memory and the risk of serving slightly stale data
All durability guarantees of the database
2. Why do we use caching in applications?
We use caching to reduce latency, lower load on the backend and handle more traffic with the same hardware. A Redis lookup typically returns in under a millisecond, while a complex SQL query or a remote API call can take tens or hundreds of milliseconds.
- Speed: memory reads beat disk and network round trips.
- Scalability: a high hit ratio means the database sees only a fraction of requests.
- Cost: fewer expensive queries and fewer paid third-party API calls.
- Resilience: a cache can keep serving popular data during short backend slowdowns.
Caching pays off most for data that is read often, changes rarely and is expensive to compute. It is a poor fit for data that changes on every request.
Take quiz
Data that is written on every request and never read
Data that is unique to every single request
Data that is read often, changes rarely and is costly to produce
It forces the database to run more queries
Fewer requests reach it, so its load drops
It makes the database store extra copies of rows
3. What are the common types of caches?
Caches are usually grouped by where they sit in the request path. The closer to the user, the lower the latency, but the harder it is to control freshness.
| Type | Where it lives | Typical use |
| Browser cache | User's device | Static files, images, API responses with cache headers |
| CDN cache | Edge servers near users | Images, JS/CSS, video, cacheable pages |
| In-process cache | Application heap (Caffeine, Guava) | Config, small lookup tables, per-instance hot data |
| Distributed cache | Separate cluster (Redis, Memcached) | Sessions, shared query results, rate-limit counters |
| Database cache | Inside the DB engine | Buffer pool, query plan and result caches |
Most real systems stack several of these, for example browser, CDN, local cache and Redis in front of the database.
Take quiz
An in-process cache on the application heap
The browser cache on a user's laptop
A distributed cache such as Redis
Inside the application's heap memory
On edge servers close to the users
On the database server's disk
4. What is the principle of locality in caching?
Locality of reference is the observation that programs and users tend to access the same data, or nearby data, again and again. Caches work only because of this behavior.
- Temporal locality: data used recently is likely to be used again soon, for example a trending product page.
- Spatial locality: data near recently used data is likely to be needed next, for example the next block of a file or the next page of results.
Temporal locality is why policies like LRU work well. Spatial locality is why CPUs and disks fetch whole cache lines or blocks, and why some systems prefetch the next page.
If access is purely random across a huge key space, locality is weak and a cache gives little benefit.
Take quiz
Spatial locality of memory addresses only
Network locality between data centers
Temporal locality
A single byte cannot be stored in a cache
Nearby bytes are likely to be needed soon (spatial locality)
Cache lines are cheaper to evict than bytes
5. What is a cache hit and a cache miss?
A cache hit happens when the requested key is found in the cache (and is still valid), so the value is returned directly. A cache miss happens when the key is absent or expired, so the application must fetch it from the source.
On a miss the usual flow is: read from the database, store the result in the cache, then return it. The first request pays the full cost; later requests benefit.
value = cache.get(key) if value is None: # cache miss value = db.query(key) # slow path cache.set(key, value, ttl=300) return value # a later call for the same key is a hit
An expired entry counts as a miss even if the key physically exists.
Take quiz
The data is fetched from the source and usually stored in the cache
The request is rejected with an error
The cache deletes every other key
Yes, because the key still exists
Only if the value is smaller than 1 KB
No, it is treated as a miss
6. How do you calculate the cache hit ratio?
The hit ratio is the share of lookups served from the cache:
hit ratio = hits / (hits + misses)
If a cache handled 9,500 hits and 500 misses, the ratio is 9,500 / 10,000 = 95%. Redis exposes the raw counters as keyspace_hits and keyspace_misses in INFO stats.
The ratio matters because average latency depends on it. If a hit takes 1 ms and a miss costs 50 ms in total, a 95% ratio gives about 0.95 x 1 + 0.05 x 50 = 3.45 ms. At 80% the same system averages 10.8 ms.
Track the ratio per cache or key prefix, not just globally, because one noisy workload can hide problems in another.
Take quiz
90%
10%
9%
used_memory and maxmemory
connected_clients and blocked_clients
keyspace_hits and keyspace_misses
7. What are the types of cache misses?
Cache misses are classified into three classic types, a model that comes from CPU cache design but is useful for any cache.
| Miss type | Cause | Typical fix |
| Compulsory (cold) | First access to an item, nothing cached yet | Cache warming, prefetching |
| Capacity | Working set is larger than the cache, so useful items get evicted | Increase cache size, better eviction policy |
| Conflict | Different items compete for the same slot or set (set-associative or hashed caches) | Higher associativity, better hashing |
In application caches you also see expiry misses, where an entry vanished because its TTL ran out, and invalidation misses, where it was removed after the source changed.
Take quiz
Compulsory (cold) miss
Capacity miss
Conflict miss
Compulsory miss
Coherence miss on the first request
Capacity miss
8. What is the cache-aside pattern?
In cache-aside (lazy loading), the application itself manages the cache. It checks the cache first, and only on a miss does it read the database and then populate the cache.
sequenceDiagram
participant App
participant Cache
participant DB
App->>Cache: GET user:42
Cache-->>App: miss
App->>DB: SELECT user 42
DB-->>App: row
App->>Cache: SET user:42 (TTL)
App-->>App: return row
On writes, the common approach is to update the database and then delete the cached key, so the next read reloads fresh data.
Only data that is actually requested ends up in the cache, which keeps memory use efficient.
Take quiz
The application code
The database automatically
The cache server on its own
Copy the whole table into the cache
Restart the cache server
Delete (invalidate) the cached key
9. What are the pros and cons of cache-aside?
Cache-aside is the most widely used pattern because it is simple and fault-tolerant, but it shifts work onto the application.
| Pros | Cons |
| Only requested data is cached, so memory is used well | First request for each key is always a miss (cold start) |
| If the cache is down, the app can still read from the DB | Cache and database can briefly disagree |
| Works with any cache and any database | Every caller must repeat the get-check-load logic |
| Cache failures do not break writes | A popular key expiring can cause a stampede |
Wrapping the logic in one repository or helper class avoids duplicating it and reduces bugs.
Take quiz
The application can still serve data from the database
All reads fail until the cache is restored
Writes to the database are blocked
Every write goes to the cache twice
The cache must hold the entire database
The first read of each key is a miss
10. How does cache-aside differ from read-through?
Both patterns load data on a miss. The difference is who does the loading.
| Aspect | Cache-aside | Read-through |
| Loading logic | In the application | Inside the cache layer or library |
| Application code | Checks cache, then DB, then fills cache | Only calls the cache, which loads on a miss |
| Cache failure | App can fall back to the DB | Depends on the cache provider |
| Typical tools | Redis or Memcached used directly | Caffeine LoadingCache, Hazelcast MapLoader, NCache |
Read-through keeps application code cleaner, while cache-aside gives you more control over error handling and what to cache.
Take quiz
The browser
The cache layer through a configured loader
A nightly batch job only
Cache-aside
Read-through
Write-back
11. What is TTL in caching?
TTL (Time to Live) is the number of seconds an entry may stay in the cache before it is treated as expired and removed or ignored.
SET session:abc "data" EX 1800 # expires in 30 minutes TTL session:abc # remaining seconds
TTL is the simplest invalidation mechanism. You do not need to track changes, you just accept that data can be stale for at most the TTL.
Redis removes expired keys in two ways: lazily when a key is accessed, and by a periodic background sample of keys with a TTL.
Take quiz
The key can be read 1800 times
The key expires after 1800 seconds
The key is 1800 bytes long
A periodic background sampling of keys that have a TTL
It never removes them
It asks the application to delete them
12. How do you choose an appropriate TTL?
Pick the TTL from the business tolerance for stale data, not from a default value. Ask how wrong the data can be and for how long before users or money are affected.
| Data | Reasonable TTL |
| Static config, country lists | Hours to a day |
| Product catalog | Minutes to an hour |
| Search results, feeds | Seconds to a few minutes |
| Stock price, inventory count | Very short, or use event-based invalidation |
Also consider the cost of a miss: expensive queries justify longer TTLs. Add small random jitter (for example plus or minus 10%) so many keys do not expire together, and review the hit ratio after launch to tune the value.
Take quiz
The length of the key name
How stale the data is allowed to be
The programming language of the client
To stop many keys expiring at the same moment
To make keys larger
To disable eviction
13. What is the difference between absolute and sliding expiration?
Absolute expiration sets a fixed deadline from the time the entry was created. Sliding expiration resets the timer every time the entry is read, so it lives as long as it keeps being used.
| Aspect | Absolute | Sliding |
| Timer starts | At creation or write | At last access |
| Active item | Still expires on schedule | Can live indefinitely |
| Staleness risk | Bounded by the TTL | Unbounded unless combined with a cap |
| Good for | Reference data, tokens | Sessions, user-specific working data |
A safe combination is sliding expiration with an absolute maximum, so a constantly used item is still refreshed from the source at some point.
Take quiz
Absolute expiration
Sliding expiration
Fixed-window expiration only
So a heavily used entry is still refreshed eventually
To make the entry expire sooner than it was written
To stop the cache from storing it at all
14. What is cache eviction and why is it needed?
Eviction is the removal of entries to make space when the cache reaches its memory or size limit. Since memory is finite, a cache must decide what to drop to admit new data.
Eviction is different from expiry. Expiry removes data because it is too old, eviction removes data because there is no room, even if the TTL has not elapsed.
- LRU: drop the least recently used item.
- LFU: drop the least frequently used item.
- FIFO: drop the oldest inserted item.
- Random: drop an arbitrary item.
In Redis the behavior is set with maxmemory and maxmemory-policy. With noeviction, writes fail once memory is full.
Take quiz
A key reaching its TTL
The cache reaching its memory limit
A client closing its connection
maxmemory-policy
appendonly
requirepass
15. What is LRU cache eviction?
LRU (Least Recently Used) evicts the entry that has not been accessed for the longest time. It assumes that data used recently will be used again soon, which is temporal locality.
Example with capacity 3: after accessing A, B, C and then A again, the order from oldest to newest is B, C, A. Adding D evicts B.
LRU adapts well to changing access patterns and is the default choice for general-purpose caches. Its weakness is a scan: reading a large dataset once pushes out genuinely hot items.
Redis offers allkeys-lru and volatile-lru, both using an approximated LRU based on sampling a few keys rather than tracking a perfect order.
Take quiz
A
C
B
Repeated reads of the same few keys
A one-time scan over a large dataset
A cache that is nearly empty
16. How is an LRU cache implemented efficiently?
A classic LRU uses a hash map plus a doubly linked list. The map gives O(1) lookup of a node by key. The list keeps nodes ordered by recency, with the most recent at the head and the least recent at the tail.
- On
get: find the node via the map and move it to the head. - On
putof an existing key: update the value and move it to the head. - On
putof a new key at full capacity: remove the tail node and its map entry, then insert at the head.
Both operations stay O(1). In Python, OrderedDict already provides this combination:
from collections import OrderedDict class LRU: def __init__(self, cap): self.cap, self.d = cap, OrderedDict() def get(self, k): if k not in self.d: return None self.d.move_to_end(k) return self.d[k] def put(self, k, v): self.d[k] = v self.d.move_to_end(k) if len(self.d) > self.cap: self.d.popitem(last=False) # evict oldest
In Java, LinkedHashMap with access order enabled does the same job.
Take quiz
To sort keys alphabetically
To store values on disk
To move or remove any node in O(1) once it is found
At the head of the list
At the tail of the list
Outside the list, in the map only
17. What is the difference between LRU, LFU and FIFO?
All three decide which entry to evict. They differ in the signal they use.
| Policy | Evicts | Strength | Weakness |
| LRU | Entry unused for the longest time | Adapts quickly to new hot data | One-time scans pollute the cache |
| LFU | Entry with the fewest accesses | Keeps long-term popular items | Old popular items linger; needs counter aging |
| FIFO | Entry inserted earliest | Very simple and cheap | Ignores usage, may evict hot data |
Use LRU as a safe default, LFU when popularity is stable over time (Redis allkeys-lfu, Caffeine's TinyLFU), and FIFO only when simplicity matters more than hit ratio.
Take quiz
FIFO
LRU
LFU
LFU
FIFO
LRU
18. What is cache invalidation?
Cache invalidation is the process of removing or updating cached entries when the underlying data changes, so users do not keep seeing outdated values.
Without it, the cache keeps returning the old copy until the TTL ends or the entry is evicted. For a profile page that may be fine, for a price or a permission change it is not.
- Delete: remove the key so the next read reloads it.
- Update: write the new value into the cache.
- Expire: let the TTL handle it.
Deleting is usually safer than updating, because it avoids writing a stale value during concurrent updates.
Take quiz
To increase the cache size
To encrypt cached values
To stop outdated data from being served after the source changes
Deleting uses more memory
A concurrent writer cannot leave a stale value behind
Overwriting is not supported by caches
19. What are the common cache invalidation strategies?
There is no single best strategy. Teams usually combine two or three.
| Strategy | How it works | Trade-off |
| TTL-based | Entry expires after a set time | Simple, but data can be stale until expiry |
| Write-invalidate | App deletes the key after updating the DB | Fresh reads, needs code on every write path |
| Event-driven | Change events (CDC, message bus) trigger deletes | Decoupled, adds infrastructure |
| Versioned keys | Key includes a version, e.g. product:42:v7 |
No deletes needed, old versions wait for eviction |
| Purge or tag-based | Clear groups of keys by tag or prefix (CDN purge) | Powerful, can cause a burst of misses |
A common mix is write-invalidate for correctness plus a TTL as a safety net for missed events.
Take quiz
TTL-based expiry
Random eviction
Versioned keys
It makes writes faster
It limits damage if an invalidation event is missed
It replaces the database
20. Why is cache invalidation considered hard?
The difficulty is that the cache and the database are two separate systems that cannot be updated atomically. Any gap between the two writes is a window where they disagree.
- Race conditions: a slow reader loads old data from the DB, a writer updates the DB and deletes the key, then the reader writes the old value into the cache.
- Failures: the DB update succeeds but the cache delete fails or times out.
- Derived data: one row change can affect many cached results (lists, counts, search pages), and you must know every key to clear.
- Many layers: browser, CDN, app and Redis may all hold copies.
Because perfect consistency is costly, most systems accept bounded staleness and rely on TTLs, retries and idempotent deletes.
Take quiz
A slow reader writes an old value after the writer already deleted the key
The cache has too much free memory
The key name is too short
Lists cannot be cached
Derived data never changes
One change can affect many cached keys you must track
21. What is the write-through caching policy?
In write-through, every write goes to the cache and the database synchronously. The write is acknowledged only after both have succeeded.
flowchart LR
A[Application] -->|1. write| C[Cache]
C -->|2. write sync| D[(Database)]
D -->|3. ack| C
C -->|4. ack| A
Because the cache is updated on every write, later reads find fresh data and the cache and database stay consistent. The cost is higher write latency, since each write waits for the slower store.
It is often paired with read-through so the cache layer handles both reading and writing.
Take quiz
After both the cache and the database are updated
Immediately, before touching the database
Only at the end of the day
Stale reads after every write
Risk of losing acknowledged writes on a cache crash
Higher write latency
22. What are the advantages and drawbacks of write-through?
Write-through trades write speed for consistency and durability.
| Advantages | Drawbacks |
| Cache and DB stay in sync | Every write pays DB latency |
| No data loss if the cache crashes | Data that is never read still fills the cache |
| Reads right after writes are fast and fresh | Write-heavy workloads gain little |
| Simple mental model | Cache layer must support write handlers |
Because rarely read data is cached anyway, write-through can waste memory. Some systems add a TTL or only write through for keys that are likely to be read.
Take quiz
It caches written data even if nobody reads it later
It refuses to store any new data
It stores each value twice in the database
They are lost
They are replayed from the browser
They are safe because the database already has them
23. When should you choose write-through over cache-aside?
Choose write-through when data is written and then read soon after, and when readers must never see stale values. Examples are user profiles, shopping carts and account settings.
Choose cache-aside when you want simple application-controlled caching, when many written items are never read again, or when your cache provider has no write-through support.
- Write-through fits: strong read-after-write expectations, moderate write volume.
- Cache-aside fits: read-heavy workloads, tolerance for brief staleness, flexible invalidation.
The decision is really about where consistency work happens. Write-through does it on the write path automatically, cache-aside leaves it to your code.
Take quiz
Data read soon after it is written, where staleness is unacceptable
Data written once and never read
Data that can be rebuilt nightly
It guarantees zero staleness
It never needs a TTL or eviction
It is simple and avoids caching data nobody reads
24. What is the write-back (write-behind) cache policy?
In write-back, the application writes only to the cache. The cache acknowledges immediately and flushes changes to the database asynchronously, often in batches.
sequenceDiagram
participant App
participant Cache
participant DB
App->>Cache: write order 17
Cache-->>App: ack (fast)
Note over Cache: dirty entry queued
Cache->>DB: batched flush later
Writes become very fast and the database sees fewer, larger operations. The price is a window where the cache holds newer data than the database.
Take quiz
Later, asynchronously, often in batches
Before acknowledging every write
Never
An expired key
A key with an invalid name
A cached value not yet flushed to the database
25. What are the risks of write-back caching?
The main risk is data loss. If the cache node fails before dirty entries are flushed, those acknowledged writes are gone.
- Durability gap: the DB lags behind the cache.
- Stale reads from the DB: other systems reading the database directly see old data.
- Ordering and conflicts: flushes can apply out of order or collide with direct DB updates.
- Complexity: you need queues, retries and monitoring for flush failures.
This is acceptable for things like view counters or analytics events, where losing a few seconds of data is tolerable. It is a poor fit for payments or inventory.
Take quiz
Bank account balances
Page view counters
Payment confirmations
Losing acknowledged writes if the cache fails before flushing
Slower writes than write-through
Cache never storing new keys
26. How do you make write-back caching safer?
You cannot remove the risk, but you can shrink it.
- Replicate the cache so a single node failure does not lose dirty data.
- Persist a write-ahead log or queue (Kafka, Redis streams with AOF) before acknowledging.
- Flush frequently with a small batch size or short time limit.
- Flush on shutdown and drain the queue during deploys.
- Make flushes idempotent with retries and a dead-letter queue for failures.
- Monitor lag between dirty entries and DB state.
If the data cannot tolerate any loss, prefer write-through or write directly to the database and cache aside.
Take quiz
It makes reads slower on purpose
Dirty writes survive a cache crash and can be replayed
It removes the need for a database
Retries after a failure should not apply a change twice
So writes are never queued
So the cache never expires
27. What is the write-around caching policy?
In write-around, writes go straight to the database and bypass the cache. Data enters the cache only when it is later read, on a miss.
This avoids filling the cache with data that may never be read, for example log records, bulk imports or one-off uploads.
The downside is that the first read after a write is a miss, and any older cached copy of that key must be invalidated or it will be stale.
Write-around is often combined with cache-aside for reads, so the cache holds only genuinely requested data.
Take quiz
Only to the cache
Directly to the database
To a CDN edge node
The first read after a write misses the cache
Every write is slower than write-through
The database never receives the write
28. What is the difference between write-through, write-back and write-around?
All three describe how a write flows between cache and database.
| Policy | Write path | Write latency | Consistency | Data loss risk |
| Write-through | Cache and DB together, synchronous | Higher | Strong | Low |
| Write-back | Cache first, DB later, asynchronous | Lowest | Eventual | Higher |
| Write-around | DB only, cache filled on read | Same as DB | Needs invalidation | Low |
Pick write-through for read-after-write freshness, write-back for write-heavy loads that tolerate small loss, and write-around for data written often but rarely read.
Take quiz
Write-through
Write-back
Write-around
Write-around
Write-through
Write-back
29. What is a cache stampede?
A cache stampede (also called the dogpile effect) happens when a popular cache entry expires and many concurrent requests all miss at once, so every one of them hits the database to rebuild the same value.
Example: a homepage query takes 2 seconds to run and is cached for 60 seconds. When it expires, 500 requests arrive in that 2-second gap and 500 identical queries hit the database, which may slow down or crash.
The cause is that the check-and-rebuild step is not coordinated. It is a single hot key problem, unlike an avalanche, which involves many keys.
Take quiz
The cache is empty at startup for all keys
A popular key expires and many requests rebuild it at once
A client sends an invalid key
A stampede involves one hot key, an avalanche involves many keys
They are the same thing
A stampede only happens with write-back
30. How do you prevent a cache stampede?
The goal is to let only one request rebuild the value while others wait or use the old one.
- Lock or single-flight: the first request takes a lock (for example
SET key:lock 1 NX EX 10) and rebuilds, others wait or retry. - Stale-while-revalidate: serve the expired value briefly while one request refreshes it in the background.
- Probabilistic early expiration: each request may refresh slightly before expiry, with a probability that grows near the deadline.
- Background refresh: a scheduled job renews the hottest keys before they expire.
- TTL jitter: avoids many related keys expiring together.
Set the lock timeout above the rebuild time, otherwise a second request may start the rebuild anyway.
Take quiz
Deletes the key permanently
Blocks all readers until the database restarts
Serves the old value while one request refreshes it
So the lock can be stored in the database
So a crashed worker cannot block rebuilds forever
So the cache evicts it with LFU
31. How does request coalescing work in caching?
Request coalescing (single-flight) merges concurrent requests for the same missing key into one backend call. The first caller does the work, and the others wait for its result and share it.
inflight = {} # key -> Future def get(key): if (v := cache.get(key)) is not None: return v if key in inflight: # someone is already loading it return inflight[key].result() f = inflight[key] = Future() try: v = db.load(key) cache.set(key, v, ttl=60) f.set_result(v) return v finally: del inflight[key]
This version is simplified and ignores thread-safety details. Go has it built in as singleflight.Group. Within one process no external lock is needed. Across servers you need a distributed lock, or accept one rebuild per instance.
Take quiz
Sends one call per request in parallel
Drops all requests except the last
Sends one backend call and shares the result
It cannot be used with Redis
Each server still performs its own rebuild
It needs the database to be offline
32. What is a cache avalanche?
A cache avalanche happens when a large number of cache entries expire at the same time, or the whole cache goes down, and the sudden flood of misses overloads the database.
- Mass expiry: keys loaded together with the same TTL (for example at midnight) all expire together.
- Cache outage: a Redis node or cluster fails, so all traffic falls through.
Unlike a stampede on a single key, an avalanche affects many different keys, and the database sees a broad spike of different queries.
Take quiz
Using a very long TTL on one key
Storing values in compressed form
Many keys given the same TTL expiring together
Adding a new column to the database
The cache cluster going down
Using HTTPS
33. How do you prevent a cache avalanche?
Spread out expiry and protect the database so a burst of misses cannot knock it over.
- TTL jitter:
ttl = base + random(0, 300)instead of a fixed value. - High availability: Redis replicas with Sentinel or Cluster so one node failure is not a full outage.
- Multi-level caching: a small local cache absorbs traffic when Redis is unavailable.
- Rate limiting and circuit breakers: cap the queries that reach the database.
- Staggered warm-up: load keys gradually after a restart.
- Graceful degradation: return defaults or stale data for non-critical features.
Jitter handles mass expiry, while replication, rate limiting and fallbacks handle outages.
Take quiz
Disabling eviction
Using one fixed TTL for everything
Adding random jitter to the TTL
The browser from slow images
The database from excessive query load
The DNS server
34. What is cache penetration?
Cache penetration occurs when requests ask for data that does not exist in either the cache or the database. Each request misses the cache, hits the database, finds nothing, and nothing gets cached, so the next request repeats the whole thing.
A typical case is an attacker calling /users/-1 or random IDs in a loop. The cache never helps because there is no value to store, so the database takes the full load.
It differs from a stampede, where the data exists and many callers rebuild it. In penetration, the data is never there.
Take quiz
The key is too popular
The cache runs out of memory
The requested data does not exist anywhere
Caches reject numeric keys
There is no value to store, so every request reaches the database
The database caches them automatically
35. How do you prevent cache penetration?
Stop invalid or non-existent lookups before they reach the database.
- Validate input: reject malformed IDs, negative numbers and out-of-range values at the API.
- Cache null results: store an empty marker for a missing key with a short TTL (30-60 seconds).
- Bloom filter: keep a compact set of all valid IDs and reject keys that are definitely absent.
- Rate limit clients that generate many misses.
- Authenticate and monitor to block scanning behavior.
Use a short TTL for null markers. If the record is created later, a long-lived null entry would hide it.
Take quiz
The missing record might be created soon
Null values take too much memory
The cache cannot store empty values for long
Increasing the cache size
Using a longer TTL
Input validation at the API
36. How does a Bloom filter help with cache penetration?
A Bloom filter is a compact probabilistic structure that answers "is this key possibly in the set?" using a bit array and several hash functions.
- If it says no, the key is definitely not in the set.
- If it says yes, the key is probably present, with a small false-positive rate.
Load the IDs of all valid records into the filter. Before checking the cache or database, test the key. If the filter says no, return not-found immediately.
if not bloom.might_contain(user_id): return NOT_FOUND # never touches cache or DB return get_user_cached(user_id)
It never gives false negatives, so valid keys are never blocked. The tradeoffs are extra memory, keeping the filter updated as new records appear, and that standard Bloom filters do not support deletion.
Take quiz
The key is definitely not in the set
The key is probably in the set
The key is expired
False negatives
Both false positives and false negatives equally
False positives
37. What is a hot key in caching?
A hot key is a cache key that receives a disproportionately large share of traffic, such as a viral post, a flash-sale product or a global config value.
In a sharded cache, a key lives on a single node. When one key gets, say, 100,000 reads per second, that node's CPU or network saturates while the others stay idle, so adding more nodes does not help.
The symptoms are one overloaded shard, rising latency for all keys on that node, and possible timeouts. It is a load-distribution problem rather than a capacity problem.
Take quiz
The key still lives on one node
Hot keys disappear automatically
More nodes make keys expire
All shards are idle
The database is overloaded but the cache is not used
One shard is overloaded while others are idle
38. How do you detect hot keys in Redis?
You can find hot keys with built-in tools, client-side metrics or proxy-level monitoring.
redis-cli --hotkeysreports frequently accessed keys, but it requires an LFU eviction policy such asallkeys-lfu.MONITORshows every command in real time, but it is expensive and only suitable for short checks.redis-cli --bigkeysfinds large keys, which are a different problem but often confused with hot keys.- Client-side counters or a proxy (Twemproxy, Envoy, Redis Cluster proxies) can track per-key request rates.
- Per-shard metrics such as CPU, ops/sec and network bytes reveal an uneven shard.
Avoid running MONITOR on a busy production node for long, as it can slow the server itself.
Take quiz
An LFU-based maxmemory-policy
Persistence disabled
A cluster of at least ten nodes
They delete expired keys
They disable replication
They add overhead to a busy server
39. How do you mitigate hot keys?
Spread the load for the hot key across more places.
- Local (L1) cache: keep the hot value in application memory for a few seconds, so most reads never reach Redis.
- Key replication: store copies as
item:42#0toitem:42#9on different shards and read a random one. - Read replicas: send reads to replicas of the shard that owns the key.
- Request coalescing so concurrent misses trigger one rebuild.
- CDN or edge caching for public data.
The cost of replicated copies is more complex invalidation, because every copy must be updated or deleted together. Short local TTLs keep staleness small.
Take quiz
Most reads are served from app memory without calling Redis
It deletes the key from Redis
It moves the key to the database
The key can no longer be read
The cache needs a bigger TTL
Every copy must be invalidated or updated together
40. What is cache warming?
Cache warming (pre-warming or pre-loading) is filling the cache with the data you expect to be needed before real traffic arrives, so users do not hit a cold cache full of misses.
A new cache instance, a restarted node or a fresh deployment starts empty. Without warming, the first wave of requests all miss and pound the database.
Typical sources for warm-up data are the most requested keys from the previous day, top products, configuration tables and the homepage. Warming trades a bit of startup time and load for a smoother start.
Take quiz
When its hit ratio is 100%
When it is empty or lacks the data traffic needs
When it uses LRU
Avoid a burst of misses after a restart or deployment
Delete unused keys
Change the TTL for all keys
41. When should you use cache warming and how?
Use warming when a cold cache would cause real pain: after deployments, cache failover or restart, before a planned traffic spike such as a sale, or when queries are very expensive.
- Startup loader: the app loads a fixed list of keys at boot, before joining the load balancer.
- Scheduled job: a cron job refreshes known hot data before it expires.
- Replay logs: replay recent read traffic from access logs against the new cache.
- Snapshot restore: persist Redis (RDB/AOF) so a restart reloads data.
Throttle the warm-up job so it does not overload the database itself. Warm only data that is likely to be requested, because loading everything wastes memory and time.
Take quiz
So keys expire faster
So it does not overload the database it reads from
So the cache becomes read-only
Loading an RDB or AOF snapshot
Disabling eviction
Using a shorter TTL only
42. What is distributed caching?
A distributed cache spreads cached data across multiple servers that act as one logical cache, shared by many application instances. Redis Cluster, Memcached pools, Hazelcast and Apache Ignite are common examples.
Compared with a local in-process cache, it gives you larger total capacity, one shared view of data (instance A and B see the same entry), and survival of cache contents when an app server restarts.
The tradeoffs are a network hop on every access (typically around a millisecond), serialization cost, and the operational work of running a cluster.
Take quiz
It has zero network latency
All application instances share the same cached data
It never needs serialization
A network round trip on each access
It cannot store strings
It can only be used with one app server
43. How does a distributed cache scale horizontally?
It scales by sharding (partitioning) keys across nodes and by replicating shards for availability.
- Sharding splits the key space so each node holds a part. Adding nodes adds capacity and throughput.
- Replication keeps copies of each shard on other nodes for failover and extra read capacity.
Redis Cluster maps every key to one of 16,384 hash slots using CRC16(key) mod 16384, and each node owns a range of slots. Moving slots between nodes lets you rebalance without remapping everything.
Memcached has no built-in clustering, so clients choose the node, usually with consistent hashing.
Take quiz
1,024
16,384
65,536
The client library, often using consistent hashing
The Memcached servers vote
The database
44. Which is better, Redis or Memcached, and why?
Neither is always better. Memcached is a simple, fast, multi-threaded key-value cache. Redis is a richer data structure server with persistence and built-in replication.
| Feature | Redis | Memcached |
| Data types | Strings, hashes, lists, sets, sorted sets, streams | Strings (byte blobs) |
| Persistence | RDB snapshots and AOF | None |
| Replication and clustering | Built in | Client-side sharding only |
| Eviction | Several policies including LRU and LFU | LRU |
| Threading | Command execution mostly single-threaded | Multi-threaded |
Choose Memcached for a plain, high-throughput cache of simple objects. Choose Redis when you need data structures, persistence, pub/sub, atomic operations or high availability.
Take quiz
Memcached
Redis
Neither of them
Memcached
Redis only
Neither of them
45. What is consistent hashing?
Consistent hashing is a way to assign keys to nodes so that adding or removing a node moves only a small fraction of keys.
Both nodes and keys are hashed onto the same circular space (the ring). A key belongs to the first node found clockwise from its position.
flowchart LR
K["key hash"] --> R((Hash ring))
R --> N1["Node A"]
R --> N2["Node B"]
R --> N3["Node C"]
When a node is added, it takes over only the keys between itself and its predecessor on the ring. On average only about K/N keys move, where K is the number of keys and N the number of nodes. It is used in Memcached clients, Cassandra, DynamoDB-style systems and CDNs.
Take quiz
The node with the shortest name
A random node each time
The first node clockwise from the key's position
Almost all keys
About 1/N of the keys
None of the keys
46. Why is consistent hashing better than modulo hashing for caches?
With node = hash(key) % N, changing N changes the result for most keys. Going from 4 to 5 nodes remaps roughly 80% of keys, so most lookups become misses at once and the database takes the hit.
| Event | Modulo hashing | Consistent hashing |
| Add 1 node to N | About N/(N+1) of keys remapped | About 1/(N+1) of keys remapped |
| Remove 1 node | Most keys remapped | Only that node's keys remapped |
| Cache impact | Mass misses, possible avalanche | Small, localized misses |
Modulo is fine if N never changes. In a cluster that scales or loses nodes, consistent hashing keeps most of the cache valid.
Take quiz
No keys change node
Only one key changes node
Most keys map to a different node
It deletes the database
Most cached keys are suddenly looked up on the wrong node
It disables TTL
47. What are virtual nodes in consistent hashing?
Virtual nodes (vnodes) place each physical server on the ring many times, for example 100-200 points per server, using labels like nodeA#1, nodeA#2 and so on.
With only a few points per server, the ring segments are uneven, so one node can own a much larger range and take more load. Many virtual points smooth the distribution.
- Better balance: load spreads more evenly.
- Smoother rebalancing: when a node leaves, its keys scatter across many neighbors instead of overloading one.
- Weighted capacity: a bigger server gets more virtual nodes.
The cost is a larger ring structure to store and search, which is usually small.
Take quiz
To reduce the number of servers
To disable replication
To spread load more evenly across servers
Give it a shorter name
Give it more virtual nodes
Use a shorter TTL for it
48. What is cache consistency?
Cache consistency is how closely the cached copy of data matches the source of truth, and how closely multiple copies (local caches, replicas, CDN) match each other.
An inconsistency appears when the database changes but the cache still returns the old value, or when two cache nodes hold different versions of the same key.
Perfect consistency is expensive, so teams pick a level that matches the data: user permissions need near-instant freshness, a product description can lag by minutes.
Take quiz
How many keys the cache holds
How fast the cache server boots
How well cached data matches the source of truth
A blog post's view count
User permission changes
A rarely changed product description
49. How do you handle stale data and race conditions between the database and cache?
The standard problem: a reader loads an old row from the DB, a writer updates the DB and deletes the key, then the reader writes its old value into the cache. The cache is now stale until TTL.
- Update the DB first, then delete the cache key. It narrows the race window compared with deleting first.
- Delayed double delete: delete again after a short delay (for example 500 ms) to remove a stale value written in the gap.
- Versioned writes: store a version or timestamp and only accept cache writes with a newer version (Redis
SETwith check in a Lua script). - CDC invalidation: consume the DB change log (Debezium) and delete keys from there, so deletes follow the real order of changes.
- Short TTL as a backstop.
Make deletes retryable, since a failed delete is otherwise a stale entry waiting for the TTL.
Take quiz
Slow database queries
Cache memory fragmentation
A stale value written to the cache after the first delete
It removes the need for a database
Deletes follow the actual order of database changes
It stops all expiry
50. What is the difference between strong and eventual cache consistency?
Strong consistency means every read sees the latest committed write. Eventual consistency means copies may differ for a while but converge if no new writes occur.
| Aspect | Strong | Eventual |
| Read freshness | Always latest | May be stale briefly |
| Write cost | Higher, coordination needed | Lower |
| Availability and speed | Lower under failures | Higher |
| Typical cache approach | Write-through, synchronous invalidation | TTL, cache-aside with async invalidation |
| Good for | Balances, permissions, inventory at checkout | Feeds, counts, catalog pages |
Most caches are eventually consistent by design. When strong guarantees are needed, read critical data from the database directly or use write-through with careful locking.