Skip to main content
command CX Codex

setup-rate-limiting · davepoon — Claude Code command: setup and install

setup-rate-limiting is a Claude Code command for planning and adding API request limits. It covers quotas by user and endpoint.

MIT ★ 3,785 updated 2026-10-25

Install into Claude Code · Plugin marketplace All methods and platforms ↓
/plugin marketplace add davepoon/buildwithclaude
/plugin install all-commands@buildwithclaude
Open on GitHub

What setup-rate-limiting does

The command guides API traffic and endpoint analysis, policy planning for user groups, and design for limits shared across servers. Its Express.js example uses express-rate-limit with rate-limit-redis and ioredis. It sets up general API, sensitive-operation, and authentication limiters, plus factories for tier-based and endpoint-specific quotas.

The instructions also include token bucket logic and a Redis-backed variant for distributed use. The Express.js setup reads its Redis connection from REDIS_URL, so that variable must be configured for the example to connect. The command includes implementation code alongside planning guidance.

What it helps with

  • plan request quotas for API endpoints
  • throttle login attempts and sensitive operations
  • set different limits by user tier
  • share rate-limit state across servers with Redis
  • choose a request-limiting strategy

Example prompts for the agent

  • Set up API request limits in my Express.js project with Redis.
  • Add separate limits for login attempts and sensitive endpoints.
  • Plan tier-based quotas and a distributed token bucket.

How to install setup-rate-limiting

1Plugin marketplace

/plugin marketplace add davepoon/buildwithclaude
/plugin install all-commands@buildwithclaude

2Manually: put the files in place

.claude/commands/setup-rate-limiting.md

Call it with /setup-rate-limiting. For all projects use ~/.claude/commands/

Questions about setup-rate-limiting

How do I install setup-rate-limiting in Claude Code?

Run /plugin marketplace add davepoon/buildwithclaude, then /plugin install all-commands@buildwithclaude. The command file is at .claude/commands/setup-rate-limiting.md.

What does setup-rate-limiting do?

It helps plan and implement API request limits, including authentication and endpoint quotas, tier-based limits, and token bucket logic.

What does the Express.js example need to connect to Redis?

It uses express-rate-limit, rate-limit-redis, and ioredis. The Redis connection is read from REDIS_URL.

Source text

setup-rate-limiting.md · MIT
---
description: Implement API rate limiting
category: project-setup
---

# Setup Rate Limiting

Implement API rate limiting

## Instructions

1. **Rate Limiting Strategy and Planning**
   - Analyze API endpoints and traffic patterns
   - Define rate limiting policies for different user types and endpoints
   - Plan for distributed rate limiting across multiple servers
   - Consider different rate limiting algorithms (token bucket, sliding window, etc.)
   - Design rate limiting bypass mechanisms for trusted clients

2. **Express.js Rate Limiting Implementation**
   - Set up comprehensive rate limiting middleware:

   **Basic Rate Limiting Setup:**
   ```javascript
   // middleware/rate-limiter.js
   const rateLimit = require('express-rate-limit');
   const RedisStore = require('rate-limit-redis');
   const Redis = require('ioredis');

   class RateLimiter {
     constructor() {
       this.redis = new Redis(process.env.REDIS_URL);
       this.setupDefaultLimiters();
     }

     setupDefaultLimiters() {
       // General API rate limiter
       this.generalLimiter = rateLimit({
         store: new RedisStore({
           sendCommand: (...args) => this.redis.call(...args),
         }),
         windowMs: 15 * 60 * 1000, // 15 minutes
         max: 1000, // Limit each IP to 1000 requests per windowMs
         message: {
           error: 'Too many requests from this IP',
           retryAfter: '15 minutes'
         },
         standardHeaders: true,
         legacyHeaders: false,
         keyGenerator: (req) => {
           // Use user ID if authenticated, otherwise IP
           return req.user?.id || req.ip;
         },
         skip: (req) => {
           // Skip rate limiting for internal requests
           return req.headers['x-internal-request'] === 'true';
         },
         onLimitReached: (req, res, options) => {
           console.warn('Rate limit reached:', {
             ip: req.ip,
             userAgent: req.get('User-Agent'),
             endpoint: req.path,
             timestamp: new Date().toISOString()
           });
         }
       });

       // Strict limiter for sensitive endpoints
       this.strictLimiter = rateLimit({
         store: new RedisStore({
           sendCommand: (...args) => this.redis.call(...args),
         }),
         windowMs: 60 * 60 * 1000, // 1 hour
         max: 5, // Very strict limit
         message: {
           error: 'Too many attempts for this sensitive operation',
           retryAfter: '1 hour'
         },
         skipSuccessfulRequests: true,
         keyGenerator: (req) => `${req.user?.id || req.ip}:${req.path}`
       });

       // Authentication rate limiter
       this.authLimiter = rateLimit({
         store: new RedisStore({
           sendCommand: (...args) => this.redis.call(...args),
         }),
         windowMs: 15 * 60 * 1000, // 15 minutes
         max: 5, // Limit login attempts
         skipSuccessfulRequests: true,
         keyGenerator: (req) => `auth:${req.ip}:${req.body.email || req.body.username}`,
         message: {
           error: 'Too many authentication attempts',
           retryAfter: '15 minutes'
         }
       });
     }

     // Dynamic rate limiter based on user tier
     createTierBasedLimiter(windowMs = 15 * 60 * 1000) {
       return rateLimit({
         store: new RedisStore({
           sendCommand: (...args) => this.redis.call(...args),
         }),
         windowMs,
         max: (req) => {
           const user = req.user;
           if (!user) return 100; // Anonymous users
           
           switch (user.tier) {
             case 'premium': return 10000;
             case 'pro': return 5000;
             case 'basic': return 1000;
             default: return 500;
           }
         },
         keyGenerator: (req) => `tier:${req.user?.id || req.ip}`,
         message: (req) => ({
           error: 'Rate limit exceeded for your tier',
           currentTier: req.user?.tier || 'anonymous',
           upgradeUrl: '/upgrade'
         })
       });
     }

     // Endpoint-specific rate limiter
     createEndpointLimiter(endpoint, config) {
       return rateLimit({
         store: new RedisStore({
           sendCommand: (...args) => this.redis.call(...args),
         }),
         windowMs: config.windowMs || 60 * 1000,
         max: config.max || 100,
         keyGenerator: (req) => `endpoint:${endpoint}:${req.user?.id || req.ip}`,
         message: {
           error: `Rate limit exceeded for ${endpoint}`,
           limit: config.max,
           window: config.windowMs
         },
         ...config
       });
     }
   }

   module.exports = new RateLimiter();
   ```

