Caching: Redis, CDNs and Cache Invalidation Interview Questions
261 multiple-choice tech interview questions on Caching: Redis, CDNs and Cache Invalidation: cache-aside, write-through, TTLs and eviction, Redis data types, HTTP caching and CDNs, stampedes. Written for technical phone screens and interview prep, organized by subtopic, with a short explanation for every answer. Learn the 237 key terms with the flashcards first, then test yourself.
Take the practice test · Flashcards · All study tools
What it covers
- 6.1 Caching fundamentals and patterns
- 6.2 Redis data types and commands
- 6.3 Redis persistence, replication and clustering
- 6.4 Redis memory, eviction and operations
- 6.5 Application and distributed caching
- 6.6 HTTP caching and CDNs
- 6.7 Invalidation and consistency
- 6.8 Failure modes and resilience
- 6.9 Managed caches and alternatives
Key terms
6.1 Caching fundamentals and patterns
- Cache-aside
- The app checks the cache, loads from the database on a miss, and stores the result
- Write-through
- Writes update the cache and database together
- Hit ratio
- The share of lookups served from cache
- LRU
- Least recently used: evicts the entry untouched for the longest time
- Read-through
- Cache loads misses itself
- Write-around
- Writes skip the cache
- Refresh-ahead
- Reload before expiry
- Average latency
- Hit share × cache + miss share × source
- Miss rate
- Share reaching the source
- Cache affinity
- Same server per user
- Versioned key
- Format-safe cache keys
- Cache layers
- Browser to database
- Cold cache
- Empty after restart
- Working set
- Regularly used data
- Skewed access
- Few items, most hits
- Scan pollution
- One-off reads evict hot data
- Source of truth
- Durable store
- Fragment caching
- Parts of pages
- Staleness budget
- Acceptable age
- Write coalescing
- Batched writes
- Eviction rate
- Entries pushed out
- Key naming
- user:42:profile
- Content-addressed cache
- Hash keys
6.2 Redis data types and commands
- TTL
- Time to live: how long a cached entry stays before it expires
- Sorted set
- Redis type keeping members ordered by score
- Hash
- Field-value object
- List queue
- LPUSH and BRPOP
- Set
- Unique members
- PFADD/PFCOUNT
- HyperLogLog commands
- Bitmap
- One bit per ID
- Redis Streams
- Persistent log with groups
- Pending entries list
- Unacknowledged messages
- Geo commands
- GEOADD and GEOSEARCH
- INCR
- Atomic counter
- MULTI/EXEC
- Queued commands, no rollback
- WATCH
- Optimistic locking
- EVAL
- Atomic Lua script
- Redis Functions
- Named, persisted scripts
- Pipelining
- Batched round trips
- MGET
- Multi-key read
- TTL -1 and -2
- No expiry or missing
- KEEPTTL
- Keep expiry on SET
- HEXPIRE
- Per-field expiry
- Sliding window log
- Sorted set of timestamps
- Keyspace notifications
- Key events
- Safe unlock
- Compare token, then delete
- BLMOVE
- Reliable queue move
- Capped list
- LPUSH plus LTRIM
6.3 Redis persistence, replication and clustering
- RDB
- Point-in-time snapshot
- appendfsync everysec
- About 1 s loss
- AOF rewrite
- Compact log
- Copy-on-write
- Fork memory growth
- Multi-part AOF
- RDB base plus increments
- No persistence
- Rebuildable cache
- Async replication
- Possible loss on failover
- WAIT
- Replica acknowledgment
- Replica reads
- Possibly stale
- Sentinel
- Monitoring and failover
- Sentinel quorum
- Agreement on failure
- Hash slots
- 16,384 per cluster
- Hash tag
- {part} hashed
- CROSSSLOT
- Keys in different slots
- MOVED
- Slot on another node
- Cluster database 0
- No SELECT
- Minimum cluster
- Three primaries
- min-replicas-to-write
- Refuse unsafe writes
- I/O threads
- Parallel network I/O
- Partial resync
- Backlog catch-up
- Replica expiry
- Primary sends DEL
- Empty primary restart
- Wipes replicas
- Sharded Pub/Sub
- Per-shard channels
- Big key
- Uneven node load
- Load time
- Dataset loading on restart
6.4 Redis memory, eviction and operations
- maxmemory
- Memory cap
- noeviction
- Write errors when full
- volatile-lru
- Evict keys with TTLs
- allkeys-lfu
- Evict least frequently used
- Approximate LRU
- Sampling eviction
- MEMORY USAGE
- Per-key memory
- --bigkeys
- Find large keys
- UNLINK
- Non-blocking delete
- SLOWLOG
- Slow command log
- MONITOR
- Live command stream
- keyspace_hits
- Hit counter
- Fragmentation ratio
- RSS vs data size
- Compact encoding
- listpack for small types
- Protected mode
- Blocks unauthenticated remote access
- Redis ACL
- Per-user permissions
- Disable FLUSHALL
- Prevent accidents
- Exposed Redis
- Host takeover risk
- maxclients
- Connection limit
- O(N) commands
- Block other clients
- vm.overcommit_memory
- Allow fork
- Swapping
- Latency disaster
- --hotkeys
- Popular keys
- Output buffer limits
- Drop slow clients
- redis_exporter
- Prometheus metrics
- LATENCY DOCTOR
- Latency report
- SCAN duplicates
- Keys may repeat
- Per-key overhead
- Metadata cost
- Memory headroom
- Margin below RAM
6.5 Application and distributed caching
- Static field leak
- Shared across requests
- Two-level cache
- Local plus distributed
- Client-side caching
- Redis tracking
- @Cacheable
- Spring method cache
- @CacheEvict
- Spring cache removal
- Self-invocation
- Bypasses Spring proxy
- Shared mutable object
- Callers change cached data
- refreshAfterWrite
- Reload while serving old value
- Caffeine
- Guava cache successor
- lru-cache
- Node in-memory cache
- TTLCache
- Python cachetools
- cache_page
- Django view cache
- Rails.cache.fetch
- Get or compute
- Second-level cache
- Shared ORM entity cache
- MySQL query cache
- Removed in 8.0
- GC pressure
- Large heaps pause
- Network hop
- Distributed cache cost
- Materialized view
- Database-maintained result
- Warm instance cache
- Serverless lifetime
- Read replica
- Any-query read scaling
- Per-service cache
- Avoids coupling
- Third-party API cache
- Latency and limits
- Local flag cache
- Periodic refresh
- JVM DNS cache
- networkaddress.cache.ttl
- Weigher
- Size by weight
- Deserialization miss
- Reload on failure
- Concurrent cache
- Thread-safe access
- Duplicate local caches
- Memory times instances
6.6 HTTP caching and CDNs
- Cache-Control
- HTTP header that sets caching rules such as max-age, private and no-store
- ETag
- A version identifier for a resource, used for conditional requests and 304 responses
- CDN
- Content delivery network: edge servers that cache content close to users
- Surrogate keys
- Tag-based purge
- Soft purge
- Mark stale, refetch
- Request collapsing
- One origin fetch per miss
- Cache policy
- Cache key and TTLs
- Invalidation paths
- Free quota, then billed
- Default TTL
- Used when origin is silent
- Cloudflare HTML
- Not cached by default
- ESI
- Edge page assembly
- stale-while-revalidate
- Serve stale while refreshing
- Varnish
- Caching reverse proxy
- Grace mode
- Serve expired on trouble
- proxy_cache
- nginx response cache
- proxy_cache_lock
- One fill per miss
- proxy_cache_use_stale
- Serve stale on errors
- cf-cache-status
- Cloudflare hit or miss
- Edge TLS termination
- Faster dynamic pages
- Purge on publish
- Short TTL plus purge
- CloudFront Functions
- Lightweight edge code
- Purge everything
- Origin flood risk
- Multi-CDN
- Resilience and reach
- Azure Front Door
- Azure CDN path
- Split TTLs
- Shorter browser TTL
- Byte hit ratio
- Share of bytes from cache
- Post-deploy dip
- Cold new assets
- Microcaching
- One-second caching
- Workers KV
- Eventually consistent edge store
6.7 Invalidation and consistency
- Cross-service staleness
- Other services' caches
- Cache-aside race
- Stale fill after delete
- Delayed double delete
- Second delete after a pause
- CDC invalidation
- Log-driven key deletes
- TTL safety net
- Bounds staleness
- Memcache lease
- Token to fill a key
- Version key
- Namespace invalidation
- Read-your-writes cache
- Bypass for the writer
- Dual write
- Two stores can diverge
- Dependency invalidation
- Derived entries
- App cache tags
- Group invalidation
- Multi-region invalidation
- Every region's cache
- Replica refill
- Stale value cached
- Time vs event invalidation
- Simple vs fresh
- Negative entry
- Cached not-found
- List caching
- Cache IDs separately
- Purge endpoint
- Emergency invalidation
- Global version bump
- Mass miss
- Pattern delete
- Needs a scan
- Order-free delete
- Idempotent invalidation
- Write-behind lag
- Database is behind
- Checkout check
- Read source for exact data
- Purge order
- Origin first, then CDN
- Write-heavy key
- Low hit ratio
- Key-based expiration
- updated_at in key
- Sliding staleness
- Hot entries never expire
6.8 Failure modes and resilience
- Cache stampede
- Many requests rebuilding the same expired key at once
- Slow shard
- Touches most pages
- Log flood
- Errors drown signals
- XFetch
- Probabilistic early refresh
- Rebuild lock
- One rebuilder per key
- Cache timeout
- Fall back fast
- Optional cache
- Not a hard dependency
- Reconnect jitter
- Spread reconnects
- Big values
- Latency spikes
- Validate before caching
- No cached errors
- Stale endpoint IP
- DNS after failover
- Cold-cache load test
- Database headroom
- Hit ratio alert
- Early warning
- Serve stale on outage
- Degraded reads
- Cache bulkhead
- Separate pool
- MGET batching
- Fewer round trips
- Metastable failure
- Self-sustaining overload
- BUSY
- Long script blocks Redis
- Cluster failover blip
- Seconds of errors
- Key cardinality
- Unbounded unique keys
- Cache chaos test
- Kill the cache
- Restore flush
- Clear cache after restore
- Cache migration
- Dual write, then switch
- Readiness and caches
- Optional dependency
- Keys without TTL
- Memory creep
- Static fallback
- Last-resort response
6.9 Managed caches and alternatives
- Redis 8 AGPL
- Open source option
- Valkey
- Linux Foundation Redis fork
- Memcached
- Multithreaded string cache
- Client-side hashing
- Memcached distribution
- Memcached item limit
- 1 MB default
- cas
- Check-and-set
- ElastiCache Serverless
- Auto-scaling cache
- Valkey on ElastiCache
- Lower price
- MemoryDB
- Durable Redis-compatible database
- Azure Managed Redis
- Azure Cache for Redis successor
- Valkey GLIDE
- Official client library
- Dragonfly
- Multithreaded Redis-compatible
- Garnet
- .NET RESP server
- Data grid
- Hazelcast or Ignite
- JCache
- JSR-107
- DAX
- DynamoDB cache
- Redis 8 built-ins
- JSON, search, time series
- Semantic caching
- Similar-meaning reuse
- Managed cache
- Provider runs ops
- Identity auth
- IAM or Entra ID
- Active-Active
- CRDT geo-replication
- Upstash
- Serverless HTTP Redis
- Postgres as cache
- Fewer systems
- Compatibility check
- Commands you use
- Reserved memory
- Headroom on nodes
- Global Datastore
- Cross-region ElastiCache
- Azure Managed Redis tiers
- Memory to compute balance
Sample practice questions
In the cache-aside (lazy loading) pattern, what happens on a cache miss?
- The cache queries the database itself on the application's behalf
- The app reads the database, then stores the result in the cache
- The request fails with an error until the cache has been warmed
- The database pushes every row into the cache when it starts up
Answer: B. The app reads the database, then stores the result in the cache The application owns the logic: check cache, fall back to the source, then populate the cache.
Which Redis data type is best for a real-time leaderboard ranked by score?
- A sorted set, with `ZADD` and `ZREVRANGE`
- A plain string, with `INCRBY` per player
- A list, with `LPUSH` and `LRANGE`
- A set, with `SADD` and `SMEMBERS`
Answer: A. A sorted set, with `ZADD` and `ZREVRANGE` Sorted sets keep members ordered by score with O(log N) updates and fast rank queries.
Why is Redis so fast?
- It stores all of its data on solid-state disks only
- It compiles each incoming query to native machine code
- In-memory data and a mostly single-threaded event loop
- It caches query results inside users' browsers
Answer: C. In-memory data and a mostly single-threaded event loop Since Redis 6, network I/O can use extra threads, but command execution remains single-threaded per instance.
Why is running `KEYS *` on a production Redis server dangerous?
- It deletes every key in the database without asking first
- It isn't a valid Redis command and crashes the server
- It forces Redis to flush all of its data to disk at once
- It scans every key, blocking the server; use SCAN instead
Answer: D. It scans every key, blocking the server; use SCAN instead Redis executes commands one at a time, so a long command stalls all other clients.
An app keeps a local in-memory cache in front of Redis. What's the main challenge?
- Local caches can't store more than ten entries
- Redis refuses to work with any local cache
- Copies on other servers go stale unless told to drop them
- Local caches are always slower than Redis
Answer: C. Copies on other servers go stale unless told to drop them Pub/Sub messages or short TTLs keep them in check.
What does the HTTP header `Cache-Control: max-age=3600` tell a browser?
- The server itself will cache the response for one hour on its side
- The response must never be stored in any cache, including the browser
- The client must revalidate with the server once every 3,600 requests
- It can reuse the response for 3,600 seconds without asking the server
Answer: D. It can reuse the response for 3,600 seconds without asking the server After max-age expires, the browser revalidates with the server, typically using ETag or Last-Modified.
Phil Karlton famously said there are only two hard things in computer science. One is naming things. What is the other?
- Cache invalidation
- Sorting
- Recursion
- Garbage collection
Answer: A. Cache invalidation Keeping caches fresh without serving stale data is notoriously difficult.
What is a cache stampede (thundering herd)?
- The cache running out of memory and evicting everything
- Having too many cache servers in a single cluster
- A hot key expires and many misses hit the database at once
- A cache returning another user's data by mistake
Answer: C. A hot key expires and many misses hit the database at once Fixes include request coalescing (single-flight), locks around recomputation, early refresh and jittered TTLs.
In Redis 7.4 and later, what licensing change prompted the Valkey fork?
- Redis became fully closed source, with no free version available to anyone
- Redis left BSD for source-available licenses; Valkey forked the last BSD code
- Redis was donated to the Apache Software Foundation under the Apache license
- Redis dropped Linux support, so the community forked it to keep Linux builds
Answer: B. Redis left BSD for source-available licenses; Valkey forked the last BSD code In 2024 Redis moved from BSD to RSALv2/SSPL, and the Linux Foundation forked Redis 7.2 as Valkey. Redis 8 later added AGPLv3 as another license option.
What does a write-through cache do?
- Writes go only to the cache, and the database is updated much later
- Writes bypass the cache entirely and go straight to the database
- Writes update the cache and database together, keeping it current
- The whole cache is rebuilt from scratch after every single write
Answer: C. Writes update the cache and database together, keeping it current Write-through keeps reads fresh but adds write latency and may cache data that is never read.
More Storage and Data
- Relational Database Design and Normalization
- SQL Queries, Joins and Window Functions
- Indexing and Query Optimization
- Transactions, ACID and Isolation Levels
- NoSQL Databases: Document, Key-Value, Wide-Column and Graph
- ORMs: Entity Framework Core and Hibernate
- Data Warehousing and ETL
- Message Queues and Event Streaming: Kafka, RabbitMQ and Service Bus
- Blob and Object Storage
- Backups, Replication and Disaster Recovery