Message Queues & Rate Limiting

System Design · Distributed Systems · Advanced · 14 min

Do slow work later, and stop any one user from flooding you.

A jar of tickets by the club door. Each guest takes one ticket; a new ticket drops into the jar every second, but the jar only holds a few. A crowd arriving at once empties the jar and the rest wait outside. Behind the door, a ticket rail holds orders until the cooks are free.

The idea in everyday words

A message queue is a restaurant ticket rail: the waiter clips orders on the rail and goes back to customers; cooks pick tickets when ready. Rate limiting is a nightclub bouncer letting in only 10 people per minute. A 'token bucket' is a jar of entry tickets that refills slowly.

Why queues?

  • Decouple: the sender doesn't wait for slow work (emails, video encoding).
  • Absorb spikes: the queue grows, and workers catch up.
  • Retry failed jobs. After a few failed attempts, a dead-letter queue (DLQ) catches the message so one bad job can't block the rest.
  • Most queues (including SQS standard) deliver at least once, so a job can run twice: make workers idempotent (safe to repeat).

Tools: Kafka, RabbitMQ, AWS SQS/SNS, GCP Pub/Sub, Azure Service Bus.

Token bucket rate limiter

  • Bucket holds up to capacity tokens.
  • Tokens refill at rate per second.
  • Each request spends 1 token. No token → 429 Too Many Requests.

Allows short bursts but limits the average. Store buckets in Redis so all servers share them.

Go deeper (senior / staff)

Failure modes to name.

  • Poison messages: a message that always fails is retried until maxReceiveCount, then the redrive policy moves it to the DLQ. Alarm on DLQ depth and on the age of the oldest message, not only on queue depth.
  • Visibility timeout too short: if it is shorter than the worst-case processing time, a second worker gets the message while the first is still working. For Lambda event sources, AWS suggests a visibility timeout several times the function timeout.
  • Retry amplification: clients retry after a 429, the handler retries its dependency, and SQS redelivers. One bad minute multiplies load. Pick one retry layer and cap it.
  • FIFO head-of-line blocking: a failing message blocks later messages in the same message group. Use many groups (per order, per account) so one stuck group doesn't stall everyone.

Exact vs approximate limits. API Gateway throttling and usage plan quotas are applied on a best-effort basis, so treat them as protection, not billing. For exact per-tenant limits use an atomic counter in ElastiCache or a DynamoDB conditional update, at the cost of a network hop per request. Decide whether the limiter fails open or closed when its store is down; for a public API, failing open with a coarse local limit usually beats an outage.

Multi-region. SQS queues are regional, so each Region drains its own queue, and consumers must be idempotent because failover can replay work. Exact global limits across Regions are expensive; most teams split the quota per Region.

Cost reasoning. SQS bills per request: batch sends and receives (up to 10 messages per call) and use long polling to avoid empty receives. Set maximum concurrency on the Lambda event source so draining a backlog doesn't overload the database behind it.

Step by step

  1. Bucket = 3:

    capacity 3, refill 1 token/sec.

  2. t=0: 3 requests:

    All allowed → bucket 0.

  3. t=0: 4th request:

    No tokens → rejected (429).

  4. t=1:

    1 token refilled → next request allowed.

Code example

import time
class TokenBucket:
    def __init__(self, capacity, rate):
        self.capacity, self.rate = capacity, rate
        self.tokens, self.last = capacity, 0.0
    def allow(self, now):
        self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
        self.last = now
        if self.tokens >= 1:
            self.tokens -= 1
            return True
        return False

b = TokenBucket(3, 1)
print([b.allow(t) for t in [0, 0, 0, 0, 1, 1.5, 3]])

Interview tips

  • Kafka = durable log, replayable, high throughput. SQS = simple managed queue.

  • Rate limiter algorithms: token bucket, leaky bucket, fixed window, sliding window.

  • Return HTTP 429 with a Retry-After header.

Challenge: Token Bucket

Implement token_bucket(capacity, rate, times). The bucket starts full at time 0. Tokens refill at rate per second (never above capacity). For each request time (sorted), return True/true if allowed (spend 1 token), else False/false.

Example: token_bucket(2, 1, [0, 0, 0, 1]) → [True, True, False, True]

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Distributed Systems

Previous: Monolith vs Microservices · Next: Event-Driven Architecture: SQS, SNS, EventBridge & Kinesis