Difficulty: Beginner
How would you protect a login endpoint from brute-force and credential-stuffing attacks?
Protect a login endpoint with layered controls: rate limiting per IP and per account, progressive delays or CAPTCHA after failed attempts, multi-factor authentication, and breached-password checks. No single control is enough because attackers spread attempts across thousands of IPs (credential stuffing) or target one account slowly. The goal is to make guessing too slow and noisy to succeed while keeping real users unblocked.
Password@123) tried against many accounts, staying under per-account limits.Per-IP limits alone stop the first only partially, and barely touch the third.
| Algorithm | How it works | Trade-off |
|---|---|---|
| Fixed window | Count requests per clock minute | Simple; allows bursts at window edges |
| Sliding window | Count over the last N seconds | Smoother, slightly more storage |
| Token bucket | Tokens refill at a fixed rate; each request spends one | Allows controlled bursts; common in API gateways |
OTP verification is a classic Indian-app weak spot: a 6-digit OTP has only a million combinations. Limit attempts per OTP (for example 5), expire it in a few minutes, and rate limit OTP sending too, or attackers will burn your SMS budget and spam users.
req.ip may be the proxy's IP. Configure trust proxy correctly, or every user shares one bucket.X-Forwarded-For unless it comes from your own proxy.429 Too Many Requests with a Retry-After header for legitimate clients.import { RateLimiterRedis } from 'rate-limiter-flexible';
const byIp = new RateLimiterRedis({
storeClient: redis, keyPrefix: 'login_ip', points: 10, duration: 60,
});
const failsByEmail = new RateLimiterRedis({
storeClient: redis, keyPrefix: 'login_fail', points: 5, duration: 15 * 60,
});
app.post('/login', async (req, res) => {
const email = String(req.body.email).toLowerCase();
try {
await byIp.consume(req.ip);
const state = await failsByEmail.get(email);
if (state && state.remainingPoints <= 0) throw state;
} catch (rej) {
res.set('Retry-After', String(Math.ceil((rej.msBeforeNext ?? 60000) / 1000)));
return res.status(429).json({ error: 'Too many attempts' });
}
const user = await verifyCredentials(email, req.body.password);
if (!user) {
await failsByEmail.consume(email); // count only failures
return res.status(401).json({ error: 'Invalid email or password' });
}
await failsByEmail.delete(email);
// continue to MFA step...
});
The IP limiter caps raw volume, while the per-email counter only increments on failures and resets on success, so real users are rarely affected.
Rate Limiting, Credential Stuffing, Token Bucket, Redis, Account Lockout, MFA