APIs are a critical part of modern web applications, but they are also a common target for abuse—whether from malicious actors, misconfigured scripts, or even enthusiastic users. Two straightforward tools to protect your Express APIs are rate limiting and request slowing. Together, they help you control traffic, reduce the risk of denial-of-service (DoS) attempts, and keep your services responsive for legitimate users.
Key Takeaways
- Rate limiting restricts how many requests a client can make in a given time window to protect your API from abuse and overload.
- Slow down mechanisms delay responses after a threshold of requests, discouraging aggressive or automated traffic without fully blocking it.
- Express apps can easily integrate rate limiting and slow down using established middleware like
express-rate-limitandexpress-slow-down. - Effective configuration depends on your use case: public APIs, login endpoints, and admin tools may need different limits.
- Combining these techniques with logging, monitoring, and security best practices creates a stronger, more resilient API.
Why Rate Limiting Matters for Your API
Any public or semi-public API will eventually receive more requests than you expect. Sometimes it is growth. Sometimes it is a bug in a client app. Other times it is malicious traffic trying to brute-force logins, scrape data, or overload your server.
Without controls, these spikes can:
- Exhaust server resources and slow down your application.
- Increase hosting costs due to unnecessary processing and bandwidth.
- Expose security weaknesses (e.g., credential stuffing or brute-force attacks).
- Impact legitimate users who are simply trying to access your service.
Rate limiting gives you a way to define boundaries. Instead of letting a single IP or token send unlimited requests, you define “fair use” and enforce it in code.
Core Concepts: Rate Limit vs. Slow Down
What Is Rate Limiting?
Rate limiting enforces a hard or soft cap on how many requests a client can make within a defined time frame. For example:
- Max 100 requests per 15 minutes per IP address.
- Max 5 login attempts per minute for a given account.
Once the limit is exceeded, your API typically returns an HTTP 429 Too Many Requests response, optionally with headers indicating when the client can try again. This protects your infrastructure and encourages well-behaved clients to back off.
What Is Slow Down?
Slowing down requests is a more gradual control. Instead of immediately blocking a client that sends many requests, you:
- Allow initial requests with no delay.
- Add a small delay once a threshold is reached.
- Increase delays as requests continue.
This strategy is useful when you want to discourage high request volumes (such as scraping or brute-forcing) while still allowing traffic to proceed, just at a controlled pace.
Implementing Rate Limiting in Express
For Node.js and Express, one of the most widely used tools for rate limiting is the express-rate-limit middleware. It is straightforward to configure and works well for many small business and startup use cases.
Adding a Basic Rate Limit
First, install the package:
(Run in your project root)
npm install express-rate-limit
Then, in your Express app:
// app.js or index.js
const express = require('express');
const rateLimit = require('express-rate-limit');
const app = express();
// Basic rate limiter: 100 requests per 15 minutes per IP
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100,
standardHeaders: true, // Return rate limit info in the RateLimit-* headers
legacyHeaders: false, // Disable the X-RateLimit-* headers
});
// Apply to all /api routes
app.use('/api', apiLimiter);
app.get('/api/example', (req, res) => {
res.json({ message: 'This is a rate-limited endpoint.' });
});
app.listen(3000, () => console.log('Server started on port 3000'));
Key options:
windowMs: The time window for the limit (in milliseconds).max: Maximum number of requests per window per client.standardHeadersandlegacyHeaders: Control how rate limit headers are returned.
Customizing Responses and Limits Per Route
You might want stricter limits on sensitive endpoints such as login or password reset. You can define separate limiters and custom messages:
// Stricter limiter for authentication routes
const authLimiter = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
max: 5, // 5 attempts per window
message: {
error: 'Too many login attempts. Please try again in a few minutes.',
},
});
// Apply only to /auth routes
app.use('/auth', authLimiter);
This makes it much harder for attackers to rapidly guess passwords or tokens, while honest users will usually never hit the limit.
Implementing Slow Down in Express
If you want a more gradual response to heavy usage, you can use express-slow-down. This middleware introduces a growing delay after a certain number of requests, instead of blocking outright.
Setting Up Request Slow Down
Install the package:
npm install express-slow-down
Then configure it in your app:
const slowDown = require('express-slow-down');
// Slow down after 50 requests per 15 minutes
const speedLimiter = slowDown({
windowMs: 15 * 60 * 1000, // 15 minutes
delayAfter: 50, // allow 50 requests without delay
delayMs: 500, // add 500ms delay per request above 50
});
// Apply to all API routes
app.use('/api', speedLimiter);
With this configuration:
- Requests 1–50: No added delay.
- Request 51: 500ms delay.
- Request 52: 1000ms delay.
- Request 53: 1500ms delay, and so on.
The more aggressively a client sends requests, the slower their responses become. This makes abusive behavior less effective and more expensive, while regular user traffic is rarely affected.
Combining Rate Limit and Slow Down
In many scenarios, using both strategies together provides stronger protection. For example, you might:
- Use slow down to discourage moderate bursts of traffic.
- Use rate limiting as a hard cap to stop extreme abuse.
A simple pattern is:
- Apply
express-slow-downfirst to introduce delay. - Apply
express-rate-limitnext to enforce a maximum.
// Apply slow down first, then rate limit
app.use('/api',
speedLimiter, // soft control: adds delay after threshold
apiLimiter // hard control: returns 429 after maximum is exceeded
);
Be sure to test your configuration under expected and edge traffic patterns so you do not unintentionally harm normal users or internal tools.
Designing Limits That Match Your Business
There is no universal “correct” rate limit. Your choices should reflect how your application is used and the cost of each request.
Questions to Guide Your Configuration
- What is a normal user workflow? A dashboard user might make a few dozen API calls per minute; an automated integration might make more.
- How heavy are your requests? Expensive operations (search, report generation, external API calls) justify stricter limits.
- How sensitive is the endpoint? Login, signup, and payment APIs should usually have tighter controls than read-only data endpoints.
- Do you have known high-volume clients? You may want different limits based on API keys, plans, or roles.
Practical Patterns
- Public read APIs: Moderate limits with gentle slow down; higher caps for authenticated or paying users.
- Authentication endpoints: Very low limits and shorter windows to reduce brute-force attempts.
- Administrative tools: Reasonable limits but with additional protections such as IP allowlists or VPN access.
Operational Best Practices
Adding rate limiting and slow down is only part of a secure and stable API strategy. To get the most value from these mechanisms:
- Log exceeded limits: Log when clients hit thresholds so you can identify problem patterns, bots, or misconfigurations.
- Monitor in production: Track 429 responses and latency from slow down to ensure you are not harming real users.
- Communicate limits to clients: Document your rate limits in your API docs so integrators can design around them.
- Use appropriate identifiers: By default, IP-based limits work for many cases, but for authenticated APIs you may want to limit by user ID, API key, or tenant.
- Combine with other security layers: Use HTTPS, validation, authentication, authorization, and input sanitization alongside rate controls.
Conclusion: Build Safer, More Reliable Express APIs
Rate limiting and slow down middleware give you practical, low-friction ways to protect your Express APIs against abuse and unexpected traffic spikes. With a few lines of configuration, you can:
- Shield your infrastructure from overload.
- Reduce the impact of bots and brute-force attacks.
- Keep your services responsive for legitimate users.
As your application grows, revisit your limits, monitor real-world usage, and refine your configuration. Thoughtful rate control is not just about security—it is also about predictable performance and a smoother experience for your customers and integration partners.
Need Help Hardening and Scaling Your API?
If you want support designing, implementing, and tuning Express APIs—including security controls, performance optimizations, and deployment best practices—Izende Studio Web can help you move faster with fewer surprises.
Explore our web application and API development services to see how we can help you build safer, more reliable systems for your business.
