GuardAPI Logo
GuardAPI

Fix Lack of Resources & Rate Limiting in Fastify

Fastify's performance is a double-edged sword. Out of the box, it's built for speed, but without explicit resource constraints, you're handing attackers a low-cost DoS vector. If you aren't capping request sizes or throttling the firehose, you're one loop away from an OOM kill or thread starvation.

The Vulnerable Pattern

const fastify = require('fastify')();

// VULNERABLE: No global body limits or rate limiting. // An attacker can send massive payloads or flood the event loop. fastify.post(‘/submit’, async (request, reply) => { return { status: ‘processed’ }; });

fastify.listen({ port: 3000 });

The Secure Implementation

To harden Fastify, we implement a multi-layered defense. First, we set 'bodyLimit' in the constructor; this ensures the server rejects oversized payloads at the socket level before they saturate the heap. Second, we integrate '@fastify/rate-limit' to prevent brute-force and volumetric DoS. By defining 'max' requests within a 'timeWindow', we ensure that a single malicious actor cannot monopolize the event loop or downstream database connections. We also set 'connectionTimeout' to automatically reap slow-client connections that attempt to hold file descriptors open indefinitely.

const fastify = require('fastify')({
  // Limit body size to 1MB globally to prevent memory exhaustion
  bodyLimit: 1048576,
  connectionTimeout: 5000
});

// Register rate-limit plugin fastify.register(require(‘@fastify/rate-limit’), { max: 100, timeWindow: ‘1 minute’, // Use a custom key generator (e.g., IP or API Key) keyGenerator: (req) => req.ip });

fastify.post(‘/submit’, async (request, reply) => { return { status: ‘secured’ }; });

fastify.listen({ port: 3000 });

System Alert • ID: 7984
Target: Fastify API
Potential Vulnerability

Your Fastify API might be exposed to Lack of Resources & Rate Limiting

74% of Fastify apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.