Where does Fastify's speed advantage over Express come from?

Express is the long-standing minimalist Node.js web framework. It wraps Node's http module with a router and a middleware stack, where each request flows through (req, res, next) functions in registration order. Fastify is a newer web framework designed around low per-request overhead. It does not change the event loop or the HTTP parser. Its speed comes from doing less work per request in three places.

JSON serialization compiled from schemas

When you declare a response schema on a Fastify route, Fastify uses fast-json-stringify to generate a serializer for that exact shape at startup. JSON.stringify has to inspect each value's type at runtime. The generated function already knows the keys and types, so it skips most of that inspection. It also drops properties that are not in the schema. Without a response schema, Fastify falls back to JSON.stringify and this advantage disappears.

Radix-tree routing

Fastify's router, find-my-way, stores routes in a radix tree keyed by path segments. Lookup cost depends on the length of the URL, not on how many routes are registered. Express keeps an ordered list of layers and tests the request path against each layer's pattern until one matches. In apps with many routes, that linear scan adds measurable time to every request.

A shorter request lifecycle

In Express, global middleware is one flat chain. Every function runs on every request it matches, and each next() call adds a step. Fastify runs code at named hooks such as onRequest and preHandler. Hooks are scoped to the plugin context where they are registered, so routes only run the hooks that apply to them.

  EXPRESS (middleware chain)          FASTIFY (hooks + schemas)
+----------------------------+      +--------------------------------+
| HTTP request (node:http)   |      | HTTP request (node:http)       |
+-------------+--------------+      +---------------+----------------+
              v                                     v
+----------------------------+      +--------------------------------+
| Layer list: test path      |      | find-my-way radix tree         |
| against layer 1, 2 ... N   |      | lookup cost ~ URL length,      |
| (linear scan)              |      | not number of routes           |
+-------------+--------------+      +---------------+----------------+
              v                                     v
