APIレスポンスのキャッシュと圧縮
インメモリおよび分散キャッシュ層、適切なキャッシュ無効化、ペイロード削減によってバックエンドのレスポンスを高速化し、リクエストごとのサーバー処理を減らします。
「APIレスポンスのキャッシュと圧縮」はCoddyKit上の無料Web Performance Optimization & Lighthouseレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはWeb Performance Optimization & Lighthouse学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Web Performance Optimization & Lighthouseコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
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.
AI チューターと学ぶ Web Performance Optimization & Lighthouse — 無料
ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。
- コース
- 12
- レッスン
- 48
よくある質問
「APIレスポンスのキャッシュと圧縮」レッスンは無料ですか?
はい。「APIレスポンスのキャッシュと圧縮」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Web Performance Optimization & Lighthouseコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Web Performance Optimization & Lighthouseコースには全4レッスンが含まれています。
「APIレスポンスのキャッシュと圧縮」で何を学びますか?
インメモリおよび分散キャッシュ層、適切なキャッシュ無効化、ペイロード削減によってバックエンドのレスポンスを高速化し、リクエストごとのサーバー処理を減らします。 ブラウザで直接実行するハンズオンコードでWeb Performance Optimization & Lighthouseを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Web Performance Optimization & Lighthouseを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのWeb Performance Optimization & Lighthouseは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「APIレスポンスのキャッシュと圧縮」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このWeb Performance Optimization & Lighthouseレッスンでコードを書いて実行できますか?
はい。すべてのWeb Performance Optimization & Lighthouseレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- バックエンドのパフォーマンスボトルネック
- データベースクエリの最適化
- Server-Side Rendering(SSR)の影響
- APIレスポンスのキャッシュと圧縮