Skip to content

15 min read

What is rate limiting and how to manage secrets

In one sentence: Rate limiting puts a maximum on how many times something can be tried in a given time: after 10 wrong passwords in 15 minutes, the shop answers 429 and says how long to wait. Secrets are protected another way: long, random, out of the code and out of Git, and changed as soon as they leak.

What you will learn

  • Explain how a limit on attempts slows down brute force, and compare fixed window, sliding window and token bucket.
  • Answer 429 with Retry-After, and limit by account and by IP knowing their traps.
  • Keep secrets out of the code and out of Git, generate them with openssl and rotate them.
  • Give the database role only the permissions the API needs.

Before you start, read: 07-csrf-and-ssrf.md

Imagine a Sunday at three in the morning. A program sends Ana’s email, the administrator’s, to POST /v2/session, each time with a password from a list of the most used ones. Each attempt takes about 30 ms, which is what the slow hash from lesson 1, “Passwords,” costs: the first 1000, in half a minute. Nothing in the shop asks it to stop.

At the same time, another program crawls GitHub looking for keys uploaded by mistake. If it finds the shop’s WEBHOOK_SECRET in an old commit, it doesn’t guess anything: it signs fake payment notifications, and the shop believes them (webhooks lesson).

This lesson closes both doors: a limit on how many times something can be tried, and secrets that never leave the server.

The analogy

If you get your phone’s PIN wrong several times in a row, it stops asking you for a while: “Try again in 1 minute.” To you it costs a minute, once. To someone who finds it on a park bench and wants to try all 10,000 possible PINs, an eternity.

Where the analogy breaks down

  • The phone knows whoever is typing is holding it. The shop only sees an email and an IP: it can’t tell Ana from someone pretending to be her, so whoever tries with her email locks her out too.
  • The phone can only be reached by hand. The shop, from the whole internet, and an attacker can spread their attempts across thousands of addresses.

What happens at three in the morning is Brute forceGuessing something secret, like a password, by trying possibilities one after another until one works, usually with a program. It’s slowed down by making each attempt expensive, with a slow hash, and by limiting how many are allowed, with rate limiting.Go to definition: trying possibilities one after another until one is right. Against a login it takes three forms:

  • Many passwords against one account: Ana’s.
  • One password against many accounts (password spraying): 123456 with every known email.
  • The email and password pairs from another leak: the credential stuffing from lesson 1.

Lesson 1 made each attempt against a stolen table expensive, but here nobody needs the table: asking the server is enough. The brake is Rate limitingSetting a maximum on how many times something can be done in a period of time, like 10 login attempts every 15 minutes. Past it, the server answers 429 and says how long to wait. It slows down whoever tries passwords nonstop and whoever abuses an API.Go to definition: a maximum number of attempts per period of time. With 10 every 15 minutes, the 1000 passwords go from half a minute to more than a day, and whoever watches the logs sees it coming.

It also protects the server: each attempt costs it about 30 ms of processor and 19 MiB of memory, and thousands at once would leave it no time for anyone else.

With the shop’s limit, 10 attempts every 15 minutes:

Fixed window Sliding window Token bucket
How it counts One counter per clock slot (from 10:00 to 10:15, from 10:15 to 10:30…), which goes back to zero when each one starts The attempts of the last 15 minutes, counted from right now 10 tokens: each attempt spends one, and one comes back every 90 seconds
What it stores A number The time of each attempt The tokens and when the last one came back
Its drawback Between two slots it lets twice as many through: 10 at 10:14 and 10 at 10:15 It stores more data After spending all 10, tokens keep coming back: almost 20 fit in 15 minutes
Where you see it Quotas: “1000 requests per day” Sign-ins APIs that accept short bursts, like Amazon API Gateway

The shop writes down the time of each attempt and, to decide, counts the ones in the last 15 minutes (sliding window log). It’s the most exact, and here storing them costs little: at most, 10 instants per email and 30 per IP.

