Reject Excess Requests Before a Service Runs Out of Capacity

Published · System Administration

A service can be very busy doing work its callers have already abandoned. Requests wait for a connection, wait for a worker, wait for the database, and finally execute after the caller's deadline. Meanwhile, fresh requests join the same queues.

Accepting everything is a policy. It is usually a terrible overload policy.

Admission control gives the service an earlier decision: can this request enter the protected work path with a reasonable chance of completing usefully? If the answer is no, reject it before it consumes the resources needed by work already in progress. The engineering task is to choose that boundary, make waiting finite, and tell callers what happened.

Find the resource you are protecting

Start with the bottleneck, rather than a convenient requests-per-second number. A cached lookup and a large export may arrive through the same listener while placing very different demands on CPU, memory, database connections, and downstream services.

Google SRE's overload chapter explains why request rate alone can be a poor capacity model when request costs vary. Use that warning to guide measurement; do not copy another service's limit because its traffic graph looks similar.

For your service, identify what becomes scarce first under representative load. Then ask which admitted work holds that resource and for how long. A database pool can be exhausted while CPU remains comfortable. Memory can climb because waiting requests retain large bodies even though relatively few handlers are executing.

Choose a protected unit you can count and enforce: active expensive handlers, concurrent database operations, retained request bytes, or a separately budgeted work class. You may need several limits. A handler limit does not automatically bound bytes per request or fan-out per handler.

Keep the first implementation understandable. A measured fixed concurrency limit is often easier to reason about than an adaptive controller whose signals and failure behavior nobody has verified.

Put the gate before expensive work

Rejecting immediately before the final database call may be too late if the request has already parsed a huge payload, allocated a working set, and launched several dependency calls.

Map the whole path:

  • What does the proxy buffer before forwarding?
  • When does the server read and retain the request body?
  • Does middleware create tasks before admission?
  • Is authentication itself a scarce dependency?
  • Which executor or connection pool adds another waiting room?

Protect the edge with appropriate connection, body-size, and request-reading limits as well as the application gate. Use trusted request classification; letting a caller label every request “critical” defeats a priority policy.

An application admission boundary is not a complete denial-of-service defense. Its narrower promise is that excess ordinary work does not enter a particular constrained path. Document which resources sit outside that promise.

Give a queue both a size and a deadline

A queue can absorb a short burst. It cannot create sustained processing capacity. Once arrivals consistently exceed completions, an unbounded queue converts overload into growing latency and memory use.

Bound both the number of waiting requests and how long each can wait. Use the earlier of a local queue deadline and the caller's remaining useful budget. Account for execution time after admission; a request with two milliseconds left should not enter a path that ordinarily takes hundreds.

Consider a hypothetical service with 64 execution slots, at most 16 queued requests, and a 50-millisecond maximum queue wait. Those figures illustrate three separate controls, not production defaults. You must measure whether that service's workload and latency objective justify any of them.

The queue also needs a cancellation policy. An expired or disconnected waiter must leave it, and a cancellation racing with slot assignment must not leak a permit. Otherwise the advertised bound gradually stops representing real work.

Make the admission transition atomic

This pseudocode describes a controller contract, not a runnable framework implementation:

handle(request):
    deadline = earlier(local_queue_deadline(), useful_start_deadline(request))
    result = admission.acquire_or_queue(
        max_active=64, max_waiting=16,
        deadline=deadline, cancellation=request.cancellation
    )

    if result is rejected:
        return overload_response(result.reason)

    permit = result.permit
    try:
        return execute_with_remaining_deadline(request)
    finally:
        permit.release()

The controller must atomically choose among an available execution slot, a bounded queue position, and rejection. Two concurrent requests cannot both claim the final slot by reading the same counter and incrementing it later.

Its contract must also cover timeout-versus-grant races, cancellation cleanup, and exactly one release for each granted permit. A timeout that loses a race with assignment must return the granted capacity through the controller's cleanup path. Use a mature implementation or test those transitions directly.

