Cache invalidation

2 snippets across 2 stacks — Docker, Interview Prep

DKDocker

Accidental Build Cache Invalidation

DK · Common Mistakes
syntax
# Problem — COPY . . before RUN npm ci
COPY . .
RUN npm ci
example
# Every source code change re-runs npm ci (~30-60 seconds).
# Fix — copy manifests first:
COPY package.json package-lock.json ./
RUN npm ci
COPY . .

Note Docker invalidates a layer's cache when any input changes. A broad COPY . . changes whenever ANY file in your project changes, nuking the cache for all subsequent layers. Order Dockerfile instructions from least-frequently to most-frequently changing.

DSAInterview Prep

Caching

DSA · System Design Basics
syntax
Store frequently accessed data in fast storage (memory).
Layers: browser cacheCDNapplication cachedatabase cache

Patterns:
- Cache-aside: app checks cache first, loads from DB on miss
- Write-through: write to cache and DB simultaneously
- Write-back: write to cache, async flush to DB
example
// Cache-aside pattern (most common):
// 1. App receives request
// 2. Check cache (Redis/Memcached)
// 3. Cache HIT → return cached data
// 4. Cache MISS → query database → store in cache → return

// Eviction policies:
// LRU: remove least recently used (most common)
// LFU: remove least frequently used
// TTL: expire after fixed time

// Cache invalidation strategies:
// 1. TTL-based: set expiry, eventually consistent
// 2. Event-based: invalidate on write
// 3. Version-based: cache key includes version number
output
Cache hit: ~1ms | Database query: ~10-100ms | 10-100x speedup

Note Cache invalidation is one of the two hard problems in CS (along with naming things). Always discuss: cache stampede (many misses at once → thundering herd), consistency vs performance trade-off, and cold start (empty cache after deploy). Redis is the go-to answer for distributed caching.