src/rate-limits.ts
// Looks at how that key stands, without recording anything.
async check(of: string): Promise<State> {
const now = clock();
const attempts = await store.attempts(key(of), now - window);
const secondsUntil = (instant: number) => Math.ceil((instant + window - now) / 1000);
const allowed = attempts.length < limit.max;
return {
allowed,
left: Math.max(0, limit.max - attempts.length),
// For another one to fit, the one that leaves exactly "max" attempts inside has to leave.
retryIn: allowed ? 0 : secondsUntil(attempts[attempts.length - limit.max]!),
resetIn: attempts.length === 0 ? 0 : secondsUntil(attempts[0]!),
};
},
  • store.attempts(key(of), now - window): the attempts of that key (the limit and the email, or the limit and the IP) in the last 15 minutes.
  • allowed: another one fits if there are fewer than max.
  • retryIn: in how many seconds the attempt that’s in the way leaves the window. Then one fits again.
  • check only looks. record, next to it, stores an attempt with the current time.
src/rate-limits.ts
// The shop's limits. When signing in only the failures count, and from two sides: by email (it
// protects each account, even if the attack comes from a thousand IPs) and by IP (it slows down
// whoever tries many accounts at once). The trap of the limit by email: anyone can use up Ana's 10
// attempts and leave her out for 15 minutes. That's why it's a while, not a lock forever. And the
// IP's is higher, because behind one IP there can be a whole office, or a university.
export const limits = {
signInByEmail: createLimiter({ name: 'session-email', max: 10, window: 15 * 60 }),
signInByIp: createLimiter({ name: 'session-ip', max: 30, window: 15 * 60 }),
// Creating accounts: every attempt counts, whether it goes well or badly.
accountsByIp: createLimiter({ name: 'accounts-ip', max: 5, window: 60 * 60 }),
};
  • signInByEmail: 10 failures per email. It protects each account even if the attempts come from a thousand IPs.
  • signInByIp: 30 failures per IP, whatever the email. It slows down whoever tries many accounts from one place.
  • accountsByIp: 5 new accounts per IP and hour, whether they go well or badly. It slows down mass sign-ups, and whoever uses the 409 from lesson 1 to ask which emails have an account.

When signing in, only the failures count. The route, in src/v2.ts:

src/v2.ts
v2.openapi(contract.signIn, async (c) => {
const { email, password } = c.req.valid('json');
const byEmail = email.toLowerCase();
const ip = ipOf(c);
const before = await checkSignInLimits(byEmail, ip);
if (before.some(([, state]) => !state.allowed)) return tooManyAttempts(c, before);
const user = await checkCredentials(email, password);
if (!user) {
// One more failure, in both counts: that email's and that IP's.
await limits.signInByEmail.record(byEmail);
await limits.signInByIp.record(ip);
setHeaders(c, await checkSignInLimits(byEmail, ip));
return problem(c, {
type: problemType('invalid-credentials'),
title: 'The email or the password is not correct',
status: 400,
detail: 'Check both and try again',
});
}
await openSession(c, user.id);
return c.json(user, 200);
});
  • The limits, before the password. checkSignInLimits looks at both; if the email or the IP reached the maximum, tooManyAttempts answers without computing any hash. Not even the right password gets in: if it did, whoever is trying would keep trying, and a 200 would tell them they got it.
  • email.toLowerCase(): ANA@shop.example uses up the attempts of ana@shop.example.
  • A failure is recorded twice, for the email and for the IP, and setHeaders says how many are left.

When nothing else fits, the shop answers 429 Too Many Requests, a 4xx Status codeA three-digit number at the start of every HTTP response that sums up what happened. 200 means “all good,” 404 “that doesn’t exist” and 400 “your request is malformed.”Go to definition from Phase 2, with Problem DetailsThe standard shape of the body of an error response in an API, written down in RFC 9457: a JSON with type (what kind of problem it is), title (its summary), status (the status code), detail (what happened this time) and instance (which of the times). It’s sent with the content type application/problem+json.Go to definition and three HeaderInformation a protocol puts in front of its data to do its job. In HTTP they are text lines of the form “Name: value”, such as Host or Content-Type; in TCP or IP they are numbers in fixed positions, such as ports or addresses.Go to definition:

Header Example What it says
Retry-After 870 How many seconds to wait
RateLimit-Policy "session-email";q=10;w=900 The rule: at most q attempts in w seconds
RateLimit "session-email";r=0;t=870 You have r left, and in t seconds the oldest one leaves

