setup-rate-limiting · davepoon — команда для Claude Code: настройка и установка
Команда setup-rate-limiting помогает спроектировать и добавить ограничение частоты запросов к API. Она пригодится при настройке лимитов для пользователей и отдельных эндпоинтов.
MIT ★ 3 785 обновлён 2026-10-25
/plugin marketplace add davepoon/buildwithclaude
/plugin install all-commands@buildwithclaudeЧто делает setup-rate-limiting
Команда предлагает разобрать эндпоинты и трафик, выбрать политики для разных типов пользователей и продумать распределённые лимиты. В примере для Express.js используются express-rate-limit, rate-limit-redis и ioredis; счётчики хранятся в Redis. Есть отдельные лимитеры для API, чувствительных операций и аутентификации, а также варианты для тарифов и конкретных эндпоинтов.
В инструкции также показаны алгоритм token bucket и его версия с Redis для нескольких серверов. Перед внедрением проверьте, что в проекте настроен REDIS_URL: пример создаёт подключение Redis через эту переменную. Текст команды включает пример кода, а не только список решений для обсуждения.
Какие задачи решает
- спланировать лимиты для разных API-эндпоинтов
- ограничить попытки входа и чувствительных операций
- задать разные квоты для тарифных уровней
- синхронизировать лимиты между серверами через Redis
- выбрать стратегию ограничения запросов
Примеры запросов агенту
- Настрой ограничение частоты запросов для API на Express.js с Redis.
- Добавь отдельные лимиты для входа и чувствительных эндпоинтов.
- Спроектируй квоты по тарифным уровням и распределённый token bucket.
Как установить setup-rate-limiting
1Через маркетплейс плагинов
/plugin marketplace add davepoon/buildwithclaude/plugin install all-commands@buildwithclaude2Вручную: положить файлы
.claude/commands/setup-rate-limiting.mdВызов — /setup-rate-limiting. Для всех проектов — ~/.claude/commands/
Вручную: положить файлы
~/.codex/prompts/setup-rate-limiting.mdВызов — /prompts:setup-rate-limiting. В Codex этот формат помечен устаревшим, замена — скиллы
Вручную: положить файлы
.github/prompts/setup-rate-limiting.prompt.mdВручную: положить файлы
.gemini/commands/setup-rate-limiting.tomlGemini хранит команды в TOML: текст запроса — в поле prompt
Вопросы о setup-rate-limiting
Как установить setup-rate-limiting в Claude Code?
В Claude Code выполните /plugin marketplace add davepoon/buildwithclaude, затем /plugin install all-commands@buildwithclaude. Файл команды находится по пути .claude/commands/setup-rate-limiting.md.
Что делает setup-rate-limiting?
Помогает спланировать и реализовать API rate limiting: общие, аутентификационные и эндпоинтные лимиты, квоты по тарифам и token bucket.
Что нужно для примера с Express.js и Redis?
В примере используются express-rate-limit, rate-limit-redis и ioredis. Подключение к Redis задаётся через REDIS_URL.
Исходный текст
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
Похожие слэш-команды
Все слэш-команды по теме «Бэкенд и API» →Сначала — setup-rate-limiting от других авторов.