Rate Limiting
Fluxbase includes built-in rate limiting to protect your API from abuse, prevent brute-force attacks, and ensure fair resource usage across users.
Overview
Section titled “Overview”Rate limiting in Fluxbase provides:
- IP-based rate limiting - Limit anonymous requests per IP address
- User-based rate limiting - Higher limits for authenticated users
- API key rate limiting - Configurable limits per API key
- Endpoint-specific limits - Different limits for sensitive endpoints
- Tiered rate limiting - Different limits based on authentication level
- Automatic cleanup - In-memory storage with garbage collection
Default Rate Limits
Section titled “Default Rate Limits”| Endpoint Type | Anonymous (IP) | Authenticated User | API Key |
|---|---|---|---|
| Global API | 100 req/min | 500 req/min | 1000 req/min |
| Login | 5 req/15min | N/A | N/A |
| Signup | 3 req/hour | N/A | N/A |
| Password Reset | 3 req/hour | N/A | N/A |
| Magic Link | 3 req/hour | N/A | N/A |
| Token Refresh | 10 req/min | 10 req/min | N/A |
| Admin Setup | 5 req/15min | N/A | N/A |
| Admin Login | 10 req/min | N/A | N/A |
Quick Start
Section titled “Quick Start”Enable Global Rate Limiting
Section titled “Enable Global Rate Limiting”# .env or environment variablesFLUXBASE_SECURITY_ENABLE_GLOBAL_RATE_LIMIT=trueOr in fluxbase.yaml:
security: enable_global_rate_limit: trueThis enables 100 requests per minute per IP across all API endpoints.
Verify Rate Limiting
Section titled “Verify Rate Limiting”# Make 101 requests in 1 minutefor i in {1..101}; do curl http://localhost:8080/healthdone
# 101st request will return 429 Too Many RequestsResponse when rate limit is exceeded:
{ "error": "Rate limit exceeded", "message": "API rate limit exceeded. Maximum 100 requests per minute allowed.", "retry_after": 60}Configuration
Section titled “Configuration”Global API Rate Limiting
Section titled “Global API Rate Limiting”Applies to all API endpoints:
# Enable global rate limitingFLUXBASE_SECURITY_ENABLE_GLOBAL_RATE_LIMIT=trueDefault: 100 requests per minute per IP (when enabled)
Authentication Endpoint Rate Limits
Section titled “Authentication Endpoint Rate Limits”Login Rate Limiting
Section titled “Login Rate Limiting”# ConfigurationFLUXBASE_SECURITY_AUTH_LOGIN_RATE_LIMIT=10FLUXBASE_SECURITY_AUTH_LOGIN_RATE_WINDOW=1msecurity: auth_login_rate_limit: 10 auth_login_rate_window: 1mDefault: 10 attempts per minute per IP
Admin Setup Rate Limiting
Section titled “Admin Setup Rate Limiting”FLUXBASE_SECURITY_ADMIN_SETUP_RATE_LIMIT=5FLUXBASE_SECURITY_ADMIN_SETUP_RATE_WINDOW=15msecurity: admin_setup_rate_limit: 5 admin_setup_rate_window: 15mDefault: 5 attempts per 15 minutes per IP
Admin Login Rate Limiting
Section titled “Admin Login Rate Limiting”FLUXBASE_SECURITY_ADMIN_LOGIN_RATE_LIMIT=10FLUXBASE_SECURITY_ADMIN_LOGIN_RATE_WINDOW=1msecurity: admin_login_rate_limit: 10 admin_login_rate_window: 1mDefault: 10 attempts per minute per IP
Section titled “Default: 10 attempts per minute per IP”Rate Limiting by Endpoint
Section titled “Rate Limiting by Endpoint”Fluxbase applies different rate limits to different endpoints automatically:
Authentication Endpoints
Section titled “Authentication Endpoints”POST /api/v1/auth/signin
Section titled “POST /api/v1/auth/signin”Rate Limit: 5 requests per 15 minutes per IP
Purpose: Prevent brute-force login attacks
Response on limit:
{ "error": "Rate limit exceeded", "message": "Too many login attempts. Please try again in 15 minutes.", "retry_after": 900}POST /api/v1/auth/signup
Section titled “POST /api/v1/auth/signup”Rate Limit: 3 requests per hour per IP
Purpose: Prevent spam account creation
Response on limit:
{ "error": "Rate limit exceeded", "message": "Too many signup attempts. Please try again in 1 hour.", "retry_after": 3600}POST /api/v1/auth/password/reset
Section titled “POST /api/v1/auth/password/reset”Rate Limit: 3 requests per hour per IP
Purpose: Prevent email bombing and abuse
Key: Based on email address (if provided) or IP
Response on limit:
{ "error": "Rate limit exceeded", "message": "Too many password reset requests. Please try again in 1 hour.", "retry_after": 3600}POST /api/v1/auth/magiclink
Section titled “POST /api/v1/auth/magiclink”Rate Limit: 3 requests per hour per IP
Purpose: Prevent email bombing
Response on limit:
{ "error": "Rate limit exceeded", "message": "Too many magic link requests. Please try again in 1 hour.", "retry_after": 3600}POST /api/v1/auth/refresh
Section titled “POST /api/v1/auth/refresh”Rate Limit: 10 requests per minute per refresh token
Purpose: Prevent token abuse
Key: Based on refresh token (first 20 chars) or IP
Admin Endpoints
Section titled “Admin Endpoints”POST /api/v1/admin/setup
Section titled “POST /api/v1/admin/setup”Rate Limit: 5 requests per 15 minutes per IP
Purpose: Prevent brute-force on initial setup
Response on limit:
{ "error": "Rate limit exceeded", "message": "Too many admin setup attempts. Please try again in 15 minutes.", "retry_after": 900}POST /api/v1/admin/login
Section titled “POST /api/v1/admin/login”Rate Limit: 10 requests per minute per IP
Purpose: Prevent admin account takeover attempts
Tiered Rate Limiting
Section titled “Tiered Rate Limiting”Fluxbase implements tiered rate limiting based on authentication level:
Anonymous (IP-based)
Section titled “Anonymous (IP-based)”Limit: 100 requests per minute
Key: Client IP address
Use case: Public endpoints, unauthenticated users
# Example: Anonymous usercurl http://localhost:8080/api/v1/tables/posts# Rate limit key: ip:192.168.1.100:100Authenticated Users
Section titled “Authenticated Users”Limit: 500 requests per minute
Key: User ID from JWT token
Use case: Logged-in users with valid session
# Example: Authenticated usercurl http://localhost:8080/api/v1/tables/posts \ -H "Authorization: Bearer eyJhbGc..."# Rate limit key: user:user-uuid-here:500API Keys
Section titled “API Keys”Limit: 1,000 requests per minute (configurable per key)
Key: API key ID
Use case: Server-to-server integrations, higher throughput needs
# Example: API key authenticationcurl http://localhost:8080/api/v1/tables/posts \ -H "Authorization: Bearer sk_live_xxxxx"# Rate limit key: apikey:apikey-uuid:1000Priority Order
Section titled “Priority Order”When multiple authentication methods are present:
- API Key - Highest priority, highest limits
- User JWT - Medium priority, medium limits
- IP Address - Fallback, lowest limits
Rate Limit Headers
Section titled “Rate Limit Headers”Fluxbase includes rate limit information in response headers:
HTTP/1.1 200 OKX-RateLimit-Limit: 100X-RateLimit-Remaining: 95X-RateLimit-Reset: 1640000000Headers:
X-RateLimit-Limit- Maximum requests allowed in time windowX-RateLimit-Remaining- Requests remaining in current windowX-RateLimit-Reset- Unix timestamp when the rate limit resets
When rate limit is exceeded:
HTTP/1.1 429 Too Many RequestsX-RateLimit-Limit: 100X-RateLimit-Remaining: 0X-RateLimit-Reset: 1640000060Retry-After: 60
{ "error": "Rate limit exceeded", "message": "API rate limit exceeded. Maximum 100 requests per minute allowed.", "retry_after": 60}API Key Rate Limits
Section titled “API Key Rate Limits”When creating API keys, you can set custom rate limits:
# Create API key with custom rate limitcurl -X POST http://localhost:8080/api/v1/admin/api-keys \ -H "Authorization: Bearer admin-token" \ -H "Content-Type: application/json" \ -d '{ "name": "External Integration", "rate_limit_rpm": 5000, "expires_at": "2025-12-31T23:59:59Z" }'Response:
{ "id": "apikey-uuid", "key": "sk_live_xxxxxxxxxx", "name": "External Integration", "rate_limit_rpm": 5000, "created_at": "2024-01-26T10:00:00Z", "expires_at": "2025-12-31T23:59:59Z"}Distributed Rate Limiting (Redis)
Section titled “Distributed Rate Limiting (Redis)”For multi-instance deployments, use Redis for distributed rate limiting:
Enable Redis
Section titled “Enable Redis”FLUXBASE_REDIS_ENABLED=trueFLUXBASE_REDIS_HOST=redisFLUXBASE_REDIS_PORT=6379FLUXBASE_REDIS_PASSWORD=your-redis-passwordFLUXBASE_REDIS_DB=0redis: enabled: true host: redis port: 6379 password: your-redis-password db: 0 pool_size: 10Benefits:
- Shared rate limit state across all Fluxbase instances
- Consistent rate limiting in horizontal scaling
- Persistent rate limit counters (survives restarts)
Architecture:
┌─────────────┐│ Client │└──────┬──────┘ │ ┌────▼─────────────────────┐ │ Load Balancer │ └────┬─────────────────────┘ │ ┌────┴─────┬────────┬──────┐ │ │ │ │┌─▼──┐ ┌──▼─┐ ┌──▼─┐ ┌─▼──┐│FB 1│ │FB 2│ │FB 3│ │FB 4│└─┬──┘ └──┬─┘ └──┬─┘ └─┬──┘ │ │ │ │ └─────────┴────────┴──────┘ │ ┌─────▼──────┐ │ Redis │ │ (Shared │ │ State) │ └────────────┘Monitoring Rate Limits
Section titled “Monitoring Rate Limits”Prometheus Metrics
Section titled “Prometheus Metrics”Fluxbase exposes rate limiting metrics:
# Total rate limit hitsrate_limit_hits_total{endpoint="/api/v1/auth/signin"}
# Rate limit by statusrate_limit_status{status="allowed"}rate_limit_status{status="blocked"}
# Current rate limit usagerate_limit_current_usage{key_type="ip"}rate_limit_current_usage{key_type="user"}rate_limit_current_usage{key_type="apikey"}View Rate Limit Logs
Section titled “View Rate Limit Logs”# Enable debug loggingFLUXBASE_DEBUG=true
# View logsdocker logs fluxbase | grep "rate limit"
# Kuberneteskubectl logs -f deployment/fluxbase -n fluxbase | grep "rate limit"Sample log output:
{"level":"warn","time":"2024-01-26T10:30:00Z","ip":"192.168.1.100","endpoint":"/api/v1/auth/signin","message":"rate limit exceeded"}Client-Side Handling
Section titled “Client-Side Handling”Respect Rate Limits
Section titled “Respect Rate Limits”Implement exponential backoff when receiving 429 responses:
// TypeScript/JavaScript clientasync function fetchWithRetry(url: string, options: RequestInit, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { const response = await fetch(url, options);
if (response.status === 429) { const retryAfter = parseInt(response.headers.get('Retry-After') || '60'); console.warn(`Rate limited. Retrying after ${retryAfter} seconds...`); await new Promise(resolve => setTimeout(resolve, retryAfter * 1000)); continue; }
return response; }
throw new Error('Max retries exceeded');}
// Usageconst response = await fetchWithRetry('http://localhost:8080/api/v1/tables/posts', { headers: { 'Authorization': 'Bearer token' }});Check Rate Limit Status
Section titled “Check Rate Limit Status”const response = await fetch('http://localhost:8080/api/v1/tables/posts');
const limit = parseInt(response.headers.get('X-RateLimit-Limit') || '0');const remaining = parseInt(response.headers.get('X-RateLimit-Remaining') || '0');const reset = parseInt(response.headers.get('X-RateLimit-Reset') || '0');
console.log(`Rate limit: ${remaining}/${limit} remaining`);console.log(`Resets at: ${new Date(reset * 1000)}`);
if (remaining < 10) { console.warn('Approaching rate limit!');}Batch Requests
Section titled “Batch Requests”Reduce rate limit impact by batching requests:
// Bad: Many individual requestsfor (const id of userIds) { await fetch(`/api/v1/users/${id}`);}
// Good: Single batched requestconst users = await fetch('/api/v1/users', { method: 'POST', body: JSON.stringify({ ids: userIds })});Security Best Practices
Section titled “Security Best Practices”1. Enable Global Rate Limiting in Production
Section titled “1. Enable Global Rate Limiting in Production”# Always enable in productionFLUXBASE_SECURITY_ENABLE_GLOBAL_RATE_LIMIT=true2. Use Stricter Limits for Sensitive Endpoints
Section titled “2. Use Stricter Limits for Sensitive Endpoints”Authentication endpoints have built-in strict limits:
- Login: 5 attempts per 15 minutes
- Signup: 3 per hour
- Password reset: 3 per hour
Do not disable these unless absolutely necessary.
3. Monitor for Abuse
Section titled “3. Monitor for Abuse”Set up alerts for high rate limit violations:
# Prometheus alert rulegroups: - name: rate_limiting rules: - alert: HighRateLimitViolations expr: rate(rate_limit_hits_total{status="blocked"}[5m]) > 10 for: 5m annotations: summary: "High rate limit violations detected" description: "More than 10 rate limit violations per second for 5 minutes"4. Use API Keys for Server-to-Server
Section titled “4. Use API Keys for Server-to-Server”For integrations requiring high throughput:
# Create API key with appropriate limitscurl -X POST /api/v1/admin/api-keys \ -d '{"name": "Partner API", "rate_limit_rpm": 5000}'Troubleshooting
Section titled “Troubleshooting”Rate Limit Too Strict
Section titled “Rate Limit Too Strict”Symptom: Legitimate users getting rate limited
Solution 1: Increase limits for authenticated users
# Users get 500 req/min by default# If using custom implementation, adjust accordinglySolution 2: Use API keys for high-traffic clients
# Create API key with higher limitcurl -X POST /api/v1/admin/api-keys \ -H "Authorization: Bearer admin-token" \ -d '{"name": "High Traffic Client", "rate_limit_rpm": 10000}'Rate Limit Not Working
Section titled “Rate Limit Not Working”Check 1: Verify rate limiting is enabled
# Check configurationFLUXBASE_SECURITY_ENABLE_GLOBAL_RATE_LIMIT=trueCheck 2: Check logs
# Enable debug modeFLUXBASE_DEBUG=true
# View logsdocker logs fluxbase | grep -i "rate"Check 3: Test manually
# Send 101 requests quicklyfor i in {1..101}; do curl http://localhost:8080/healthdone
# 101st should return 429Distributed Setup Not Working
Section titled “Distributed Setup Not Working”Issue: Each instance has separate rate limits
Solution: Enable Redis
FLUXBASE_REDIS_ENABLED=trueFLUXBASE_REDIS_HOST=redisFLUXBASE_REDIS_PORT=6379Verify:
# Connect to Redisredis-cli
# Check rate limit keysKEYS rate_limit:*False Positives from Load Balancer
Section titled “False Positives from Load Balancer”Issue: All requests appear from same IP (load balancer IP)
Solution: Configure load balancer to forward real client IP
Nginx:
proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;Kubernetes Ingress:
annotations: nginx.ingress.kubernetes.io/use-forwarded-headers: "true"Fluxbase automatically uses X-Forwarded-For header when available.
Performance Impact
Section titled “Performance Impact”Rate limiting adds minimal overhead:
- In-memory storage: < 1ms per request
- Redis storage: < 5ms per request (network latency)
- Memory usage: ~100 bytes per unique key
Benchmarks (single instance):
| Storage | Requests/sec | Avg Latency | p99 Latency |
|---|---|---|---|
| Memory | 10,000 | 0.5ms | 2ms |
| Redis | 8,000 | 2ms | 10ms |
Migration from Other Systems
Section titled “Migration from Other Systems”From Supabase
Section titled “From Supabase”Supabase uses Kong for rate limiting. Fluxbase provides similar functionality:
| Supabase (Kong) | Fluxbase |
|---|---|
| Anonymous: 60 req/min | Anonymous: 100 req/min |
| Authenticated: 600 req/min | Authenticated: 500 req/min |
| Service key: Unlimited | API Key: 1000 req/min (configurable) |
Migration steps:
-
Enable rate limiting:
Terminal window FLUXBASE_SECURITY_ENABLE_GLOBAL_RATE_LIMIT=true -
Adjust limits to match Supabase (if needed):
// Custom configuration (if extending)GlobalAPILimiter(60) // Match Supabase anonymous limit -
Test with existing clients
From Firebase
Section titled “From Firebase”Firebase rate limits are per-function. Fluxbase applies global + endpoint-specific limits.
Recommended approach:
- Start with default limits
- Monitor usage patterns
- Adjust per-endpoint limits as needed
Next Steps
Section titled “Next Steps”- Authentication - Secure your API endpoints
- SDK Admin Documentation - Create API keys for integrations
- Monitoring - Set up observability
- Security - Additional security measures