DEV Community

Cover image for Performance — Fastify with TypeScript (part 17/18)
Antonio Tripodi
Antonio Tripodi

Posted on

Performance — Fastify with TypeScript (part 17/18)

Performance

Seventeenth chapter of the "Fastify with TypeScript" series. Fastify is already fast by default, but a few architectural choices make a huge difference under real-world load, and most of them are things we've already done in this series for other reasons. This chapter names them, shows what a blocked event loop looks like, and adds the one piece that is still missing: knowing when the process is in trouble.


1. Response schemas: for safety first

For years the first performance tip for Fastify was "always define a response schema", because fast-json-stringify, the library that serializes through the schema, beat JSON.stringify. JavaScript engines have moved since then: the engine's own JSON.stringify has become very fast, and with its default settings the schema-based serializer is no longer faster on objects.

Keep the response schemas anyway. They are there so that password_hash can never leave the server and so that the API has a contract (chapter 7), and that is worth far more than a serialization difference you would struggle to notice in a real request.

The library is not standing still, though. It has an opt-in mode, objectMechanism: 'native', that copies the fields the schema declares into a plain object and hands it to the engine's JSON.stringify: the schema is still applied, the output is the same, and the engine does the fast part. From Fastify you would enable it with:

const app = Fastify({
  serializerOpts: { objectMechanism: 'native' },
});
Enter fullscreen mode Exit fullscreen mode

We don't turn it on in this project, for one reason: which Node.js versions and which kinds of schema benefit from it is still changing from one release of the library to the next. Read the fast-json-stringify README for the version you have installed, and measure it on your own responses before enabling it.

That is the lesson of this section: don't trust performance advice, including this chapter's, without measuring on the Node version you actually run. What was true two versions ago may not be true today.

2. Use connection pooling

@fastify/postgres opens a pool once and reuses its connections. Opening a connection per request (a new pg.Client() inside a handler) costs a TCP handshake plus PostgreSQL authentication every time. Tune max in the pool options to what your database can handle across all your instances.

3. Don't block the event loop

Node runs your JavaScript on a single thread. While that thread is busy computing, nothing else happens: no other request is answered, no timer fires. See it for yourself. Add a temporary route to src/app.ts, above the registration of the modules:

  // Temporary: block the event loop for five seconds
  app.get('/block', { schema: { hide: true } }, async () => {
    const end = Date.now() + 5000;
    while (Date.now() < end) { /* burning CPU */ }
    return { blocked: 'for 5 seconds' };
  });
Enter fullscreen mode Exit fullscreen mode

In one terminal call curl localhost:3000/block. Half a second later, in another:

curl -w ' %{time_total}s\n' localhost:3000/health
# {"status":"ok"} 4.497438s
Enter fullscreen mode Exit fullscreen mode

The simplest route of the application took four and a half seconds, because one other request was hogging the thread. With a hundred concurrent users, one slow computation is everybody's problem. Leave the /block route where it is for now: we'll use it once more in section 6.

Work that waits (a database query, an HTTP call, reading a file) doesn't block: the thread is free while it waits. What blocks is CPU work: resizing images, generating PDFs, parsing huge JSON documents, hashing in pure JavaScript. For that, either use a native module that works off the main thread, as we did with argon2, or move the work to worker threads (piscina gives you a pool of them with a Promise API).

4. Stream large responses

Returning a stream (return reply.send(createReadStream(path)), chapter 5) sends bytes as they are read instead of loading the whole file in memory. The same applies to large query results: pg-query-stream streams rows out of PostgreSQL.

5. Cache expensive, repeated work

In-process with lru-cache for a single instance, Redis (@fastify/redis) when several instances must share the cache. async-cache-dedupe adds one more thing on top of caching: when ten requests ask for the same missing key at the same moment, it runs the expensive function once and gives the result to all ten.

Set a TTL and think about invalidation before adding a cache: a stale cache is worse than a slow endpoint.

6. Monitor the event loop and protect against overload

The number that tells you whether section 3 is happening in production is the event loop utilization (ELU): the share of time the loop spends working rather than waiting, from 0 to 1. An API that mostly waits for the database stays low even with many requests in flight. A value that stays near 1 means the loop is saturated and every request is queuing behind the others.

When that happens, it's better to answer 503 immediately than to let latency degrade for everyone. @fastify/under-pressure measures the loop and does exactly that:

npm install @fastify/under-pressure
Enter fullscreen mode Exit fullscreen mode

In src/plugins/security.ts, add the import:

import underPressure from '@fastify/under-pressure';
Enter fullscreen mode Exit fullscreen mode

and register it at the end of the plugin, after the rate limiter:

  // Answer 503 when the event loop is saturated, instead of letting every request slow down
  await fastify.register(underPressure, {
    maxEventLoopDelay: 1000,              // ms of lag
    maxEventLoopUtilization: 0.98,        // share of time the loop is busy...
    eventLoopUtilizationMode: 'interval', // ...over the last second, not since startup
  });
Enter fullscreen mode Exit fullscreen mode

