速率限制与暴力破解防护
使用 Redis 等高速存储,通过速率限制、账户锁定和指数退避,防御针对 SaaS 身份验证和 API 的滥用行为。
速率限制与暴力破解防护 是 CoddyKit 上的免费 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Powered SaaS: Stripe + Auth + Billing + Deploy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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.
用 AI 导师学习 AI Powered SaaS: Stripe + Auth + Billing + Deploy — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 12
- 课程
- 48
常见问题解答
「速率限制与暴力破解防护」课时是免费的吗?
是的 — 「速率限制与暴力破解防护」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课程的其余内容,请升级到 CoddyKit PRO。 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课程共包含 4 节课。
「速率限制与暴力破解防护」这节课中我会学到什么?
使用 Redis 等高速存储,通过速率限制、账户锁定和指数退避,防御针对 SaaS 身份验证和 API 的滥用行为。 你通过在浏览器中直接运行的动手代码来练习 AI Powered SaaS: Stripe + Auth + Billing + Deploy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Powered SaaS: Stripe + Auth + Billing + Deploy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「速率限制与暴力破解防护」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课中编写并运行代码吗?
能。每节 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- OAuth 2.0 集成
- 多重身份验证(MFA)
- 基于角色的访问控制(RBAC)
- 速率限制与暴力破解防护