+----------------------------+      +--------------------------------+
| Global middleware chain    |      | Hooks scoped to plugin ctx     |
| mw1 -> next() -> mw2 ->    |      | onRequest -> preHandler        |
| next() -> ... every match  |      | (only this route's hooks)      |
+-------------+--------------+      +---------------+----------------+
              v                                     v
+----------------------------+      +--------------------------------+
| Route handler              |      | Route handler                  |
+-------------+--------------+      +---------------+----------------+
              v                                     v
+----------------------------+      +--------------------------------+
| JSON.stringify             |      | Serializer compiled at         |
| (runtime type checks on    |      | startup from response schema   |
|  every value)              |      | (fast-json-stringify; drops    |
|                            |      |  keys not in schema)           |
+----------------------------+      +--------------------------------+

An Express request and a Fastify request go through the same stages: routing, middleware or hooks, the handler, and serialization, and each stage shows where Fastify does less work.

Why do hello-world benchmarks overstate the gap?

A hello-world route measures almost nothing except the framework itself: parse the request, find the route, serialize a tiny response. That is the only place where Fastify and Express differ, so the gap looks large. Production handlers spend most of their time waiting on databases, upstream HTTP calls and auth checks. A fixed per-request framework cost becomes a rounding error next to that wait.

Illustrative estimate

This is an illustrative estimate built on assumed inputs, not measurements or benchmark results. Assume Express adds 0.10 ms of framework overhead per request, assume Fastify adds 0.04 ms, and assume the handler waits on one 20 ms database round trip. The real overhead of each framework on your hardware and workload will differ.

Scenario (illustrative, assumed inputs) Express total (assumed) Fastify total (assumed) Fastify advantage (derived from assumptions)
Hello-world (no I/O) 0.10 ms 0.04 ms 60% less time
One 20 ms DB query 20.10 ms 20.04 ms 0.06 ms, about 0.3%

The table is simple arithmetic on the assumed values above. Its point is the shape of the result: the same fixed framework difference that looks large with no I/O becomes a small fraction of total latency once a realistic wait is added.

Throughput follows the same pattern. While a request awaits I/O, the event loop serves other requests. The ceiling therefore usually comes from the connection pool or the upstream service, not the router.

Where the advantage shrinks or reverses

  • Synchronous logging. Writing logs synchronously blocks the event loop on every request. That cost can be larger than any routing difference.
  • Heavy validation. Compiled schemas are fast, but deeply nested or permissive schemas still cost CPU. A Fastify route that validates everything can be slower than an Express route that validates nothing.
  • Large payloads. Parsing and serializing large JSON bodies dominates request time. Fastify's serialization speedup only applies when you define response schemas.
  • CPU-bound handlers. Hashing, compression or template rendering makes the framework's share negligible.

How do you benchmark Fastify vs Express on your own workload?

A fair comparison holds everything constant except the framework. Run both servers on the same machine, the same Node.js version, and the same environment variables, and put the load generator on a separate host so it doesn't compete for CPU. Configure logging the same way in both. Fastify's built-in logger writes JSON per request, while a bare Express app logs nothing, so either enable an equivalent logger in Express or disable logging in both. Otherwise you are measuring log output, not routing.

Write handlers that do the same work. A useful minimal pair is one route per framework that reads a path parameter, queries the same database or cache through the same client and connection pool, and returns the same JSON shape. Give the Fastify version a response schema only if you plan to use schemas in production, and record which variant you tested. Use payload sizes and query patterns taken from real traffic.

Warm up each server before measuring so JIT compilation, connection pools, and caches reach steady state. Then run several measured rounds per framework, alternating between them, and report the spread across runs as well as the mean.

Don't compare peak requests per second. Set a latency target, for example p99 under your SLO. Increase the load from an open-model generator that sends at a fixed arrival rate until p99 crosses that target. The highest throughput each framework sustains below the target is the number that matters for capacity planning.

// bench-server.js: one file, two frameworks, same data layer.
// Run: FRAMEWORK=fastify node bench-server.js  or  FRAMEWORK=express node bench-server.js
const { Pool } = require('pg');

// Same pool settings for both servers, so the database is not the variable.
const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 10 });
const PORT = Number(process.env.PORT || 3000);

// Shared work: identical query and identical JSON shape for both frameworks.
async function getUser(id) {
  const { rows } = await pool.query(
    'SELECT id, name, email FROM users WHERE id = $1',
    [id]
  );
  return rows[0] || null;
}

if (process.env.FRAMEWORK === 'fastify') {
  // Logging off here, and Express below has no logger, so neither pays for log output.
  const app = require('fastify')({ logger: false });
  app.get('/users/:id', async (request, reply) => {
    const user = await getUser(request.params.id);
    if (!user) return reply.code(404).send({ error: 'not found' });
    return user;
  });
  app.listen({ port: PORT, host: '0.0.0.0' });
} else {
  const app = require('express')();
  app.get('/users/:id', async (req, res) => {
    try {
      const user = await getUser(req.params.id);
      if (!user) return res.status(404).json({ error: 'not found' });
      res.json(user);
    } catch (err) {
      // Express 4 does not catch rejected promises, so handle errors explicitly.
      res.status(500).json({ error: 'internal' });
    }
  });
  app.listen(PORT, '0.0.0.0');
}

A single server script that runs either Fastify or Express with logging disabled, the same pg connection pool, the same query, and the same JSON response, so a load test against either one varies only the framework.

How do Fastify plugins and hooks differ from Express middleware?

Express keeps one flat middleware stack. Every app.use() call appends to it, and execution order equals registration order. A router mounted under a path prefix narrows where middleware runs, but anything attached to req or app is visible everywhere. In a large codebase, this makes ordering bugs easy to introduce and hard to trace.

Fastify builds a tree instead. Each register() call creates an encapsulation context, a child scope that inherits hooks, decorators and the error handler from its parent. Anything the child adds stays inside the child. A plugin that decorates the instance with a database client, or adds an auth hook, affects only its own subtree. This is why two route groups can carry different auth schemes or error handlers without conditional checks.

