Rate Limiting & Brute-Force Protection
Defend your SaaS auth and APIs from abuse with rate limiting, account lockouts, and exponential backoff using a fast store like Redis.
Rate Limiting & Brute-Force Protection is a free AI Powered SaaS: Stripe + Auth + Billing + Deploy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Powered SaaS: Stripe + Auth + Billing + Deploy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Rate Limit?
Without limits, attackers can hammer your login endpoint to guess passwords, scrape data, or run up costs on metered APIs. Rate limiting caps how many requests a client can make in a window.
Identifying the Client
Limits are keyed on something that identifies the caller: an IP address, a user ID, or an API key. Choose the key based on what you are protecting.
const key = 'login:' + (userId ?? clientIp);The Fixed Window Algorithm
The simplest method counts requests per fixed time window. If the count exceeds the limit, reject until the window resets.
// allow 5 requests per 60 seconds
if (count > 5) return reject();Counting in Redis
Redis is ideal: INCR bumps a counter atomically, and a TTL auto-expires the window. The first request sets the expiry.
const n = await redis.incr(key);
if (n === 1) await redis.expire(key, 60);
if (n > 5) throw new Error('Too many requests');Sliding Window & Token Bucket
Fixed windows allow bursts at the edges. Sliding window smooths this, and token bucket permits short bursts while enforcing an average rate. Libraries like Upstash Ratelimit implement these for you.
import { Ratelimit } from '@upstash/ratelimit';
const rl = new Ratelimit({ redis, limiter: Ratelimit.slidingWindow(5, '60 s') });Applying in Middleware
Centralize limiting in Next.js middleware so it runs before every matched request.
export async function middleware(req) {
const { success } = await rl.limit(req.ip ?? 'anon');
if (!success) return new Response('Rate limited', { status: 429 });
}Returning 429 Properly
When limited, respond with status 429 and a Retry-After header telling clients when to try again.
return new Response('Too many requests', {
status: 429,
headers: { 'Retry-After': '60' }
});Account Lockout
For login specifically, track failed attempts per account. After several failures, temporarily lock the account to stop targeted brute force.
const fails = await redis.incr('fail:' + email);
if (fails >= 5) await redis.expire('lock:' + email, 900);Exponential Backoff
Increase the delay after each failure: 1s, 2s, 4s, 8s. This frustrates automated guessing while barely affecting legitimate users.
const delay = Math.min(2 ** fails, 60) * 1000;Avoiding False Positives
Be careful not to punish real users:
- Shared office IPs share a limit — prefer per-user keys when authenticated
- Reset counters on success
- Set generous limits for normal usage
Best Practices
Protect endpoints well:
- Key limits on IP, user, or API key
- Use Redis with sliding window or token bucket
- Return 429 with Retry-After
- Add lockout and backoff for login
Quick Check
Test your rate-limiting knowledge.
Recap
You learned to defend against abuse:
- Key rate limits on IP, user, or API key
- Count with Redis
INCRand TTL, or use sliding window libraries - Return
429withRetry-After - Add account lockout and exponential backoff for logins
Your auth and APIs now resist brute force and flooding.
Frequently asked questions
Is the “Rate Limiting & Brute-Force Protection” lesson free?
Yes — the full text of “Rate Limiting & Brute-Force Protection” is free to read here on the web, and the AI Powered SaaS: Stripe + Auth + Billing + Deploy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Powered SaaS: Stripe + Auth + Billing + Deploy course, upgrade to CoddyKit PRO.
What will I learn in “Rate Limiting & Brute-Force Protection”?
Defend your SaaS auth and APIs from abuse with rate limiting, account lockouts, and exponential backoff using a fast store like Redis. You practise AI Powered SaaS: Stripe + Auth + Billing + Deploy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Powered SaaS: Stripe + Auth + Billing + Deploy?
No prior experience is required. AI Powered SaaS: Stripe + Auth + Billing + Deploy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Rate Limiting & Brute-Force Protection” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Powered SaaS: Stripe + Auth + Billing + Deploy lesson?
Yes. Every AI Powered SaaS: Stripe + Auth + Billing + Deploy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- OAuth 2.0 Integration
- Multi-Factor Authentication (MFA)
- Role-Based Access Control (RBAC)
- Rate Limiting & Brute-Force Protection