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
The problem
Section titled “The problem”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
Section titled “The analogy”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.
How it really works
Section titled “How it really works”Trying nonstop: brute force
Section titled “Trying nonstop: brute force”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):
123456with 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.
Three ways to count attempts
Section titled “Three ways to count attempts”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 counts with a sliding window
Section titled “The shop counts with a sliding window”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.
// 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 thanmax.retryIn: in how many seconds the attempt that’s in the way leaves the window. Then one fits again.checkonly looks.record, next to it, stores an attempt with the current time.
By email and by IP: the shop’s limits
Section titled “By email and by IP: the shop’s limits”// 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 the409from lesson 1 to ask which emails have an account.
When signing in, only the failures count. The route, in 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.
checkSignInLimitslooks at both; if the email or the IP reached the maximum,tooManyAttemptsanswers without computing any hash. Not even the right password gets in: if it did, whoever is trying would keep trying, and a200would tell them they got it. email.toLowerCase():ANA@shop.exampleuses up the attempts ofana@shop.example.- A failure is recorded twice, for the email and for the IP, and
setHeaderssays how many are left.
429 and Retry-After: how long to wait
Section titled “429 and Retry-After: how long to wait”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”.
In memory: fine for a single server
Section titled “In memory: fine for a single server”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:
// 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.
Secrets, out of the code and out of Git
Section titled “Secrets, out of the code and out of Git”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:
// 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 withchange-this, the ones in.env.example.secret('WEBHOOK_SECRET')andsecret('OIDC_CLIENT_SECRET'): the same rules for both.
Better not to start than to start with a secret that can be guessed.
Generating a secret and rotating it
Section titled “Generating a secret and rotating it”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?
psql -d shop -c '\dt'What you will see:
List of tablesSchema | Name | Type | Owner--------+--------------------+-------+-------public | api_keys | table | shoppublic | categories | table | shoppublic | idempotency_keys | table | shoppublic | migrations | table | shoppublic | notifications | table | shoppublic | orders | table | shoppublic | processed_events | table | shoppublic | product_categories | table | shoppublic | products | table | shoppublic | sessions | table | shoppublic | 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 databaseCREATE 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.
Try it
Section titled “Try it”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.
Update your project
Section titled “Update your project”You start from your project from lesson 7, “CSRF and SSRF”:
- Create
src/rate-limits.ts. - In
src/config.ts, thesecretfunction and its two uses. - In
src/contract.ts, the429ofcreateAccountand ofsignIn; insrc/v2.ts, theimportof./rate-limits.tsand 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:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/31-rate-limits.tar.gztar -xzf 31-rate-limits.tar.gzcd shop-apicp ../31-rate-limits/.env.example .cp ../31-rate-limits/test/*.ts ../31-rate-limits/test/.env test/1. This lesson’s tests
npm test -- test/rate-limits.test.tsWhat 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.613555The 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.
Real secrets
Section titled “Real secrets”2. The server doesn’t start
npm startWhat 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 32In 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
openssl rand -base64 32What 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.
Ten wrong passwords
Section titled “Ten wrong passwords”In another terminal, ten attempts with Ana’s email and a password that isn’t hers:
4. Ten failures in a row
for i in {1..10}; docurl -s -o /dev/null -D - --json '{"email":"ana@shop.example","password":"any password at all"}' localhost:3000/v2/session | grep -i '^ratelimit:'doneWhat you will see:
ratelimit: "session-email";r=9;t=900, "session-ip";r=29;t=900ratelimit: "session-email";r=8;t=900, "session-ip";r=28;t=900ratelimit: "session-email";r=7;t=900, "session-ip";r=27;t=900ratelimit: "session-email";r=6;t=900, "session-ip";r=26;t=900ratelimit: "session-email";r=5;t=900, "session-ip";r=25;t=900ratelimit: "session-email";r=4;t=900, "session-ip";r=24;t=900ratelimit: "session-email";r=3;t=900, "session-ip";r=23;t=900ratelimit: "session-email";r=2;t=900, "session-ip";r=22;t=900ratelimit: "session-email";r=1;t=900, "session-ip";r=21;t=900ratelimit: "session-email";r=0;t=900, "session-ip";r=20;t=900The 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
curl -s -i -w '\n' --json '{"email":"ana@shop.example","password":"some other password"}' localhost:3000/v2/sessionWhat you will see:
HTTP/1.1 429 Too Many Requestscontent-type: application/problem+jsoncross-origin-opener-policy: same-origincross-origin-resource-policy: same-originorigin-agent-cluster: ?1ratelimit: "session-email";r=0;t=870, "session-ip";r=20;t=870ratelimit-policy: "session-email";q=10;w=900, "session-ip";q=30;w=900referrer-policy: no-referrerretry-after: 870strict-transport-security: max-age=15552000; includeSubDomainsvary: Originx-content-type-options: nosniffx-dns-prefetch-control: offx-download-options: noopenx-frame-options: SAMEORIGINx-permitted-cross-domain-policies: nonex-request-id: ffd4c9e6-92a3-49ab-8741-35c3ceabf8f2x-xss-protection: 0content-length: 141Date: Wed, 14 Oct 2026 04:50:04 GMTConnection: keep-aliveKeep-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
curl -s -o /dev/null -w '%{http_code}\n' --json '{"email":"ana@shop.example","password":"ana-practice-2026"}' localhost:3000/v2/sessioncurl -s -o /dev/null -w '%{http_code}\n' --json '{"email":"carmen@example.com","password":"carmen-practice-2026"}' localhost:3000/v2/sessionWhat you will see:
429200Ana 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.
You have already seen it
Section titled “You have already seen it”- “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.
Common mistakes
Section titled “Common mistakes”- 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.examplesecret, or a short one. - Connecting the API with the database’s superuser.
Summary
Section titled “Summary”- 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,
429withRetry-After;RateLimit-PolicyandRateLimitare 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.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Authentication Cheat Sheet (OWASP): how to slow down automated attacks on a login.
- Secrets Management Cheat Sheet (OWASP): storing and rotating secrets.
- RateLimit header fields for HTTP (IETF): the draft of the headers.
- RFC 6585, section 4 (IETF): the
429code. - Secret scanning (GitHub): what GitHub looks for in what you push.
- GRANT (PostgreSQL): the permissions of each role.