Hold the permit until the protected resource use actually ends. If cancellation merely asks a database query to stop, releasing the permit immediately can admit new work while the old query still runs. Detached tasks need explicit ownership too.

Finally, distinguish local and shared limits. Ten replicas with 64 slots each can collectively admit 640 operations. A per-process bound does not protect a database sized for a much smaller total. Budget across the fleet, and include autoscaling in that calculation.

Specify what each rejection means

Write the policy in terms operators and client owners can discuss:

Condition Admission behavior Caller-visible outcome
Protected execution slot available Admit within the remaining deadline Ordinary operation result
Brief burst; bounded queue has room Wait only within the queue budget Result or explicit queue-expiry rejection
Queue full or useful start deadline passed Do not enter business execution Overload response with a stable reason
Individual caller exceeds its quota Enforce the caller's rate policy Rate-limit response
Process is leaving service Follow its separate draining policy Shutdown behavior defined for that path

For HTTP, 503 Service Unavailable describes temporary overload or maintenance. 429 Too Many Requests describes a user sending too many requests in a period. Match the response to the actual policy rather than using every rejection as evidence that a particular caller misbehaved.

Both specifications permit Retry-After. If you send it, provide an honest delay hint rather than a promised recovery time. Define a small error body and a stable machine-readable reason so callers and telemetry can distinguish a full admission queue from other failures. Avoid expensive logging or response generation on the rejection path.

Only claim that rejection happened before business execution when your boundary actually guarantees it. A connection closing after a write began is a different outcome, potentially with an ambiguous committed result.

Keep retries from defeating the gate

A rejection can move pressure elsewhere. If every client retries immediately, your service spends more capacity receiving and rejecting traffic, and the next available slot becomes a prize in a synchronized race.

Agree with client owners on bounded retries, backoff with jitter, and one overall deadline. Include retries already performed by proxies and SDKs. An application retry budget is misleading when three other layers each retry independently.

The dependency-failure guide covers timeout, retry, and ambiguous-write handling. Keep those semantics intact: overload is not permission to replay unsafe writes blindly.

Likewise, autoscaling is useful capacity management, but it has a response time. The admission policy must remain safe while instances start, when scaling reaches its ceiling, and when a shared dependency cannot scale with the application.

Decide who shares the remaining capacity

A single queue can let expensive batch work crowd out interactive requests. Separate budgets can preserve a useful service class, but they also add policy and operational complexity.

If you reserve capacity, name the classes, use a trustworthy classification, and decide what happens when one class is idle. Strict priority can starve lower-priority work. Unlimited borrowing can erase the reservation precisely when it matters. Measure both outcomes.

Health and administrative paths may need separate small budgets so operators can observe and control an overloaded process. Keep those paths cheap; exempting an expensive status endpoint creates another way to consume the capacity you meant to protect.

Planned termination remains a separate lifecycle. The shutdown guide explains stopping intake and draining accepted work when an instance leaves. Overload control decides what a serving instance can safely accept now.

Verify useful work survives overload

Run a bounded test in a representative environment with an explicit stop condition. Ensure the load generator can maintain the intended arrival pressure as response times rise; a client that waits for every response before sending another request may quietly reduce the test load.

Include these cases:

  • A short burst fills the queue, then drains within its deadline.
  • Sustained excess arrivals produce bounded waiting and explicit rejection.
  • Slow dependencies increase resource holding time without unbounded accumulation.
  • Canceled waiters and execution failures return capacity correctly.
  • Different request costs and caller classes exercise the intended sharing policy.
  • Client retries remain bounded through the real proxy and SDK path.
  • After pressure falls, useful throughput and latency recover without a restart.

Observe admitted completions, rejections by reason, queue age, active work, resource use, and caller outcomes. A low average latency can hide the fact that most clients receive fast errors. A high acceptance rate can hide work finishing after its deadline.

Define success as useful completed work with bounded resource use and explainable rejection. The service should remain capable of serving its intended workload after the burst ends. Refusing excess work is part of that capability, not an admission that reliability has failed.

More practical engineering guidance lives at Slaptijack.

Slaptijack's Koding Kraken