medium.com 4 min read Original Source

System Design – Multi-Tenant API Rate Limiting Service

A multi-tenant rate limiter enforces each tenants and their users with specific usage limits such that users of a tenant does not consume all the resources negatively impacting others.

Key Concepts

  • Provide Tenant Isolation — Tenants are isolated to provide at least a pseudo uniform performance across services and protecting from “noisy-neighbor” problems.
  • Enforcement — usually the enforcement happens at the API gateway / reverse Proxy as this is way most of the traffic is intercepted. Logic can be embedded at the application code which will provide the most context awareness however leading to higher overheads as application code has to manage more layers within its program.
  • Response — When a tenant/user exceeds their limit, requests are typically rejected with a HTTP 429 Too many requests status. The system could also add a X-Ratelimit-Retry-After header to the client for the client to retry after the wait period.

Algorithms

Refer to my post on the various algorithms here.

  • Token Bucket
  • Sliding Window Log
  • Leaky Bucket
  • Fixed Window Counter
  • Sliding Window Counter

System Design

Functional Requirements

  1. Tenant onboarding — Customers register endpoints (route/method/host) to protect.
  2. Create policy — Policies are set of rules that are bounded to an endpoint.
  3. Rate-limit enforcement — The API gateway checks the limit and enforces the rule on the request.
  4. Safe deployment — The rate limiter should support percent rollout(eg: enforce in stages like 5%->25%->100%), shadow/enforce mode and versioning with rollback.

Non-Functional Requirements

  1. Low Latency: The rate limiter should not slow down actual request traffic. ~50ms@p95
  2. Throughput: ~30k req/s per region.
  3. Availability: 99.99% for enforcement plane.
  4. Multi-tenancy: Strong tenant isolation.
  5. Observability: metrics/logs/traces on why throttled.

High-level Design

Split the service into Control plane(management) and Data plane (enforcement) allowing for better responsibility isolation of the service supporting:

  • Control plane can be slower, strongly consistent, fully audited.
  • Data plane is optimized for fast, scalable decision making.
  • Policy distribution avoids control-plane calls on hot path.
  • Shards + consistent hashing provides throughput and predictable hotspots.

Services

Control Plane

  • Endpoint Registry Service: endpoint onboarding + metadata.
  • Policy Service: policies/rules CRUD, validation, versioning.
  • Rollout Orchestrator: staged rollout, canary, rollback.
  • Policy Distribution Service: pushes policy snapshots to data plane + edge caches.

Data Plane

  • Gateway Integration: a gateway plugin/filter that calls limiter service.
  • Rate Limiter Shard Service: low-latency decision engine (token bucket/sliding window).
  • Counter Store: distributed in-memory store (Redis cluster) or custom in-memory + persistence.
  • Decision Telemetry Pipeline: emits allow/deny events + reason codes.

Deep Dive

Endpoint Registry Service

Responsibilities

  • Store per-tenant endpoints (route patterns/methods).
  • Provide endpoint stable identifier.
  • Attach policy bindings (policyId, version, rollout mode).

APIs

  • POST /tenants/{tenantId}/endpoints
  • GET /tenants/{tenantId}/endpoints/{endpointId}
  • PUT /tenants/{tenantId}/endpoints/{endpointId}/bindings

Data model

{
  "tenantId": "t1",
  "endpointId": "e123",
  "match": { "host": "api.walmart.com", "path": "/v1/orders/*", "method": "GET" },
  "bindings": [
    {
      "policyId": "p789",
      "version": 12,
      "rollout": { "mode": "ENFORCE", "percent": 25, "startTime": "..." }
    }
  ]
}
{
  "tenantId": "t1",
  "endpointId": "e123",
  "match": { "host": "api.walmart.com", "path": "/v1/orders/*", "method": "GET" },
  "bindings": [
    {
      "policyId": "p789",
      "version": 12,
      "rollout": { "mode": "ENFORCE", "percent": 25, "startTime": "..." }
    }
  ]
}

