StackPractices
intermediate By Mathias Paulenko

Shed Load Pattern: Drop Excess Traffic Before Overload

Drop requests proactively under extreme load to protect the system. Reject excess traffic before it consumes resources and causes cascading failures.

Overview

A system hit with more traffic than it can process doesn’t fail cleanly — queues grow, latency climbs, memory runs out, and everything falls over together. Load shedding breaks that spiral. The system refuses excess requests at the door, before they consume resources, instead of accepting everything and dying slowly. The requests that do get in keep a responsive service; the rest get a fast, honest error — typically HTTP 503.

The pattern watches a load signal (active concurrency, CPU, memory, queue depth). Cross the threshold and new requests get turned away at the edge; drop back under it and the door opens again. It pairs naturally with the Back-Pressure Pattern: backpressure slows producers down, while load shedding refuses work outright when slowing down isn’t possible.

When to Use

Use the Shed Load Pattern when:

  • Traffic spikes can exceed your capacity — flash sales, viral events, retry storms, DDoS.
  • Each request costs real resources: CPU, memory, database connections.
  • A fast rejection is better than a slow timeout. Cascading timeouts kill systems that would survive a short burst of 503s.
  • You must protect critical paths during overload — checkouts and payments over recommendation widgets.
  • Typical hosts: API gateways, payment processors, real-time streaming, worker queues.

Don’t use it when requests can’t be retried safely, or when every request is equally critical — in that case scale capacity or queue work instead of dropping it.

Solution

Python

# pip install psutil
from dataclasses import dataclass
from typing import Callable
from enum import Enum
import threading
import time
import concurrent.futures

import psutil

class LoadStatus(Enum):
    ACCEPTED = "accepted"
    SHED = "shed"

@dataclass
class LoadMetrics:
    active_requests: int = 0
    queue_depth: int = 0
    cpu_usage: float = 0.0
    memory_usage: float = 0.0

class LoadShedder:
    def __init__(self, max_concurrent: int = 100,
                 cpu_threshold: float = 0.85,
                 memory_threshold: float = 0.90,
                 queue_threshold: int = 500):
        self.max_concurrent = max_concurrent
        self.cpu_threshold = cpu_threshold
        self.memory_threshold = memory_threshold
        self.queue_threshold = queue_threshold
        self._active = 0
        self._lock = threading.Lock()
        self._shed_count = 0
        self._accept_count = 0

    def _get_metrics(self) -> LoadMetrics:
        cpu = psutil.cpu_percent(interval=0.05) / 100.0
        mem = psutil.virtual_memory().percent / 100.0
        return LoadMetrics(
            active_requests=self._active,
            queue_depth=self._active * 10,
            cpu_usage=cpu,
            memory_usage=mem,
        )

    def should_shed(self) -> bool:
        metrics = self._get_metrics()
        if self._active >= self.max_concurrent:
            return True
        if metrics.cpu_usage >= self.cpu_threshold:
            return True
        if metrics.memory_usage >= self.memory_threshold:
            return True
        return metrics.queue_depth >= self.queue_threshold

    def execute(self, request_id: str, handler: Callable) -> dict:
        with self._lock:
            if self.should_shed():
                self._shed_count += 1
                return {
                    "request_id": request_id,
                    "status": LoadStatus.SHED.value,
                    "message": "Service overloaded, retry later",
                    "http_status": 503,
                }
            self._active += 1
            self._accept_count += 1

        try:
            result = handler(request_id)
            return {
                "request_id": request_id,
                "status": LoadStatus.ACCEPTED.value,
                "result": result,
                "http_status": 200,
            }
        finally:
            with self._lock:
                self._active -= 1

    def stats(self) -> dict:
        total = self._accept_count + self._shed_count
        return {
            "accepted": self._accept_count,
            "shed": self._shed_count,
            "active": self._active,
            "shed_rate": self._shed_count / max(total, 1),
        }

# Usage
shedder = LoadShedder(
    max_concurrent=3, cpu_threshold=0.95,
    memory_threshold=0.95, queue_threshold=10000,
)

def mock_handler(req_id: str) -> str:
    time.sleep(0.1)
    return f"processed-{req_id}"

def send_request(i: int) -> dict:
    return shedder.execute(f"req-{i}", mock_handler)

with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool:
    results = list(pool.map(send_request, range(10)))

for r in results:
    print(f"  {r['request_id']}: {r['status']} (HTTP {r['http_status']})")

print(f"\nStats: {shedder.stats()}")

JavaScript