Retry-After is standard (RFC 9110). RateLimit-Policy and RateLimit are an IETF draft, not a standard: their shape has changed between versions and may change again. Many APIs use their own, like x-ratelimit-remaining in GitHub’s. The shop also sends RateLimit with every 400, so a program knows how much it has left.

The traps: shared IPs and locked-out victims

Section titled “The traps: shared IPs and locked-out victims”

An IP isn’t a person. Because of the NATNAT stands for Network Address Translation.What the router does on the way out to the internet: it replaces your device’s private IP address with its own public one, and notes the change so it can undo it in the replies.Go to definition from Phase 0, an office, a university or a carrier’s phones go out to the internet with a single Public IP addressIP stands for Internet Protocol.An IP address that is unique across the whole internet, so a computer can be reached with it from anywhere. At home, it usually belongs to your router and all your devices share it.Go to definition. With 10 failures per IP, a few absent-minded people would lock out the whole campus: that’s why the IP’s is 30. And whoever attacks from thousands of borrowed IPs doesn’t reach the limit of any of them: that’s what the email’s is for.

The limit by email has its own trap: anyone can use up another person’s attempts. With ten made-up passwords, someone leaves Ana unable to get in for 15 minutes. That’s why it lasts a while and isn’t a permanent lock. Big sites add a CAPTCHA, or an email to the owner.

Against credential stuffing spread across thousands of IPs, what really works is the second factor from lesson 2, “Sessions”.

The attempts are kept in the server’s memory, in a Map like the one in Phase 4 (createMemoryStore). The limiter talks to it with two functions:

src/rate-limits.ts
// Where the attempts are kept. Here, in the server's memory: if it restarts, they're forgotten,
// and with two servers each one would keep its own count. In Phase 7 the store will be Redis,
// shared by all: writing another store with these two functions is enough, without touching the
// rest.
export interface LimitStore {
/** The instants (in ms) of that key's attempts after "since", from oldest to newest. */
attempts(key: string, since: number): Promise<number[]>;
/** Records an attempt of that key at that instant. */
record(key: string, instant: number): Promise<void>;
}
  • When the server restarts, they’re forgotten. Stopping the shop also ends a lock.
  • With several copies of the server, each one keeps its own count. With three, an attacker tries up to 30 passwords per email, if their requests land on different copies.

A shared store is needed, and the usual one is Redis, the Key-value storeA database that stores each piece of data under a name, its key, and gives it back when you give it that name, like a dictionary. It doesn’t search by conditions or combine data, and in exchange it’s very fast. Redis is the best known, and it’s widely used as a cache.Go to definition from Phase 5. In Phase 7 you’ll start it next to the shop, and its store will have the same two functions: the limiter won’t change.

A SecretA piece of data that gives access to something and that only the people and programs that need it should know, like a database password or an API key. It’s never written inside the code.Go to definition never goes in the code, as you saw in the environment variables lesson: it goes in the .env, and the .env, in .gitignore.

What people forget is that Git doesn’t forget. Each commit is a snapshot of the project (“Git internals”), and deleting the secret in the next commit doesn’t remove it from the earlier ones. A secret that reached Git has leaked, and it gets changed. Cleaning the history comes later, and it doesn’t delete the copies already made.

No example secrets: the server won’t start

Section titled “No example secrets: the server won’t start”

Another way to leak a secret: not changing the example one, which is in Git for anyone to see. From this lesson on, src/config.ts doesn’t allow it:

src/config.ts
// A secret (lesson 8): it has to be there, be long (32 characters, like the ones
// openssl rand -base64 32 gives) and not be the example one from .env.example, which is in Git and
// anyone can read. If not, the server doesn't start: better not to start than to start with a
// secret that can be guessed.
const secret = (name: string) =>
z
.string({ error: `${name} is missing` })
.min(32, `${name} is too short: at least 32 characters`)
.refine(
(value) => !value.startsWith('change-this'),
`${name} is the example one: generate one with openssl rand -base64 32`,
);
  • .min(32, …): at least 32 characters. A short one is guessed by brute force, and with no limits: whoever has a signed notification tries secrets on their own computer until the signature matches.
  • .refine(…): a check of our own in Zod, which rejects the ones starting with change-this, the ones in .env.example.
  • secret('WEBHOOK_SECRET') and secret('OIDC_CLIENT_SECRET'): the same rules for both.