Policy Service

Responsibilities

  • Create/update versioned policies.
  • Validate supported dimensions and rule types.
  • Store “effective policy” artifacts for distribution.

APIs

  • POST /tenants/{tenantId}/policies
  • PUT /tenants/{tenantId}/policies/{policyId} (creates new version)
  • GET /tenants/{tenantId}/policies/{policyId}?version=12
  • POST /tenants/{tenantId}/policies/{policyId}/validate

Policy rule model

{
  "policyId": "p789",
  "version": 12,
  "rules": [
    {
      "ruleId": "r1",
      "dimension": "USER",
      "keySource": "jwt.sub",
      "algorithm": "TOKEN_BUCKET",
      "limit": 100,
      "windowSec": 60,
      "burst": 20,
      "action": "DENY",
      "priority": 10
    },
    {
      "ruleId": "r2",
      "dimension": "REGION",
      "keySource": "gateway.region",
      "algorithm": "SLIDING_WINDOW",
      "limit": 30000,
      "windowSec": 60,
      "action": "DENY",
      "priority": 20
    }
  ]
}
{
  "policyId": "p789",
  "version": 12,
  "rules": [
    {
      "ruleId": "r1",
      "dimension": "USER",
      "keySource": "jwt.sub",
      "algorithm": "TOKEN_BUCKET",
      "limit": 100,
      "windowSec": 60,
      "burst": 20,
      "action": "DENY",
      "priority": 10
    },
    {
      "ruleId": "r2",
      "dimension": "REGION",
      "keySource": "gateway.region",
      "algorithm": "SLIDING_WINDOW",
      "limit": 30000,
      "windowSec": 60,
      "action": "DENY",
      "priority": 20
    }
  ]
}

Rollout Orchestrator

Responsibilities

  • Manage rollout state machine:DRAFT → SHADOW → ENFORCE(%) → ENFORCE(100) → ROLLBACK
  • Gate escalation on metrics: false throttles, latency increase, error budgets.

APIs

  • POST /tenants/{tenantId}/rollouts
  • PATCH /tenants/{tenantId}/rollouts/{rolloutId} (increase percent)
  • POST /tenants/{tenantId}/rollouts/{rolloutId}/rollback

Key design choice

Rollout percent selection happens at the gateway (stable bucketing):

  • hash(tenantId, endpointId, userId/ip) % 100 < percent → enforce path. This avoids inconsistent rollout across shards.

Policy Distribution Service & Policy Cache

Responsibilities

  • Generate policy snapshots (compact, ready for evaluation).
  • Push via pubsub (Event Hub / Service Bus) to regional caches.

Support:

  • versioned snapshots
  • atomic swap
  • rollback to previous version quickly

Cache behavior

  • Each limiter shard keeps a local in-memory cache:policyId -> compiled_ruleset
  • Cache refresh via push + periodic pull fallback.

Rate Limiter Shard Service (Data plane)

Responsibilities

  • Stateless (mostly), horizontally scalable.
  • For each request:
    • compute dimension keys
    • fetch compiled policy rules
    • perform algorithm checks via Counter Store
    • return ALLOW/DENY + retryAfter + reason
  • Emit telemetry.

CheckLimit API

POST /v1/check

{
  "tenantId": "t1",
  "endpointId": "e123",
  "timestampMs": 1730000000,
  "dimensions": {
    "user": "u456",
    "ip": "1.2.3.4",
    "region": "westus"
  },
  "rolloutContext": { "mode": "ENFORCE", "percent": 25 }
}
{
  "tenantId": "t1",
  "endpointId": "e123",
  "timestampMs": 1730000000,
  "dimensions": {
    "user": "u456",
    "ip": "1.2.3.4",
    "region": "westus"
  },
  "rolloutContext": { "mode": "ENFORCE", "percent": 25 }
}

Response:

