惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
MyScale Blog
MyScale Blog
Microsoft Security Blog
Microsoft Security Blog
量子位
B
Blog
aimingoo的专栏
aimingoo的专栏
Apple Machine Learning Research
Apple Machine Learning Research
阮一峰的网络日志
阮一峰的网络日志
The GitHub Blog
The GitHub Blog
T
The Exploit Database - CXSecurity.com
N
News | PayPal Newsroom
Cloudbric
Cloudbric
A
About on SuperTechFans
AI
AI
Hacker News: Ask HN
Hacker News: Ask HN
S
Schneier on Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LINUX DO - 最新话题
T
The Blog of Author Tim Ferriss
Simon Willison's Weblog
Simon Willison's Weblog
有赞技术团队
有赞技术团队
H
Heimdal Security Blog
J
Java Code Geeks
大猫的无限游戏
大猫的无限游戏
D
Docker
Security Archives - TechRepublic
Security Archives - TechRepublic
N
News and Events Feed by Topic
IT之家
IT之家
Know Your Adversary
Know Your Adversary
N
Netflix TechBlog - Medium
T
Tailwind CSS Blog
B
Blog RSS Feed
C
Cybersecurity and Infrastructure Security Agency CISA
C
Cisco Blogs
博客园 - 叶小钗
美团技术团队
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
H
Hackread – Cybersecurity News, Data Breaches, AI and More
L
LangChain Blog
The Hacker News
The Hacker News
Y
Y Combinator Blog
I
Intezer
The Register - Security
The Register - Security
F
Full Disclosure
V
V2EX
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Last Week in AI
Last Week in AI
Martin Fowler
Martin Fowler

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Día 12: 5.000 personas hicieron click al mismo tiempo. Tu servidor pidió perdón.
Alejandro La · 2026-04-24 · via DEV Community

Tu tienda online sale a internet. Llevas meses preparándote. La campaña de marketing hizo su trabajo. 5.000 personas están esperando con el dedo en el botón de "Comprar". La cuenta regresiva llega a cero. Todos hacen click al mismo tiempo.

Tu servidor tiene 20 threads. Se saturan en menos de un segundo. Los otros 4.980 requests se encolan. Empiezan los timeouts. El login deja de funcionar. La página de inicio no carga. El botón de "Comprar" gira y gira. La gente empieza a refrescar. Cada refresh son más requests. Más cola. Más timeouts. El ciclo se retroalimenta.

En 3 minutos, lo que iba a ser tu mejor día se convirtió en tu peor pesadilla.

No es un problema de capacidad. Es un problema de control.

La reacción instintiva es "necesitamos más servidores". Y sí, tal vez. Pero el problema real es otro: tu API no tiene límites. Cualquier cliente puede hacer las requests que quiera, a la velocidad que quiera. No hay semáforo. No hay velocidad máxima. No hay nada que diga "para un poco".

Esto no es exclusivo del lanzamiento de una tienda. Es el mismo problema cuando:

  • Un bot descubre tu API y la empieza a scrapear
  • Un frontend con un bug hace polling cada 100ms en vez de cada 10 segundos
  • Un partner de integración reintenta sin backoff exponencial
  • Un usuario frustrado martillea F5 porque la página "no carga"

Sin rate limiting, tu API es un buffet libre donde un solo comensal se puede comer toda la comida y dejar a los demás sin nada.

Rate limiting: el concepto

La idea es simple: poner un límite a cuántas requests puede hacer cada cliente en un período de tiempo. Si lo supera, la API le responde con un error claro (HTTP 429 — Too Many Requests) en vez de intentar procesar todo y colapsar.

El algoritmo más usado se llama Token Bucket y funciona así:

  1. Cada cliente tiene un "balde" con N tokens
  2. Cada request consume 1 token
  3. Los tokens se regeneran a velocidad constante (por ejemplo, 50 por minuto)
  4. Si el balde está vacío, la request se rechaza con 429

Es elegante porque permite ráfagas cortas (si el balde está lleno, puedes hacer varias requests rápidas) pero limita el tráfico sostenido.

Este algoritmo lo usan:

  • AWS API Gateway — Token Bucket con burst
  • Stripe API — 100 requests por segundo por defecto
  • GitHub API — 5.000 requests por hora para autenticados
  • Twitter/X API — Rate limits por endpoint y por ventana de tiempo
  • Cloudflare — Token Bucket configurable por zona
  • nginxlimit_req con leaky bucket (variante similar)

No es un concepto oscuro ni experimental. Es infraestructura estándar que cualquier API pública del mundo implementa. La pregunta no es "¿necesito rate limiting?" — es "¿por qué todavía no lo tengo?"

Implementación: cómo se ve

En cualquier lenguaje, rate limiting es un filtro que se ejecuta ANTES de tu lógica de negocio. Si el cliente ya superó su límite, ni siquiera llegas al controller.

La implementación del Token Bucket en Java es sorprendentemente simple:

public class TokenBucket {

    private final long capacity;
    private final double refillRatePerMs;
    private double tokens;
    private long lastRefillTimestamp;