Better not to start than to start with a secret that can be guessed.

openssl rand -base64 32 takes 32 bytes from the system’s random generator and writes them in base64: 44 characters, 256 bits. No computer in the world guesses them by trying.

Rotating a secret is replacing it with a new one: as soon as it leaks or may have leaked (in Git, in a chat, in a log), when someone who knew it leaves, and every so often if your rules ask for it, so you know how to do it the day it’s urgent.

Each secret has two sides, and both get changed: the WEBHOOK_SECRET, in the shop and at the gateway; the OIDC_CLIENT_SECRET, in the shop and at the provider; the database password, in PostgreSQL and in the DATABASE_URL. That’s why many gateways let the old one stay valid for a few hours.

GitHub looks for secrets pushed by mistake

Section titled “GitHub looks for secrets pushed by mistake”

GitHub checks what gets pushed, looking for keys with known formats, from hundreds of services (Amazon, Stripe, GitHub…). It’s secret scanning. If it finds one, it warns the repository’s owner and, in public repositories, the key’s service, which can revoke it. With push protection, it rejects the git push before it arrives.

This course’s repository has both turned on, free because it’s public. But a secret that came out of openssl has no format GitHub recognizes: the defense is that it never reaches Git.

The database, with just the permissions it needs

Section titled “The database, with just the permissions it needs”

The DATABASE_URL carries the password of the shop role. Whoever has it can do whatever that role can do:

Who owns the tables?

Ventana de terminal
psql -d shop -c '\dt'

What you will see:

List of tables
Schema | Name | Type | Owner
--------+--------------------+-------+-------
public | api_keys | table | shop
public | categories | table | shop
public | idempotency_keys | table | shop
public | migrations | table | shop
public | notifications | table | shop
public | orders | table | shop
public | processed_events | table | shop
public | product_categories | table | shop
public | products | table | shop
public | sessions | table | shop
public | users | table | shop
(11 rows)

\dt lists the tables, and Owner says whose each one is: all of them belong to shop, which is also the database’s owner since the introduction to Phase 5. If notifications is missing, you didn’t apply the migration from lesson 7.

Being the owner lets it do everything inside shop: read the hashes in users, change orders, DROP TABLE orders or delete the whole database. It isn’t a superuser: it doesn’t create roles, or read other roles’ tables, or the server’s files. It’s Least privilegeThe rule of giving each user and each program only the permissions it needs, and no more. If something fails or someone gets in where they shouldn’t, the damage stays within the little it could touch.Go to definition halfway.

It has to be the owner because of the MigrationA file with a change to a database’s tables, such as adding a column, that is applied only once and in order, without deleting the data already there. The database itself records in a table which ones have already been applied.Go to definition, which create tables. A stricter setup uses shop only to migrate when deploying, and another role for the API, which only reads and writes rows:

-- As a superuser, connected to the shop database
CREATE ROLE shop_app LOGIN PASSWORD '…';
GRANT USAGE ON SCHEMA public TO shop_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO shop_app;
ALTER DEFAULT PRIVILEGES FOR ROLE shop IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO shop_app;

GRANT USAGE opens the schema, the folder of the tables; the second GRANT, the tables that already exist; ALTER DEFAULT PRIVILEGES, the ones the migrations will create. Tested on PostgreSQL 18: as shop_app, DROP TABLE orders answers ERROR: must be owner of table orders. It can still delete rows: least privilege reduces the damage, it doesn’t remove it. The project uses a single role so as not to complicate the .env.

The goal: start the shop with real secrets, and check that after ten wrong passwords not even the right one opens Ana’s account, while Carmen gets in without a problem.

You’re going to try passwords against your own shop, on localhost. Doing it against an account or a system that isn’t yours, without permission, is a crime.

You start from your project from lesson 7, “CSRF and SSRF”:

  1. Create src/rate-limits.ts.
  2. In src/config.ts, the secret function and its two uses.
  3. In src/contract.ts, the 429 of createAccount and of signIn; in src/v2.ts, the import of ./rate-limits.ts and the limits of those two routes. Whatever you haven’t seen here, copy it from the step.