3. **Advanced Rate Limiting Algorithms**
   - Implement sophisticated rate limiting strategies:

   **Token Bucket Implementation:**
   ```javascript
   // rate-limiters/token-bucket.js
   class TokenBucket {
     constructor(capacity, refillRate, refillPeriod = 1000) {
       this.capacity = capacity;
       this.tokens = capacity;
       this.refillRate = refillRate;
       this.refillPeriod = refillPeriod;
       this.lastRefill = Date.now();
     }

     consume(tokens = 1) {
       this.refill();
       
       if (this.tokens >= tokens) {
         this.tokens -= tokens;
         return true;
       }
       
       return false;
     }

     refill() {
       const now = Date.now();
       const timePassed = now - this.lastRefill;
       const tokensToAdd = Math.floor(timePassed / this.refillPeriod) * this.refillRate;
       
       this.tokens = Math.min(this.capacity, this.tokens + tokensToAdd);
       this.lastRefill = now;
     }

     getAvailableTokens() {
       this.refill();
       return this.tokens;
     }

     getTimeToNextToken() {
       if (this.tokens > 0) return 0;
       
       const timeSinceLastRefill = Date.now() - this.lastRefill;
       return this.refillPeriod - (timeSinceLastRefill % this.refillPeriod);
     }
   }

   // Redis-backed token bucket for distributed systems
   class DistributedTokenBucket {
     constructor(redis, key, capacity, refillRate, refillPeriod = 1000) {
       this.redis = redis;
       this.key = key;
       this.capacity = capacity;
       this.refillRate = refillRate;
       this.refillPeriod = refillPeriod;
     }

     async consume(tokens = 1) {
       const script = `
         local key = KEYS[1]
         local capacity = tonumber(ARGV[1])
         local refillRate = tonumber(ARGV[2])
         local refillPeriod = tonumber(ARGV[3])
         local tokensRequested = tonumber(ARGV[4])
         local now = tonumber(ARGV[5])
         
         local bucket = redis.call('HMGET', key, 'tokens', 'lastRefill')
         local tokens = tonumber(bucket[1]) or capacity
         local lastRefill = tonumber(bucket[2]) or now
         
         -- Calculate tokens to add
         local timePassed = now - lastRefill
         local tokensToAdd = math.floor(timePassed / refillPeriod) * refillRate
         tokens = math.min(capacity, tokens + tokensToAdd)
         
         local success = 0
         if tokens >= tokensRequested then
           tokens = tokens - tokensRequested
           success = 1
         end
         
         -- Update bucket
         redis.call('HMSET', key, 'tokens', tokens, 'lastRefill', now)
         redis.call('EXPIRE', key, 3600) -- 1 hour TTL
         
         return {success, tokens, math.max(0, refillPeriod - (timePassed % refillPeriod))}
       `;

       const result = await this.redis.eval(
         script,
         1,
         this.key,
         this.capacity,
         this.refillRate,
         this.refillPeriod,
         tokens,
         Date.now()
       );

       return {
         allowed: result[0] === 1,
         tokensRemaining: result[1],
         timeToNextToken: result[2]
       };
     }
   }

   module.exports = { TokenBucket, DistributedTokenBucket };
   ```

   **Sliding Window Rate Limiter:**
   ```javascript
   // rate-limiters/sliding-window.js
   class SlidingWindowRateLimiter {
     constructor(redis, windowSize, maxRequests) {
       this.redis = redis;
       this.windowSize = windowSize; // in milliseconds
       this.maxRequests = maxRequests;
     }

     async isAllowed(key) {
       const now = Date.now();
       const windowStart = now - this.windowSize;

       const script = `
         local key = KEYS[1]
         local windowStart = tonumber(ARGV[1])
         local now = tonumber(ARGV[2])
         local maxRequests = tonumber(ARGV[3])
         
         -- Remove old entries
         redis.call('ZREMRANGEBYSCORE', key, 0, windowStart)
         
         -- Count current requests in window
         local currentCount = redis.call('ZCARD', key)
         
         if currentCount < maxRequests then
           -- Add current request
           redis.call('ZADD', key, now, now)
           redis.call('EXPIRE', key, math.ceil(ARGV[4] / 1000))
           return {1, currentCount + 1, maxRequests - currentCount - 1}
         else
           return {0, currentCount, 0}
         end
       `;

       const result = await this.redis.eval(
         script,
         1,
         key,
         windowStart,
         now,
         this.maxRequests,
         this.windowSize
       );

       return {
         allowed: result[0] === 1,
         currentCount: result[1],
         remaining: result[2]
       };
     }

     async getRemainingRequests(key) {
       const now = Date.now();
       const windowStart = now - this.windowSize;
       
       await this.redis.zremrangebyscore(key, 0, windowStart);
       const currentCount = await this.redis.zcard(key);
       
       return Math.max(0, this.maxRequests - currentCount);
     }
   }

   module.exports = SlidingWindowRateLimiter;
   ```