    public TokenBucket(long capacity, long refillPerMinute) {
        this.capacity = capacity;
        this.refillRatePerMs = refillPerMinute / 60000.0;
        this.tokens = capacity;
        this.lastRefillTimestamp = System.currentTimeMillis();
    }

    public synchronized boolean tryConsume() {
        refill();
        if (tokens >= 1) {
            tokens--;
            return true;
        }
        return false;
    }

    private void refill() {
        long now = System.currentTimeMillis();
        double newTokens = (now - lastRefillTimestamp) * refillRatePerMs;
        tokens = Math.min(capacity, tokens + newTokens);
        lastRefillTimestamp = now;
    }
}

Enter fullscreen mode Exit fullscreen mode

En Python con Flask sería un decorator. En Node con Express un middleware. En Go un middleware con golang.org/x/time/rate. El patrón es idéntico: interceptar, verificar, dejar pasar o rechazar.

Aplicándolo al escenario de la tienda

Volvamos al lanzamiento. Lo que necesitas es:

@Component
public class RateLimitFilter implements Filter {

    private final Map<String, TokenBucket> buckets = new ConcurrentHashMap<>();

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        String clientIp = request.getRemoteAddr();
        String path = request.getRequestURI();

        TokenBucket bucket = buckets.computeIfAbsent(
            clientIp + ":" + path, k -> crearBucket(path));

        if (bucket.tryConsume()) {
            response.setHeader("X-Rate-Limit-Remaining",
                String.valueOf(bucket.getAvailableTokens()));
            chain.doFilter(req, res);
        } else {
            response.setStatus(429);
            response.setHeader("Retry-After", "10");
            response.getWriter().write("Too Many Requests");
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Ahora cada IP tiene un límite. Los primeros 10 "Comprar" pasan. Del 11 en adelante reciben un 429 limpio en milisegundos, sin ocupar threads, sin tocar la base de datos, sin degradar el servicio para los demás.

Límites diferentes para rutas diferentes

No todos los endpoints son iguales. El endpoint de compra necesita protección fuerte (stock limitado, procesamiento pesado). El listado de productos puede ser más generoso:

Endpoint Límite Razón
/comprar 10/min Proteger stock, procesamiento de pago
/productos 60/min Lectura, ligero
/login 5/min Prevención de fuerza bruta
/imágenes 100/min Assets estáticos (mejor en CDN)

Los headers que el cliente necesita

Cuando rechazas una request con 429, sé un buen ciudadano HTTP. Dile al cliente cuándo puede reintentar:

HTTP/1.1 429 Too Many Requests
Retry-After: 10
X-Rate-Limit-Limit: 50
X-Rate-Limit-Remaining: 0

Enter fullscreen mode Exit fullscreen mode

El frontend (o el bot, o el partner de integración) puede leer estos headers y adaptarse: mostrar un mensaje al usuario, implementar backoff, o simplemente dejar de disparar requests.

Los números del escenario de la tienda

Sin rate limit Con rate limit
Requests en ráfaga 5.000 simultáneas 10/min por IP
Latencia p95 (otros endpoints) 2.800ms 180ms
CPU promedio en pico 95% 45%
Disponibilidad bajo carga 78% 99.5%

El rate limiting no hizo que "Comprar" fuera más rápido. Hizo que todo lo demás siguiera funcionando. El login, la página de inicio, el carrito — todo siguió vivo porque un grupo de clientes impacientes no pudo agotar los recursos del servidor.

¿Rate limiting en el backend o en el API Gateway?

En un sistema real, generalmente lo quieres en ambos:

  • API Gateway / Load Balancer (nginx, AWS API Gateway, Cloudflare): Primera línea de defensa. Bloquea tráfico malicioso antes de que llegue a tu app. Protege contra DDoS.
  • Aplicación (tu código): Segunda línea. Límites específicos por lógica de negocio (por ejemplo, máximo 3 compras del mismo producto por usuario para evitar acaparadores).

El gateway protege tu infraestructura. Tu app protege tu negocio.

Rate limiting no es hostilidad

Esto es importante: rate limiting no es ser malo con tus clientes. Es proteger la experiencia de todos tus clientes. Incluyendo los que no están haciendo nada mal.

Es como el límite de velocidad en una autopista. No existe para molestarte. Existe para que la autopista funcione para todos.

Una API sin rate limiting es una autopista sin límite de velocidad. Funciona bien con poco tráfico. El día que aparece un camión, un bot, o 5.000 personas emocionadas — se pudre todo.

Esto es el Día 12

Este artículo es parte de #100ArchitectureDays — una serie de problemas reales de arquitectura con soluciones reales. Si tu API no tiene rate limiting, el próximo bot, el próximo lanzamiento, o el próximo Black Friday te va a recordar por qué lo necesitas.

Sigue la saga completa en #100ArchitectureDays.

Todo el código está en GitHub — con una implementación manual del Token Bucket sin dependencias externas para que entiendas el algoritmo por dentro. Si te está sirviendo, déjame una estrella — es gratis y ayuda a que más gente lo encuentre.