Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 39 ยท Serialization and Performance

Caching, ETags and Compression

Make Fastify responses cheaper: Cache-Control headers, ETags with 304 answers, a small in-memory cache with expiry, and when to compress responses with gzip.

The fastest request is the one your handler never runs. HTTP has built-in tools for that: headers that tell browsers and CDNs how long a response stays fresh, validators (ETag) that let a client ask "has this changed?", and compression that shrinks what is sent. Fastify does not hide any of this. You set headers on the reply, or you register a plugin that does it for you.

In this lesson you will build each idea from scratch so you can see what the plugins @fastify/etag, @fastify/caching and @fastify/compress actually do. After Performance Tuning Fastify Applications, this is the "do less work" part of the checklist.

Real Fastify and its plugins are not installed on this site. The first example uses a small stand-in with the same get, addHook and inject shapes as Fastify; the others use only node:zlib and plain JavaScript. Real plugin calls appear as read-only snippets.

Three ways to skip work

Freshness Cache-Control says how long to reuse.
Validation ETag lets the client ask if it changed.
Compression Smaller bodies travel faster.

Each one saves a different resource.

1 / 2

Cache-Control: freshness

Cache-Control tells every cache on the path how long a response may be reused without asking again. The directives you will use most:

Directive Meaning
max-age=60 Any cache may reuse the response for 60 seconds.
s-maxage=600 Same, but only for shared caches (CDNs, proxies).
public / private Shared caches may / may not store it. Use private for per-user data.
no-store Never store it (balances, tokens, personal pages).
no-cache Store it, but check with the server before each reuse.
immutable The URL's content never changes (fingerprinted assets).

In a Fastify route this is just reply.header('cache-control', 'public, max-age=60'). For a whole group of routes, set it in an onSend hook inside a plugin, as you saw in Request and Reply Hooks in Practice.

ETag: validation with 304

Freshness runs out. Then the client has a choice: download everything again, or ask "I have version abc, is it still current?". The server answers 304 Not Modified with no body when the validator matches. The validator is the ETag header, usually a hash of the body.

The next example implements the whole flow in an onSend hook: hash the body, compare with If-None-Match, and turn the response into a bodiless 304 when they match.

Node.js ETag and 304 in an onSend hook

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The second request costs almost nothing on the wire. Note that your handler still ran: an ETag saves bandwidth, not CPU. To save the CPU too, combine it with a cache in front of the handler, as shown next.

In real Fastify, @fastify/etag registers this hook for you:

JavaScript
import etag from '@fastify/etag';
await app.register(etag);   // adds ETag to every payload and answers 304 when it matches

A small in-process cache

For slow data that many users share (a product list, exchange rates, a rendered report), keep the result in memory for a short time. A Map with an expiry timestamp is enough for one process:

Node.js A TTL cache in front of a slow lookup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Three cautions about caches in your own process:

  1. Every process has its own copy. With several processes or containers, use Redis or accept slightly different answers.
  2. Cache keys must include everything that changes the answer: the user, the language, the query string.
  3. Bound the size. An unbounded Map keyed by user input is a memory leak and an attack surface.

Compression

Text compresses well: JSON often shrinks by 70 to 90 percent with gzip. The client announces what it understands in Accept-Encoding, and the server answers with Content-Encoding. Node ships the compressors in node:zlib, which is what @fastify/compress uses.

Node.js gzip and brotli on a JSON body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last line is the reason for a threshold: do not compress tiny bodies, images, videos or anything already compressed (zip, jpg, mp4). In real Fastify:

JavaScript
import compress from '@fastify/compress';
await app.register(compress, { threshold: 1024, encodings: ['br', 'gzip'] });

Compression costs CPU on every request. If a CDN or nginx sits in front of your app, let it compress and keep Fastify lean.

Choosing a strategy

  • Public and rarely changing (docs, catalogs): public, max-age plus a CDN.
  • Public but changing: short max-age plus ETag, so revisits are cheap.
  • Private: private or no-store; use in-process caching keyed by user only if needed.
  • Always: Vary: Accept-Encoding when you compress, so caches do not mix encodings (the compress plugin adds it).

A response that depends on cookies or an Authorization header must never be public. A shared cache would serve one user's page to another.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a server send when the client's If-None-Match matches the current ETag?

    A match means the client's copy is current, so the server answers 304 and skips the body.
  2. 2. Which header value is right for a page that shows one user's account balance?

    Personal data must not be stored by shared caches, and a balance should not be reused at all.
  3. 3. Why should you set a compression threshold?

    gzip adds headers, so very small payloads can get bigger. Skip them and skip already-compressed files.
  4. 4. What is a weakness of a Map-based cache inside the Node process?

    In-process caches are not shared between processes or containers. Use Redis when you need one shared view.

Summary

  • Cache-Control sets freshness; private, no-store and public decide who may store a response.
  • An ETag plus If-None-Match lets clients revalidate and get a bodiless 304; it saves bandwidth, not handler CPU.
  • A TTL cache in front of slow lookups saves CPU and database calls, but each process has its own copy and keys must include everything that varies.
  • Compress text above a threshold, never already-compressed files, and let a CDN or proxy do it if one exists.
  • Never mark user-specific responses public.

Next: JWT Authentication with Fastify