{
  "decision": "DENY",
  "httpStatus": 429,
  "retryAfterMs": 1200,
  "reason": {
    "policyId": "p789",
    "version": 12,
    "ruleId": "r2",
    "dimension": "REGION",
    "limit": "30000/60s"
  }
}
{
  "decision": "DENY",
  "httpStatus": 429,
  "retryAfterMs": 1200,
  "reason": {
    "policyId": "p789",
    "version": 12,
    "ruleId": "r2",
    "dimension": "REGION",
    "limit": "30000/60s"
  }
}

Algorithm choice

Use Token Bucket for most dimensions (user/ip) and optionally sliding window for strict fairness. Token bucket is the usual production choice due to:

  • constant-time
  • natural burst control
  • easy implementation with atomic counters

Implementation approach
For each rule, we need atomic update:

  • store (tokens, last_refill_ts)
  • refill based on time delta
  • decrement if available else deny

Counter Store

Key design choice

You want fast atomic ops. The simplest pragmatic choice:

  • Redis Cluster with Lua scripts for atomic token bucket updates.
  • Keys include TTL so inactive tenants don’t consume memory.

Key format:
rl:{tenantId}:{endpointId}:{ruleId}:{dimensionKey}

Value:

  • tokens
  • last_refill_ts

Lua script updates atomically.

Observability

What gets emitted

  • decision events (allow/deny)
  • per-rule evaluation latency
  • store latency
  • cache hit ratio
  • per-tenant throttling rates (noisy neighbor detection)

Trace correlation

  • Gateway generates traceid
  • passes it to limiter
  • limiter logs/exports spans:
  • CheckLimit
  • FetchPolicyCache
  • UpdateTokenBucket

Scale, performance, availability, geo, hotspots, shard placement

Throughput

Given ~30k req/s per region.
Assume:

  • Gateway call to limiter: 1 network hop
  • Limiter does 1–3 rule checks; each rule may do 1 Redis Lua op

Data plane capacity

If one limiter instance handles ~5k req/s comfortably:

  • need ~6 instances + auto-scale

Redis cluster sized for ops/sec:

  • worst case 3 rules per request → 90k ops/sec
  • scale Redis shards accordingly

Latency

Budget:

  • Gateway to Limiter: 2–5ms intra-region
  • Policy cache: in-memory ~sub ms
  • Redis Lua: 1–3ms typical
  • Total limiter: ~5–15ms typical, p95 well under 50ms overhead.

Availability

Fail-open vs fail-closed

Enterprise-critical decision:

  • Default fail-open if limiter unavailable (do not drop customer traffic)
  • Allow fail-closed configurable per tenant/endpoint for strict protection.

Multi-AZ redundancy

  • Limiter shards deployed across zones behind LBs
  • Redis cluster multi-AZ
  • Policy distribution multi-AZ with replay

Geo replication

  • Each region runs its own data plane (limiter + Redis)
  • Policies are replicated from control plane to each region’s cache.
  • Enforcement is regional by default.

Parallelization

  • Evaluate rules in parallel inside the limiter only if independent and store ops allow pipelining.
  • Use Redis pipelining or a single Lua script that checks multiple rules when possible.

Hotspots & shard placement

Shard key

Shard by:
hash(tenantId, endpointId, ruleId, dimensionKey)

This distributes evenly unless dimensionKey is extremely skewed (e.g., one IP attacks).

Hot key mitigation

  • Detect via telemetry: top keys by deny count

Apply:

  • per-key replication (read replicas won’t help atomic writes)
  • token leasing: shard allocates a batch of tokens to gateway (eg: 100 tokens) instead of checking 1 token at a time.
  • dynamic re-sharding: split big tenants across multiple Redis shards via key salting: salt = hash(requestId) % N only for hot tenants/endpoints
  • Rate limiting itself is protection against hotspots, so denial rates can be huge; ensure counters can handle it.

Storage

Redis stores active keys with TTL:

  • If each key ~100 bytes and active keys ~1M:
  • ~100MB memory
    TTL prevents unbounded growth.