Concern Express Fastify
Scope Global stack, path-filtered Encapsulated plugin tree
Shared state Mutate req/app decorate, decorateRequest, decorateReply
Lifecycle Single (req, res, next) shape Named hooks: onRequest, preParsing, preValidation, preHandler, preSerialization, onSend, onResponse, onError
Async errors Historically required next(err) or a wrapper; newer majors forward rejected promises Throwing in an async hook or handler routes the error to the scoped error handler

Named hooks let you place work at a specific stage. For example, preHandler runs after body validation, and onSend can change the serialized payload.

The learning curve comes from encapsulation itself. A decorator registered in one plugin is undefined in a sibling plugin, which surprises engineers coming from Express. The usual workaround is wrapping the plugin in fastify-plugin, which skips encapsulation and exposes its decorators to the parent scope. That approach suits genuinely shared infrastructure. Applying it reflexively to silence errors recreates Express's global namespace and removes the isolation that made Fastify worth adopting.

const fastify = require('fastify')();
const fp = require('fastify-plugin');

// fp() skips encapsulation: 'db' is added to the root instance, so all scopes see it
fastify.register(fp(async function dbPlugin(instance) {
  instance.decorate('db', { query: async (sql) => [{ id: 1, sql }] });
}));

// Encapsulated plugin: its decorator and hook apply only inside this subtree
fastify.register(async function adminScope(instance) {
  instance.decorate('adminLabel', 'admin-area');

  instance.addHook('onRequest', async (request) => {
    if (request.headers['x-admin-token'] !== 'example-token') {
      const err = new Error('Unauthorized');
      err.statusCode = 401;
      throw err; // goes to this scope's error handler, no next(err)
    }
  });

  instance.get('/admin', async () => ({ area: instance.adminLabel }));
});

// Sibling scope: inherits root decorators but not the admin scope's additions
fastify.register(async function publicScope(instance) {
  instance.get('/public', async () => ({
    hasDb: instance.hasDecorator('db'),                 // true, exposed by fp()
    hasAdminLabel: instance.hasDecorator('adminLabel'), // false, encapsulated
    rows: await instance.db.query('SELECT 1')           // admin onRequest hook does not run here
  }));
});

fastify.listen({ port: 3000 }).catch((err) => {
  console.error(err);
  process.exit(1);
});

Encapsulation in practice: the admin scope's decorator and onRequest hook do not reach its sibling, the fastify-plugin-wrapped db decorator is visible everywhere, and an error thrown in an async hook goes to the error handler without next(err).

How does schema-first validation save engineering time?

With a validation library in Express, request checking and response shaping are separate jobs that you assemble yourself. You add middleware that validates req.body and returns a 400 response. Then each handler has to remember not to send internal fields. API documentation is a third artifact that is usually written by hand or produced by another tool, and it drifts from both.

Fastify combines these into one declaration. A route's schema option accepts JSON Schema for body, querystring, params and headers, plus a response map keyed by status code. Fastify compiles the request schemas into validators when the route is registered, so invalid input is rejected before your handler runs. It compiles the response schemas into serializers. Because the serializer writes only the properties the schema declares, a handler that returns a full user record cannot leak passwordHash or an internal tenant ID. The leak is prevented by construction, not by a reviewer catching it. The @fastify/swagger plugin reads the same schemas to generate an OpenAPI document, so the docs describe what the server actually enforces.

The stripping behavior also has a downside. If someone adds a field to the handler's output and forgets the response schema, the field disappears without an error or warning. A contract test that compares the response against expected fields catches this.

The second cost is duplication. If you already maintain TypeScript interfaces or another validator, JSON Schema becomes a third copy. To avoid that, generate everything from one source: write schemas with a builder and derive types through Fastify's type providers, or generate schemas from your existing types.

const fastify = require('fastify')({ logger: true });

