Pidoku

Archive

This learning material is in the archive. It is not currently maintained and has not been updated with the latest information, so tool versions, prices and dates may be out of date.

Rate Limiting and Load Shedding

Module 6 Lesson 6.d 1h Difficulty 4/5

Prerequisites 6.a, 3.a

The idea in one minute#

Every service has a maximum throughput. When more work arrives than it can do, something has to give. If nothing is designed to give, the queue grows, every request waits longer, clients time out, and the service ends up spending all its capacity on requests nobody is waiting for — its useful throughput (goodput) falls towards zero even though it is 100% busy.

Two protections stop that:

  • Rate limiting caps how much work each client may send (for example 100 requests per second per API key), usually with a token bucket. It enforces fairness and contracts.
  • Load shedding protects the server: when it is near capacity, it rejects the excess immediately and cheaply — newest, lowest-priority or already-expired requests first — so the work it does accept finishes in time.

An analogy#

A popular restaurant. A reservation limit per party (rate limiting) stops one group of fifty taking every table. When the kitchen is full, the host tells newcomers at the door “45-minute wait, or come back later” (load shedding) — instead of seating everyone and serving every dish an hour late, cold, to people who have already left.

A picture#

flowchart LR
  C1[":i-user: Client A"] & C2[":i-user: Client B"] & C3[":i-bot: Noisy client"] --> RL[":kong: <b>Rate limiter</b><br/><small>token bucket per key</small>"]
  RL -->|"429 + Retry-After"| C3
  RL --> LS{"<b>Load shedder</b><br/><small>queue nearly full?<br/>priority? deadline?</small>"}
  LS -->|"503, cheap and early"| X["Rejected"]
  LS --> Q["Bounded queue"] --> W[":go: Workers<br/><small>fixed concurrency</small>"]
  class C1,C2,C3 neutral
  class RL io
  class LS,Q queue
  class X warn
  class W compute

How it really works#

Why an unbounded queue is the enemy#

With capacity μ and arrival rate λ > μ, the queue grows by λ − μ per second, and the wait for a new request grows without limit. Once the wait exceeds the client’s timeout, every request the server completes is one the client has already abandoned. The server is 100% busy and 0% useful. Worse, clients retry (6.b), raising λ further. This is the core of most overload outages.

Rule: every queue must be bounded, and the bound should be expressed in time — at most about as much queued work as can be done within the client’s timeout.

Token bucket rate limiting#

A bucket holds up to burst tokens and refills at rate tokens per second. Each request takes a token; with none left, the request is rejected (or delayed). It allows short bursts while enforcing the average rate. Go’s golang.org/x/time/rate package implements it; so do NGINX (limit_req), Envoy (local and global rate limiting), API gateways (Kong, AWS API Gateway) and Redis-backed libraries for limits shared across instances.

AlgorithmBehaviourUse
Token bucketAverage rate + burstsDefault for APIs
Leaky bucketSmooth constant output rateShaping outbound traffic
Fixed window counterN per minute, resets each minuteSimple; allows 2N at the window edge
Sliding windowN in any rolling minuteFair; more state
Concurrency limitAt most N in flightProtects against slow requests, not just many

Return 429 Too Many Requests with a Retry-After header, and tell clients their limits (RateLimit-Limit, RateLimit-Remaining headers).

Load shedding#

Shedding decides, under load, which work to reject:

  1. Cheaply and early. Reject at the front door — before parsing the body, before authentication if possible, certainly before calling dependencies. A rejection that costs as much as serving is useless.
  2. By priority. Tag requests: critical (checkout, login), default, sheddable (prefetch, analytics, batch). Shed sheddable first. Google’s SRE book describes critical, critical-plus, sheddable-plus and sheddable criticalities propagated with each request.
  3. By deadline. Drop requests whose deadline has already passed or cannot be met (6.a).
  4. By queue time. If the oldest request has waited longer than a target, shed — the idea behind the CoDel algorithm and adaptive LIFO: under overload, serve the newest requests first (their clients are still waiting) and drop the oldest.
  5. By concurrency. Cap in-flight requests at what the service can handle; reject beyond.

Adaptive concurrency limits#

Fixed limits go stale as code and hardware change. Adaptive concurrency measures latency and adjusts the in-flight limit automatically, the way TCP congestion control does: increase the limit slowly while latency stays near its minimum, cut it sharply when latency rises (additive increase, multiplicative decrease — AIMD). Netflix’s concurrency-limits library and Envoy’s adaptive concurrency filter work this way.

Shed at every layer, return the right signal#

  • Clients should treat 429 and 503 as “back off” signals, not “retry immediately”.
  • The load balancer can shed too (max connections, max pending requests: 6.c).
  • Shed before the point of collapse: start rejecting at, say, 90% of measured capacity, not after latency has already exploded.

A worked example#

A search service has 10 workers, each taking 100 ms per query: capacity 100 queries per second. Clients time out after 1 s. A marketing email drives 150 queries per second for a minute.

StrategyWhat happens
Unbounded FIFO queueQueue grows 50/s; after a few seconds every query waits more than 1 s; goodput falls to nearly zero while the service is 100% busy
Bounded queue (50 waiting)Excess rejected at once; accepted queries wait ≤ 0.5 s; goodput ≈ 100/s
Drop expired at dequeueWorkers skip queries already past their deadline; goodput ≈ 100/s
Priority + deadline30% of queries are from logged-in shoppers (critical): all of them succeed; anonymous queries absorb the shedding, and expired ones are dropped