The .env.example and the tests come in the lesson’s folder; its test/.env has longer test secrets:

Ventana de terminal
cd ~/backend-course/phase-3
curl -O https://backenddesdecero.com/practicas/shop-api/31-rate-limits.tar.gz
tar -xzf 31-rate-limits.tar.gz
cd shop-api
cp ../31-rate-limits/.env.example .
cp ../31-rate-limits/test/*.ts ../31-rate-limits/test/.env test/

1. This lesson’s tests

Ventana de terminal
npm test -- test/rate-limits.test.ts

What you will see:

> shop-api@1.0.0 test
> node --env-file=test/.env --test --test-concurrency=1 test/rate-limits.test.ts
✔ the eleventh failed attempt with the same email: 429 with Retry-After, even if the password is right (281.808825ms)
✔ another email from the same IP has its own count; the IP, its own, with a higher limit (597.354473ms)
✔ creating accounts: at most 5 per hour from the same IP (98.603519ms)
✔ the window slides: once the oldest attempt is past, one fits again (0.788269ms)
✔ the store can be swapped for another (Redis, in Phase 7) without touching the limiter (0.154054ms)
✔ without a secret, with a short one or with the example one, the server does not start (1926.103975ms)
ℹ tests 6
ℹ suites 0
ℹ pass 6
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 3906.613555

The outputs are from Node 26.11.1 and PostgreSQL 18; your times and your seconds to wait will be different. If any test fails with Configuration: …, you didn’t copy test/.env.

2. The server doesn’t start

Ventana de terminal
npm start

What you will see:

> shop-api@1.0.0 start
> node --env-file-if-exists=.env src/server.ts
Configuration: OIDC_CLIENT_SECRET: OIDC_CLIENT_SECRET is the example one: generate one with openssl rand -base64 32

In lesson 4, “OAuth,” you copied the example OIDC_CLIENT_SECRET, because the practice provider accepts any. Your WEBHOOK_SECRET, 48 characters long since Phase 4, passes; if it shows up too, change it all the same.

3. A new secret

Ventana de terminal
openssl rand -base64 32

What you will see:

8NpIFEvAgdHuQV1yPC6YtVVTFrDtMURK4QdZ2+QiPes=

Yours will be different, 44 characters long. Put it after OIDC_CLIENT_SECRET= in your .env and start with npm start: now the log says The shop is listening on http://localhost:3000. The practice gateway reads the WEBHOOK_SECRET from the same .env on every notification: here, rotating it is changing one line and restarting the shop.

In another terminal, ten attempts with Ana’s email and a password that isn’t hers:

4. Ten failures in a row

Ventana de terminal
for i in {1..10}; do
curl -s -o /dev/null -D - --json '{"email":"ana@shop.example","password":"any password at all"}' localhost:3000/v2/session | grep -i '^ratelimit:'
done

What you will see:

ratelimit: "session-email";r=9;t=900, "session-ip";r=29;t=900
ratelimit: "session-email";r=8;t=900, "session-ip";r=28;t=900
ratelimit: "session-email";r=7;t=900, "session-ip";r=27;t=900
ratelimit: "session-email";r=6;t=900, "session-ip";r=26;t=900
ratelimit: "session-email";r=5;t=900, "session-ip";r=25;t=900
ratelimit: "session-email";r=4;t=900, "session-ip";r=24;t=900
ratelimit: "session-email";r=3;t=900, "session-ip";r=23;t=900
ratelimit: "session-email";r=2;t=900, "session-ip";r=22;t=900
ratelimit: "session-email";r=1;t=900, "session-ip";r=21;t=900
ratelimit: "session-email";r=0;t=900, "session-ip";r=20;t=900

The for from the scripts lesson repeats the command ten times. -D - writes the headers on the screen, -o /dev/null throws away the body, and grep keeps the RateLimit line. There are 9, 8… down to 0 left for the email, and 20 for the IP. If it doesn’t start at r=9, you had already failed with Ana: restart the server and repeat.

5. The eleventh attempt

Ventana de terminal
curl -s -i -w '\n' --json '{"email":"ana@shop.example","password":"some other password"}' localhost:3000/v2/session

What you will see:

HTTP/1.1 429 Too Many Requests
content-type: application/problem+json
cross-origin-opener-policy: same-origin
cross-origin-resource-policy: same-origin
origin-agent-cluster: ?1
ratelimit: "session-email";r=0;t=870, "session-ip";r=20;t=870
ratelimit-policy: "session-email";q=10;w=900, "session-ip";q=30;w=900
referrer-policy: no-referrer
retry-after: 870
strict-transport-security: max-age=15552000; includeSubDomains
vary: Origin
x-content-type-options: nosniff
x-dns-prefetch-control: off
x-download-options: noopen
x-frame-options: SAMEORIGIN
x-permitted-cross-domain-policies: none
x-request-id: ffd4c9e6-92a3-49ab-8741-35c3ceabf8f2
x-xss-protection: 0
content-length: 141
Date: Wed, 14 Oct 2026 04:50:04 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"type":"https://shop.example/problems/too-many-attempts","title":"Too many attempts","status":429,"detail":"Wait 870 seconds and try again"}

A 429, and retry-after: 870: 30 seconds went by between the tenth failure and this one, already taken off the 900. ratelimit-policy carries both rules. The rest are the security headers from lesson 6, “Injection”.

If you get a 400, the server restarted in between (with npm run dev, when you save a file) and forgot the failures.

Now Ana really signs in, and then Carmen, from the same IP:

6. Ana, locked out; Carmen, not

Ventana de terminal
curl -s -o /dev/null -w '%{http_code}\n' --json '{"email":"ana@shop.example","password":"ana-practice-2026"}' localhost:3000/v2/session
curl -s -o /dev/null -w '%{http_code}\n' --json '{"email":"carmen@example.com","password":"carmen-practice-2026"}' localhost:3000/v2/session

What you will see:

429
200

Ana stays out with her right password: the trap of the limit by email, in your terminal. Carmen gets in: her email has its own count, and your IP has 20 failures left. For Ana to get back in, wait as long as Retry-After says or restart the server: the limit lives in its memory.

  • “Too many attempts. Try again later,” or a sudden CAPTCHA, when you get it wrong several times signing in to a website.
  • The card the ATM keeps after three wrong PINs: a lock with no end date, which the bank can afford because it can see you at the branch.
  • APIs with limits, like the AI model APIs from Phase 11, which answer 429.
  • Locking the account forever, or letting people in with the right password during the lock.
  • Limiting by the connection’s IP behind a proxy (Phase 8): everything comes from it. And X-Forwarded-For, the header with the real IP, is only valid if your proxy sets it: anyone can write it.
  • Counting in each server’s memory, with several servers.
  • Deleting a secret pushed to Git and still using it.
  • Leaving the .env.example secret, or a short one.
  • Connecting the API with the database’s superuser.
  • A limit on attempts per period of time makes brute force slow and visible.
  • The fixed window lets twice as many through between slots; the token bucket accepts bursts; the sliding window, the shop’s, counts exactly the last 15 minutes.
  • When over the limit, 429 with Retry-After; RateLimit-Policy and RateLimit are a draft.
  • By email and by IP, with their traps: shared IPs and locked-out victims. Keeping them in memory works for one server; with several, Redis.
  • Long, random secrets, never in Git, rotated when they leak; and the database, with just the permissions it needs.
An API limits to 10 attempts per fixed window of 15 minutes: from 10:00 to 10:15, from 10:15 to 10:30… How many attempts can someone make between 10:14 and 10:16?

A university goes out to the internet through a single public IP address. If the shop limited to 10 failures per IP every 15 minutes, what would happen?

Someone makes ten wrong attempts with Luis’s email. Two minutes later, Luis types his right password. What does the shop answer him?

You run three copies of the server; each request goes to one of them, and each copy keeps the attempts in its memory. How many passwords can someone try against one email in 15 minutes?

You push the .env with the WEBHOOK_SECRET to GitHub by mistake. In the next commit you delete it and add .env to .gitignore. Can you keep using that secret?

Someone gets the shop’s DATABASE_URL, with the shop role from Phase 5, owner of the database. What can they do with it?

phase-6 · lesson 8/9