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

I Built a Rate Limiter in 13 Lines of Node, Then Load-Tested It

I built a rate limiter in plain Node with zero packages, then load-tested it until it failed. Token bucket, 13 lines, no timers. Here is the code, the four tests, and the exact numbers. The limiter A token bu

I built a rate limiter in plain Node with zero packages, then load-tested it until it failed. Token bucket, 13 lines, no timers. Here is the code, the four tests, and the exact numbers.

The limiter

A token bucket per client. Each client gets a bucket of 10 tokens, every request costs one token, and the bucket refills at 5 tokens per second. A client can burst, but it cannot keep going forever.

The whole limiter is a function that takes a capacity and a refill rate, keeps a Map of buckets keyed by client, refills based on elapsed time, and returns true or false. 13 lines, no timers, no dependencies.

The server is tiny on purpose: it reads a client name from a header, asks the limiter, and returns 429 with a Retry-After header when the answer is no. Otherwise it says okay.

The tests

Test 1: the burst. A client called Alice sends 100 requests at once.

  • 10 got a 200
  • 90 got a 429

Exactly the bucket size. Nothing else leaked through.

Test 2: client isolation. Right after Alice's burst, a different client, Bob, sends one request.

  • Bob gets a 200

One noisy client did not block the others, because each client has its own bucket.

Test 3: the refill. Wait one second, then Alice sends 10 more.

  • 5 got a 200
  • 5 got a 429

That matches the refill rate of 5 tokens per second. After one second, exactly 5 tokens had come back.

Test 4: under the limit. Carol sends 20 requests at 4 per second.

  • All 20 got a 200

Under the refill rate, the limiter is invisible.

The limits

This lives in memory, so it only works on one server. Behind a load balancer with multiple instances, each server gets its own copy of the buckets and the real limit becomes n times what you configured. For many servers you need shared storage, usually Redis.

Also, this was a short run on my own machine, which is the honest scope of the result: the logic is verified, the performance at real production scale is not.

The full build, the code, and all four test runs are in the video:

https://youtu.be/9fCCbBhJc6M

We are building Ship Stack: real experiments on real backends, with the actual numbers, no hand-waving. More of these are on the channel.

📰 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.