Caching e compressione delle risposte API
Velocizzi le risposte del backend con livelli di caching in memoria e distribuiti, un’invalidazione intelligente della cache e la riduzione dei payload, così i server svolgano meno lavoro per richiesta.
Caching e compressione delle risposte API è una lezione Web Performance Optimization & Lighthouse 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 Web Performance Optimization & Lighthouse, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Web Performance Optimization & Lighthouse include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Why Cache on the Backend?
Recomputing the same response for every request wastes CPU and database time. Caching stores computed results so repeat requests return instantly, cutting both latency and load.
Layers of Caching
- In-process memory fastest, but per-instance.
- Distributed cache (Redis/Memcached) shared across servers.
- HTTP/CDN cache at the edge.
A Simple Cache-Aside Pattern
The most common pattern: check the cache, return on hit, otherwise compute, store, and return. This is called cache-aside.
async function getUser(id) {
const hit = await redis.get('user:' + id);
if (hit) return JSON.parse(hit);
const user = await db.findUser(id);
await redis.set('user:' + id, JSON.stringify(user), 'EX', 300);
return user;
}Choosing a TTL
A time to live balances freshness against hit rate. Volatile data needs short TTLs; reference data can live much longer. Always set some expiry to avoid stale buildup.
Invalidation Strategies
The hard part of caching is invalidation. On writes, either delete the affected keys or update them (write-through). Stale data here is a common production bug.
async function updateUser(id, data) {
await db.update(id, data);
await redis.del('user:' + id);
}HTTP Caching Headers
For cacheable API responses, set Cache-Control so browsers and CDNs can reuse them, removing the request entirely on a hit.
res.set('Cache-Control', 'public, max-age=60, stale-while-revalidate=300');Conditional Requests
ETag and If-None-Match let the server reply 304 Not Modified with no body when data is unchanged, saving bandwidth.
res.set('ETag', hashOf(payload));
// next time: if If-None-Match matches, send 304Shrinking the Payload
Return only the fields clients need, paginate large lists, and avoid over-fetching. Smaller payloads serialize faster and transfer quicker.
Compressing Responses
Enable gzip or Brotli on JSON responses. Combined with caching, this minimizes both compute and transfer per request.
const compression = require('compression');
app.use(compression());Avoiding Stampedes
When a hot key expires, many requests may hit the database at once (a cache stampede). Mitigate with locks, request coalescing, or stale-while-revalidate.
Strategy Summary
- Cache-aside with sensible TTLs.
- Invalidate on writes.
- Use Cache-Control and ETags.
- Trim and compress payloads.
- Guard against stampedes.
Quick Check
After a user updates their profile, the API keeps returning the old data for several minutes. What is the most likely cause?
Recap
You learned to cut backend work with layered caching (cache-aside, TTLs, invalidation on writes), HTTP caching via Cache-Control and ETags, payload trimming, and compression, while guarding against cache stampedes.
Domande Frequenti
La lezione «Caching e compressione delle risposte API» è gratuita?
Sì — il testo completo di «Caching e compressione delle risposte API» è 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 Web Performance Optimization & Lighthouse, passa a CoddyKit PRO. Il corso Web Performance Optimization & Lighthouse include 4 lezioni in totale.
Cosa imparerò in «Caching e compressione delle risposte API»?
Velocizzi le risposte del backend con livelli di caching in memoria e distribuiti, un’invalidazione intelligente della cache e la riduzione dei payload, così i server svolgano meno lavoro per richies… Eserciti Web Performance Optimization & Lighthouse 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 Web Performance Optimization & Lighthouse?
Non è richiesta alcuna esperienza precedente. Web Performance Optimization & Lighthouse 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 «Caching e compressione delle risposte API»?
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 Web Performance Optimization & Lighthouse?
Sì. Ogni lezione Web Performance Optimization & Lighthouse 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
- Colli di bottiglia delle prestazioni backend
- Ottimizzazione delle query al database
- Impatto del rendering lato server (SSR)
- Caching e compressione delle risposte API