4. **Custom Rate Limiting Middleware**
   - Build flexible rate limiting solutions:

   **Advanced Rate Limiting Middleware:**
   ```javascript
   // middleware/advanced-rate-limiter.js
   const { TokenBucket, DistributedTokenBucket } = require('../rate-limiters/token-bucket');
   const SlidingWindowRateLimiter = require('../rate-limiters/sliding-window');

   class AdvancedRateLimiter {
     constructor(redis) {
       this.redis = redis;
       this.rateLimiters = new Map();
       this.setupRateLimiters();
     }

     setupRateLimiters() {
       // API endpoints with different limits
       this.rateLimiters.set('api:general', {
         type: 'sliding-window',
         limiter: new SlidingWindowRateLimiter(this.redis, 60000, 1000) // 1000 req/min
       });

       this.rateLimiters.set('api:upload', {
         type: 'token-bucket',
         capacity: 10,
         refillRate: 1,
         refillPeriod: 10000 // 1 token per 10 seconds
       });

       this.rateLimiters.set('api:search', {
         type: 'sliding-window',
         limiter: new SlidingWindowRateLimiter(this.redis, 60000, 100) // 100 req/min
       });
     }

     createMiddleware(limiterKey, options = {}) {
       return async (req, res, next) => {
         try {
           const userKey = this.generateUserKey(req, limiterKey);
           const config = this.rateLimiters.get(limiterKey);

           if (!config) {
             return next(); // No rate limiting configured
           }

           let result;
           
           if (config.type === 'sliding-window') {
             result = await config.limiter.isAllowed(userKey);
           } else if (config.type === 'token-bucket') {
             const bucket = new DistributedTokenBucket(
               this.redis,
               userKey,
               config.capacity,
               config.refillRate,
               config.refillPeriod
             );
             result = await bucket.consume(options.tokensRequired || 1);
           }

           // Set rate limit headers
           this.setRateLimitHeaders(res, result, config);

           if (!result.allowed) {
             return res.status(429).json({
               error: 'Rate limit exceeded',
               retryAfter: this.calculateRetryAfter(result, config),
               remaining: result.remaining || 0
             });
           }

           // Add rate limit info to request
           req.rateLimit = result;
           next();

         } catch (error) {
           console.error('Rate limiting error:', error);
           next(); // Fail open - don't block requests on rate limiter errors
         }
       };
     }

     generateUserKey(req, limiterKey) {
       const userId = req.user?.id || req.ip;
       const endpoint = req.route?.path || req.path;
       return `${limiterKey}:${userId}:${endpoint}`;
     }

     setRateLimitHeaders(res, result, config) {
       if (result.remaining !== undefined) {
         res.set('X-RateLimit-Remaining', result.remaining.toString());
       }
       
       if (result.currentCount !== undefined) {
         res.set('X-RateLimit-Used', result.currentCount.toString());
       }

       if (config.type === 'sliding-window') {
         res.set('X-RateLimit-Limit', config.limiter.maxRequests.toString());
         res.set('X-RateLimit-Window', (config.limiter.windowSize / 1000).toString());
       } else if (config.type === 'token-bucket') {
         res.set('X-RateLimit-Limit', config.capacity.toString());
       }
     }

     calculateRetryAfter(result, config) {
       if (result.timeToNextToken) {
         return Math.ceil(result.timeToNextToken / 1000);
       }
       
       if (config.type === 'sliding-window') {
         return Math.ceil(config.limiter.windowSize / 1000);
       }
       
       return 60; // Default 1 minute
     }

     // Dynamic rate limiting based on system load
     createAdaptiveLimiter(baseLimit) {
       return async (req, res, next) => {
         const systemLoad = await this.getSystemLoad();
         let dynamicLimit = baseLimit;

         // Reduce limits during high load
         if (systemLoad > 0.8) {
           dynamicLimit = Math.floor(baseLimit * 0.5);
         } else if (systemLoad > 0.6) {
           dynamicLimit = Math.floor(baseLimit * 0.7);
         }

         // Apply dynamic limit
         const limiter = new SlidingWindowRateLimiter(this.redis, 60000, dynamicLimit);
         const userKey = this.generateUserKey(req, 'adaptive');
         const result = await limiter.isAllowed(userKey);

         res.set('X-RateLimit-Adaptive', 'true');
         res.set('X-RateLimit-System-Load', systemLoad.toString());
         
         if (!result.allowed) {
           return res.status(429).json({
             error: 'Rate limit exceeded (adaptive)',
             systemLoad: systemLoad,
             retryAfter: 60
           });
         }

         next();
       };
     }

     async getSystemLoad() {
       // Get system metrics (CPU, memory, etc.)
       const os = require('os');
       const loadAvg = os.loadavg()[0]; // 1-minute load average
       const cpuCount = os.cpus().length;
       return Math.min(1, loadAvg / cpuCount);
     }
   }

   module.exports = AdvancedRateLimiter;
   ```

