/engineering:saas-rate-limiting-and-quotasfrom engineering
Designs per-tenant rate limits, plan-aware quotas, fair queueing, and usage reporting for multi-tenant SaaS APIs.
Ships in engineering. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Acknowledgement: Shared by Peter Bamuhigire, techguypeter.com, +256 784 464178.
| Input | Required | Use |
|---|---|---|
| Tenant, product, and lifecycle scope | yes | Bound the SaaS decision |
| Current architecture, plans, policies, and constraints | yes | Preserve enforceable behaviour |
| Production data or verified evidence | conditional | Validate thresholds and migrations |
Skill-specific inputs:
saas-entitlements-and-plan-gating.saas-architecture-strategy — affects where enforcement lives.Default to read-only analysis. Change configuration, billing, identity, tenant data, infrastructure, or customer communications only with explicit authority, least-privilege credentials, tenant scope, rollback, and auditable approval. Never expose secrets or cross tenant boundaries.
If production access, policy, telemetry, or authoritative records are unavailable, produce a labelled design or dry-run plan. Do not claim deployment, reconciliation, deletion, delivery, or measured outcomes; list missing evidence and verification.
| Condition | Action | Stop condition |
|---|---|---|
| Tenant isolation, money, identity, or deletion is affected | Require approval and rollback evidence | Scope or authority is ambiguous |
| Evidence supports a reversible change | Stage, test, and record it | Acceptance checks fail |
| Only partial context is available | Return assumptions and validation | A production claim cannot be verified |
X-RateLimit-Remaining, in-product usage panel).frontend-performance / backend perf skills.saas-entitlements-and-plan-gating. This skill is the enforcement runtime.SKILL.md.Retry-After, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset.usage.approaching_limit / usage.limit_hit).| Category | Artifact | Format | Example |
|---|---|---|---|
| Performance | Rate-limit + quota inventory | Markdown table | docs/saas/rate-limits.md |
| Release evidence | Response contract spec | Markdown doc with examples | docs/saas/rate-limit-response.md |
| Operability | Limit hit + denial dashboard | Dashboard link | docs/saas/quota-dashboard.md |
references/algorithms.md — token bucket, sliding window, leaky bucket, fixed window — when each fits.references/fair-queueing-patterns.md — per-tenant queues, weighted fair queueing, DRR.references/redis-implementation.md — atomic Lua scripts for token bucket + sliding window.saas-entitlements-and-plan-gating, saas-architecture-strategy, multi-tenant-saas-architecture, observability-monitoring, microservices-resilience.| Type | Example | Time horizon |
|---|---|---|
| Request rate | 100 req/sec per tenant | seconds |
| Concurrency | Max 50 in-flight requests per tenant | instantaneous |
| Period quota | 100k API calls per month | rolling month |
| Per-resource quota | 10 active workflows per tenant | always-on (entitlement) |
Most SaaS need all four.
For every SaaS, list:
| Limit | Type | Per-plan values | Enforcement layer | Storage |
|---|---|---|---|---|
| API requests | rate | free 10/s, pro 100/s, enterprise 1000/s | gateway | Redis |
| API requests | period | free 1k/mo, pro 100k/mo, enterprise unlimited | gateway | Redis + DB |
| Concurrent requests | concurrency | free 5, pro 50, enterprise 500 | gateway | Redis |
| Webhook deliveries | rate | 100/s per tenant | worker | Redis |
| DB connections | concurrency | per-tenant pool size | DB pool | PgBouncer / pg pooler |
| Heavy reports | concurrency | free 1, pro 5, enterprise 20 | worker | Redis |
| AI token budget | period | per AI plan | service | DB |
| Login attempts | rate | 5/min per IP+email | app | Redis |
Default recommendation: token bucket for rate, sliding window for period quotas, atomic counter for concurrency.
Edge / CDN (Cloudflare, Fastly, CloudFront)
↓
Gateway (Kong, Envoy, Tyk, AWS API Gateway, ALB)
↓
Application / service
↓
Database connection pool (PgBouncer / pgpool / RDS Proxy)
↓
Async worker (with per-tenant queues)
Enforce as close to the edge as possible. Reasons:
Pattern:
| Storage | Latency | Capacity | Use case |
|---|---|---|---|
| Redis (single) | < 1ms | up to ~50k ops/sec | Default for most SaaS |
| Redis cluster | < 1ms | millions ops/sec | At scale |
| Cloudflare Rate Limiting Rules / WAF | < 1ms | unlimited (their infra) | DDoS + simple per-IP/per-route |
| AWS API Gateway throttling | < 5ms | scaled | If on API Gateway already |
| In-memory (per-process) | sub-µs | scoped to one process | NOT for multi-instance; only for local rate limits |
| DB (Postgres counter) | 1-5ms | ops/sec | For period quotas reconciled periodically |
Default: Redis (managed: ElastiCache / Upstash / Redis Cloud) with atomic Lua scripts.
-- KEYS[1] = bucket key (e.g., "rl:tenant:123")
-- ARGV[1] = capacity, ARGV[2] = refill_per_second, ARGV[3] = now_ms, ARGV[4] = cost
local capacity = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2])
local now_ms = tonumber(ARGV[3])
local cost = tonumber(ARGV[4])
local b = redis.call('HMGET', KEYS[1], 'tokens', 'last_ms')
local tokens = tonumber(b[1]) or capacity
local last_ms = tonumber(b[2]) or now_ms
local elapsed = math.max(0, now_ms - last_ms)
tokens = math.min(capacity, tokens + (elapsed / 1000) * refill_rate)
local allowed = 0
if tokens >= cost then
tokens = tokens - cost
allowed = 1
end
redis.call('HMSET', KEYS[1], 'tokens', tokens, 'last_ms', now_ms)
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / refill_rate * 1000 * 2))
return {allowed, tokens}
HTTP 429 Too Many Requests for rate / concurrency violations.
HTTP 402 Payment Required or HTTP 403 Forbidden for plan-quota violations (the user needs to upgrade, not just wait).
Headers (always include):
X-RateLimit-Limit: 100 — total in window.X-RateLimit-Remaining: 0 — current remaining.X-RateLimit-Reset: 1746576000 — unix timestamp when window resets.Retry-After: 30 — seconds to wait (only on 429).Body:
{
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "You have exceeded 100 requests/minute. Retry in 30 seconds.",
"retry_after_seconds": 30,
"limit_type": "api_rate_per_minute",
"tenant_id": "ten_123"
}
}
For quota (period or plan):
{
"error": {
"code": "QUOTA_EXCEEDED",
"message": "Monthly API call limit of 100,000 reached. Upgrade your plan to continue.",
"limit_type": "api_calls_monthly",
"current_usage": 100000,
"limit_value": 100000,
"upgrade_url": "https://app.example.com/billing/upgrade?context=api_quota"
}
}
Without fair-queueing, one tenant's 10,000-job batch saturates the worker pool. Patterns:
Producers → push to per-tenant queue (e.g., Redis Lists keyed `q:tenant:123`)
Dispatcher → round-robins across active tenant queues; pushes one job to shared worker pool per turn
Workers → consume from shared pool
weight = ceil(plan_seats / 10) or weight = tier_factor).Tenants who don't know they're being limited are angry tenants.
GET /api/v1/me/quota returns current usage + limits per metered dimension.saas-lifecycle-email-orchestration).X-RateLimit-*.SELECT COUNT(*) per request. Slow + race-prone. Fix: Redis counter.usage.approaching_limit event. Lifecycle email can't trigger; expansion revenue lost.saas-entitlements-and-plan-gating — defines what limits exist per plan.saas-architecture-strategy — drives where enforcement lives.multi-tenant-saas-architecture — tenant context drives the bucket keys.microservices-resilience — circuit breakers, bulkheads (complementary to rate limits).observability-monitoring — surface limits + denials in dashboards.saas-lifecycle-email-orchestration — emit approaching-limit events for upgrade triggers.AI features introduce distinct quota dimensions beyond generic API rate limits:
| AI dimension | Type | Per-plan example | Enforcement layer |
|---|---|---|---|
| AI tokens / minute | rate | Free 1k/m, Pro 100k/m, Enterprise 1M/m | LLM gateway (Redis token bucket) |
| AI generations / day | period | Free 50, Starter 500, Pro 5k | LLM gateway (sliding window) |
| AI tokens / month | period | Free 100k, Pro 20M | LLM gateway + DB |
| AI USD / month | period (currency) | Free $0, Pro $50, Enterprise custom | LLM gateway |
| Concurrent agent sessions | concurrency | Free 0, Business 5, Enterprise 50 | gateway + worker |
| Agent steps per session | per-resource | Free 0, Business 20, Enterprise 50 | agent runtime |
| KB pages ingested | period | Starter 500, Pro 10k | KB service |
| Embedding-jobs / hour per tenant | rate | tier-specific | ingestion dispatcher |
Where enforced:
Agentic features need a richer quota set than single-shot AI. The dimensions:
| Quota | Algorithm | Default — Pro | Default — Enterprise | Enforcement |
|---|---|---|---|---|
| Concurrent agent sessions per tenant | concurrency counter (atomic INCR/DECR in Redis) | 3 | 20 | Runtime task-create handler |
| Agent steps per tenant per day | sliding window | 500 | 10,000 | Runtime step-enter handler |
| Agent tasks per user per hour | token bucket | 20 | 100 | Runtime task-create handler |
| Long-running tasks (wallclock > 5 min) in-flight per tenant | concurrency counter | 1 | 10 | Runtime task-create handler |
| Per-task wallclock cap | budget (ai-agent-cost-and-step-budgets) | 5 min | 30 min | Runtime budget check |
| Per-task cost cap (USD) | budget | $1 | $10 | Runtime budget check |
| Standing approvals invocations per tenant per day | counter | 100 | unlimited | Approval runtime |
def claim_agent_session(tenant_id: int, max_concurrent: int) -> bool:
key = f"agent:concurrent:{tenant_id}"
val = redis.incr(key)
redis.expire(key, 86400, nx=True)
if val > max_concurrent:
redis.decr(key)
return False
return True
def release_agent_session(tenant_id: int):
redis.decr(f"agent:concurrent:{tenant_id}")
release is called on every task terminal transition (COMPLETED, FAILED, KILLED, BUDGET_EXCEEDED, ABANDONED). A janitor reconciles drift by counting actual in-flight tasks vs counter every 5 minutes.
{
"error": "agent_concurrency_limit",
"code": "AGENT_CONCURRENCY_LIMIT",
"current": 3,
"limit": 3,
"plan": "pro",
"retry_after_seconds": 60,
"upgrade_url": "/billing/upgrade?plan=enterprise&context=agent_concurrency"
}
The user sees: "You've reached your concurrent-agent limit (3). Wait for an active task to finish, or upgrade for 20 concurrent."
Quotas are declared in saas-entitlements-and-plan-gating (catalogue) and enforced in the agent runtime (this skill's runtime layer). The two skills hold the contract:
Cross-references:
ai-agent-runtime-architecture — where agent quotas are enforced.ai-agent-cost-and-step-budgets — per-task budgets (the inner quota layer).saas-entitlements-and-plan-gating — agent quota catalogue.ai-model-gateway — implements per-tenant token+USD caps.ai-cost-per-tenant-attribution — soft/hard ceilings with comms.ai-rag-multi-tenant — KB-side caps.ai-on-saas-architecture — overall architecture.Not every quota breach is an SLA event. The platform commits to enforcement, not to unlimited capacity. The mapping below classifies each breach so the SLA-credit pipeline (ai-agent-sla-credit-automation) can route correctly.
| Breach pattern | Customer-observable? | SLA-impact? | Treatment |
|---|---|---|---|
| Tenant hits committed monthly quota (e.g., 50k tasks/Pro) | Yes (429 / "limit reached") | No — expected guard | UX: clear comms + upsell prompt; no credit. |
| Tenant hits a soft ceiling we set (cost protection) | Yes (slowed or refused) | No — platform self-protection | UX: notify tenant; document in account. |
| Tenant blocked because a neighbor exhausted shared pool (noisy-neighbor) | Yes (429 on tenant who didn't breach) | Yes — eligible breach | Pool isolation fix; credit the affected tenant. |
| Platform-wide quota mis-configuration blocking tenants under their committed cap | Yes | Yes — eligible breach | Mass-credit via incident pipeline. |
| Tenant blocked due to negotiated bespoke cap they signed | Yes | No — customer-caused | No credit; comms cite the contract. |
| Burst rate-limit fires during agent task → task aborts | Sometimes | Conditional — eligible if tier commits resolution rate AND breach traces to platform side | |
| Burst rate-limit fires because tenant launched 10k concurrent tasks | Yes | No — customer-caused | Document in audit. |
When a quota breach terminates a billable event (task abort, refused request), the limiter emits:
{
"event": "quota.breach.classified",
"tenant_id": "...",
"quota_key": "tasks_per_month | tokens_per_min | concurrent_tasks | ...",
"limit": 50000,
"consumed": 50001,
"scope": "committed | soft | shared_pool",
"cause": "tenant_traffic | neighbor_traffic | platform_misconfig | tenant_bespoke_cap",
"sla_classification": "expected_guard | eligible_breach | customer_caused",
"task_id": "...",
"timestamp": "..."
}
The SLA-credit pipeline subscribes to events with sla_classification='eligible_breach'.
Shared-pool quotas (rate-limit buckets that several tenants draw from) are the most common source of accidental eligible breaches. Pool design should prefer per-tenant buckets for any quota that gates a committed SLA dimension. Where shared pools must remain, the SLA-class table (ai-agent-sla-and-commitments) should explicitly call out the elevated breach probability.
ai-agent-sla-credit-automation/references/eligibility-rules.md — consumes the sla_classification field.ai-agent-sla-and-commitments — defines which quotas map to committed dimensions.ai-agent-cost-and-step-budgets — inner quota layer with its own SLA handoff.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub peterbamuhigire/chwezi-dev-engine --plugin engineering169 skills in this plugin
/accounting-engineUse when designing or implementing double-entry accounting policy and an embedded ledger engine for invoices, payments, stock, balanced postings, mapped accounts, idempotency, reversals, period locks, audit trails, and financial statements./accounting-finance-controllerUse when coordinating accounting and finance implementation reviews, doctrine routing, control evidence, remediation priorities, and release decisions across a software system./advanced-testing-strategyUse when designing or reviewing test strategy for production systems, APIs, mobile apps, SaaS platforms, ERP workflows, and AI-enabled systems. Covers unit, integration, contract, end-to-end, regression, release-gate, and risk-based testing decisions./ai-agent-commercial-operationsUse when pricing, billing, refunding, recognizing revenue, or packaging commercial terms for agentic AI services, or when defining agent SLAs, customer commitments, SLA dashboards, breach credits, and service evidence./ai-agent-compliance-controlsUse when mapping AI agent operations to SOC 2, ISO 27001, HIPAA, audit logs, control testing, attestations, and compliance evidence, including drill-cadence evidence, approval-completeness (PI1.1) gap checks, and signed agent-memory erasure proofs./ai-agent-governance-and-limitsUse when defining agent budgets, step limits, reversibility, blast-radius controls, kill switches, and governance policy for agentic AI systems.Other plugins' skills for the same job