Caching Strategies: Redis + CDN + Edge Computing · Lezione

TTL e scadenza in Redis

Scopra come Redis gestisce la scadenza delle chiavi: impostazione dei TTL, comandi EXPIRE e SETEX, funzionamento della scadenza lazy e attiva e interazione tra le policy di eviction maxmemory e i TTL.

Lezione 4 di 413 passaggi

TTL e scadenza in Redis è una lezione Caching Strategies: Redis + CDN + Edge Computing 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 Caching Strategies: Redis + CDN + Edge Computing, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Caching Strategies: Redis + CDN + Edge Computing include 4 lezioni in totale.

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

Why Expire Cache Keys?

Cached data goes stale. Time To Live (TTL) lets Redis automatically remove a key after a set duration, so your cache stays reasonably fresh without manual cleanup.

Setting a TTL with EXPIRE

The EXPIRE command sets a timeout in seconds on an existing key. After that time, Redis deletes the key automatically.

SET user:1 "Alice"
EXPIRE user:1 60
TTL user:1

SET with EX in One Step

You can set a value and its TTL together. SET key value EX seconds (or the older SETEX) avoids a race between writing and expiring.

SET session:abc "data" EX 300

Checking Remaining TTL

The TTL command returns seconds left. PTTL returns milliseconds. Special return values matter:

  • -1: key exists but has no expiry
  • -2: key does not exist
def interpret_ttl(value):
    if value == -1:
        return 'no expiry set'
    if value == -2:
        return 'key does not exist'
    return str(value) + 's remaining'

print(interpret_ttl(-2))
print(interpret_ttl(45))

Removing an Expiry

The PERSIST command removes the TTL from a key, making it permanent again. Useful when a value should stop expiring after some condition is met.

PERSIST user:1

Lazy Expiration

Redis does not check every key constantly. With lazy expiry, an expired key is only removed when someone tries to access it. Until then it lingers in memory.

Active Expiration

To reclaim memory from keys nobody touches, Redis also runs a background sampler that periodically removes a batch of expired keys. This is active expiry. Together with lazy expiry it keeps memory in check.

TTL vs Eviction

TTL is voluntary removal at a set time. Eviction happens when Redis hits its maxmemory limit and must drop keys to make room. They are different mechanisms that often work together.

volatile vs allkeys Policies

Eviction policies decide what to drop under memory pressure:

  • volatile-lru: evict least-recently-used keys that have a TTL
  • allkeys-lru: evict LRU among all keys

For a pure cache, allkeys policies are common.

Choosing TTL Values

Pick TTLs from the data's tolerance for staleness: seconds for fast-changing prices, hours for catalogs, days for rarely-changing config. Add jitter to avoid synchronized mass expiry.

import random
base = 3600
print('TTL:', base + random.randint(0, 300), 'seconds')

Common Pitfall: No TTL

Forgetting to set a TTL turns a cache into an ever-growing store that eventually exhausts memory. For cache use cases, almost every key should have an expiry or rely on an allkeys eviction policy.

Quick Check

What does the Redis command TTL mykey return if the key exists but has no expiration set?

Recap

You learned TTL and expiration in Redis:

  • EXPIRE / SET ... EX set timeouts; TTL/PTTL inspect them; PERSIST removes them.
  • Redis uses lazy plus active expiration.
  • Eviction policies (volatile vs allkeys) handle memory pressure.
  • Always set TTLs (or an allkeys policy) for cache keys.

Good expiration keeps a cache both fresh and bounded.

Gratis per iniziare

Impara Caching Strategies: Redis + CDN + Edge Computing con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
12
Lezioni
48

Domande Frequenti

La lezione «TTL e scadenza in Redis» è gratuita?

Sì — il testo completo di «TTL e scadenza in Redis» è 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 Caching Strategies: Redis + CDN + Edge Computing, passa a CoddyKit PRO. Il corso Caching Strategies: Redis + CDN + Edge Computing include 4 lezioni in totale.

Cosa imparerò in «TTL e scadenza in Redis»?

Scopra come Redis gestisce la scadenza delle chiavi: impostazione dei TTL, comandi EXPIRE e SETEX, funzionamento della scadenza lazy e attiva e interazione tra le policy di eviction maxmemory e i TTL. Eserciti Caching Strategies: Redis + CDN + Edge Computing 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 Caching Strategies: Redis + CDN + Edge Computing?

Non è richiesta alcuna esperienza precedente. Caching Strategies: Redis + CDN + Edge Computing 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 «TTL e scadenza in Redis»?

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 Caching Strategies: Redis + CDN + Edge Computing?

Sì. Ogni lezione Caching Strategies: Redis + CDN + Edge Computing 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. Introduzione al caching con Redis
  2. Strutture dati Redis per la cache
  3. Operazioni di base sulla cache Redis
  4. TTL e scadenza in Redis
← Torna a Caching Strategies: Redis + CDN + Edge Computing