Skip to content

Latency vs Throughput

Definitions

  • Latency — the time to perform some action or produce some result.
  • Throughput — the number of such actions or results produced per unit of time.

The relationship

  • These two are often traded against each other, but the goal is usually: maximal throughput with acceptable latency.

  • A system can have low latency but low throughput (a single request is fast, but you can't handle many at once), or high throughput with high latency.

Analogy

Think of a factory assembly line:

  • Latency = how long it takes one item to go through the line.
  • Throughput = how many items come off the line per hour.

Adding more parallel lines (workers) increases throughput, but the time for any one item (latency) stays roughly the same.

Key takeaways

  • Don't confuse the two: latency is per-operation time; throughput is operations per time unit.

  • Many scaling decisions (e.g., batching, replication, async processing) deliberately accept higher latency to achieve higher throughput.

Rate Limiting Algorithms & Distributed Enforcement

Core algorithms

  • Fixed window — count requests in the current time window; reset at each boundary. Simple, but allows up to twice the limit at window edges.
  • Sliding window log — store a timestamp per request; reject if the number of timestamps in the last window exceeds the limit. Accurate but memory-heavy.
  • Sliding window counter — approximate by combining the previous window's weighted count with the current window's count. Cheaper than the log approach.
  • Token bucket — tokens refill at a fixed rate up to a burst capacity; each request consumes a token. Allows short bursts while preserving a long-term rate.
  • Leaky bucket — requests enter a queue and are processed at a constant outflow rate. Smooths bursts but can add latency or drop requests.

Distributed enforcement

  • Enforce at the edge/gateway or application tier; a distributed system needs shared counters in a store like Redis.
  • Use Redis INCR + EXPIRE or a Lua script to perform atomic check-and-increment, avoiding race conditions between multiple API servers.
  • Trade off single-node rate limiting (fast, local, but inconsistent across replicas) vs distributed rate limiting (consistent, but adds a Redis round-trip of latency).
  • Return 429 Too Many Requests with Retry-After (and optionally X-RateLimit-* headers) to help clients back off.
flowchart LR
    C[Client] --> RL[Rate Limiter]
    RL -->|allow| B[Backend API]
    RL -->|reject 429| C
    RL --> S[(Redis INCR + EXPIRE)]

Common Interview Questions

Design an API rate limiter

Why it's asked here: a rate limiter is a pure latency/throughput problem — you must cap throughput (requests/sec) while keeping latency acceptable.

Key points to discuss:

  • Algorithms: token bucket, leaky bucket, fixed window, and sliding window (counter or log).

  • Where to enforce: client, gateway, or service; single-node vs distributed.

  • Trade-off: tight limits protect the backend (throughput) but may reject/queue requests (latency).

  • Use a backing store (Redis) for distributed counters with atomic increments.

flowchart LR
    C[Client] --> RL[Rate Limiter]
    RL -->|allow| B[Backend API]
    RL -->|reject 429| C
    RL --> S[(Redis counters)]
Return the top-k requests during a time interval

Why it's asked here: a streaming top-k problem forces you to reason about how much work you can do per second (throughput) and how fresh results are (latency).

Key points to discuss:

  • Count-min sketch / lossy counting for high-throughput approximate counts.
  • Heavy-hitters via a heap over sliding windows.
  • Batch vs streaming: batching raises throughput at the cost of result latency.
  • Discuss read vs write throughput and how to bound memory.
flowchart LR
    E[Event stream] --> W[Sliding window]
    W --> K[Count-min sketch]
    K --> H[Top-K heap]
    H --> R[Result]

Further reading


API Rate Limiter Detailed Design

A rate limiter is an edge component that caps how many requests a client or API key can send to a service in a time window. To size it, assume a public API with 10 million daily active users and about 100 million requests per day, roughly 1,200 requests per second on average and 5,000 requests per second at peak. The functional requirement is to identify each caller and either allow the request or reject it with HTTP 429 and a Retry-After header. The non-functional requirements are low added latency, high availability, accurate enforcement for most users, and the ability to work across many horizontally scaled API servers. The system must support per-client, per-endpoint, and per-plan limits, and it must store enough state to enforce limits exactly enough without becoming a database bottleneck.

The high-level architecture places the rate limiter at the edge, either as a separate gateway that fronts the API servers or as middleware inside each API server. Requests first arrive at a load balancer and are distributed to stateless rate-limiter instances. Each instance extracts the caller identity from an API key, user ID, IP address, or signed session, then applies the rate-limit rules for that caller. The actual counters live in a shared Redis cluster rather than on individual application hosts, so all rate-limiter instances see the same usage state. On a successful check, the instance forwards the request to the backend API and returns the backend response. On a rejection, the instance returns 429 with Retry-After and does not touch the backend. This flow keeps the API servers protected and makes the rate-limiter tier horizontally scalable.

The main data is small but very hot. Rate-limit policies can be stored in a configuration service or a simple database table describing which user tier, API endpoint, or key is allowed how many requests per second or minute. The operational state that changes on every request belongs in Redis. A typical key is a string that combines the namespace, caller ID, and time bucket, with an integer count and a TTL. For sliding-window or token-bucket algorithms, the value may also be a small structure holding the timestamp of the last update and the token balance. Redis is the right backing store because rate limiting needs atomic updates, sub-millisecond latency, very high write throughput, and automatic expiration of old counters. A disk-based SQL stores the rules and audit events, but it is too slow to be on every request path.

The core algorithm is the token bucket. Each caller is assigned a bucket that holds up to a fixed number of tokens, and tokens are added at a steady rate. A request may proceed only if at least one token is available; if it proceeds, one token is removed. This allows a caller to tolerate a short burst while still being held to a long-term average. The implementation uses a Redis Lua script because Lua executes atomically on the Redis server. The script reads the current bucket state, computes how many tokens should have accumulated based on the elapsed time, checks whether the request can be served, and updates the bucket. By doing the read, arithmetic, and write in one atomic script, the design prevents race conditions when many rate-limiter processes judge the same caller at the same time.

For scaling and availability, the stateless rate-limiter tier can be scaled horizontally behind a load balancer because all shared state is in Redis. The Redis layer is sharded by caller ID using consistent hashing or a Redis Cluster, so the total token state is spread across multiple nodes instead of overwhelming one instance. Redis replicas and sentinel-based failover prevent the counter store from becoming a single point of failure. If a rate-limiter process dies, the load balancer removes it and other processes continue with the same Redis data, so no client state is lost. The system must also decide failure behavior when Redis is unavailable: fail-open allows traffic through and preserves availability, while fail-closed rejects traffic and preserves backend protection. In most APIs, the gateway can fall back to local approximate rate limiting or fail-open for good users while still rejecting clearly abusive traffic, but the choice depends on the product.

The important trade-offs are accuracy versus latency and availability versus strict enforcement. A centralized Redis check adds one network round trip per request, which is acceptable for most APIs but can be avoided with a local token bucket that synchronizes asynchronously; the local approach is faster but allows small over-limit bursts across replicas. Fixed-window counters are simple and cheap but can allow twice the limit on window boundaries, while sliding-window logs are accurate but more memory-heavy. Token buckets are a middle ground that supports bursts with bounded state. The algorithm and storage choices therefore trade exactness and burst behavior for memory, Redis load, and implementation complexity.

flowchart LR
    C[Client] --> LB[Load Balancer]
    LB --> R1[Rate Limiter 1]
    LB --> R2[Rate Limiter 2]
    R1 --> LUA[Redis Lua script]
    R2 --> LUA
    LUA --> RC[(Redis Cluster counters sharded by caller)]
    LUA -->|allow| API[Backend API]
    LUA -->|reject 429| C
    API --> C

Return the Top-k Requests During a Time Interval

To design a top-k request system, first define the workload. Suppose an API or edge service emits up to 1 million request events per second, and operators need the top 100 endpoints, user agents, or query strings over a rolling interval between one minute and one day. The functional requirement is to ingest events continuously and answer queries for the most frequent keys in a time interval. The non-functional requirements are high write throughput, low query latency, bounded memory, and tolerance of machine failures. Approximate counts are acceptable only if the approximation error can be bounded and explained.

The high-level architecture starts with event producers such as load balancers, proxies, or API gateways that publish normalized request records to a distributed log such as Kafka. Kafka acts as a durable buffer and decouples traffic bursts from processing. Stream processors such as Flink, Spark Streaming, or Kafka Streams consume partitions in parallel, update windowed frequency summaries, and publish those summaries to a serving store. A query service reads the summaries and returns the top-k entries. The request flow is therefore a streaming pipeline from producers to the log, then to parallel aggregators, then to a query-facing store.

The data model has two main parts. Raw events contain the request key being counted, such as a normalized URL, endpoint, customer ID, or query string, along with a timestamp and optional metadata. Raw events can be retained in Kafka with a TTL so the system can replay or backfill after failures. The serving state maps each request key to its frequency inside the selected time window. In an exact design, that mapping is a hash table per processor. In an approximate design, each time bucket contains a count-min sketch for frequencies and a small heap of size k for the most likely heavy hitters. Redis sorted sets may be used for small, stable key spaces, but a custom windowed store is more appropriate when the key cardinality is huge and a global sort is too expensive.

The core mechanism is a frequent-items algorithm over a sliding window. Each stream processor slices time into small buckets, such as one second or ten seconds, and updates a count-min sketch keyed by request identity for the current bucket. A count-min sketch hashes each event into several counters and increments the smallest counters, which bounds overcounting. In parallel, the processor updates a size-k min-heap to estimate which keys are heavy hitters. At query time, the query service merges the buckets inside the requested interval, retrieves the approximate or exact frequencies, and extracts the k largest. The key idea is to avoid sorting all keys on every event. Instead, the system maintains only likely heavy hitters and merges a small number of bucket summaries when a query arrives.

For scaling and availability, the system relies on partitioned, replicated event processing. Events are partitioned across Kafka by request key or by shard, and each stream processor owns a subset of partitions with local bucket summaries. Adding more processors increases throughput as long as the number of partitions is sufficient. Local state is backed by changelog topics, so if a processor fails, another processor can rebuild the same summaries from its changelog without losing accepted counts. The query service is replicated behind a load balancer and can read from a shared summary store or query the processors responsible for the requested buckets. Memory is bounded by the number of retained buckets multiplied by the sketch dimensions plus the top-k heap, so old buckets are evicted when they leave the maximum supported window. For very long intervals, a tiered approach keeps fine-grained buckets in memory and rolls older buckets into hourly or daily summaries in a database.

The main trade-offs are accuracy versus memory and latency versus throughput. Exact counters give precise top-k but can be impractical when there are too many distinct keys. Count-min sketch reduces memory substantially but can overcount some keys and may miss candidates that never enter the size-k heap, producing occasional false positives or false negatives in the approximate top-k. Short windows provide fresher results but less stable rankings, while long windows provide more reliable rankings but retain more state. Batch processing can compute exact historical top-k at low cost, but its results arrive late. Streaming gives low-latency fresher results but adds operational complexity and approximation risk. A centralized Redis-style store simplifies queries but adds a network hop, while local processor state reduces query latency but requires the query layer to merge results from multiple shards.

flowchart LR
    P[Load balancers / API gateways] --> K[Kafka event log]
    K --> S1[Stream processor 1]
    K --> S2[Stream processor 2]
    S1 --> B1[(Local windowed sketches and heap)]
    S2 --> B2[(Local windowed sketches and heap)]
    S1 & S2 --> Q[Query service]
    Q --> R[Client]
    S1 -.changelog.-> C[(Kafka changelog)]
    S2 -.changelog.-> C