Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 39 ยท Serialization and Performance

Performance Tuning Fastify Applications

Why Fastify is fast and how to keep it fast: protect the event loop, compile serializers, cut logging cost, use caching headers, pools, clustering and benchmarks.

Fastify's marketing line is speed, and the numbers are real: in common benchmarks it handles several times more requests per second than older Node frameworks on the same hardware. But the framework is only a small part of your response time. A route that waits 40 ms on a database or burns 15 ms of CPU building a report is slow no matter how fast the router is.

This lesson explains where Fastify's speed comes from, which mistakes throw it away, and a short checklist of tuning steps ordered by how much they usually matter.

No numbers from benchmarks are quoted for your machine, because they depend on hardware, Node version and payload. The examples print structure and relative behavior. Real Fastify is not installed on this site; these examples use plain Node, which is where every Fastify performance rule comes from.

Where Fastify gets its speed

Radix-tree router Finds a route without scanning a list.
Compiled serializers Response schemas become tight code.
Low overhead hooks Few allocations per request.
Fast logger Pino writes JSON with little work.

Your handler is usually the slow part.

1 / 2

Rule 1: never block the event loop

Node runs your JavaScript on one thread. While a handler runs a long synchronous computation (a big JSON.parse, a CPU loop, fs.readFileSync on a slow disk, bcrypt written in sync style), every other request waits. A server that handles a thousand requests per second can be crushed by one endpoint that takes 50 ms of CPU.

The next example proves it with a real server on loopback. It sends a slow-CPU request and a quick request together, once with a blocking handler and once with one that yields to the event loop between chunks of work.

Node.js One blocking handler delays everyone

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 remedies, in order of preference:

  1. Do less: cache the result, paginate, select fewer columns.
  2. Move work off the thread: a worker thread (node:worker_threads), a separate job queue, or a native async API (most crypto, zlib and file functions have async versions that run on libuv's thread pool).
  3. Slice the work as shown above (setImmediate), which keeps the server responsive even if total CPU time stays the same.

Rule 2: let Fastify compile your serializers

A response schema (Response Serialization and Schemas) is the cheapest speedup you can get. To see why, look at what a compiler like fast-json-stringify does: it reads the schema once, at startup, and generates a function whose body contains the exact steps for that shape. No type checks, no property enumeration, no guessing at request time.

Node.js What a compiled serializer looks like

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 generated function mentions id, name and score by name, so the engine can optimize it like hand-written code. It also never touches secret, which is why a schema doubles as a filter. Real fast-json-stringify handles nested objects, arrays, $ref, anyOf, dates and BigInt, and escapes strings safely.

Rule 3: concurrency, not queues

Independent awaits belong in Promise.all:

JavaScript
// slow: 3 round trips one after another
const user = await db.user(id);
const orders = await db.orders(id);
const prefs = await db.prefs(id);

// fast: 3 round trips together (limited by the slowest)
const [user, orders, prefs] = await Promise.all([db.user(id), db.orders(id), db.prefs(id)]);

Do not overdo it: start thousands of queries at once and the pool becomes the bottleneck. Use a connection pool with a sensible size, and a limit on parallel work.

Rule 4: log with intent

Fastify's built-in logger is Pino, one of the fastest JSON loggers. Even so, logging has costs: formatting, serializing and writing bytes. The usual setup is:

  • info level in production, debug only while investigating;
  • logging the request summary (one line per request, which Fastify does for you), not every step;
  • no huge objects in log lines, and never secrets (see the next lesson, Logging with Pino).

Rule 5: help clients and proxies cache

The fastest request is the one you never serve. For public data, set Cache-Control and ETag headers (the @fastify/etag and @fastify/caching plugins help) and put a CDN or reverse proxy in front. For private data, a short in-process cache (a Map with expiry, or Redis) in front of slow queries often turns 80 ms into under 1 ms.

Compression (@fastify/compress) saves bandwidth but costs CPU: compress text responses above a few hundred bytes, never images, and consider letting nginx or the CDN do it instead.

Rule 6: use all your cores

A Node process uses one core for JavaScript. To use an 8-core machine, run several processes: the cluster module, a process manager such as PM2, or simply several containers behind a load balancer. Keep the processes stateless so any of them can serve any request.

Measure before you tune

Opinions about performance are cheap and often wrong. Use a load tool such as autocannon against a production-like build and look at latency percentiles (p50, p99), not only the average:

Terminal
# real command, run on your own machine
npx autocannon -c 100 -d 20 http://localhost:3000/users

Then profile with node --prof or clinic.js to see where time is spent. Change one thing at a time, and re-measure. A typical order of wins is: fix slow queries and missing indexes, add caching, add response schemas, then trim logging.

Run benchmarks with NODE_ENV=production and a realistic logger level. A development setup with pretty-printed logs can be several times slower than production, which makes a comparison meaningless.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a long synchronous loop in one handler harmful for the whole server?

    The event loop cannot serve other requests while synchronous code runs. Offload, cache or slice heavy work.
  2. 2. What does a response schema let Fastify do?

    The schema is compiled once into code made for that shape, which is faster than inspecting every value with JSON.stringify.
  3. 3. Three independent database calls are awaited one after another. What is the best fix?

    Independent promises can be started together with Promise.all. Total time is about the slowest call, not the sum.
  4. 4. Which metric is more useful than the average when you test latency?

    Averages hide slow outliers. p99 shows what your slowest 1 percent of users experience.

Summary

  • Fastify is fast because of its router, compiled serializers, low-overhead hooks and Pino; your handler code is usually the real bottleneck.
  • Never block the event loop: cache, offload to workers or async APIs, or slice the work.
  • Add response schemas, run independent awaits with Promise.all, log at info in production.
  • Use cache headers and a CDN, compress selectively, and run one process per core.
  • Measure with percentiles under production settings before and after each change.

Next: Logging with Pino