Dev.to WebDev 🛠 Dev 👁 0 📖 9 min read

The Buffet and the Guy With Five Plates

Picture an all-you-can-eat buffet. It's a good deal, the food is great, and most people behave: they take a plate, eat, maybe go back for seconds. Then one guy shows up with five plates, a tray, and a very determined lo

Picture an all-you-can-eat buffet. It's a good deal, the food is great, and most people behave: they take a plate, eat, maybe go back for seconds.

Then one guy shows up with five plates, a tray, and a very determined look. He's not breaking any rule you wrote down. But while he's loading up, a whole line of regular customers is standing there, hungry, watching the food disappear.

A sensible restaurant doesn't ban buffets. It just adds a gentle rule: one plate at a time, please.

That's rate limiting. It's the polite way an app says: "You're welcome here, but you can only ask so many times, so everyone gets a turn."

In Part 5 we talked about caching, which keeps your servers from doing the same work twice. Rate limiting is the other half of protecting them: it keeps any single visitor from asking for too much.

Why Would an App Limit Its Own Users?

It sounds backwards. Don't we want traffic? Yes, but not all traffic is equal, and your servers are not infinite. Here's what rate limiting protects you from.

Accidents. A frontend developer writes a loop that calls your API in a tight cycle by mistake. Suddenly one buggy app is sending ten thousand requests a minute. Nobody's evil, but your server is on fire.

Attacks. Someone tries thousands of passwords against a login form (a brute-force attack), or floods your site to knock it offline (a denial-of-service attack). A limit slows them to a crawl.

Scrapers and abusers. Bots that copy your whole catalog, or users who hammer your free tier as if it were unlimited.

Unfairness. One heavy user hogging capacity so everyone else gets slower service. Limits keep things fair, like the one-plate rule.

Your own bill. If every request costs you money (database calls, third-party APIs, SMS messages), unlimited requests means an unlimited bill.

So rate limiting isn't about distrust. It's about keeping the lights on for everyone.