The program simulates each strategy millisecond by millisecond.

Code#

Go
// shedding.go — a token bucket, then an overloaded service under four queueing strategies.
package main

import (
	"fmt"
	"sort"
)

// ── token bucket ────────────────────────────────────────────────────────────

type bucket struct {
	rate, burst, tokens float64
	last                float64 // seconds
}

func (b *bucket) allow(now float64) bool {
	b.tokens += (now - b.last) * b.rate
	if b.tokens > b.burst {
		b.tokens = b.burst
	}
	b.last = now
	if b.tokens >= 1 {
		b.tokens--
		return true
	}
	return false
}

func tokenBucketDemo() {
	b := &bucket{rate: 10, burst: 20, tokens: 20}
	allowed := 0
	// A client sends 50 requests in the first second, then 1 every 50 ms for 4 seconds.
	var times []float64
	for i := 0; i < 50; i++ {
		times = append(times, float64(i)*0.02)
	}
	for t := 1.0; t < 5; t += 0.05 {
		times = append(times, t)
	}
	for _, t := range times {
		if b.allow(t) {
			allowed++
		}
	}
	fmt.Printf("token bucket (10/s, burst 20): %d of %d requests allowed over 5 s\n\n", allowed, len(times))
}

// ── overloaded service ──────────────────────────────────────────────────────

type req struct {
	arrive   int // ms
	critical bool
}

type result struct{ served, good, rejected, goodCritical, critical int }

func simulate(strategy string) result {
	const (
		workers   = 10
		service   = 100  // ms per request → capacity 100/s
		timeout   = 1000 // client gives up after 1 s
		duration  = 60_000
		perSecond = 150
		maxQueue  = 50
	)
	var queue []req
	busyUntil := make([]int, workers)
	var r result
	acc := 0.0
	seq := 0
	for t := 0; t < duration; t++ {
		acc += perSecond / 1000.0
		for acc >= 1 {
			acc--
			seq++
			q := req{arrive: t, critical: seq%10 < 3}
			if q.critical {
				r.critical++
			}
			switch strategy {
			case "unbounded FIFO", "drop expired at dequeue":
				queue = append(queue, q)
			case "bounded queue (50)":
				if len(queue) >= maxQueue {
					r.rejected++
					continue
				}
				queue = append(queue, q)
			case "priority + deadline":
				if len(queue) >= maxQueue {
					victim := -1 // the newest sheddable request, if any
					for i := len(queue) - 1; i >= 0 && q.critical; i-- {
						if !queue[i].critical {
							victim = i
							break
						}
					}
					r.rejected++ // the victim, or this request
					if victim < 0 {
						continue
					}
					queue = append(queue[:victim], queue[victim+1:]...)
				}
				queue = append(queue, q)
				// Critical first, oldest first within a class.
				sort.SliceStable(queue, func(i, j int) bool { return queue[i].critical && !queue[j].critical })
			}
		}
		for w := 0; w < workers; w++ {
			if busyUntil[w] > t {
				continue
			}
			for len(queue) > 0 {
				q := queue[0]
				queue = queue[1:]
				if (strategy == "drop expired at dequeue" || strategy == "priority + deadline") && t+service-q.arrive > timeout {
					r.rejected++ // cannot finish in time: do not waste a worker on it
					continue
				}
				busyUntil[w] = t + service
				r.served++
				if t+service-q.arrive <= timeout {
					r.good++
					if q.critical {
						r.goodCritical++
					}
				}
				break
			}
		}
	}
	return r
}

func main() {
	tokenBucketDemo()
	fmt.Println("capacity 100/s, offered 150/s for 60 s, client timeout 1 s, 30% critical")
	fmt.Printf("%-24s %8s %10s %9s %10s %16s\n", "strategy", "served", "goodput/s", "wasted", "rejected", "critical served")
	for _, s := range []string{"unbounded FIFO", "bounded queue (50)", "drop expired at dequeue", "priority + deadline"} {
		r := simulate(s)
		fmt.Printf("%-24s %8d %10.1f %9d %10d %15.0f%%\n",
			s, r.served, float64(r.good)/60, r.served-r.good, r.rejected, 100*float64(r.goodCritical)/float64(r.critical))
	}
}

The unbounded FIFO row is the lesson: the service completes thousands of requests and almost none of them in time. Every other strategy keeps goodput near capacity by refusing work it cannot do; the priority strategy also protects the requests that matter most.

Remember this#

  • Past capacity, an unbounded queue drives goodput to zero while the service is 100% busy.
  • Bound every queue, ideally in time: no more queued work than fits inside the client’s timeout.
  • Rate limit per client (token bucket, 429 + Retry-After) for fairness; shed load at the server for survival.
  • Shed early and cheaply, by priority, by deadline, by queue age; consider adaptive concurrency limits.
  • Start shedding before collapse, not after.

Try it#

  1. Run shedding.go. Lower the offered load to 95/s. Do the strategies still differ?
  2. Change maxQueue to 500. What happens to the bounded queue’s goodput, and why?
  3. Add an “adaptive LIFO” strategy: when the queue is longer than 20, take the newest request instead of the oldest.

Check yourself#

  1. Why does goodput fall to nearly zero in an overloaded unbounded queue?
  2. What is the difference between rate limiting and load shedding?
  3. Why must rejection be cheap?
  4. How does adaptive concurrency decide the limit?

Sources#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in