5. **API Quota Management**
   - Implement comprehensive quota systems:

   **Quota Management System:**
   ```javascript
   // services/quota-manager.js
   class QuotaManager {
     constructor(redis, database) {
       this.redis = redis;
       this.database = database;
       this.quotaTypes = {
         'api_calls': { resetPeriod: 'monthly', defaultLimit: 10000 },
         'data_transfer': { resetPeriod: 'monthly', defaultLimit: 1073741824 }, // 1GB in bytes
         'storage': { resetPeriod: 'none', defaultLimit: 5368709120 }, // 5GB
         'concurrent_requests': { resetPeriod: 'none', defaultLimit: 10 }
       };
     }

     async checkQuota(userId, quotaType, amount = 1) {
       const userQuota = await this.getUserQuota(userId, quotaType);
       const currentUsage = await this.getCurrentUsage(userId, quotaType);

       const available = userQuota.limit - currentUsage;
       const allowed = available >= amount;

       if (allowed) {
         await this.incrementUsage(userId, quotaType, amount);
       }

       return {
         allowed,
         usage: currentUsage + (allowed ? amount : 0),
         limit: userQuota.limit,
         remaining: Math.max(0, available - (allowed ? amount : 0)),
         resetDate: userQuota.resetDate
       };
     }

     async getUserQuota(userId, quotaType) {
       // Get user-specific quota from database
       const customQuota = await this.database.query(
         'SELECT * FROM user_quotas WHERE user_id = $1 AND quota_type = $2',
         [userId, quotaType]
       );

       if (customQuota.rows.length > 0) {
         return customQuota.rows[0];
       }

       // Get plan-based quota
       const user = await this.database.query(
         'SELECT plan FROM users WHERE id = $1',
         [userId]
       );

       const planQuota = await this.getPlanQuota(user.rows[0]?.plan || 'free', quotaType);
       return planQuota;
     }

     async getPlanQuota(plan, quotaType) {
       const planQuotas = {
         free: {
           api_calls: 1000,
           data_transfer: 104857600, // 100MB
           storage: 1073741824, // 1GB
           concurrent_requests: 5
         },
         basic: {
           api_calls: 10000,
           data_transfer: 1073741824, // 1GB
           storage: 10737418240, // 10GB
           concurrent_requests: 10
         },
         pro: {
           api_calls: 100000,
           data_transfer: 10737418240, // 10GB
           storage: 107374182400, // 100GB
           concurrent_requests: 50
         },
         enterprise: {
           api_calls: 1000000,
           data_transfer: 107374182400, // 100GB
           storage: 1099511627776, // 1TB
           concurrent_requests: 200
         }
       };

       const limit = planQuotas[plan]?.[quotaType] || this.quotaTypes[quotaType].defaultLimit;
       const resetDate = this.calculateResetDate(quotaType);

       return { limit, resetDate };
     }

     async getCurrentUsage(userId, quotaType) {
       const quotaConfig = this.quotaTypes[quotaType];
       
       if (quotaConfig.resetPeriod === 'none') {
         // Non-resetting quota (like storage)
         const key = `quota:${userId}:${quotaType}:current`;
         const usage = await this.redis.get(key);
         return parseInt(usage) || 0;
       } else {
         // Resetting quota (like monthly API calls)
         const period = this.getCurrentPeriod(quotaConfig.resetPeriod);
         const key = `quota:${userId}:${quotaType}:${period}`;
         const usage = await this.redis.get(key);
         return parseInt(usage) || 0;
       }
     }

     async incrementUsage(userId, quotaType, amount) {
       const quotaConfig = this.quotaTypes[quotaType];
       
       if (quotaConfig.resetPeriod === 'none') {
         const key = `quota:${userId}:${quotaType}:current`;
         await this.redis.incrby(key, amount);
         await this.redis.expire(key, 86400 * 365); // 1 year TTL
       } else {
         const period = this.getCurrentPeriod(quotaConfig.resetPeriod);
         const key = `quota:${userId}:${quotaType}:${period}`;
         await this.redis.incrby(key, amount);
         
         // Set TTL to end of period
         const ttl = this.getTTLForPeriod(quotaConfig.resetPeriod);
         await this.redis.expire(key, ttl);
       }

       // Update usage analytics
       await this.recordUsageAnalytics(userId, quotaType, amount);
     }

     getCurrentPeriod(resetPeriod) {
       const now = new Date();
       
       switch (resetPeriod) {
         case 'daily':
           return now.toISOString().split('T')[0]; // YYYY-MM-DD
         case 'weekly':
           const weekStart = new Date(now);
           weekStart.setDate(now.getDate() - now.getDay());
           return weekStart.toISOString().split('T')[0];
         case 'monthly':
           return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
         case 'yearly':
           return now.getFullYear().toString();
         default:
           return 'current';
       }
     }

     calculateResetDate(quotaType) {
       const config = this.quotaTypes[quotaType];
       if (config.resetPeriod === 'none') return null;

       const now = new Date();
       const resetDate = new Date();

       switch (config.resetPeriod) {
         case 'daily':
           resetDate.setDate(now.getDate() + 1);
           resetDate.setHours(0, 0, 0, 0);
           break;
         case 'weekly':
           resetDate.setDate(now.getDate() + (7 - now.getDay()));
           resetDate.setHours(0, 0, 0, 0);
           break;
         case 'monthly':
           resetDate.setMonth(now.getMonth() + 1, 1);
           resetDate.setHours(0, 0, 0, 0);
           break;
         case 'yearly':
           resetDate.setFullYear(now.getFullYear() + 1, 0, 1);
           resetDate.setHours(0, 0, 0, 0);
           break;
       }

       return resetDate;
     }

     getTTLForPeriod(resetPeriod) {
       const resetDate = this.calculateResetDate({ resetPeriod });
       return Math.ceil((resetDate.getTime() - Date.now()) / 1000);
     }

     async recordUsageAnalytics(userId, quotaType, amount) {
       // Record usage for analytics and billing
       const analyticsKey = `analytics:usage:${userId}:${quotaType}:${new Date().toISOString().split('T')[0]}`;
       await this.redis.incrby(analyticsKey, amount);
       await this.redis.expire(analyticsKey, 86400 * 90); // 90 days retention
     }

     // Middleware for quota checking
     createQuotaMiddleware(quotaType, amountFn = () => 1) {
       return async (req, res, next) => {
         if (!req.user) {
           return next(); // Skip quota check for unauthenticated requests
         }

         const amount = typeof amountFn === 'function' ? amountFn(req) : amountFn;
         const result = await this.checkQuota(req.user.id, quotaType, amount);

         // Set quota headers
         res.set('X-Quota-Type', quotaType);
         res.set('X-Quota-Limit', result.limit.toString());
         res.set('X-Quota-Remaining', result.remaining.toString());
         res.set('X-Quota-Used', result.usage.toString());
         
         if (result.resetDate) {
           res.set('X-Quota-Reset', result.resetDate.toISOString());
         }

         if (!result.allowed) {
           return res.status(429).json({
             error: 'Quota exceeded',
             quotaType: quotaType,
             limit: result.limit,
             usage: result.usage,
             resetDate: result.resetDate
           });
         }

         req.quota = result;
         next();
       };
     }
   }

   module.exports = QuotaManager;
   ```

