Gathering detailed insights and metrics for flame-limit
Gathering detailed insights and metrics for flame-limit
Gathering detailed insights and metrics for flame-limit
Gathering detailed insights and metrics for flame-limit
A smart and flexible rate-limiting middleware compatible with Express, Koa, Fastify, or plain Node.js HTTP servers.
npm install flame-limit
Typescript
Module System
Min. Node Version
Node Version
NPM Version
JavaScript (100%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
12 Stars
6 Commits
1 Forks
1 Watchers
1 Branches
1 Contributors
Updated on May 24, 2025
Latest Version
2.0.1
Package Id
flame-limit@2.0.1
Unpacked Size
25.16 kB
Size
7.51 kB
File Count
9
NPM Version
10.8.1
Node Version
20.16.0
Published on
Apr 22, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
1
A smart, fast, and customizable rate-limiting middleware compatible with Express, Koa, Fastify, or plain Node.js HTTP servers.
1npm install flame-limit
Flame Limit is a powerful rate-limiting library designed to protect your API and server resources from abuse. It provides multiple strategies for limiting requests, customizable configuration options, and support for different server frameworks.
Rate limiting is essential for:
Flame Limit provides three rate-limiting strategies, each with its own strengths and ideal use cases:
Strategy | Description | Pros | Cons | Best For |
---|---|---|---|---|
Fixed Window | Limits requests in fixed time windows (e.g., 100 req/minute at clock-time boundaries) | ✅ Simple implementation ✅ Low memory usage ✅ Predictable reset times | ❌ Burst traffic at window boundaries ❌ Less fair at window edges | - General purpose rate limiting - Simple APIs - When predictable reset times matter |
Sliding Window | Distributes limits proportionally across two time windows | ✅ Smoother rate limiting ✅ Prevents boundary bursts ✅ More accurate limiting | ❌ Higher complexity ❌ Slightly more resource intensive | - Public APIs - When preventing traffic spikes is important - User-facing services |
Token Bucket | Allows for burst traffic with a continuous refill rate | ✅ Allows controlled bursts ✅ Natural traffic patterns ✅ Adapts to usage patterns | ❌ Refill logic is more complex ❌ Less predictable limits | - Bursty workloads - Client SDKs - When some bursts are acceptable |
Backend | Description | Pros | Cons | Best For |
---|---|---|---|---|
Memory | Stores rate-limit data in application memory | ✅ Fast access ✅ Zero dependencies ✅ Simple setup | ❌ Not shared between nodes ❌ Lost on restart ❌ Memory consumption | - Single server setups - Development - Small to medium traffic |
Redis | Stores rate-limit data in a Redis database | ✅ Shared across nodes ✅ Persists across restarts ✅ Scalable | ❌ External dependency ❌ Slightly higher latency ❌ Additional operational overhead | - Clusters/multiple servers - High availability setups - Production environments |
1const express = require('express'); 2const flameLimit = require('flame-limit'); 3 4const app = express(); 5 6// Basic usage with defaults (100 requests per minute, fixed window) 7app.use(flameLimit()); 8 9// Advanced usage 10app.use(flameLimit({ 11 limit: 50, // 50 requests per window 12 windowMs: 15 * 60 * 1000, // 15 minutes 13 strategy: 'sliding', // Use sliding window algorithm 14 backend: 'memory', // Use in-memory storage 15 weightByPath: true, // Enable path-based weights 16 weights: { 17 '/api/search': 5, // Search endpoint costs 5 points 18 '/api/products/*': 2, // Product endpoints cost 2 points 19 '^/admin.*$': 10 // Admin routes cost 10 points 20 } 21})); 22 23app.listen(3000);
1const Koa = require('koa'); 2const flameLimit = require('flame-limit'); 3 4const app = new Koa(); 5 6// Middleware adapter for Koa 7const koaAdapter = (middleware) => { 8 return async (ctx, next) => { 9 return new Promise((resolve, reject) => { 10 middleware(ctx.req, ctx.res, (err) => { 11 if (err) reject(err); 12 else resolve(next()); 13 }); 14 }); 15 }; 16}; 17 18// Apply rate limiting 19app.use(koaAdapter(flameLimit({ 20 limit: 100, 21 windowMs: 60000 22}))); 23 24app.listen(3000);
1const fastify = require('fastify')(); 2const flameLimit = require('flame-limit'); 3 4const limiter = flameLimit({ 5 limit: 100, 6 windowMs: 60000, 7 strategy: 'token' 8}); 9 10// Register as middleware 11fastify.addHook('onRequest', (request, reply, done) => { 12 limiter(request.raw, reply.raw, (err) => { 13 if (err) { 14 reply.send(err); 15 return; 16 } 17 done(); 18 }); 19}); 20 21fastify.listen({ port: 3000 });
1const http = require('http'); 2const flameLimit = require('flame-limit'); 3 4const limiter = flameLimit({ 5 limit: 100, 6 windowMs: 60000 7}); 8 9const server = http.createServer((req, res) => { 10 // Apply rate limiting 11 limiter(req, res, (err) => { 12 if (err) { 13 return; 14 } 15 16 // Your server logic here 17 res.writeHead(200, { 'Content-Type': 'text/plain' }); 18 res.end('Hello World!'); 19 }); 20}); 21 22server.listen(3000);
1const flameLimit = require('flame-limit'); 2const redis = require('redis'); 3 4// Create Redis client 5const redisClient = redis.createClient({ url: 'redis://localhost:6379' }); 6(async () => { await redisClient.connect(); })(); 7 8// Configure rate limiter 9const limiter = flameLimit({ 10 // Basic settings 11 limit: 200, // Maximum requests per window 12 windowMs: 60 * 1000, // Window size in milliseconds (1 minute) 13 14 // Strategy selection 15 strategy: 'sliding', // 'fixed', 'sliding', or 'token' 16 17 // Storage backend 18 backend: 'redis', // 'memory' or 'redis' 19 redisClient: redisClient, // Redis client instance 20 keyPrefix: 'myapp:ratelimit:', // Key prefix for Redis 21 22 // Path weighting 23 weightByPath: true, // Enable path-based weighting 24 weights: { 25 '/api/public/*': 1, // Low weight for public endpoints 26 '/api/user/*': 5, // Medium weight for user actions 27 '/api/admin/*': 10 // High weight for admin actions 28 }, 29 30 // Client identification 31 trustProxy: true, // Trust X-Forwarded-For header 32 identifierFn: (req) => { // Custom identifier function 33 // Use API key from query or header 34 return req.query.api_key || req.headers['x-api-key'] || req.ip; 35 }, 36 37 // Response customization 38 onLimit: (req, res, next, resetTime) => { 39 res.statusCode = 429; 40 res.setHeader('Content-Type', 'application/json'); 41 res.end(JSON.stringify({ 42 error: 'Too Many Requests', 43 retryAfter: Math.ceil((resetTime - Date.now()) / 1000) 44 })); 45 } 46});
The identifierFn
option allows you to define how clients are identified for rate limiting purposes. This is powerful for creating sophisticated rate-limiting schemes.
1// Limit by API key 2flameLimit({ 3 identifierFn: (req) => req.headers['x-api-key'] || 'anonymous' 4}); 5 6// Limit by user ID (after authentication) 7flameLimit({ 8 identifierFn: (req) => req.user?.id || req.ip 9}); 10 11// Limit by combination of factors 12flameLimit({ 13 identifierFn: (req) => { 14 const ip = req.ip || req.connection?.remoteAddress; 15 const userAgent = req.headers['user-agent'] || 'unknown'; 16 return `${ip}:${userAgent.substring(0, 20)}`; 17 } 18}); 19 20// Differentiate between authenticated and anonymous users 21flameLimit({ 22 identifierFn: (req) => { 23 if (req.user?.id) { 24 // Authenticated users get their own rate limit 25 return `user:${req.user.id}`; 26 } else { 27 // Anonymous requests are rate limited by IP 28 return `ip:${req.ip}`; 29 } 30 } 31});
Consideration | Recommendation |
---|---|
High Availability | Use Redis backend with proper replication/clustering to avoid single points of failure |
Memory Usage | Monitor memory usage when using in-memory backend; large numbers of unique users can cause memory growth |
Security | Use HTTPS and validate client IPs or tokens to prevent spoofing |
Performance | Place rate limiting as early as possible in the request pipeline |
Monitoring | Log rate limit events and set up alerts for unusual patterns |
Graceful Degradation | Implement circuit breakers and fallbacks when Redis is unavailable |
Response Headers | Always include rate limit headers (X-RateLimit-* ) for client awareness |
Testing | Load test your rate limits to ensure they behave as expected under stress |
1flameLimit(options);
Option | Type | Default | Description |
---|---|---|---|
limit | Number | 100 | Maximum number of requests allowed per window |
windowMs | Number | 60000 | Time window in milliseconds |
strategy | String | 'fixed' | Rate limiting strategy ('fixed', 'sliding', 'token') |
backend | String | 'memory' | Storage backend ('memory', 'redis') |
redisClient | Object | null | Redis client instance (required when backend is 'redis') |
keyPrefix | String | 'flame-limit:' | Prefix for storage keys |
weightByPath | Boolean | false | Enable path-based request weighting |
weights | Object | {} | Mapping of path patterns to weights |
trustProxy | Boolean | false | Trust X-Forwarded-For header for IP identification |
identifierFn | Function | null | Custom function to generate client identifiers |
onLimit | Function | null | Custom handler for rate-limited requests |
MIT
No vulnerabilities found.
No security vulnerabilities found.