The third option matters more than it looks. By default the plugin reports the utilization as an average since the process started, and on a server that has been up for days that average barely moves, whatever is happening right now. 'interval' measures the last sampling window instead (one second by default), which is the number you want both for the threshold and for a dashboard.

Above either threshold, requests are refused before they do any work:

HTTP/1.1 503 Service Unavailable
retry-after: 10

{"statusCode":503,"error":"FST_UNDER_PRESSURE","message":"Service Unavailable"}
Enter fullscreen mode Exit fullscreen mode

A load balancer sees the 503s and sends traffic to healthier instances, which is the whole point.

Notice what the thresholds are not based on: memory and CPU. Node deliberately uses the memory it is given, because the garbage collector runs less often when there is room, so a process at 80% of its memory limit can be perfectly healthy. And a process at 100% CPU can still be answering quickly. Restarting or scaling on those two numbers alone wastes resources. The signals that say a Node process is in trouble are the event loop ones.

Reading the metrics

The plugin also gives you the numbers. In src/app.ts, replace the /health route with:

  // Liveness and metrics must keep answering when the process is under pressure:
  // an empty pressureHandler tells @fastify/under-pressure to let these two through
  const alwaysAnswer = { schema: { hide: true }, config: { pressureHandler: () => {} } };

  app.get('/health', alwaysAnswer, async () => ({ status: 'ok' }));

  // Node-specific metrics collected by @fastify/under-pressure
  app.get('/health/metrics', alwaysAnswer, async () => app.memoryUsage());
Enter fullscreen mode Exit fullscreen mode
curl localhost:3000/health/metrics
# {"eventLoopDelay":0.2365796288659805,"rssBytes":118640640,"heapUsed":28913448,"eventLoopUtilized":0.0035621899955730436}
Enter fullscreen mode Exit fullscreen mode

That's an idle server. (In the first second after startup the values are all 0: the plugin hasn't taken its first sample yet.) Now repeat the experiment of section 3: call curl localhost:3000/block, and as soon as it returns read the metrics again:

# {"eventLoopDelay":94.59754264150943,"rssBytes":138608640,"heapUsed":37656752,"eventLoopUtilized":0.9044871656823597}
Enter fullscreen mode Exit fullscreen mode

Utilization went from 0.004 to 0.90 because of a single blocked request, and a second later it is back to 0.01. Your numbers will differ from run to run; in my tests the peak was anywhere between 0.90 and 0.97. If it reaches the 0.98 threshold, the API routes answer 503 for about a second: that is the plugin doing its job.

Now remove the /block route from src/app.ts.

eventLoopUtilized and eventLoopDelay are the two to alert on. heapUsed is worth plotting over days: a line that only ever goes up is a memory leak. In production you would export these to your monitoring system (Prometheus, OpenTelemetry) and keep the route reachable only from inside your network.

Why the alwaysAnswer option? Without it, an overloaded process would answer 503 on /health too. An orchestrator that uses /health to decide whether the process is alive would then restart it, which is the wrong reaction to load: the new instance gets the same traffic and a cold start on top. A saturated process is alive. It should be given less traffic, and that's the job of the readiness check we'll add in the next chapter.

A test keeps both routes honest. Create test/health.test.ts:

// test/health.test.ts — liveness and metrics, no database needed
import { describe, it, before, after } from 'node:test';
import { build } from './helper.ts';
import type { App } from '../src/app.ts';

describe('Health', () => {
  let app: App;

  before(async () => {
    app = await build();
  });

  after(async () => {
    await app.close();
  });

  it('exposes Node-specific metrics', async (t) => {
    const response = await app.inject({ url: '/health/metrics' });
    t.assert.equal(response.statusCode, 200);

    const metrics = response.json();
    for (const key of ['eventLoopDelay', 'eventLoopUtilized', 'heapUsed', 'rssBytes']) {
      t.assert.equal(typeof metrics[key], 'number', key);
    }
  });

  it('keeps the health routes out of the API contract', async (t) => {
    const spec = (await app.inject({ url: '/openapi.json' })).json();
    t.assert.equal(Object.keys(spec.paths).some((path) => path.startsWith('/health')), false);
  });
});
Enter fullscreen mode Exit fullscreen mode

Measure before and after

Never optimize on intuition. autocannon gives you requests per second and latency percentiles in a few seconds:

npm run build && npm start
Enter fullscreen mode Exit fullscreen mode

and, in a second terminal:

npx autocannon -c 100 -d 30 http://localhost:3000/health
Enter fullscreen mode Exit fullscreen mode

Three rules for a measurement you can trust:

  • Run it against the built output, not against node --watch.
  • Mind the rate limiter. /health is not limited (chapter 14), so it measures the framework's overhead. To benchmark a real route you need a token in the request (-H "authorization=Bearer ...") and a higher max in the rate limiter for the duration of the test, or most of your responses will be 429s.
  • Compare the p99 latency rather than the average: the tail is what users notice.

For deeper analysis, node --cpu-prof shows where the time actually goes.


⬅️ Previous chapter: Logging · ➡️ Next chapter: Production deployment

This article is part of the "Fastify with TypeScript" series — chapter 17 of 18.

Top comments (0)