rate-limiting
Skill9 starsChanged 5 months agoApache-2.0View on GitHub
Implements rate limiting and throttling (token-bucket, sliding-window, distributed Redis counters, per-key quotas, 429 + Retry-After) to protect APIs from abuse and overload.
8 other projects use a version of this.
Adopted by
Most recently taken up by
- chunkydotdev/email-skillstheir own version, first seen Sep 29, 2026
- soden46/syarif-laravel-ai-skillstheir own version, first seen Jul 16, 2026
- shinzoxD/knackboxtheir own version, first seen Jul 10, 2026
- YepAPI/skillstheir own version, first seen Apr 12, 2026
- ffsshhttiikk/opencode-agents-skillstheir own version, first seen Feb 28, 2026
- wshaddix/dotnet-skillstheir own version, first seen Feb 16, 2026
Other versions8 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 8
- wshaddix/dotnet-skills★ 79same name
- harperaa/secure-claude-skills★ 18same name
- wpank/ai★ 11same name
- YepAPI/skills★ 8same name
- chunkydotdev/email-skills★ 5same name
- soden46/syarif-laravel-ai-skills★ 4same name
- ffsshhttiikk/opencode-agents-skills★ 2same name
- shinzoxD/knackbox★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository147 other files it gives its agents.
- second-brain/AGENTS.mdAGENTS.md
- second-brain/CLAUDE.mdCLAUDE.md
- agent-tool-mcp-builderSkill
- api-design-reviewSkill
- async-concurrency-correctnessSkill
- audit-accessibility-wcagSkill
- audit-license-complianceSkill
- audit-technical-seoSkill
- auth-jwt-sessionSkill
- author-codemodSkill
- brainstorm-designSkill
- build-audit-loggingSkill
- build-cdc-streaming-pipelineSkill
- build-cli-toolSkill
- build-data-tableSkill
- build-etl-pipelineSkill
- build-form-validationSkill
- build-native-mobile-uiSkill
- build-office-docsSkill
- build-offline-first-syncSkill
- build-react-componentSkill
- build-realtime-channelSkill
- build-spreadsheetSkill
- build-vector-searchSkill
- caching-strategySkill
- cicd-pipeline-authorSkill
- cloud-cost-optimizeSkill
- code-commentsSkill
- code-reviewSkill
- compose-local-dev-stackSkill
- configure-bundler-buildSkill
- configure-dns-tlsSkill
- configure-reverse-proxy-lbSkill
- configure-security-headers-cspSkill
- contract-testingSkill
- datetime-timezone-correctnessSkill
- db-migration-safetySkill
- debug-ci-pipeline-failureSkill
- debug-flaky-testsSkill
- debug-frontend-browserSkill
- debug-root-causeSkill
- defend-llm-prompt-injectionSkill
- deliver-webhooksSkill
- dependency-upgradeSkill
- deploy-releaseSkill
- design-api-paginationSkill
- design-authorization-modelSkill
- design-backup-dr-recoverySkill
- design-event-sourcing-cqrsSkill
- design-multi-tenancySkill
- design-protobuf-grpc-serviceSkill
- design-relational-schemaSkill
- design-search-index-infraSkill
- design-state-machineSkill
- design-token-systemSkill
- diff-table-paritySkill
- distributed-locks-leasesSkill
- dockerfile-optimizeSkill
- encrypt-sensitive-dataSkill
- error-messageSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
6 rules. 0 are common, 2 are distinctive, and 4 are very specific to this project.
0
Common
Most of the 8 edited versions we read keep these.
2
Distinctive
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 34
Default to token bucket for public API limits: capacity = max burst, refill_rate = sustained req/s.
- Very specific: line 39
Add :{route} only when limits differ per route.
- Very specific: line 56
Never do GET then SET in two app-side calls — concurrent requests both read the old value and overshoot.
- Distinctive: line 65
Place it at the edge, decide fail mode explicitly: Run the check as early middleware / at the gateway, *before* expensive work (DB, …
- Very specific: line 90
Window reset: After a 429, wait Retry-After seconds, retry → 200.
- Distinctive: line 91
Multi-instance: Run ≥2 app instances behind a balancer hitting one Redis.
“Common” is measured: kept by at least 6 in 10 of the 8 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
When to Use
Reach for this skill when the request is about controlling request rate, not request content:
- "Cap this endpoint at N req/s per user/IP/API key"
- "Add quotas per plan tier (free/pro/enterprise)"
- "We got hammered / scraped / brute-forced — throttle it"
- "Smooth out bursts to a downstream that has its own limit"
- Tuning an existing limiter (wrong window, double-counting, false 429s)
NOT this skill:
- Reducing load by serving cached responses → caching-strategy
- Deciding who the caller is → auth (rate limiting consumes identity, it does not establish it)
- Backpressure inside a queue/worker pool → concurrency/queue control
Steps
Pick the algorithm by requirement — do not default to fixed window.
Algorithm Use when Cost Fixed window Rough cap, simplest, OK to allow 2x burst at window edge 1 counter Sliding window (log) Need exact count over rolling period O(n) memory per key Sliding window (counter) Approximate rolling cap, cheap 2 counters Token bucket Allow bursts up to capacity, refill at steady rate — best general default for APIs2 fields (tokens, ts) Leaky bucket Force a constant outflow to a fragile downstream queue + drain Default to token bucket for public API limits:
capacity= max burst,refill_rate= sustained req/s.- Define the key — this is where most bugs live. Compose the rate key explicitly:
ratelimit:{scope}:{identity}:{route?}:{window?}.- Per-API-key/user for authed traffic (stable, fair).
- Per-IP only for unauthed/pre-auth routes (login, signup) — and normalize the IP from the real client header set by your trusted proxy, never a raw client-supplied
X-Forwarded-For. - Add
:{route}only when limits differ per route; otherwise one global bucket per identity is cheaper and harder to game.
Make the counter atomic in a shared store (Redis). In-memory counters break the moment you run >1 instance. Do the read-modify-write in one round trip via a Lua script (or
INCR+EXPIREfor fixed window). Race-free token bucket in Lua:-- KEYS[1]=bucket ARGV: now_ms, refill_per_ms, capacity, cost local b = redis.call('HMGET', KEYS[1], 'tokens', 'ts') local tokens = tonumber(b[1]) or tonumber(ARGV[3]) local ts = tonumber(b[2]) or tonumber(ARGV[1]) local now = tonumber(ARGV[1]) tokens = math.min(tonumber(ARGV[3]), tokens + (now - ts) * tonumber(ARGV[2])) local allowed = tokens >= tonumber(ARGV[4]) if allowed then tokens = tokens - tonumber(ARGV[4]) end redis.call('HMSET', KEYS[1], 'tokens', tokens, 'ts', now) redis.call('PEXPIRE', KEYS[1], math.ceil(tonumber(ARGV[3]) / tonumber(ARGV[2])) + 1000) return { allowed and 1 or 0, tokens }Never do
GETthenSETin two app-side calls — concurrent requests both read the old value and overshoot.- Drive limits from config, not hardcoded numbers. Map tier →
{capacity, refill_rate}in a config table so plans change without a deploy. Resolve the caller's tier after auth, fall back to an anonymous/default tier, and treat unknown tiers as the strictest limit. - Return a strict response contract on reject. On deny, respond
429 Too Many Requestsand always emit:Retry-After: <seconds>— integer seconds until one token/slot frees up (compute from refill math, don't guess).RateLimit-Limit,RateLimit-Remaining,RateLimit-Reset(or the legacyX-RateLimit-*) — also set these on allowed responses so good clients self-throttle.- A small JSON body with a stable machine-readable
code.
- Place it at the edge, decide fail mode explicitly. Run the check as early middleware / at the gateway, before expensive work (DB, downstream calls). When the limiter store (Redis) is unreachable, choose deliberately:
- Fail-open (allow) for revenue/availability-critical traffic — abuse risk during outage.
- Fail-closed (deny) for security-sensitive routes (login, payments) — availability risk. Log every fallback so a silent Redis outage doesn't quietly disable all limits.
- Verify under burst and concurrency (see Verify) before shipping. A limiter that passes single-threaded tests almost always leaks under parallel load.
Common Errors
- Two app-side calls (GET then SET / INCR then check). Under concurrency both requests see the pre-increment value and the limit is breached. Make it one atomic op (Lua /
INCRreturns the new value — check that, not a separate read). - Fixed window edge burst. With a 60s/100-req fixed window a client can send 100 at 0:59 and 100 at 1:00 = 200 in ~1s. If that's unacceptable, use sliding window or token bucket.
- Trusting client
X-Forwarded-For. Anyone can spoof it to dodge per-IP limits or frame another IP. Read only the value your own trusted proxy appends; strip/ignore the rest. - Missing
EXPIREon the counter key. Keys accumulate forever and leak memory. Every counter/bucket key must have a TTL ≥ its window. (The Lua above setsPEXPIREevery call.) - Clock skew across instances. Token-bucket math using each app server's local clock drifts. Pass
nowfrom a single source (RedisTIME, or accept the small skew but never mix sources mid-bucket). - Counting before auth on authed routes. Rate-limiting an authed endpoint by IP lets one NAT'd office exhaust the shared limit while an attacker rotates IPs. Key authed traffic by user/API key.
- Hot-key contention. A single global bucket (or one whale tenant) serializes every request on one Redis key/slot. Shard the key (
:{n}suffix, sum N sub-buckets) or move global caps to an approximate counter. Retry-Afterthat's wrong or absent. Clients then retry immediately and amplify the storm. Compute it from real refill time; emit it on every 429.- Limiter inside the app, after the DB call. Defeats the purpose — the expensive work already happened. Reject at the edge before doing anything costly.
- No headers on 2xx. Without
RateLimit-Remainingon success, well-behaved clients can't back off and only discover the limit by getting 429s.
Verify
- Single-key cap (steady): Fire exactly
limitrequests serially → all200. The next request →429withRetry-AfterandRateLimit-Remaining: 0. - Concurrency / race: Fire
limit + 50requests in parallel (e.g.hey/vegeta/aborxargs -P). Allowed count must equal the limit exactly — not limit+ε. This is the test that catches non-atomic counters; run it against the distributed store. - Burst then sustain (token bucket): Send
capacityrequests instantly (all pass), then send at exactlyrefill_rate→ steady-state passes; faster → 429s. Confirms burst capacity and refill are independent. - Window reset: After a 429, wait
Retry-Afterseconds, retry →200. Confirms TTL/refill releases on schedule andRetry-Afteris honest. - Multi-instance: Run ≥2 app instances behind a balancer hitting one Redis. The aggregate limit across instances must still equal the configured limit (proves the counter is shared, not per-process).
- Key isolation: Two different keys/users hitting the limit simultaneously must not affect each other's allowance.
- Fail mode: Kill/block Redis, send traffic → behavior matches the documented fail-open/closed choice, and a fallback is logged (not silent).
- Headers present on success: A normal
200carriesRateLimit-Limit/Remaining/Reset.
Done = tests 1–5 pass with the distributed store under parallel load, fail mode is explicit and logged, and every response (200 and 429) carries the correct rate-limit headers.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

