AI Powered SaaS: Stripe + Auth + Billing + Deploy · Lezione

Rate limiting e protezione dagli attacchi brute-force

Protegga autenticazione e API del Suo SaaS dagli abusi con rate limiting, blocco degli account ed exponential backoff usando un datastore veloce come Redis.

Lezione 4 di 413 passaggi

Rate limiting e protezione dagli attacchi brute-force è una lezione AI Powered SaaS: Stripe + Auth + Billing + Deploy gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento AI Powered SaaS: Stripe + Auth + Billing + Deploy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso AI Powered SaaS: Stripe + Auth + Billing + Deploy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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 INCR and TTL, or use sliding window libraries
  • Return 429 with Retry-After
  • Add account lockout and exponential backoff for logins

Your auth and APIs now resist brute force and flooding.

Gratis per iniziare

Impara AI Powered SaaS: Stripe + Auth + Billing + Deploy con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
12
Lezioni
48

Domande Frequenti

La lezione «Rate limiting e protezione dagli attacchi brute-force» è gratuita?

Sì — il testo completo di «Rate limiting e protezione dagli attacchi brute-force» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso AI Powered SaaS: Stripe + Auth + Billing + Deploy, passa a CoddyKit PRO. Il corso AI Powered SaaS: Stripe + Auth + Billing + Deploy include 4 lezioni in totale.

Cosa imparerò in «Rate limiting e protezione dagli attacchi brute-force»?

Protegga autenticazione e API del Suo SaaS dagli abusi con rate limiting, blocco degli account ed exponential backoff usando un datastore veloce come Redis. Eserciti AI Powered SaaS: Stripe + Auth + Billing + Deploy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare AI Powered SaaS: Stripe + Auth + Billing + Deploy?

Non è richiesta alcuna esperienza precedente. AI Powered SaaS: Stripe + Auth + Billing + Deploy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Rate limiting e protezione dagli attacchi brute-force»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione AI Powered SaaS: Stripe + Auth + Billing + Deploy?

Sì. Ogni lezione AI Powered SaaS: Stripe + Auth + Billing + Deploy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Integrazione di OAuth 2.0
  2. Autenticazione a più fattori (MFA)
  3. Controllo degli accessi basato sui ruoli (RBAC)
  4. Rate limiting e protezione dagli attacchi brute-force
← Torna a AI Powered SaaS: Stripe + Auth + Billing + Deploy