AI Powered SaaS: Stripe + Auth + Billing + Deploy · Lección

Limitación de solicitudes y protección contra fuerza bruta

Defienda la autenticación y las API de su SaaS contra abusos mediante limitación de solicitudes, bloqueo de cuentas y backoff exponencial con un almacén rápido como Redis.

Lección 4 de 413 pasos

Limitación de solicitudes y protección contra fuerza bruta es una lección gratuita de AI Powered SaaS: Stripe + Auth + Billing + Deploy en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de AI Powered SaaS: Stripe + Auth + Billing + Deploy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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 para empezar

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

Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.

Cursos
12
Lecciones
48

Preguntas frecuentes

¿La lección «Limitación de solicitudes y protección contra fuerza bruta» es gratis?

Sí — el texto completo de «Limitación de solicitudes y protección contra fuerza bruta» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy, actualiza a CoddyKit PRO. El curso de AI Powered SaaS: Stripe + Auth + Billing + Deploy incluye 4 lecciones en total.

¿Qué aprenderé en «Limitación de solicitudes y protección contra fuerza bruta»?

Defienda la autenticación y las API de su SaaS contra abusos mediante limitación de solicitudes, bloqueo de cuentas y backoff exponencial con un almacén rápido como Redis. Practicas AI Powered SaaS: Stripe + Auth + Billing + Deploy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar AI Powered SaaS: Stripe + Auth + Billing + Deploy?

No se requiere experiencia previa. AI Powered SaaS: Stripe + Auth + Billing + Deploy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Limitación de solicitudes y protección contra fuerza bruta»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de AI Powered SaaS: Stripe + Auth + Billing + Deploy?

Sí. Cada lección de AI Powered SaaS: Stripe + Auth + Billing + Deploy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Integración con OAuth 2.0
  2. Autenticación multifactor (MFA)
  3. Control de acceso basado en roles (RBAC)
  4. Limitación de solicitudes y protección contra fuerza bruta
← Volver a AI Powered SaaS: Stripe + Auth + Billing + Deploy