Rate Limits, Quotas, and Consumer Fairness

Set fair API rate limits and quotas with clear scopes, useful headers, burst handling, and protection against noisy consumers and accidental traffic spikes.

published: reading time: 10 min read author: Geek Workbench updated: November 5, 2026
Quick Summary

Rate limits set how fast a tenant can use an API; quotas cap accumulated use over a longer period. This guide shows how to add weighted cost to tenant budgets, answer a rejected request with `429` and `Retry-After`, and choose a policy for counter-store outages.

Rate Limits, Quotas, and Consumer Fairness

Introduction

Without traffic controls, a buggy integration or sudden launch can overwhelm a shared API. A rate limit caps how quickly a client can make requests. A quota caps consumption over a longer period, such as requests per day or monthly data volume. These controls protect shared capacity, but a blunt global limit can punish small clients while allowing one tenant to dominate.

Good limits explain the policy and give clients a way to recover. They should also reflect resource use: a cache hit and a large report do not cost the same. For implementation patterns, see rate limiting.

Choose the scope and algorithm

Start with an identity that matches the policy: use a tenant or API key for authenticated usage, and an IP or network address for pre-auth edge protection. Add a global limit to protect the service from aggregate load. Fixed windows are simple but can allow a burst at the reset; sliding windows smooth that boundary, while token buckets allow a defined burst and cap the long-run rate. For multi-instance services, enforce counters with atomic shared state or a gateway that provides equivalent guarantees.

Fairness when requests have different costs

Requests per second is only a rough measure of consumption. A small lookup and a report that scans a large dataset may each count as one request while using very different amounts of CPU, storage, or downstream capacity. Assign documented cost units from measured resource use, and charge those units against a tenant’s budget rather than letting clients choose their own weight.

Combine per-tenant cost budgets with a global safety limit and, for long-running work, a concurrency or queue limit. Revisit the weights when route behavior changes; stale costs can let one endpoint consume most of the shared capacity even though its request count looks normal. Keep the policy understandable enough that consumers can estimate how their usage maps to the quota.

Example: weighted budget for one tenant

The numbers below illustrate one deployment, not a default. Suppose a representative load test shows the service can sustain 6,000 normalized cost units per minute at its target SLO. The team reserves 20% for internal work and divides the rest evenly among 12 tenants, giving each an initial budget of (6,000 × 0.80) ÷ 12 = 400 units per minute.

In the same test, GET /customers/{id} costs 1 unit and POST /exports costs 10 units based on measured CPU and downstream reads. One tenant could spend its budget on 100 lookups and 30 exports (100 + 10 × 30 = 400), or another mix within the same budget. Recalculate the unit costs and per-tenant share from representative data, concurrency, and SLO results before using a production limit.

This per-minute weighted budget controls resource rate. Keep any monthly usage quota as a separate policy.

Response contract and implementation snippet

When a request exceeds its rate limit, return 429 Too Many Requests with an explanation and, when the next eligible time is known, a Retry-After value. RFC 6585 allows this header on 429 responses and requires the response not be stored by a cache. RFC 9110 defines Retry-After as either an HTTP date or a non-negative integer delay in seconds. See RFC 6585, Section 4 and RFC 9110, Section 10.2.3.

For the weighted budget above, suppose the 400-unit-per-minute policy refills evenly, the bucket currently has 3 units, and an export costs 10. It needs 7 more units; at 400 ÷ 60 units per second, the earliest whole-second delay is ceil(7 ÷ (400 ÷ 60)) = 2 seconds. The response below uses that snapshot. The value changes with the bucket state and request cost.

HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 2

{"code":"rate_limit_exceeded","message":"Tenant request budget is temporarily exhausted."}

The JSON fields are this API’s error contract; Retry-After is the standardized retry metadata. Publish the policy scope and whether the limit is a rate limit or a longer-term quota. Do not expose internal capacity thresholds.

A simplified token bucket illustrates the decision; a multi-instance API needs an atomic shared counter or a gateway with equivalent semantics.

interface Bucket {
  tokens: number;
  updatedAtMs: number;
}
function allow(
  bucket: Bucket,
  now: number,
  refillUnitsPerSecond: number,
  capacityUnits: number,
  requestCostUnits: number,
): boolean {
  const elapsed = Math.max(0, now - bucket.updatedAtMs) / 1000;
  bucket.tokens = Math.min(
    capacityUnits,
    bucket.tokens + elapsed * refillUnitsPerSecond,
  );
  bucket.updatedAtMs = now;
  if (bucket.tokens < requestCostUnits) return false;
  bucket.tokens -= requestCostUnits;
  return true;
}

When to use and when not to

Use rate limits to protect finite compute, database, or downstream-provider capacity. Use quotas for contractual or costly usage accumulated over a longer period. Apply different weights when endpoint costs vary. Rate limits are not a security plan by themselves, and a universal per-IP ceiling can punish authenticated customers behind a shared network. Pair the policy with capacity planning and backpressure; a limit cannot make an overloaded system healthy.

Production failure scenarios and mitigations

If the counter store fails

Do not return 429 when the counter store is unavailable: the service has not established that the tenant exceeded its limit. Choose a fallback by endpoint risk and measured spare capacity.

