Стратегии инвалидации кэша
Узнайте, как поддерживать актуальность и согласованность кэшированных данных с помощью TTL, сквозной записи, отложенной записи и событийной инвалидации в Redis
«Стратегии инвалидации кэша» — бесплатный урок Redis Caching & Messaging (Pub/Sub, Streams) на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Redis Caching & Messaging (Pub/Sub, Streams), и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Redis Caching & Messaging (Pub/Sub, Streams) содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Invalidation Matters
Caching speeds up reads, but a cache that serves stale data can be worse than no cache at all. Cache invalidation is the discipline of removing or refreshing entries when the underlying source of truth changes.
It is famously hard: there are only two hard things in computer science, and one of them is cache invalidation.
TTL-Based Expiry
The simplest strategy is time-to-live. You accept that data may be stale for at most N seconds.
SET key value EX 60expires after 60 secondsEXPIRE key 60sets a TTL on an existing keyTTL keyshows remaining seconds
SET user:42:profile "...json..." EX 60
TTL user:42:profile
EXPIRE user:42:profile 120Write-Through Caching
In write-through caching, every write goes to both the database and the cache in the same operation. Reads are always fresh, at the cost of slower writes.
The application is responsible for keeping the two in lockstep.
def save_user(user):
db.update(user)
redis.set('user:' + user.id, serialize(user))
return userWrite-Behind Caching
Write-behind (write-back) writes to the cache first and flushes to the database asynchronously. Writes are fast, but you risk data loss if Redis goes down before the flush.
Use a queue or stream to buffer pending writes.
redis.set('order:' + id, data)
redis.lpush('pending_writes', id)Explicit Deletion on Update
The cache-aside + delete pattern: on every update to the database, delete the cached key. The next read repopulates it.
This avoids serving stale data and is simpler than keeping the cache value in sync.
def update_product(p):
db.update(p)
redis.delete('product:' + p.id)Why Delete Beats Update
Deleting the key (instead of overwriting it) avoids a race condition: two concurrent updates could otherwise write values in the wrong order. With deletion, the next read always pulls the latest from the source of truth.
Versioned Keys
Instead of invalidating, bump a version number embedded in the key. Old keys expire naturally via TTL while new reads use the new key.
INCR config:version
GET config:version
SET config:v7:settings "..."Event-Driven Invalidation
Publish an invalidation event whenever data changes. Other application nodes subscribe and clear their local caches. This pairs Redis Pub/Sub with caching.
redis.publish('invalidate', 'user:42')
# subscribers:
redis.subscribe('invalidate')Tag-Based Invalidation
Group related keys under a tag set. When a tag becomes invalid, delete all member keys in one sweep.
SADD tag:user:42 product:1 product:2- On change:
SMEMBERS tag:user:42thenDELeach
SADD tag:user:42 cart:42 wishlist:42
SMEMBERS tag:user:42Avoiding Stampedes
When a hot key expires, many requests may hit the database at once (a cache stampede). Mitigate with a short lock, probabilistic early expiry, or serving slightly stale data while one worker refreshes.
SET lock:user:42 1 NX EX 5Choosing a Strategy
There is no single best approach:
- TTL for tolerable staleness
- Delete-on-write for correctness
- Event-driven for multi-node consistency
- Versioning for bulk config changes
Quick Check
Test your understanding of invalidation strategies.
Recap
You learned the major cache invalidation strategies: TTL expiry, write-through, write-behind, delete-on-write, versioned keys, event-driven, and tag-based invalidation, plus how to avoid cache stampedes. Pick the strategy that matches your tolerance for staleness and your consistency needs.
Изучай Redis Caching & Messaging (Pub/Sub, Streams) с ИИ-репетитором — бесплатно
Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.
- Курсы
- 12
- Уроки
- 48
Часто задаваемые вопросы
Урок «Стратегии инвалидации кэша» бесплатный?
Да — полный текст урока «Стратегии инвалидации кэша» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Redis Caching & Messaging (Pub/Sub, Streams), подпишись на CoddyKit PRO. Курс Redis Caching & Messaging (Pub/Sub, Streams) содержит 4 уроков всего.
Чему я научусь в уроке «Стратегии инвалидации кэша»?
Узнайте, как поддерживать актуальность и согласованность кэшированных данных с помощью TTL, сквозной записи, отложенной записи и событийной инвалидации в Redis Ты практикуешь Redis Caching & Messaging (Pub/Sub, Streams) с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Redis Caching & Messaging (Pub/Sub, Streams)?
Предыдущий опыт не требуется. Redis Caching & Messaging (Pub/Sub, Streams) на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Стратегии инвалидации кэша»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Redis Caching & Messaging (Pub/Sub, Streams)?
Да. Каждый урок Redis Caching & Messaging (Pub/Sub, Streams) включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Продвинутые шаблоны кэширования
- Управление сеансами с помощью Redis
- Ограничение частоты запросов и антипаттерны
- Стратегии инвалидации кэша