Cache strategies на собеседовании системного аналитика

Готовься к собесу аналитика как в Duolingo
10 минут в день — SQL, Python, A/B, метрики. 1700+ вопросов в Telegram
Открыть Карьерник в Telegram

Карьерник — Duolingo для аналитиков: 10 минут в день тренируй SQL, Python, A/B, статистику, метрики и ещё 3 темы собеса. 1500+ вопросов в Telegram-боте. Бесплатно.

Зачем cache

DB — bottleneck. Каждый request = full query = expensive.

Cache (Redis, Memcached) — store frequent results in-memory.

Without: 100 RPS → DB
With cache (90% hit): 10 RPS → DB, 90 RPS → Redis (cheap)

10× DB capacity без apparent infrastructure changes.

Cache-aside (lazy)

1. App reads → check cache.
2. Cache hit → return.
3. Cache miss → fetch from DB → write to cache → return.

Pros: simple, only cache what's actually requested.

Cons: first request slow (cache miss), inconsistency window между DB и cache.

Самый popular pattern.

Write-through

On write:
  1. Write to cache.
  2. Synchronously write to DB.
On read: same as cache-aside.

Pros: cache always consistent (no stale).

Cons: writes slower (двойная запись).

Write-back (write-behind)

On write:
  1. Write to cache.
  2. Async write to DB later (batched).

Pros: writes fast, batches DB writes.

Cons: cache failure → data loss. Riskier.

Used в high-write scenarios where some loss tolerable.

Готовься к собесу аналитика как в Duolingo
10 минут в день — SQL, Python, A/B, метрики. 1700+ вопросов в Telegram
Открыть Карьерник в Telegram

TTL и invalidation

TTL. Auto-expire after N seconds. Simple, but stale window до TTL.

Manual invalidation.

Update DB → DELETE cache key.
Next read — cache miss, refetch.

Полный, но coordination нужна (если несколько services пишут — все должны invalidate).

Two famously hard things in CS.

«There are only two hard things in Computer Science: cache invalidation and naming things.»

Cache stampede

Когда популярный key expires — все simultaneously cache miss → DB hit.

Mitigation:

  • Random TTL. Spread expirations.
  • Refresh-ahead. Refresh cache before expiration (background job).
  • Lock. First miss locks key, others wait or use stale.
  • Probabilistic early refresh. Refresh с probability based на time-to-expire.

Связанные темы

FAQ

Это официальная информация?

Нет. Статья основана на стандартных подходах caching.


Тренируйте системный анализ — откройте тренажёр с 1500+ вопросами для собесов.