When it comes to building high-performance APIs in Node.js, Fastify has emerged as a top choice thanks to its low overhead and plugin architecture. Here is how I structure projects at scale.
Why Fastify?
The benchmark numbers speak for themselves. Fastify handles roughly 15K requests per second on modest hardware compared Express’s ~5-6K under similar conditions. But beyond raw throughput there are architectural advantages:
- Schema validation built into request/response lifecycle
- TypeScript-first design with full autocomplete support across decorators
- Decoupled dependency injection through encapsulated plugins
Project Structure
I organize a typical API around feature modules that bundle routes, schemas and domain logic together:
src/
├── plugins/ # Shared services (db, auth)
├── features/
│ ├── users/
│ │ ├── plugin.ts
│ │ ├── types.d.ts
│ │ └── routes.ts
│ └── products/
└── app.ts
Each feature exports a single registration function that ties everything together inside an isolated context. This prevents cross-module pollution naturally via Fastify’s encapsulation model.
Schema Validation Example
Rather than writing manual checks before every endpoint handler we declaratively define shapes using JSON Schema:
fastify.post('/users', {
schema: {
body: {
type: 'object',
required: ['name','email'],
properties: {
name: { type:'string', minLength: 1 },
email: { type:'string', format:'email' }
}
}
},
handler(req, reply) { /* ... */ }
});
Fastify validates automatically before your code runs saving both lines of boilerplate and latency per request. It catches malformed payloads early in the pipeline so business logic only processes clean inputs.
Deploying to Production
For container environments you want graceful shutdown handling enabled via the onClose hook pattern. Pair that with proper logging using Pino (included by default) and monitoring metrics exposed as Prometheus endpoints ready for dashboards.
The ecosystem continues maturing rapidly making this combination increasingly compelling for teams shipping production-grade software today. I’ve deployed services handling millions daily events on these patterns without incident over multiple major releases now. If performance matters alongside developer experience consider giving it serious evaluation next time you spin up infrastructure from scratch!