[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M74GHXTTPC0FG1DQAP37W62P":3,"skill-same:01M74GHXTTPC0FG1DQAP37W62P":44},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":29,"install":30,"resources":43},"01M74GHXTTPC0FG1DQAP37W62P","rate-limiting-design",null,"Design rate limits and quotas — token bucket vs window, limit keys, distributed enforcement, 429 headers, fairness, rollout.","MohammadBafkar\u002Fpolymath","MohammadBafkar","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F34940462?v=4","01M74G540TQFZWK6KVAPKFVGNR","Mohammad Bafkar","01M74G541HG19QP9V5DQCJVKYE",0,"MIT","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-scalability\u002Fskills\u002Frate-limiting-design\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: rate-limiting-design\ndescription: Design rate limits and quotas — token bucket vs window, limit keys, distributed enforcement, 429 headers, fairness, rollout.\n---\n\n# rate-limiting-design\n\n> A rate limit protects a resource from a caller. Choose who is limited, by what, at which layer, and what the caller sees — then make the limiter cheaper and more available than the thing it protects.\n\n**Mode:** analytical — judgment inside a fixed frame. Keep the output shape; every verdict cites its evidence; unknowns are marked `[TBD]` or `[VERIFY]`, never filled in.\n\n## When to use\n\n- Exposing a public or partner API, or protecting an internal service from noisy callers.\n- Calling a rate-limited third party and needing to stay under its quota.\n- Overload, scraping, credential stuffing, or one tenant degrading everyone else.\n\nNot this when: the goal is shedding load by *system* health (concurrency\u002Fadaptive limits) rather than per-caller quotas — see `polymath-architecture:resilience-design`; or auth\u002Fabuse threat modeling — `polymath-security:stride-threat-model`.\n\n## Inputs\n\n- The protected resource and its measured capacity (QPS it sustains, cost per request, expensive endpoints).\n- Caller identity available at the enforcement point (API key, user, tenant, IP, token), caller tiers\u002Fplans, and legitimate burst patterns.\n- Where enforcement can happen (CDN\u002FWAF, API gateway, service middleware, sidecar) and what shared store exists (Redis, gateway-native, local only).\n- Business rules: free vs paid quotas, contractual limits, fairness expectations.\n\n## Procedure\n\n1. **Name the goal** — they need different designs: *fairness* (no tenant starves others), *protection* (stay under capacity), *abuse prevention* (brute force, scraping — also needs identity\u002Fbehavior signals, not just rates), *cost control* (metered quota), or *client-side compliance* (outbound limits to a third party).\n2. **Choose the limit key and tiers.** Prefer the strongest identity available (API key\u002Ftenant > user > IP; IP alone breaks behind NAT\u002Fmobile carriers and is bypassable). Often layer: a per-IP coarse limit at the edge, per-key limits at the gateway, per-tenant + per-endpoint cost limits in the service. Weight expensive operations (a search = 10 tokens, a read = 1) instead of one flat count.\n3. **Choose the algorithm** for the behavior wanted:\n   - **Token bucket** (rate + burst capacity): allows controlled bursts, the common default; refill rate = sustained limit, bucket size = tolerated burst.\n   - **Leaky bucket \u002F shaping**: smooths output to a constant rate (queue or delay) — for protecting a fixed-rate downstream.\n   - **Fixed window counter**: simplest, but allows 2× burst at window boundaries.\n   - **Sliding window log \u002F counter**: precise or approximate smoothing at higher memory\u002FCPU cost; the sliding-window counter is a good compromise.\n   - **Concurrency limit** (in-flight cap): protects against slow requests that rate limits miss; combine with rates.\n4. **Enforce at the right layer.** As early and cheaply as possible (edge\u002FCDN\u002Fgateway) for volume and abuse; in-service for per-tenant cost fairness that needs business context. The limiter must not become a new single point: define fail-open vs fail-closed per endpoint (login\u002Fabuse → closed or degraded local limit; low-risk reads → open) and the behavior when the shared store is down.\n5. **Distributed counting.** Options: central store (Redis with an atomic Lua script\u002F`INCR`+`EXPIRE` or a token-bucket script — one round trip, atomic); local limiters with an even share of the global limit (`limit ÷ N` instances, fails under uneven routing); local + periodic sync (approximate, cheap); gateway-native. State the accuracy you accept (exact vs ±10–20%) and the added latency (≈ one cache RTT) against the budget. Use key TTLs so state is bounded; watch hot keys for a single abusive caller.\n6. **Define the contract.** On limit: `429 Too Many Requests` with `Retry-After` (seconds or date) and, if you publish limits, `RateLimit-Limit` \u002F `RateLimit-Remaining` \u002F `RateLimit-Reset` (the IETF `RateLimit` header fields draft; document your exact semantics). Use a stable error body, a machine-readable code, and a docs link. Don't return 200 with an error, and don't silently drop. `503` is for server overload, `429` for caller quota.\n7. **Make clients behave.** Document limits and burst; SDKs honor `Retry-After`, back off exponentially with jitter, and cap retries; idempotency keys for retried writes. Publish how to request a higher limit. For outbound calls to a third party, put a token bucket in front of the client sized *below* their limit and handle their 429s the same way.\n8. **Set the numbers from capacity, not taste.** Sum of all granted sustained limits must stay under protected capacity, or you've issued oversold quotas — then decide on global load shedding by priority for the overage. Start from measured capacity × safety factor ÷ expected concurrent callers; give new\u002Ffree tiers less. Roll out in **observe-only** mode first (count and log would-be rejections), then enforce, then tighten.\n9. **Observe.** Rejections by key\u002Ftier\u002Fendpoint, near-limit callers, limiter latency and error rate, store health; alert on a sudden rise in 429s for a paying tenant (misconfiguration) and on limiter fail-open events. Provide a safe override (allow-list, temporary raise) with audit.\n10. **Test it:** burst at the boundary, multi-instance accuracy, store outage behavior, clock skew, and a retry storm from clients that ignore `Retry-After`.\n\n## Output\n\n```text\nRate-limit design: public Orders API\n\nGoal: fairness + protection (capacity 6k req\u002Fs sustained on the read path; writes 800\u002Fs).\nKeys & tiers: API key (primary); per-IP 300\u002Fmin at the CDN for unauthenticated routes; weights: GET=1, search=10, bulk export=50.\n  free 60 req\u002Fmin (1\u002Fs) burst 20 · pro 600\u002Fmin (10\u002Fs) burst 100 · enterprise by contract\n  Oversell check (all keys at sustained limit): free 1\u002Fs × 300 + pro 10\u002Fs × 400 + enterprise 1,200\u002Fs = 5.5k\u002Fs \u003C 6k\u002Fs capacity [VERIFY: key counts, recompute monthly].\nAlgorithm: token bucket (rate = sustained, bucket = burst) + concurrency cap 25 in-flight per key.\nEnforcement: gateway (edge) for per-key buckets via Redis Lua (atomic, 1 RTT ≈ 1 ms of the 15 ms budget); service-level cost limiter for exports.\nFailure: Redis unreachable → fail open on GET with local per-instance cap (limit ÷ instances), fail closed on POST \u002Fauth\u002F*.\nContract: 429 + Retry-After + RateLimit-Limit\u002FRemaining\u002FReset; body {code:\"rate_limited\", retry_after:…, docs:…}; 503 reserved for load shedding.\nClients: SDK honors Retry-After, jittered backoff, max 3 retries; idempotency keys on POST.\nRollout: observe-only 2 weeks (log would-be 429s) → enforce for free → pro → enterprise; dashboards by key\u002Ftier.\nOverrides: allow-list with expiry + audit; alert on 429 rate > 1% for a paying key.\nTests: boundary burst, 3-instance accuracy (±10%), Redis down, retry-storm client.\n```\n\n## Quality bar\n\n- The goal (fairness \u002F protection \u002F abuse \u002F cost) is stated, and the key, algorithm, and layer follow from it.\n- Limits are derived from protected capacity with an oversell check, not picked from habit.\n- The limiter's own failure mode (fail open\u002Fclosed) and latency cost are specified per endpoint class.\n- The 429 contract includes `Retry-After`, and client retry behavior is defined.\n- Rollout begins in observe-only mode and includes an audited override path.\n\n## Anti-patterns to avoid\n\n- Limiting by IP alone (NAT, carriers, IPv6 rotation) and calling it abuse protection.\n- Fixed-window counters at critical boundaries, or non-atomic `GET`-then-`SET` counters in a shared store.\n- A limiter that fails closed for everything when its store is down — it becomes an outage.\n- Granting quotas whose sum exceeds capacity.\n- Returning `200` with an error body, or `429` without `Retry-After`.\n- Enforcing for the first time directly in production with no observe-only pass.\n","# rate-limiting-design\n\n> A rate limit protects a resource from a caller. Choose who is limited, by what, at which layer, and what the caller sees — then make the limiter cheaper and more available than the thing it protects.\n\n**Mode:** analytical — judgment inside a fixed frame. Keep the output shape; every verdict cites its evidence; unknowns are marked `[TBD]` or `[VERIFY]`, never filled in.\n\n## When to use\n\n- Exposing a public or partner API, or protecting an internal service from noisy callers.\n- Calling a rate-limited third party and needing to stay under its quota.\n- Overload, scraping, credential stuffing, or one tenant degrading everyone else.\n\nNot this when: the goal is shedding load by *system* health (concurrency\u002Fadaptive limits) rather than per-caller quotas — see `polymath-architecture:resilience-design`; or auth\u002Fabuse threat modeling — `polymath-security:stride-threat-model`.\n\n## Inputs\n\n- The protected resource and its measured capacity (QPS it sustains, cost per request, expensive endpoints).\n- Caller identity available at the enforcement point (API key, user, tenant, IP, token), caller tiers\u002Fplans, and legitimate burst patterns.\n- Where enforcement can happen (CDN\u002FWAF, API gateway, service middleware, sidecar) and what shared store exists (Redis, gateway-native, local only).\n- Business rules: free vs paid quotas, contractual limits, fairness expectations.\n\n## Procedure\n\n1. **Name the goal** — they need different designs: *fairness* (no tenant starves others), *protection* (stay under capacity), *abuse prevention* (brute force, scraping — also needs identity\u002Fbehavior signals, not just rates), *cost control* (metered quota), or *client-side compliance* (outbound limits to a third party).\n2. **Choose the limit key and tiers.** Prefer the strongest identity available (API key\u002Ftenant > user > IP; IP alone breaks behind NAT\u002Fmobile carriers and is bypassable). Often layer: a per-IP coarse limit at the edge, per-key limits at the gateway, per-tenant + per-endpoint cost limits in the service. Weight expensive operations (a search = 10 tokens, a read = 1) instead of one flat count.\n3. **Choose the algorithm** for the behavior wanted:\n   - **Token bucket** (rate + burst capacity): allows controlled bursts, the common default; refill rate = sustained limit, bucket size = tolerated burst.\n   - **Leaky bucket \u002F shaping**: smooths output to a constant rate (queue or delay) — for protecting a fixed-rate downstream.\n   - **Fixed window counter**: simplest, but allows 2× burst at window boundaries.\n   - **Sliding window log \u002F counter**: precise or approximate smoothing at higher memory\u002FCPU cost; the sliding-window counter is a good compromise.\n   - **Concurrency limit** (in-flight cap): protects against slow requests that rate limits miss; combine with rates.\n4. **Enforce at the right layer.** As early and cheaply as possible (edge\u002FCDN\u002Fgateway) for volume and abuse; in-service for per-tenant cost fairness that needs business context. The limiter must not become a new single point: define fail-open vs fail-closed per endpoint (login\u002Fabuse → closed or degraded local limit; low-risk reads → open) and the behavior when the shared store is down.\n5. **Distributed counting.** Options: central store (Redis with an atomic Lua script\u002F`INCR`+`EXPIRE` or a token-bucket script — one round trip, atomic); local limiters with an even share of the global limit (`limit ÷ N` instances, fails under uneven routing); local + periodic sync (approximate, cheap); gateway-native. State the accuracy you accept (exact vs ±10–20%) and the added latency (≈ one cache RTT) against the budget. Use key TTLs so state is bounded; watch hot keys for a single abusive caller.\n6. **Define the contract.** On limit: `429 Too Many Requests` with `Retry-After` (seconds or date) and, if you publish limits, `RateLimit-Limit` \u002F `RateLimit-Remaining` \u002F `RateLimit-Reset` (the IETF `RateLimit` header fields draft; document your exact semantics). Use a stable error body, a machine-readable code, and a docs link. Don't return 200 with an error, and don't silently drop. `503` is for server overload, `429` for caller quota.\n7. **Make clients behave.** Document limits and burst; SDKs honor `Retry-After`, back off exponentially with jitter, and cap retries; idempotency keys for retried writes. Publish how to request a higher limit. For outbound calls to a third party, put a token bucket in front of the client sized *below* their limit and handle their 429s the same way.\n8. **Set the numbers from capacity, not taste.** Sum of all granted sustained limits must stay under protected capacity, or you've issued oversold quotas — then decide on global load shedding by priority for the overage. Start from measured capacity × safety factor ÷ expected concurrent callers; give new\u002Ffree tiers less. Roll out in **observe-only** mode first (count and log would-be rejections), then enforce, then tighten.\n9. **Observe.** Rejections by key\u002Ftier\u002Fendpoint, near-limit callers, limiter latency and error rate, store health; alert on a sudden rise in 429s for a paying tenant (misconfiguration) and on limiter fail-open events. Provide a safe override (allow-list, temporary raise) with audit.\n10. **Test it:** burst at the boundary, multi-instance accuracy, store outage behavior, clock skew, and a retry storm from clients that ignore `Retry-After`.\n\n## Output\n\n```text\nRate-limit design: public Orders API\n\nGoal: fairness + protection (capacity 6k req\u002Fs sustained on the read path; writes 800\u002Fs).\nKeys & tiers: API key (primary); per-IP 300\u002Fmin at the CDN for unauthenticated routes; weights: GET=1, search=10, bulk export=50.\n  free 60 req\u002Fmin (1\u002Fs) burst 20 · pro 600\u002Fmin (10\u002Fs) burst 100 · enterprise by contract\n  Oversell check (all keys at sustained limit): free 1\u002Fs × 300 + pro 10\u002Fs × 400 + enterprise 1,200\u002Fs = 5.5k\u002Fs \u003C 6k\u002Fs capacity [VERIFY: key counts, recompute monthly].\nAlgorithm: token bucket (rate = sustained, bucket = burst) + concurrency cap 25 in-flight per key.\nEnforcement: gateway (edge) for per-key buckets via Redis Lua (atomic, 1 RTT ≈ 1 ms of the 15 ms budget); service-level cost limiter for exports.\nFailure: Redis unreachable → fail open on GET with local per-instance cap (limit ÷ instances), fail closed on POST \u002Fauth\u002F*.\nContract: 429 + Retry-After + RateLimit-Limit\u002FRemaining\u002FReset; body {code:\"rate_limited\", retry_after:…, docs:…}; 503 reserved for load shedding.\nClients: SDK honors Retry-After, jittered backoff, max 3 retries; idempotency keys on POST.\nRollout: observe-only 2 weeks (log would-be 429s) → enforce for free → pro → enterprise; dashboards by key\u002Ftier.\nOverrides: allow-list with expiry + audit; alert on 429 rate > 1% for a paying key.\nTests: boundary burst, 3-instance accuracy (±10%), Redis down, retry-storm client.\n```\n\n## Quality bar\n\n- The goal (fairness \u002F protection \u002F abuse \u002F cost) is stated, and the key, algorithm, and layer follow from it.\n- Limits are derived from protected capacity with an oversell check, not picked from habit.\n- The limiter's own failure mode (fail open\u002Fclosed) and latency cost are specified per endpoint class.\n- The 429 contract includes `Retry-After`, and client retry behavior is defined.\n- Rollout begins in observe-only mode and includes an audited override path.\n\n## Anti-patterns to avoid\n\n- Limiting by IP alone (NAT, carriers, IPv6 rotation) and calling it abuse protection.\n- Fixed-window counters at critical boundaries, or non-atomic `GET`-then-`SET` counters in a shared store.\n- A limiter that fails closed for everything when its store is down — it becomes an outage.\n- Granting quotas whose sum exceeds capacity.\n- Returning `200` with an error body, or `429` without `Retry-After`.\n- Enforcing for the first time directly in production with no observe-only pass.\n",{"name":5,"description":7},"main","23f6e21841a39580c9da2b5ec941f39dda17cd86","plugins\u002Fpolymath-scalability\u002Fskills\u002Frate-limiting-design","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath","https:\u002F\u002Fgithub.com\u002FMohammadBafkar","2026-10-29 18:34:59",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add MohammadBafkar\u002Fpolymath --skill rate-limiting-design",{"tool":36,"command":37},"bunx","bunx skills add MohammadBafkar\u002Fpolymath --skill rate-limiting-design",{"tool":39,"command":40},"pnpm","pnpm dlx skills add MohammadBafkar\u002Fpolymath --skill rate-limiting-design","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-scalability\u002Fskills\u002Frate-limiting-design\u002FSKILL.md",true,[],[45,52,59,66,73,80],{"skillNo":46,"name":47,"nameZh":6,"description":48,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":49,"categories":50,"keywords":51,"publishedAt":19},"01M74GN87EBRHM9N87M7AP1HDD","runbook","Write or refresh an operational runbook for an alert\u002Fsymptom; structured as TL;DR + Pre-checks + Steps + Verification + Rollback + Escalation.","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Frunbook\u002FSKILL.md",[],[],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M74GN5GPKEC1JEKP2DFQNEQJ","rfc","Draft a lightweight design RFC to docs\u002Frfcs\u002F\u003Cslug>.md; Summary, Motivation, Detailed design, Drawbacks, Alternatives, Unresolved questions. A proposal to debate, not a recorded decision (adr).","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Frfc\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M74GN2F4CWPMV4X09TG4E304","editorial-pass","Review and tighten prose in a Markdown artifact for a target tone (terse, formal, friendly) without dropping information; preserve quotations and load-bearing constraints.","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Feditorial-pass\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M74GMZWGYMZ37C4DYGT6P23G","architecture-review-facilitation","Run an architecture review as a process — entry criteria, reviewer checklist, decision log, and follow-up actions — pairing the design artifact with a red-team pass.","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Farchitecture-review-facilitation\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M74GMXVX0YX3ETDXS527XDGM","architecture-doc","Write a C4-style architecture document; System Context + Containers (+ Components when interesting) with mermaid diagrams. Describes structure, not a decision (adr) or proposal (rfc).","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Farchitecture-doc\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M74GMVG1WSMCK066S3KE6V5K","adr","Write an Architecture Decision Record (Michael Nygard format) to docs\u002Fadrs\u002FNNNN-\u003Cslug>.md; frontmatter validated by the ADR artifact schema. Records a made decision, not a proposal to debate (rfc).","https:\u002F\u002Fgithub.com\u002FMohammadBafkar\u002Fpolymath\u002Fblob\u002Fmain\u002Fplugins\u002Fpolymath-writing\u002Fskills\u002Fadr\u002FSKILL.md",[],[]]