6. **Rate Limiting for Different Services**
   - Implement service-specific rate limiting:

   **Database Rate Limiting:**
   ```javascript
   // rate-limiters/database-rate-limiter.js
   class DatabaseRateLimiter {
     constructor(redis, pool) {
       this.redis = redis;
       this.pool = pool;
       this.connectionLimiter = new Map();
       this.queryLimiter = new Map();
     }

     // Limit concurrent database connections per user
     async acquireConnection(userId) {
       const key = `db:connections:${userId}`;
       const maxConnections = await this.getMaxConnections(userId);
       
       const script = `
         local key = KEYS[1]
         local maxConnections = tonumber(ARGV[1])
         local ttl = tonumber(ARGV[2])
         
         local current = redis.call('GET', key) or 0
         current = tonumber(current)
         
         if current < maxConnections then
           redis.call('INCR', key)
           redis.call('EXPIRE', key, ttl)
           return 1
         else
           return 0
         end
       `;

       const allowed = await this.redis.eval(script, 1, key, maxConnections, 300); // 5 min TTL
       
       if (!allowed) {
         throw new Error('Database connection limit exceeded');
       }

       return {
         release: async () => {
           await this.redis.decr(key);
         }
       };
     }

     // Rate limit expensive queries
     async checkQueryLimit(userId, queryType, cost = 1) {
       const key = `db:queries:${userId}:${queryType}`;
       const windowMs = 60000; // 1 minute
       const maxCost = await this.getMaxQueryCost(userId, queryType);

       const script = `
         local key = KEYS[1]
         local windowMs = tonumber(ARGV[1])
         local maxCost = tonumber(ARGV[2])
         local cost = tonumber(ARGV[3])
         local now = tonumber(ARGV[4])
         
         local windowStart = now - windowMs
         
         -- Remove old entries
         redis.call('ZREMRANGEBYSCORE', key, 0, windowStart)
         
         -- Get current cost
         local currentCost = 0
         local entries = redis.call('ZRANGE', key, 0, -1, 'WITHSCORES')
         for i = 2, #entries, 2 do
           currentCost = currentCost + tonumber(entries[i])
         end
         
         if currentCost + cost <= maxCost then
           redis.call('ZADD', key, cost, now)
           redis.call('EXPIRE', key, math.ceil(windowMs / 1000))
           return {1, currentCost + cost, maxCost - currentCost - cost}
         else
           return {0, currentCost, maxCost - currentCost}
         end
       `;

       const result = await this.redis.eval(
         script, 1, key, windowMs, maxCost, cost, Date.now()
       );

       return {
         allowed: result[0] === 1,
         currentCost: result[1],
         remaining: result[2]
       };
     }

     async getMaxConnections(userId) {
       // Get from user plan or use default
       const user = await this.getUserPlan(userId);
       const connectionLimits = {
         free: 2,
         basic: 5,
         pro: 20,
         enterprise: 100
       };
       return connectionLimits[user.plan] || 2;
     }

     async getMaxQueryCost(userId, queryType) {
       const user = await this.getUserPlan(userId);
       const costLimits = {
         free: { select: 100, insert: 50, update: 30, delete: 10 },
         basic: { select: 500, insert: 200, update: 100, delete: 50 },
         pro: { select: 2000, insert: 1000, update: 500, delete: 200 },
         enterprise: { select: 10000, insert: 5000, update: 2500, delete: 1000 }
       };
       return costLimits[user.plan]?.[queryType] || 10;
     }
   }
   ```

   **File Upload Rate Limiting:**
   ```javascript
   // rate-limiters/upload-rate-limiter.js
   class UploadRateLimiter {
     constructor(redis) {
       this.redis = redis;
     }

     // Limit file upload size and frequency
     async checkUploadLimit(userId, fileSize, fileType) {
       const checks = await Promise.all([
         this.checkFileSizeLimit(userId, fileSize),
         this.checkUploadFrequency(userId),
         this.checkStorageQuota(userId, fileSize),
         this.checkFileTypeLimit(userId, fileType)
       ]);

       const failed = checks.find(check => !check.allowed);
       if (failed) {
         return failed;
       }

       // Record the upload
       await this.recordUpload(userId, fileSize, fileType);

       return { allowed: true, checks };
     }

     async checkFileSizeLimit(userId, fileSize) {
       const user = await this.getUserPlan(userId);
       const sizeLimits = {
         free: 10 * 1024 * 1024,      // 10MB
         basic: 50 * 1024 * 1024,     // 50MB
         pro: 200 * 1024 * 1024,      // 200MB
         enterprise: 1000 * 1024 * 1024 // 1GB
       };

       const maxSize = sizeLimits[user.plan] || sizeLimits.free;
       const allowed = fileSize <= maxSize;

       return {
         allowed,
         type: 'file_size',
         current: fileSize,
         limit: maxSize,
         message: allowed ? null : `File size ${fileSize} exceeds limit of ${maxSize} bytes`
       };
     }

     async checkUploadFrequency(userId) {
       const key = `uploads:frequency:${userId}`;
       const windowMs = 60000; // 1 minute
       const maxUploads = await this.getMaxUploadsPerMinute(userId);

       const current = await this.redis.incr(key);
       if (current === 1) {
         await this.redis.expire(key, Math.ceil(windowMs / 1000));
       }

       return {
         allowed: current <= maxUploads,
         type: 'upload_frequency',
         current,
         limit: maxUploads,
         window: windowMs
       };
     }

     async checkStorageQuota(userId, fileSize) {
       const key = `storage:used:${userId}`;
       const currentUsage = parseInt(await this.redis.get(key)) || 0;
       const maxStorage = await this.getMaxStorage(userId);

       const allowed = (currentUsage + fileSize) <= maxStorage;

       return {
         allowed,
         type: 'storage_quota',
         current: currentUsage + fileSize,
         limit: maxStorage,
         fileSize
       };
     }

     async checkFileTypeLimit(userId, fileType) {
       const allowedTypes = await this.getAllowedFileTypes(userId);
       const allowed = allowedTypes.includes(fileType);

       return {
         allowed,
         type: 'file_type',
         fileType,
         allowedTypes,
         message: allowed ? null : `File type ${fileType} not allowed`
       };
     }

     async recordUpload(userId, fileSize, fileType) {
       const now = Date.now();
       
       // Update storage usage
       await this.redis.incrby(`storage:used:${userId}`, fileSize);
       
       // Record upload in analytics
       const analyticsKey = `analytics:uploads:${userId}:${new Date().toISOString().split('T')[0]}`;
       await this.redis.hincrby(analyticsKey, 'count', 1);
       await this.redis.hincrby(analyticsKey, 'bytes', fileSize);
       await this.redis.expire(analyticsKey, 86400 * 30); // 30 days
     }

     createUploadMiddleware() {
       return async (req, res, next) => {
         if (!req.user) {
           return res.status(401).json({ error: 'Authentication required' });
         }

         // Check if this is a file upload
         if (!req.files || !req.files.length) {
           return next();
         }...

© BuildWithClaude Community · MIT · davepoon/buildwithclaude

Similar slash commands

All slash commands for Backend and APIs →

setup-rate-limiting by other authors comes first.

setup-rate-limiting davila7 setup-rate-limiting — a slash command that inspects your project and builds a rate limiting setup: algorithms, per-user quotas, counter storage. CX Codex +1 247installs api-rate-limiting secondsky api-rate-limiting is a Claude Code skill for adding request limits to APIs. It activates for public API protection, tier-based access, or denial-of-service prevention. CX Codex +1 515installs rate-limiting-implementation aj-geddes rate-limiting-implementation — a skill that walks your agent through adding rate limiting, quotas and backpressure to a service. Useful when an API is public or traffic keeps growing. CX Codex +1 508installs rate-limiting-abuse-protection patricio0312rev rate-limiting-abuse-protection — a skill that adds request throttling to your API: per-route policies, IP and user limits, sliding windows, and clean error responses. CX Codex +1 333installs API Rate Limiting taste f API Rate Limiting taste — a prompt for ChatGPT that defines rate limiting rules for API endpoints. Helps design backend protection against abuse and traffic spikes. GP ChatGPT ★ 178,201repo stars implementing-api-rate-limiting-and-throttling mahipal The implementing-api-rate-limiting-and-throttling skill configures Redis-backed sliding window and token bucket rate limiters to protect API endpoints against brute force attacks. CX Codex +1 418installs rate-limiting dev-toolings rate-limiting guides Claude Code through setting up Symfony RateLimiter policies, controller attributes, and 429 responses with Retry-After headers. CX Codex +1 ★ 234repo stars

From the same set235

The whole set →
gsd-debugger gsd-debugger investigates bugs using falsifiable hypotheses, manages persistent debug sessions, and handles checkpoints when manual input is needed. CX Codex ★ 3,785repo stars gsd-planner The gsd-planner subagent turns a development phase into executable plans, maps dependencies, and checks work backward from the goal. Run it through /gsd:plan-phase. CX Codex ★ 3,785repo stars production-fast-api-template production-fast-api-template is a Claude Code skill that defines conventions and file layout for a unified production-ready FastAPI backend with RAG and agentic AI on AWS ECS Fargate. CX Codex +1 ★ 3,785repo stars fix fix fetches vulnerability intelligence and suggests actionable package remediation steps for your project. CX Codex +1 ★ 3,785repo stars ops-marketing ops-marketing is a Claude Code and Cursor skill that consolidates marketing metrics from email, ads, GA4, search, and social channels in one dashboard. CX Codex +1 ★ 3,785repo stars setup setup is a Claude Code skill that runs an interactive configuration wizard for claude-ops, installing missing CLIs, connecting notification channels, and saving project settings to a local registry. CX Codex +1 ★ 3,785repo stars baizhi-agent-toolkit Connects Baizhi Agent Toolkit through a remote MCP server and adds an opt-in skill for bounded research. A Baizhi account and API key are required. ★ 3,785repo stars skyvern Wires Skyvern's hosted browser into Claude Code over MCP. The agent navigates pages, fills forms, screenshots, extracts data and reruns saved workflows. ★ 3,785repo stars

Project sponsors

Companies that keep this analytics open