Rate Limiting vs Throttling (They're Cousins)

You'll hear both words, often used interchangeably. There's a small difference worth knowing:

  • Rate limiting is a hard line. Go past it and you get turned away: "Too many requests. No more for now."
  • Throttling is a slowdown. Instead of refusing you, the system slows you down, queues your requests, or serves you at a reduced speed.

Think of a highway: a rate limit is a bouncer saying "no more cars right now," while throttling is traffic lights that make everyone slow down but keep moving. Many real systems use both.

How Do You Actually Count Requests? (The Four Classic Methods)

Every rate limiter needs to answer one question: "Has this visitor asked too many times recently?" The clever part is how you define "recently." Here are the four common ways, in plain language.

1. Fixed window: the simple one

Divide time into blocks, like each minute on the clock. Allow, say, 100 requests per block. When the minute ends, the counter resets to zero.

It's easy to build and easy to understand. But it has a quirky flaw. Someone can send 100 requests in the last second of one minute, and another 100 in the first second of the next. That's 200 requests in two seconds, while technically following the rules. It's a burst loophole at the edge of every window.

2. Sliding window: the fairer one

Instead of resetting at fixed clock boundaries, look at the last 60 seconds from right now, whenever the request arrives. The "minute" slides along with time, so there's no sneaky boundary to exploit.

It's more accurate and fairer, though it takes a bit more memory and effort to track. Many production systems prefer it.

3. Token bucket: the friendly one (very popular)

Imagine a bucket that holds tokens. Every request costs one token. Tokens drip back into the bucket at a steady rate, say 10 per second, up to a maximum capacity.

  • If there's a token, your request goes through.
  • If the bucket is empty, you wait (or get refused) until more tokens drip in.

The beauty: it allows short bursts (a full bucket lets you send a quick flurry) while still enforcing a steady average. It feels natural to real users, who tend to be bursty: nothing for a while, then a few quick clicks.

In rough pseudocode:

function allowRequest(user) {
  refillTokens(user);              // add tokens based on time passed
  if (user.tokens >= 1) {
    user.tokens -= 1;              // spend one token
    return true;                   // allowed
  }
  return false;                    // bucket empty: too many requests
}

4. Leaky bucket: the smoothing one

Picture a bucket with a small hole in the bottom. Requests pour in at the top (as fast or slow as they like), but they leak out the bottom at a fixed, steady speed. If the bucket overflows, the extra requests are dropped.

The result is a perfectly even flow, no matter how bursty the input. It's great when the thing behind your limiter needs a calm, constant pace, like a payment provider or an SMS gateway that can't handle spikes.

Quick way to tell the buckets apart:

  • Token bucket: "you may spend saved-up tokens, so bursts are okay."
  • Leaky bucket: "no matter how you pour, it comes out at one steady speed."

Who Are You Limiting? (Choosing the "Who")

Before counting, you have to decide who the counter belongs to. Common choices:

  • By IP address: easy, but many people can share one IP (an office, a school, a phone network), so you might punish innocent users. And attackers can switch IPs.
  • By user account or ID: fairer for logged-in users, because the limit follows the person.
  • By API key: the standard for APIs, where each customer gets their own allowance.
  • By endpoint: different limits for different routes. Login might allow 5 attempts per minute, while reading public data allows 100.

Good designs often combine these: a gentle limit per IP for anonymous visitors, a more generous one per logged-in user, and a very strict one on sensitive actions like login and password reset.

What the User Sees: Saying No Politely

How you refuse matters just as much as whether you refuse. The standard way is an HTTP status code, 429 Too Many Requests. It tells the client, in a universal language: "Not an error on your end. You're just going too fast."

A good response also tells the client when to try again:

HTTP/1.1 429 Too Many Requests
Retry-After: 30
Content-Type: application/json

{ "error": "Too many requests. Please try again in 30 seconds." }

Many APIs also send helpful headers on every response, so well-behaved clients can pace themselves before hitting the wall:

  • how many requests you're allowed
  • how many you have left
  • when the counter resets

This is the difference between a bouncer who silently shoves you out and one who says, "Come back in half an hour." Both enforce the rule. Only one leaves you feeling respected.

And if you're the one calling someone else's API and you get a 429, the grown-up response is to wait and retry with a growing delay (try after 1 second, then 2, then 4, and so on). This is called exponential backoff, and it's how well-behaved clients avoid making things worse.

Where Does the Limiter Live?

Remember our layers from earlier in the series? Rate limiting can live at several of them, and each has its place:

  • At the edge or CDN: blocks floods before they even reach you (this is where DDoS protection lives).
  • At the API gateway (Part 4): the most common spot. One consistent set of rules at the front door, applied before any service does work.
  • Inside your application: useful for fine-grained, business-specific rules ("5 password attempts per account," "3 coupon redemptions per day").

The earlier you stop a bad request, the less it costs you. Turning someone away at the front door is far cheaper than letting them walk through the whole building first.

The "Many Servers" Problem

Here's a subtle one that catches people out. Remember from Part 2 that you probably have several servers behind a load balancer? If each server keeps its own count in its own memory, a user can get a fresh allowance on every server.

Say your limit is 100 requests per minute, and you have 4 servers. If each tracks separately, one user could effectively make 400 requests a minute. The limit is meaningless.

The fix connects back to Part 5: keep the counters in a shared place that all servers can see, like Redis. Fast, shared, and it can automatically expire counters when the time window ends. That's one of the best everyday uses for Redis, beyond just caching.

The Mistakes That Bite Teams

Limiting everyone the same. A regular user and a paying enterprise customer shouldn't share an allowance. Tier your limits.

Limits so strict they hurt real users. If a normal person doing normal things hits the wall, your limit is wrong. Watch real usage before choosing numbers.

Limiting only by IP. Shared networks mean innocent people get blocked together. Combine signals.

No helpful error message. A bare "403 Forbidden" with no explanation leaves developers guessing. Use 429 and say when to retry.

Forgetting the sensitive routes. Login, signup, password reset, and OTP or SMS endpoints are prime targets, and each message may cost you money. Give them their own strict limits.

Setting it and forgetting it. Traffic changes. Review your limits, and track how often they trigger.

How to Design One (A Simple Checklist)

Same spirit as the cache checklist from Part 5. Ask yourself these seven questions:

  1. What am I protecting? Servers, money, a fragile third-party service, user accounts?
  2. Who am I counting? IP, user, API key, or a mix?
  3. What's a normal amount? Look at real usage, then set the limit comfortably above it.
  4. Which method fits? Token bucket for friendly bursts, leaky bucket for steady output, sliding window for fairness, fixed window for simplicity.
  5. Where does it live? Edge, gateway, app, or several layers.
  6. How do I say no? A 429 status, a clear message, and a retry hint.
  7. How will I watch it? Track how often limits trigger and who triggers them.

Protect, who, normal, method, where, refusal, watch. That's the whole recipe.

Putting the Series Together

Notice the pattern across all six parts. Each one is really about protecting something precious (your users' time, your servers' capacity) with a small, sensible rule:

  • CDN (Part 1): keep content close to users
  • Load balancer (Part 2): spread the load
  • Reverse proxy (Part 3): stand guard in front of servers
  • API gateway (Part 4): one smart front door
  • Caching (Part 5): don't repeat work
  • Rate limiting (this post): don't let anyone take more than a fair share

Good infrastructure isn't about being clever. It's about being fair and calm under pressure.

What to Take Away

  1. Rate limiting is fairness, not hostility. It keeps one visitor from spoiling it for everyone.
  2. Rate limit = hard stop; throttle = slow down. Many systems do both.
  3. Know the four methods: fixed window (simple), sliding window (fairer), token bucket (allows bursts), leaky bucket (smooths the flow).
  4. Decide who you're counting: IP, user, API key, or endpoint, ideally a mix.
  5. Say no kindly: return 429 with a Retry-After, and as a client, back off and retry.
  6. Share the counters across servers (Redis is the usual choice).
  7. Put strict limits on sensitive routes like login and SMS.

The next time an API politely tells you to wait 30 seconds, don't be annoyed. It's just the buffet owner making sure there's still food left for the person behind you.

Next in this series: DNS, the internet's phone book, and how a friendly name like a website address turns into the number computers actually use.

Have you ever been rate limited by an API in the middle of building something? How did you find out? Tell me in the comments.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.