APIs · Intermediate · 25 min
Rate limit an API in application code with a token bucket
By Padding · Updated 18 Nov 2026
node:26 (Debian 13) · Node.js 26.13 · Express 5.3 · iovalkey 0.4 · Valkey 8.1 or later
You will give each API key its own token bucket in an Express 5.3 app, answer over-limit callers with 429, Retry-After and RateLimit headers, set different limits per plan, and share the buckets between app instances through Valkey.
On this page
A limit at the proxy, as in rate limit an API with Nginx, counts requests per IP address. That stops floods, but it cannot tell your customers apart. Two paying customers behind one office router share a limit, and one customer with ten servers gets ten limits. Many mobile networks, including large ones in Nigeria, Kenya and South Africa, put thousands of phones behind a few public addresses (carrier-grade NAT), so a per-IP limit there punishes people who did nothing wrong. Once a request carries an API key, your application knows who is calling, and it can limit that caller fairly.
In this tutorial you build that limit in an Express 5.3 app on Node.js 26. Each API key gets a token bucket: a bucket holds a few tokens, each request spends one, and tokens drip back in at a steady rate. A full bucket allows a short burst, and the drip sets the long-run rate. Free keys get a small bucket and pro keys a larger one. Refused requests get 429 Too Many Requests, a Retry-After header that says how many seconds to wait, and the RateLimit and RateLimit-Policy headers from the IETF draft that is close to becoming a standard (draft-ietf-httpapi-ratelimit-headers-11, May 2026). Then you run two copies of the app, see the limit double, and fix it by keeping the buckets in Valkey with a script that runs atomically.
Everything listens on 127.0.0.1, so nothing is reachable from outside your machine. Keep the per-IP limit at the proxy as well: it protects the login route and anything that runs before a key is checked.
Step 1 · Create the project and two API keys
Make a throwaway folder and install Express. The range ~5.3.0 allows 5.3 patch releases only:
mkdir -p ~/ratelimit-demo
cd ~/ratelimit-demo
npm init -y
npm pkg set type=module
npm install express@~5.3.0The app needs keys to limit. Generate one free key and one pro key. The script writes them to .env, where the app reads them, and writes a header file for each key so that curl can send it without the key appearing on a command line, in your shell history or in the process list. Every file is created with mode 600, readable by you only, from the moment it exists:
node --input-type=module -e '
import { randomBytes } from "node:crypto"
import { writeFileSync } from "node:fs"
const key = (plan) => `demo_${plan}_` + randomBytes(24).toString("base64url")
const free = key("free")
const pro = key("pro")
const save = (file, text) => writeFileSync(file, text, { mode: 0o600, flag: "wx" })
save(".env", `FREE_KEYS=${free}\nPRO_KEYS=${pro}\n`)
save("free.header", `Authorization: Bearer ${free}\n`)
save("pro.header", `Authorization: Bearer ${pro}\n`)
'The demo_free_ and demo_pro_ prefixes make the keys easy to recognise if one leaks into a log. These are local demo keys. A real service stores only a hash of each key in its database; protect an API with API keys shows that part.
Check it worked
ls -l .env free.header pro.header
cut -d_ -f1-3 .envAll three files show -rw-------. The second command prints FREE_KEYS=demo_free and PRO_KEYS=demo_pro, which shows the keys are there without printing them.
Step 2 · Write the token bucket
A bucket is two numbers: how many tokens it holds, and when you last looked. You do not need a timer to refill it. Each time a request arrives, work out how many tokens have dripped in since the last look, add them up to the bucket's capacity, then spend one if there is one to spend. The bucket also answers two questions the headers need: how many whole tokens are left, and how long until the next token arrives.
Create bucket.js:
cat > bucket.js <<'JS'
// One token bucket per key, kept in this process's memory.
// A plan is { capacity, refillMs }: the bucket holds `capacity` tokens
// and gains one token every `refillMs` milliseconds.
export function createMemoryStore({ now = () => Date.now() } = {}) {
const buckets = new Map()
return {
async take(key, { capacity, refillMs }) {
const time = now()
const bucket = buckets.get(key) ?? { tokens: capacity, at: time }
const dripped = Math.max(0, time - bucket.at) / refillMs
bucket.tokens = Math.min(capacity, bucket.tokens + dripped)
bucket.at = time
let allowed = false
if (bucket.tokens >= 1) {
bucket.tokens -= 1
allowed = true
}
buckets.set(key, bucket)
// Milliseconds until the next whole token arrives.
const waitMs = Math.ceil((1 - (bucket.tokens % 1)) * refillMs)
return { allowed, remaining: Math.floor(bucket.tokens), waitMs }
},
}
}
JSTwo choices in it matter:
- The clock is a parameter. The app uses the real clock, but a check can pass a fake one and get the same answer every time.
- Tokens are fractions. Half a refill period gives half a token, so nobody gains or loses time to rounding.
The map only gets an entry for keys that passed the key check (you add that next), so its size is bounded by the number of keys you issued. A bucket keyed on something an attacker controls, such as a header value, would let them fill your memory.
Check it worked
Drive a bucket with a fake clock. It holds three tokens and gains one per second. Four requests at time zero, then two more one second later:
node --input-type=module -e '
import { createMemoryStore } from "./bucket.js"
let time = 0
const store = createMemoryStore({ now: () => time })
const plan = { capacity: 3, refillMs: 1000 }
const results = []
for (let i = 0; i < 4; i++) results.push((await store.take("k", plan)).allowed)
time = 1000
for (let i = 0; i < 2; i++) results.push((await store.take("k", plan)).allowed)
console.log(results.join(" "))
'The output is true true true false true false. The burst of three is allowed, the fourth is refused, and one second buys exactly one more request.
Step 3 · Identify the caller and answer with 429
Three small files turn the bucket into middleware. First, the plans. A free key may burst 5 requests and then gets one every 2 seconds. A pro key may burst 20 and then gets one every half second. Both fill from empty in 10 seconds. The numbers are small so that you can see them work; a real service would use something like 100 per minute:
cat > plans.js <<'JS'
export const plans = {
free: { capacity: 5, refillMs: 2000 },
pro: { capacity: 20, refillMs: 500 },
}
JSNext, auth.js. It reads the keys from the environment, keeps only their SHA-256 hashes in memory, and attaches the caller's plan and a short key ID to the request. The ID is a slice of the hash, so the raw key never becomes a bucket name, a log line or, later, a Valkey key:
cat > auth.js <<'JS'
import { createHash } from 'node:crypto'
import { plans } from './plans.js'
const sha256 = (value) => createHash('sha256').update(value).digest('hex')
// FREE_KEYS and PRO_KEYS hold comma-separated keys.
export function loadKeys(env) {
const keys = new Map()
for (const plan of Object.keys(plans)) {
const list = env[`${plan.toUpperCase()}_KEYS`] ?? ''
for (const key of list.split(',').map((k) => k.trim()).filter(Boolean)) {
keys.set(sha256(key), plan)
}
}
return keys
}
export function authenticate(keys) {
return (req, res, next) => {
const match = /^Bearer (\S+)$/.exec(req.get('authorization') ?? '')
const hash = match ? sha256(match[1]) : null
const plan = hash ? keys.get(hash) : undefined
if (!plan) {
res.set('WWW-Authenticate', 'Bearer')
return res.status(401).json({ error: 'Missing or unknown API key' })
}
req.client = { keyId: hash.slice(0, 16), plan }
next()
}
}
JSNow ratelimit.js, the limiter itself. It takes a token from the caller's bucket and sets two headers on every response. RateLimit-Policy describes the plan: q is the quota and w the window in seconds. RateLimit describes the caller's state right now: r is the requests left and t the seconds within which they cannot use more than r, which for a token bucket is the time until the next token. When the bucket is empty, the response is 429 with a Retry-After of the same number of seconds:
cat > ratelimit.js <<'JS'
import { plans } from './plans.js'
export function rateLimit(store) {
return async (req, res, next) => {
const { keyId, plan: planName } = req.client
const plan = plans[planName]
let result
try {
result = await store.take(`rl:${keyId}`, plan)
} catch (err) {
console.error('rate limit store failed:', err.message)
res.set('Retry-After', '5')
return res.status(503).json({ error: 'Rate limiter unavailable, try again shortly' })
}
const windowSeconds = Math.ceil((plan.capacity * plan.refillMs) / 1000)
const waitSeconds = Math.ceil(result.waitMs / 1000)
res.set('RateLimit-Policy', `"${planName}";q=${plan.capacity};w=${windowSeconds}`)
res.set('RateLimit', `"${planName}";r=${result.remaining};t=${waitSeconds}`)
if (result.allowed) return next()
res.set('Retry-After', String(waitSeconds))
res.status(429).json({ error: 'Too many requests', retryAfterSeconds: waitSeconds })
}
}
JSThe try block decides what happens when the store fails. In memory it never does, but the shared store you add later can, and this code refuses the request with 503 rather than letting it through unlimited. A later step tests that.
Wire it into an app. The health check stays outside the limit, so a load balancer polling it never uses anyone's quota. Everything else under /api is checked for a key, then limited, in that order, so unknown keys never get a bucket:
cat > app.js <<'JS'
import express from 'express'
import { authenticate, loadKeys } from './auth.js'
import { rateLimit } from './ratelimit.js'
export function createApp({ store, env = process.env }) {
const app = express()
app.disable('x-powered-by')
app.get('/api/health', (req, res) => res.json({ status: 'ok' }))
app.use('/api', authenticate(loadKeys(env)), rateLimit(store))
app.get('/api/quote', (req, res) => {
res.json({ quote: 'Measure twice, cut once.', plan: req.client.plan })
})
app.use((req, res) => res.status(404).json({ error: 'Not found' }))
app.use((err, req, res, next) => {
if (res.headersSent) return next(err)
console.error(err)
res.status(500).json({ error: 'Internal server error' })
})
return app
}
JS
cat > server.js <<'JS'
import { createApp } from './app.js'
import { createMemoryStore } from './bucket.js'
const store = createMemoryStore()
const port = Number(process.env.PORT ?? 8000)
const server = createApp({ store }).listen(port, '127.0.0.1', (error) => {
if (error) throw error
console.log(`Listening on http://127.0.0.1:${port} with in-memory buckets`)
})
for (const signal of ['SIGINT', 'SIGTERM']) {
process.on(signal, () => server.close(() => process.exit(0)))
}
JSStart it in your second terminal and leave it running. --env-file=.env loads the keys without them ever being typed:
cd ~/ratelimit-demo
node --env-file=.env server.jsIt prints Listening on http://127.0.0.1:8000 with in-memory buckets.
Check it worked
Back in your first terminal, call the API with no key, then with the free key. -H @free.header reads the header from the file:
curl -s -w ' %{http_code}\n' http://127.0.0.1:8000/api/quote
curl -si -H @free.header http://127.0.0.1:8000/api/quote | grep -iE '^(HTTP|ratelimit)'The first line is {"error":"Missing or unknown API key"} 401. The second call shows HTTP/1.1 200 OK, RateLimit-Policy: "free";q=5;w=10 and RateLimit: "free";r=4;t=2: one of five tokens spent, and the next token arrives within 2 seconds.
Step 4 · Burst-test both plans
One request at a time does not show a limit. Write a small burst script that fires many requests at once and counts the status codes. It takes a header file, a count, and one or more URLs, which it uses in turn:
cat > burst.mjs <<'JS'
// Usage: node burst.mjs <header-file> <count> <url> [more urls...]
import { readFileSync } from 'node:fs'
const [headerFile, count, ...urls] = process.argv.slice(2)
const line = readFileSync(headerFile, 'utf8').trim()
const colon = line.indexOf(':')
const headers = { [line.slice(0, colon)]: line.slice(colon + 1).trim() }
const statuses = await Promise.all(
Array.from({ length: Number(count) }, async (_, i) => {
const res = await fetch(urls[i % urls.length], { headers })
await res.arrayBuffer()
return res.status
}),
)
const tally = {}
for (const status of statuses) tally[status] = (tally[status] ?? 0) + 1
console.log(Object.entries(tally).map(([s, n]) => `${s}: ${n}`).join(' '))
JSWait 12 seconds, a little longer than the 10 it takes to refill, so the buckets you used in the last step are full again, then send 30 requests with each key:
sleep 12
node burst.mjs free.header 30 http://127.0.0.1:8000/api/quote
node burst.mjs pro.header 30 http://127.0.0.1:8000/api/quoteThe free key prints 200: 5 429: 25 and the pro key 200: 20 429: 10. On a slow machine a burst can take long enough for a token to drip back, so one extra 200 is normal.
Now look at a refused response in full:
curl -si -H @free.header http://127.0.0.1:8000/api/quoteIt starts HTTP/1.1 429 Too Many Requests and includes Retry-After: 2 (or 1), RateLimit: "free";r=0;t=2 with the same number, and the body {"error":"Too many requests","retryAfterSeconds":2}.
Check it worked
Do what a well-behaved client does: wait for the time Retry-After gave, then try again:
sleep 2
curl -s -o /dev/null -w '%{http_code}\n' -H @free.header http://127.0.0.1:8000/api/quoteThe output is 200. If you write the client side too, make it read Retry-After and wait that long before retrying. Apps on patchy mobile connections often retry at once in a loop, and each of those retries spends quota for nothing.
Step 5 · Run two copies and watch the limit double
Production apps usually run more than one process: several Node processes on one server, or several servers behind a load balancer. Start a second copy on port 8001 in your third terminal:
cd ~/ratelimit-demo
PORT=8001 node --env-file=.env server.jsWait for the free bucket to refill, then spread a burst across both copies, as a load balancer would:
sleep 12
node burst.mjs free.header 30 http://127.0.0.1:8000/api/quote http://127.0.0.1:8001/api/quoteCheck it worked
The output is 200: 10 429: 20. Each process has its own map, so each gave the key a full bucket of 5. With ten processes, a free key would get 50. The fix is to keep the buckets somewhere every copy shares.
Step 6 · Share the buckets through Valkey
Stop both copies with Ctrl+C. Valkey, the open-source fork of Redis, is a good home for buckets: it is fast, every app copy can reach it, and it can expire keys by itself.
The obvious version, read the bucket, do the sums in Node, write it back, is wrong with two copies. Both can read the same bucket at the same moment, both see one token left, and both let a request through. The bucket logic has to run inside Valkey as one step. Valkey runs a Lua script atomically: no other command runs while it does. The script also takes the time from Valkey's own clock with TIME, so app servers with slightly different clocks still agree.
Install the client. iovalkey is the Valkey project's Node.js client:
npm install iovalkey@~0.4.0Create take-token.lua. It is the same bucket as bucket.js, line for line:
cat > take-token.lua <<'LUA'
-- KEYS[1]: the bucket. ARGV[1]: capacity. ARGV[2]: milliseconds per token.
local capacity = tonumber(ARGV[1])
local refill_ms = tonumber(ARGV[2])
local time = redis.call('TIME')
local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
local saved = redis.call('HMGET', KEYS[1], 'tokens', 'at')
local tokens = tonumber(saved[1]) or capacity
local at = tonumber(saved[2]) or now
tokens = math.min(capacity, tokens + math.max(0, now - at) / refill_ms)
local allowed = 0
if tokens >= 1 then
tokens = tokens - 1
allowed = 1
end
redis.call('HSET', KEYS[1], 'tokens', tostring(tokens), 'at', tostring(now))
-- A bucket left alone this long is full again, the same as no bucket at all.
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity * refill_ms))
local wait_ms = math.ceil((1 - tokens % 1) * refill_ms)
return { allowed, math.floor(tokens), wait_ms }
LUAValkey's scripting API still calls itself redis, for compatibility, so redis.call is correct here. The PEXPIRE line means idle buckets clean themselves up.
Create valkey-store.js. It has the same take method as the memory store, so the middleware does not change:
cat > valkey-store.js <<'JS'
import { readFileSync } from 'node:fs'
import { Valkey } from 'iovalkey'
const lua = readFileSync(new URL('./take-token.lua', import.meta.url), 'utf8')
export function createValkeyStore(url) {
// Give up on a command after one reconnect attempt instead of queueing it,
// so a Valkey outage turns into a fast 503, not a hanging request.
const client = new Valkey(url, { maxRetriesPerRequest: 1 })
client.on('error', (err) => console.error('valkey:', err.message))
client.defineCommand('takeToken', { numberOfKeys: 1, lua })
return {
async take(key, { capacity, refillMs }) {
const [allowed, remaining, waitMs] = await client.takeToken(key, capacity, refillMs)
return { allowed: allowed === 1, remaining, waitMs }
},
close: () => client.quit(),
}
}
JSdefineCommand loads the script once and then calls it by its hash with EVALSHA, so the script text is not sent with every request. Replace server.js so that it uses Valkey whenever VALKEY_URL is set:
cat > server.js <<'JS'
import { createApp } from './app.js'
import { createMemoryStore } from './bucket.js'
import { createValkeyStore } from './valkey-store.js'
const url = process.env.VALKEY_URL
const store = url ? createValkeyStore(url) : createMemoryStore()
const port = Number(process.env.PORT ?? 8000)
const server = createApp({ store }).listen(port, '127.0.0.1', (error) => {
if (error) throw error
console.log(`Listening on http://127.0.0.1:${port} with ${url ? 'Valkey' : 'in-memory'} buckets`)
})
for (const signal of ['SIGINT', 'SIGTERM']) {
process.on(signal, () =>
server.close(async () => {
await store.close?.()
process.exit(0)
}),
)
}
JSAdd the Valkey URL to .env. This reads the password from the config file that the Valkey tutorial set up, so it is never typed or shown. .env is already private, and appending keeps it that way:
printf 'VALKEY_URL=valkey://:%s@127.0.0.1:6379\n' "$(sudo awk '$1 == "requirepass" {print $2}' /etc/valkey/valkey.conf)" >> .env
cut -d= -f1 .envThe second command lists FREE_KEYS, PRO_KEYS and VALKEY_URL, names only. Start the two copies again, one in each server terminal:
node --env-file=.env server.jsPORT=8001 node --env-file=.env server.jsEach prints Listening on ... with Valkey buckets.
Check it worked
Run the same burst across both copies, then one for the pro key:
node burst.mjs free.header 30 http://127.0.0.1:8000/api/quote http://127.0.0.1:8001/api/quote
node burst.mjs pro.header 30 http://127.0.0.1:8000/api/quote http://127.0.0.1:8001/api/quoteThe free key prints 200: 5 429: 25 and the pro key 200: 20 429: 10, the same as with one process. The two copies now share one bucket per key. Look at the buckets in Valkey. The password goes into REDISCLI_AUTH for this shell. valkey-cli reads it from there, so it never appears on the command line. Valkey 8.1's client reads only this name, not VALKEYCLI_AUTH:
export REDISCLI_AUTH="$(sudo awk '$1 == "requirepass" {print $2}' /etc/valkey/valkey.conf)"
valkey-cli --scan --pattern 'rl:*'
valkey-cli HGETALL "$(valkey-cli --scan --pattern 'rl:*' | head -n 1)"There are two keys, rl: followed by 16 hexadecimal characters, one per API key. Neither contains the API key itself. HGETALL shows tokens, a number near zero, and at, a time in milliseconds. Ten seconds after your last request both keys are gone, because a bucket left alone that long is full again.
Step 7 · Decide what happens when Valkey is down
If Valkey stops, the limiter cannot read a bucket. There are two honest answers. Fail open lets requests through unlimited, which keeps the API up but removes your protection exactly when something is already wrong. Fail closed refuses requests until Valkey is back. This app fails closed, in the try block in ratelimit.js, which suits an API where the limit protects paid resources such as SMS sends or payments. If uptime matters more, change that block to log the error and call next(), and alert on the log line.
Check what callers see. Start a third copy whose VALKEY_URL points at a port where nothing listens. A variable set on the command line wins over the same one in .env, and this URL carries no password:
PORT=8002 VALKEY_URL=valkey://127.0.0.1:6390 node --env-file=.env server.jsThat terminal keeps printing valkey: connect ECONNREFUSED 127.0.0.1:6390 as the client retries.
Check it worked
curl -s --max-time 10 -w ' %{http_code}\n' -H @pro.header http://127.0.0.1:8002/api/quoteThe output is {"error":"Rate limiter unavailable, try again shortly"} 503, within a second or so. The health check on the same copy still answers 200, so a load balancer keeps sending traffic and the API recovers by itself when Valkey returns. Stop this copy with Ctrl+C.
Step 8 · Stop the app and clean up
Press Ctrl+C in both server terminals. The buckets in Valkey expire by themselves within 10 seconds, so there is nothing to delete there. Clear the password from your shell, then delete the project folder, which holds only what you made here, including the demo keys:
unset REDISCLI_AUTH
cd ~
rm -rf ~/ratelimit-demoCheck it worked
ls -d ~/ratelimit-demo 2>/dev/null || echo "removed"The output is removed. Valkey itself keeps running, as it was before you started.
Next steps
- Keep a per-IP limit in front of the app for login and other routes that run before a key is checked: rate limit an API with Nginx.
- Replace the demo keys with hashed keys you can rotate and revoke: protect an API with API keys.
- Run Valkey with a password and memory limit on your server: install Valkey on Ubuntu.
- Add validation and error handling around the routes: build a REST API with Express 5.
Part of these paths
Related tutorials
- How to Rate Limit an API with NginxYou will put request limits in front of a small API with Nginx 1.30 on Ubuntu 26.04, give the login route a stricter limit than the rest, return a proper 429 response with Retry-After, exempt a trusted address, and watch every limit work with real requests.
- Protect an API with API keys you can rotate and revokeYou will build an API key system for an Express 5.3 API on Node.js 26 that issues prefixed random keys, stores only their SHA-256 hashes, checks scopes, records last use, and rotates or revokes any key without breaking the partners who hold the others.
- How to Install Valkey 9.1 (a Redis-Compatible Cache) on Ubuntu 26.04You will install Valkey 9.1 from the project's official binary release, run it as its own user with a password and a memory limit, and use it as a cache from the command line.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials