0Pricing
Redis Caching & Messaging (Pub/Sub, Streams) · Lezione

Strategie di invalidazione della cache

Impari a mantenere aggiornati e coerenti i dati nella cache usando TTL, write-through, write-behind e invalidazione guidata dagli eventi in Redis.

Strategie di invalidazione della cache è una lezione Redis Caching & Messaging (Pub/Sub, Streams) gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Redis Caching & Messaging (Pub/Sub, Streams), e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Redis Caching & Messaging (Pub/Sub, Streams) include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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 60 expires after 60 seconds
  • EXPIRE key 60 sets a TTL on an existing key
  • TTL key shows remaining seconds
SET user:42:profile "...json..." EX 60
TTL user:42:profile
EXPIRE user:42:profile 120

Write-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 user

Write-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:42 then DEL each
SADD tag:user:42 cart:42 wishlist:42
SMEMBERS tag:user:42

Avoiding 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 5

Choosing 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.

Domande Frequenti

La lezione «Strategie di invalidazione della cache» è gratuita?

Sì — il testo completo di «Strategie di invalidazione della cache» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Redis Caching & Messaging (Pub/Sub, Streams), passa a CoddyKit PRO. Il corso Redis Caching & Messaging (Pub/Sub, Streams) include 4 lezioni in totale.

Cosa imparerò in «Strategie di invalidazione della cache»?

Impari a mantenere aggiornati e coerenti i dati nella cache usando TTL, write-through, write-behind e invalidazione guidata dagli eventi in Redis. Eserciti Redis Caching & Messaging (Pub/Sub, Streams) con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Redis Caching & Messaging (Pub/Sub, Streams)?

Non è richiesta alcuna esperienza precedente. Redis Caching & Messaging (Pub/Sub, Streams) su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Strategie di invalidazione della cache»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Redis Caching & Messaging (Pub/Sub, Streams)?

Sì. Ogni lezione Redis Caching & Messaging (Pub/Sub, Streams) include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Pattern di caching avanzati
  2. Gestione delle sessioni con Redis
  3. Rate limiting e anti-pattern
  4. Strategie di invalidazione della cache
← Torna a Redis Caching & Messaging (Pub/Sub, Streams)