// One declaration covers request validation, response serialization, and the input for OpenAPI docs.
const createUserSchema = {
  body: {
    type: 'object',
    required: ['email', 'name'],
    properties: {
      email: { type: 'string', format: 'email' },
      name: { type: 'string', minLength: 1 }
    }
  },
  response: {
    // Only these properties are serialized. Anything else the handler returns is dropped.
    201: {
      type: 'object',
      properties: {
        id: { type: 'string' },
        email: { type: 'string' },
        name: { type: 'string' }
      }
    }
  }
};

fastify.post('/users', { schema: createUserSchema }, async (request, reply) => {
  // An invalid body never reaches this point. Fastify has already replied with a 400.
  const user = {
    id: 'usr_123',
    ...request.body,
    passwordHash: '$2b$10$placeholderhashvalue', // not in the schema, so it is never sent
    tenantId: 'tenant_internal_42'               // also stripped by the serializer
  };
  reply.code(201);
  return user;
});

fastify.listen({ port: 3000 });

A Fastify route whose JSON Schema rejects invalid request bodies before the handler runs and serializes only the declared response fields, so passwordHash and tenantId never reach the client.

What are the ecosystem and migration trade-offs?

Express's advantage is age. Almost any concern, such as auth strategies, session stores, upload parsing or rate limiting, has several middleware options, and years of answered questions cover the edge cases. Fastify's core team maintains a smaller set of plugins under the @fastify scope. These tend to track core releases closely. Community plugins beyond that set thin out quickly, and many target an older major version of Fastify.

Download counts tell you little about either ecosystem, because they reflect transitive installs and CI caches rather than active maintenance. Check these signals instead:

Signal What to look for Why it matters
Recent releases Releases within the last several months Shows someone is still shipping fixes
Issue response Maintainer replies to new issues and PRs Predicts how fast your bug gets fixed
Major-version compatibility Declared support for the framework major you run Encapsulation and hook changes break stale plugins
Maintainer count More than one person with publish rights Reduces the risk of abandonment

For migration, a compatibility plugin such as @fastify/express lets Express-style (req, res, next) middleware run inside Fastify. It only covers middleware that relies on Node's raw request and response objects. Anything that depends on Express-specific extensions like res.locals, res.render or Express's req.params will break or need rewriting. Each request that passes through the compatibility layer also skips part of Fastify's optimized path, which erodes the throughput you migrated for.

The lower-risk path is incremental. Put a reverse proxy in front of both apps, then move routes to a new Fastify service one at a time. Share auth by issuing tokens both services can verify, rather than sharing session middleware.

If throughput is the only motivation, compare the rewrite cost with simply adding instances. When the framework accounts for a small share of each request's latency, scaling horizontally is usually cheaper and less risky than a rewrite.

When should you choose Fastify, and when should you stay on Express?

The opposite holds when profiling shows framework overhead (routing, serialization, middleware dispatch) taking a meaningful share of CPU time on hot endpoints. That is typical for high-volume, low-latency services that return small JSON payloads without much I/O. If most latency comes from the database, fix that first. An index or a removed N+1 query will usually save more time than any framework change.

Performance should rarely decide this on its own. These factors often matter more:

Factor Favors Fastify Favors staying on Express
Logging You want structured, low-overhead logging built in You already have a logging setup that works and is widely used
TypeScript You want route types inferred from schemas Your types are maintained by hand and the team accepts that
Validation Many endpoints need strict input and output contracts Validation needs are light or already handled elsewhere
Team experience The team knows encapsulation and the plugin lifecycle The team's Express knowledge is deep and it ships reliably
Onboarding and hiring You can budget time to teach the plugin model You need new hires productive on day one

Express familiarity is a real asset. Almost every Node.js developer has used it, so reviews, debugging, and on-call handoffs are easier.

You don't have to choose all or nothing. You can stay on Express and make targeted optimizations: add schema-based serialization on hot routes, cache responses, or remove middleware that runs on every request. You can also build new services in Fastify and leave stable Express services alone. Either path gives you most of the gains without a rewrite.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to fastify vs express, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.