class LoadShedder {
  constructor(options = {}) {
    this.maxConcurrent = options.maxConcurrent ?? 100;
    this.cpuThreshold = options.cpuThreshold ?? 0.85;
    this.memoryThreshold = options.memoryThreshold ?? 0.90;
    this.queueThreshold = options.queueThreshold ?? 500;
    this.active = 0;
    this.shedCount = 0;
    this.acceptCount = 0;
  }

  _getMetrics() {
    const mem = process.memoryUsage();
    const memUsage = mem.rss / (mem.rss + 512 * 1024 * 1024);
    return {
      activeRequests: this.active,
      queueDepth: this.active * 10,
      cpuUsage: Math.min(this.active / this.maxConcurrent, 1.0),
      memoryUsage: memUsage,
    };
  }

  shouldShed() {
    const m = this._getMetrics();
    if (this.active >= this.maxConcurrent) return true;
    if (m.cpuUsage >= this.cpuThreshold) return true;
    if (m.memoryUsage >= this.memoryThreshold) return true;
    return m.queueDepth >= this.queueThreshold;
  }

  async execute(requestId, handler) {
    if (this.shouldShed()) {
      this.shedCount++;
      return {
        requestId,
        status: "shed",
        message: "Service overloaded, retry later",
        httpStatus: 503,
      };
    }
    this.active++;
    this.acceptCount++;
    try {
      const result = await handler(requestId);
      return { requestId, status: "accepted", result, httpStatus: 200 };
    } finally {
      this.active--;
    }
  }

  stats() {
    const total = this.acceptCount + this.shedCount;
    return {
      accepted: this.acceptCount,
      shed: this.shedCount,
      active: this.active,
      shedRate: this.shedCount / Math.max(total, 1),
    };
  }
}

// Usage
const shedder = new LoadShedder({
  maxConcurrent: 3, cpuThreshold: 0.95, memoryThreshold: 0.95,
});

async function mockHandler(reqId) {
  await new Promise(r => setTimeout(r, 100));
  return `processed-${reqId}`;
}

(async () => {
  const requests = Array.from({ length: 10 }, (_, i) =>
    shedder.execute(`req-${i}`, mockHandler));
  const results = await Promise.all(requests);
  for (const r of results) {
    console.log(`  ${r.requestId}: ${r.status} (HTTP ${r.httpStatus})`);
  }
  console.log(`\nStats:`, shedder.stats());
})();

Java

import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.Function;

public class LoadShedder {

    private final int maxConcurrent;
    private final double cpuThreshold;
    private final double memoryThreshold;
    private final int queueThreshold;
    private final AtomicInteger active = new AtomicInteger();
    private final AtomicInteger shedCount = new AtomicInteger();
    private final AtomicInteger acceptCount = new AtomicInteger();

    public LoadShedder(int maxConcurrent, double cpuThreshold,
                       double memoryThreshold, int queueThreshold) {
        this.maxConcurrent = maxConcurrent;
        this.cpuThreshold = cpuThreshold;
        this.memoryThreshold = memoryThreshold;
        this.queueThreshold = queueThreshold;
    }

    private boolean shouldShed() {
        if (active.get() >= maxConcurrent) return true;
        double cpuLoad = (double) active.get() / maxConcurrent;
        if (cpuLoad >= cpuThreshold) return true;
        long freeMem = Runtime.getRuntime().freeMemory();
        long totalMem = Runtime.getRuntime().totalMemory();
        double memUsage = 1.0 - ((double) freeMem / totalMem);
        if (memUsage >= memoryThreshold) return true;
        return active.get() * 10 >= queueThreshold;
    }

    public String execute(String requestId,
                          Function<String, String> handler) {
        if (shouldShed()) {
            shedCount.incrementAndGet();
            return String.format(
                "{\"requestId\":\"%s\",\"status\":\"shed\",\"httpStatus\":503}",
                requestId);
        }
        active.incrementAndGet();
        acceptCount.incrementAndGet();
        try {
            String result = handler.apply(requestId);
            return String.format(
                "{\"requestId\":\"%s\",\"status\":\"accepted\"," +
                    "\"result\":\"%s\",\"httpStatus\":200}",
                requestId, result);
        } finally {
            active.decrementAndGet();
        }
    }

    public String stats() {
        int total = acceptCount.get() + shedCount.get();
        return String.format(
            "accepted=%d, shed=%d, active=%d, shedRate=%.2f",
            acceptCount.get(), shedCount.get(), active.get(),
            (double) shedCount.get() / Math.max(total, 1));
    }