Endpoint Fallback Guard
Cached, idempotent read Fail open only while an independent edge or local guard has measured headroom. Mark the request as unmetered and record accepted cost in a separate durable usage log if available. If the independent guard is also unavailable or capacity headroom is gone, return 503 Service Unavailable.
Expensive export or side-effecting operation Fail closed with 503 Service Unavailable; do not accept work that cannot be charged to a tenant. Send Retry-After only when the expected recovery delay is known. RFC 9110, Section 15.6.4 permits it on a 503 response.

Rehearse the fallback under load. Replay logged usage after the counter store recovers; if no durable source can reconstruct it, report the unmetered interval and do not claim quotas were enforced during the outage. If the service cannot protect capacity without the shared counters, fail closed for that route.

  • A burst crosses a fixed-window reset and overloads the database. Use a token bucket or sliding window to smooth the boundary.
  • A customer rotates API keys to bypass per-key limits. Enforce the policy against a stable tenant identity.
  • A route becomes more expensive but its weight stays the same. Watch resource use by route and review its cost during rollout.

Observability checklist

  • Track allowed and rejected requests by route, tenant tier, and limit scope.
  • Measure downstream saturation alongside throttle counts.
  • Monitor counter-store latency and fallback mode.
  • Alert on sudden shifts in top consumers and repeated 429 responses.
  • Keep dashboards privacy-aware; hash or aggregate identifiers where practical.

Security and compliance notes

Authenticate before applying tenant-specific rules, but maintain pre-auth protections against credential stuffing and volumetric abuse. Make API keys revocable and do not use them as query parameters. Ensure counters cannot be manipulated by changing case or alternate identity formats. Return consistent errors without revealing whether a guessed account exists. Retain usage records only as long as needed for billing, abuse investigations, or contractual audits, and avoid storing raw credentials or unnecessary personal data in those records.

Common pitfalls

Do not treat every 429 as a client bug. It may indicate a contractual quota or service-side load shedding; keep those causes separate in internal metrics. Limits keyed only by API key are easy to bypass when customers can rotate keys. A counter reset that doubles the allowance at a window boundary has the same problem from another angle.

Quick recap checklist

  • Define the identity, resource, burst allowance, and time window for each limit.
  • Combine tenant-level fairness rules with service-wide protection where needed.
  • Return 429 with useful retry guidance, including Retry-After when available.
  • Track throttling alongside the capacity and user impact the policy is meant to address.

Interview questions

1. How does a token bucket allow bursts?

Tokens accumulate at a configured rate up to a capacity. Each request consumes tokens, so a client can spend a saved burst while its long-run average remains bounded by the refill rate.

2. Why combine global and per-tenant limits?

A tenant limit isolates customer usage, while a global limit protects the whole service from aggregate demand or traffic that cannot yet be attributed to a tenant.

3. What should a client do after receiving 429?

Respect `Retry-After` if present, reduce concurrency, and retry with backoff. Repeating requests immediately can keep the client throttled and increase pressure on the service.

4. How does a quota differ from a rate limit?

A rate limit controls request frequency over a shorter interval. A quota caps accumulated usage over a longer period, such as a daily request count or monthly data volume.

5. When should a rate limiter fail open versus fail closed?

Choose by route risk. A low-risk read may fail open with a separate global safety guard to preserve availability; a costly or abuse-sensitive operation may fail closed to protect capacity. Make the fallback explicit and observable.

6. Why can per-IP limits be unfair to authenticated customers?

Many users can share one IP through a corporate network or mobile carrier, so they may consume a combined allowance. Use stable tenant or caller identity for fairness and retain IP limits for pre-auth edge protection.

7. How can weighted request costs improve fairness?

Charge expensive routes more units based on measured resource use, so a small number of costly operations does not consume the same budget as many cheap lookups. Keep weights documented and review them as implementations change.

8. Why can a monthly quota reset cause a traffic spike?

Consumers may wait until the reset and then spend their full allowance at once. Pair long-term quotas with short-window rate limits or a gradual refill policy to control bursts.

9. What should a team monitor to judge whether a fairness policy works?

Compare allowed and rejected usage by tenant and route with downstream saturation and customer impact. A policy that lowers request counts but still lets one tenant dominate expensive work needs better cost weights or concurrency controls.

Further reading

Conclusion

Rate limits are capacity and fairness rules expressed as an API contract. Choose limits around stable identities and actual resource costs, allow controlled bursts, and give clients enough information to back off. Monitor whether the policy protects service health without unfairly blocking normal consumers.

Category

Related Posts

GraphQL Federation: Subgraphs, Routing, and Trade-offs

Learn how GraphQL federation composes subgraphs, routes operations, and affects service ownership, query planning, latency, failure handling, and authorization.

#graphql #federation #microservices

API Clients, Servers, and Network Boundaries Explained

Understand what API clients and servers each own, how network boundaries fail, and how timeouts, retries, and trust boundaries shape reliable integrations.

#api-design #networking #distributed-systems

API Examples, Schemas, and Useful Error Documentation

Write API examples, schemas, and error docs that help developers send valid requests, handle failures, and understand exactly what a response means.

#api-documentation #schemas #error-handling