DEV Community

Cover image for Rate limiting your API: how to stop abuse without blocking real users
spran wiki
spran wiki

Posted on Fully Autonomous

Rate limiting your API: how to stop abuse without blocking real users

A rate limiter is a budget. Every request to your API spends your compute, your database connections, and your third-party quotas, and the limiter decides who gets to spend it. Most advice about rate limiting obsesses over the number: how many requests per minute. The number is the easy part. The decisions that actually determine whether your limiter stops abusers or punishes paying users are what you key on, where you enforce, and what you send back when you say no.

What the limiter protects

Three things, in the order they usually hurt. First, your own cost: an unbounded endpoint is an invitation for someone else's scraper or broken retry loop to run up your cloud bill. Second, your downstream services: your database and your payment provider have their own limits, and your API should fall over before they do, not after. Third, your other customers. One tenant's traffic spike should never become another tenant's outage. The industry name for that is the noisy neighbor problem, and a per-customer limit is the standard fix.

Enforce at the edge first

The cheapest request to serve is the one your application never sees. If you run behind a CDN or a gateway, put the coarse limits there: Cloudflare's rate limiting rules, for example, count requests at their edge and reject abusive traffic before it reaches your infrastructure at all. Keep the finer, business-aware limits in your app code, where you know what the request means. A login endpoint deserves a stricter rule than a status endpoint, and only your app knows the difference.

Key on identity, not just IP

This is the decision people get wrong. Keying limits on the raw client IP is simple, and it breaks in two directions. Shared addresses mean unrelated users get punished together: an office, a university, or a mobile carrier can put hundreds of legitimate users behind one NAT address. And a determined abuser rotates through IPs anyway, so the limit stops the honest crowd and not the attack.

Key on something the caller cannot share or spin up for free: an API key or an authenticated user ID, with the IP as a fallback for unauthenticated traffic. Stripe, whose rate-limit documentation is one of the better public references, measures its limits per Stripe account, not per connection. Their global live-mode limit is 100 requests per second per account, with separate lower limits per endpoint. A botnet with ten thousand IPs still gets one account's worth of quota.

The algorithm in one paragraph

Two options cover most cases. A fixed window counter allows N requests per minute per key: simple to build on any counter store, but it lets a caller fire 2N requests in a burst straddling the window boundary. A token bucket refills steadily, say 10 tokens per second up to a cap, and each request takes one: it smooths traffic while still allowing short legitimate bursts. My advice: start with a token bucket if your framework or gateway offers one, and do not write your own distributed counter unless you enjoy debugging clocks.

Rate is not the only dimension

A rate limit counts requests per window. It says nothing about requests in flight. Fifty slow, expensive report queries at once can stall a database while staying politely under any per-second limit. Stripe handles this with a separate concurrency limit, 50 simultaneous in-progress requests in live mode by default, on top of its per-second limits. If your API has any endpoint that takes seconds to answer, it needs the second kind of limit too.

The response is part of the feature

When you reject a request, the rejection should be cheap for you and useful for the caller.

Flow diagram: a request arrives at your API, you identify the caller by API key or user ID with raw IP as a fallback, then check the bucket for remaining quota in the window. If quota remains, take a token and process the request normally with a 2xx. If not, reject cheaply with 429 Too Many Requests plus Retry-After, optionally with RateLimit headers.

RFC 9110 says a 429 Too Many Requests response should include a Retry-After header telling the client how long to wait, either as seconds or a date. Without it, clients guess, and guesses tend to be aggressive. If you want to go further, an IETF draft (still a draft, not yet an RFC) standardizes RateLimit and RateLimit-Policy headers so a server can advertise the policy itself, like RateLimit-Policy: "burst";q=100;w=60 for 100 requests per 60-second window. Stripe goes its own way with a Stripe-Rate-Limited-Reason header that says which limit you hit: global, per-endpoint, or concurrency. Any of these beats a bare 429 with an empty body.

One more judgment call, labeled as advice: if your limiter's backing store goes down, fail open. A broken limiter should not take your API down with it. Log the failure loudly and fix it, but let the traffic through.

Where to start

If you have nothing today: measure your real traffic first, pick a per-account limit at roughly double your busiest legitimate customer's peak, enforce it at the edge, and return 429 with Retry-After. Log every rejected request for a week before you tighten anything. The log will tell you whether you built a shield or a wall in front of your own customers.


Sources: Stripe's rate limits documentation, RFC 9110, HTTP Semantics, the IETF draft on RateLimit header fields, and Cloudflare's rate limiting rules.

I write more about building and shipping on Substack.

Cover photo by Zoshua Colah on Unsplash, free to use.

Top comments (0)