    public static void main(String[] args) throws Exception {
        var shedder = new LoadShedder(3, 0.95, 0.95, 10000);
        var executor = Executors.newFixedThreadPool(10);
        var futures = new java.util.ArrayList<Future<String>>();

        for (int i = 0; i < 10; i++) {
            final int idx = i;
            futures.add(executor.submit(() -> shedder.execute(
                "req-" + idx,
                req -> {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    return "processed-" + req;
                })));
        }

        for (Future<String> f : futures) {
            System.out.println("  " + f.get());
        }
        System.out.println("\nStats: " + shedder.stats());
        executor.shutdown();
    }
}

Explanation

The shedder sits at the entry point and makes a go/no-go call on every request:

flowchart diagram: Incoming request
  1. Measure: before accepting, read the load signals — active requests, CPU, memory, queue depth. Keep this cheap; a shed check that costs a database query defeats the purpose.
  2. Decide: if any signal is over threshold, shed immediately. The caller gets 503 plus Retry-After in microseconds, not a 30-second timeout.
  3. Track: accepted requests bump the active counter; finishing one frees capacity for the next.

The pattern is proactive. The system doesn’t wait for the crash — it starts refusing work while it’s still healthy, which is what keeps the accepted traffic fast. In effect you’re buying a small, predictable error rate now to avoid a total outage later.

Picking thresholds: load test until the system degrades, then set thresholds at 80–90% of the breaking point. If 1,000 concurrent requests is where p99 latency falls apart, cap at ~850 and let shedding absorb the overshoot. Revisit the numbers after infrastructure changes — thresholds tied to a retired instance size will shed too early or too late.

In production the check often lives outside your code. Envoy enforces connection and concurrency limits at the listener, nginx does it with limit_conn and limit_req (which answer 503 by default), and most managed API gateways expose request quotas — same pattern, different signal. If you implement it in code, treat the shed rate itself as a first-class metric: graph it next to p99 latency and CPU, alert when it stays above zero for more than a few minutes, and feed it to your autoscaler. A shedder that never sheds tells you nothing; one that always sheds is a capacity alarm, not a resilience feature.

Priority shedding adds one small piece: a cheap classifier in front of the check. Tag requests by route, API key tier, or an explicit priority header, then shed the lowest tier first as load climbs. The common bug is making the classifier expensive — a lookup per request is fine, a database query isn’t.

Variants

VariantDescriptionUse Case
Priority-based sheddingDrop low-priority requests first, keep premium trafficTiered SLAs, freemium APIs
Gradual sheddingReject a growing percentage as load climbsSmoother than a hard cutoff
Queue-based sheddingShed when the work queue exceeds a depth limitWorker pools, message consumers
Adaptive sheddingFeed the shed rate into autoscaling decisionsTemporary shedding while capacity catches up

Priority-based shedding is what production gateways tend to converge on. Netflix, for example, has published how it sheds non-critical device traffic first so playback stays up during partial outages — a good model if your traffic is heterogeneous.

What Works

  • Shed at the edge — API gateway or load balancer — before requests reach internal services.
  • Answer with 503 plus Retry-After; well-behaved clients back off on their own.
  • Alert on shed rate. A sustained high rate is a capacity problem, not a resilience win.
  • Shed cheap traffic classes first and protect critical paths.
  • Keep the shed check in the microsecond range; it runs on every request.
  • Combine with the Circuit Breaker Pattern — the breaker handles failing dependencies, the shedder handles arriving traffic.

Common Mistakes

  • Shedding after resources are already exhausted — the pattern only works proactively.
  • Counting queued requests but not in-flight ones, so the load signal lags reality.
  • Returning a bare 503 with no Retry-After and no body; clients retry instantly and make the spike worse.
  • A shed check expensive enough to show up in profiles — use cheap signals (counters, sampled gauges), not scans.
  • Treating all traffic as equal and dropping checkouts alongside health-check pings.
  • Shedding deep inside the service after the work is already priced in — shed at the boundary.

Further Reading

Frequently Asked Questions

How is load shedding different from rate limiting?

Rate limiting caps requests per client over a window (100 req/min) to stop one noisy client. Load shedding caps total system load based on health signals to protect the whole service. You usually want both.

What HTTP status should shed requests return?

503 Service Unavailable with a Retry-After header — it tells clients the failure is temporary and when to come back. Don't return 500; that reads as a bug, not as protection.

Where should the shed check live?

At the edge of the system — gateway, load balancer, or the first line of request handling — and it must run synchronously in microseconds. A slow check is just a slower way to overload.

Can I shed requests I'm already processing?

That's load shedding's cousin, early timeouts or deadline propagation, and yes — dropping work that will miss its deadline anyway frees capacity sooner. Keep it separate from admission shedding so you can measure each.

How do I calculate the right thresholds?

Load test to the breaking point, then set thresholds at 80–90% of it. If the system degrades at 1,000 concurrent requests, cap at ~850. Re-measure after capacity changes.