Skip to content

High-throughput gateway: tiered caches, balancing, failure and GPU autoscaling

14 min reading

Design a high-throughput gateway with tiered caches, load balancing and workload-derived GPU scaling.

Page details

GenAI · Lesson 37 of 45 · 5 / case 3

Sources · 14 min reading · 32 min with practice

Published · Last edited:

More
20px

Progress is saved in this browser when storage is available.

View guided paths and progress

Know first: Replicas, model partitions, routing, admission and workload-derived scaling. Optional help: GenAI foundations.

Optional background references

Hypothetical scenario. Northwind’s serving topology is explicit. Maya wants a shared gateway for its workloads. Dev enables a fallback destination that accepts the request, but Priya notices that its tool and structured-output behavior differ from the original route.

Maya: “If the fallback responds, can the application treat it as the same service?”

Dev: “A shared request shape does not establish the same supported behavior.”

Priya: “Check route eligibility and the task contract before spending the retry budget.”

You will combine tiered cache decisions, eligible routing and workload-derived scaling in a gateway design. Separate caller identity from provider credentials, and distinguish spare model capacity from a request blocked on another dependency.

Which route can preserve the requested service?

Hypothetical scenario. Choose 12 admitted requests per second and an average two-second in-service lifetime for a steady illustrative workload. Average concurrent service demand is 12 × 2 = 24 requests. If an independently measured replica supports eight such concurrent requests at the required service level, the arithmetic lower bound is 24/8 = 3 replicas under those assumptions. It excludes bursts, failures and startup delay; it is not a recommendation for a particular GPU.

A scaling policy should distinguish eligible-model queues, prefill/decode demand, cache reuse and blocked external tools. GPU utilization alone cannot tell whether adding a replica will help a request waiting on a tool. Balance only among eligible healthy destinations; preserve deadlines and operation identity across retries. The tiered cache design must expose exact-response, semantic-response and prefix reuse separately so that the scaling estimator does not treat all saved work as equivalent.

The fallback accepts the request but changes its meaning

Northwind places a gateway between its applications and model services. Dev normalizes request fields and enables a fallback route. During an interruption, another provider accepts the same payload, but its tool behavior and structured output differ. Priya cannot tell which response contract the customer received, while Sam sees several retry layers spending the same request budget.

The gateway needs a semantic contract, not just a transport adapter. State which input modalities, context bounds, output schemas, tool semantics and data destinations each route supports. Normalize representations where appropriate, but preserve capability differences that affect acceptance. A common endpoint can simplify integration while still exposing materially different task behavior.

Trace one gateway request through reservation and recovery

Hypothetical scenario. The gateway authenticates a tenant, chooses eligible model/provider capabilities and reserves bounded exposure before dispatch. Exact response caches, semantic candidates and prefix/KV reuse occupy different boundaries; a hit at one does not authorize a hit at another.

Trace one gateway request through reservation and recovery
ArtifactConcrete evidenceDecision boundary
Request Ktenant, task capabilities, deadlineOriginal contract
Reservationmaximum exposure, attempts, pending usageShared budget
Route generationeligible providers/models, validityServing policy
Reserve and validate: Tenant / gateway → Budget + route policy.Reserve and validate: Tenant / gateway → Budget + route policy. Tenant / gateway to Budget + route policy: reserve and validate; Budget + route policy to Eligible serving group: bounded compatible attempt.Tenant / gatewayBudget + routepolicyEligible servinggroupreserve and validatebounded compatible attempt
Reserve and validate: Tenant / gateway → Budget + route policy. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

A provider timeout can leave both work and cost uncertain. Retain its reservation while deciding whether a fallback is separately eligible and budgeted. Control-plane configuration and serving data plane have different outage behavior: a valid retained policy may permit continued routing, but expired authority cannot be invented. GPU autoscaling adds capacity only after compatible serving groups become eligible, and cannot replace safe admission during startup or dependency loss.

Authenticate callers before selecting a provider credential

The application caller and upstream provider account are different identities. Authenticate the caller, determine the permitted task and destination, then select a scoped upstream credential through the gateway's controlled configuration. Do not allow model-generated text or an arbitrary client field to choose a privileged provider account.

Per-caller keys can support policy and usage accounting, but possessing a key does not prove every underlying permission check is correct. Define resource scope, revocation, secret storage and audit records. Exclude secret material from prompts and ordinary request traces. A proxy becomes a sensitive control point precisely because it can reach several providers.

LiteLLM's virtual-key documentation describes one implementation of gateway access and usage controls. It is a concrete reference to inspect, not a claim that choosing a gateway library establishes Northwind's complete security boundary.

Normalize syntax while retaining capability differences

Describe each route through an application-owned capability record: supported input, accepted output contract, context policy and permitted tools. Test the record with actual task examples. Two services accepting similar JSON can still differ in schema enforcement, streaming events, token accounting and how tool proposals are returned.

Version the provider model selection, adapter configuration and prompt transformation. If normalization rewrites an error into a generic success or drops a refusal signal, it changes application behavior. Preserve enough provider-specific evidence to diagnose the actual outcome without exposing unnecessary sensitive content.

Compatibility is a tested relationship for a defined task. It is not a universal attribute of an endpoint. A route can be acceptable for ordinary prose and unsuitable for a required image input or a particular tool contract. Route eligibility should express that distinction before an outage forces the decision.

Classify an attempt by what is known about its outcome

A definite rejection before execution is different from a timeout after the request may have been accepted. A partial stream is different from no response, and both differ from a completed but unsuitable answer. The gateway should expose these states so the application can decide whether another attempt is meaningful and permitted.

A provider error category can inform the decision, but it does not establish the status of downstream actions that an application already executed. Keep tool effects under their own operation identity and reconciliation contract. Restarting generation should not automatically replay a refund or send another customer notification.

The existing API operation chapter develops timeouts and bounded retries. The gateway's additional responsibility is to preserve that contract across provider adaptation and fallback rather than hiding another independent retry mechanism behind one application request.

The gateway preserves one task and deadline across provider attemptsCaller identity and task policy reach a gateway with a shared budget. It selects an eligible primary or fallback route. Both attempts report explicit outcomes into the same application state; tool effects remain behind a separate executor boundary.Caller and taskauthorizationGateway budgetone deadlineEligible primaryEligible fallbacksame task contract

A fallback must fit the time that remains

Hypothetical scenario. Choose an application deadline of 6,000 milliseconds. Authentication and policy checks take an assumed 500 milliseconds, evidence retrieval 1,000, and the failed primary attempt consumes 3,000. Remaining time is 6,000 − 500 − 1,000 − 3,000 = 1,500 milliseconds.

If the chosen fallback allowance requires 2,000 milliseconds, it cannot fit that remaining budget. Starting another full deadline at the provider boundary would change the customer's contract. Return the defined failure or asynchronous outcome instead of concealing the overrun behind a successful upstream request.

The values are selected for arithmetic. A measured latency distribution, cancellation behavior and safety margin would inform an actual policy. The equation identifies which intervals share the deadline; it does not promise that a provider finishes inside a chosen allowance.

Several retry layers multiply rather than add attempts

Choose a hypothetical client that permits two gateway attempts, a gateway that permits three provider attempts per call and an upstream wrapper that permits two attempts per provider operation. The selected maximum is 2 × 3 × 2 = 12 upstream attempts for one logical request. Calling each layer's policy “only a small retry” hides the product.

Assign one request-level owner for the total attempt budget. Other layers can expose failure information or perform narrowly defined recovery within that shared accounting. Record whether an attempt started, may have consumed work, completed or was canceled authoritatively. Do not release a reservation twice because both a wrapper and gateway observed the same completion.

Hedged requests deliberately overlap attempts to reduce some latency risks. They also spend capacity and can produce multiple valid outputs. If used, include their work in the same budget and ensure only the selected result progresses. Hedging does not make uncertain tool effects safe to repeat.

A partial answer cannot be silently joined to a new generation

If a stream reaches the user before failure, the application has already exposed content. A second provider may choose different wording, evidence or conclusions. Appending it as if it were a continuation can create a response that neither provider actually produced or evaluated.

Choose an explicit user-facing behavior: mark the response interrupted, restart with a clearly identified replacement, or provide a supported partial outcome when the task allows it. Keep the prior output in diagnostic state according to retention policy. Do not mistake a new connection for continuation of the original generation's internal state.

Structured output requires particular care. A partial object is not a validated final decision, and a second fragment cannot be assumed to complete its semantics. Validate the complete selected response and apply action authorization afterward.

Failover needs spare accepted capacity, not only a healthy region

Choose a hypothetical secondary region able to complete 150 requests per second under the selected workload contract. It already serves 80 requests per second, leaving 150 − 80 = 70 requests per second of selected spare capacity. If the failed region contributes 180 requests per second, the shortfall is 180 − 70 = 110 requests per second.

A traffic switch does not eliminate that shortfall. Define admission, service classes and degraded behavior before failure. A supposedly healthy fallback can otherwise become overloaded and cause a wider interruption. The selected rates are illustrative; actual capacity depends on task mix, input lengths and held resources.

Destination eligibility still applies. A region with spare capacity can be unsuitable because of the application's data-processing agreement or required local dependencies. Do not equate geographic redundancy with permission to move every request. Keep those policy decisions explicit and independently reviewed.

In the wild: gateways expose recovery policy as configuration

LiteLLM's reliability documentation describes retry and fallback mechanisms in its proxy. These are useful implementation capabilities to examine against an application contract. They do not prove that arbitrary models are interchangeable or that several enabled policies share one logical request budget automatically.

Hypothetical scenario. Northwind enables regional fallback, but all regions depend on one credential service and the same upstream provider account limit. A failure in that shared dependency affects every route. Document dependency overlap and test a representative interruption rather than counting region names as independent availability.

Review the failure path as carefully as the normal route

Exercise rejection, uncertain timeout, partial stream, exhausted budget and incomplete serving groups. Check what the caller sees and which work remains outstanding. Keep the tested fallback capability record with the release, including any allowed differences in response behavior.

A gateway helps when several applications need consistent mediation and provider access policy. It adds less value when it obscures one simple dependency behind many transformations without clear ownership. Its own configuration, identity service and budget store become dependencies that require monitoring and recovery decisions.

Gateway policy is a versioned release artifact

A route change can alter data destination, model behavior and recovery even when application code is unchanged. Review gateway configuration with its capability tests and rollback identity. Record the effective policy used for each request rather than only the latest configuration visible to an operator after an incident.

Protect the control plane independently from ordinary inference callers. The ability to submit a request should not imply the ability to add a provider, change a regional constraint or raise a shared budget. Audit administrative changes without placing provider secrets in the resulting records.

Test the request k boundary

Recovery keeps the original contract: usage remains uncertain.Recovery keeps the original contract: usage remains uncertain. Provider timeout to Pending reservation: usage remains uncertain; Pending reservation to Fallback admission: new attempt needs eligible budget.Provider timeoutPending reservationFallback admissionusage remains uncertainnew attempt needs eligible budget
Recovery keeps the original contract: usage remains uncertain. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

The primary times out and a cheaper provider is available. Is price sufficient to permit fallback?

Reveal the design reasoning

No. Check data permission, task/model capability, remaining deadline and unresolved exposure. Preserve the original intention and report unavailable when no authorized route remains.

Decision: Approve gateway recovery by eligibility and shared exposure, not provider availability alone.

Preserve the original promise through failure

The primary consumed 4,500 milliseconds of a 6,000-millisecond total budget. Can a fallback receive a new two-second deadline?

Not under the original promise. Only 1,500 milliseconds remain in the selected ledger. Reject, degrade or use an explicitly different asynchronous contract rather than silently resetting the application deadline.

Two client attempts, three gateway attempts and two wrapper attempts are enabled. What is the selected maximum?

Twelve upstream attempts: 2 × 3 × 2. Assign a shared owner and budget so nested recovery does not multiply work invisibly. An uncertain effect needs reconciliation, not another untracked attempt.

A secondary region has 70 requests/s spare and must absorb 180 requests/s. Is changing the route sufficient?

No. The selected shortfall is 110 requests/s. Admission and degraded service must respect the secondary's actual capacity and destination eligibility. A healthy route can still be an unsuitable or overloaded destination.

Northwind decision log

  1. Enforce caller and provider eligibility before request normalization and dispatch.
  2. Keep one deadline, attempt budget and explicit outcome record across fallbacks.
  3. Validate spare regional capacity and shared dependencies before calling a route a continuity plan.

Go deeper: mediation and replicated service boundaries

Autoscaling turns those observations into a bounded control loop: estimate eligible queued work, compare it with measured capacity, request additional replicas, wait for warm-up and verify the effect. Scale-in must drain or transfer owned requests safely. Use a declared observation interval and avoid reversing a decision merely because the first post-change sample is noisy. A new replica cannot help an ineligible model class or an external tool bottleneck.

Check the mechanism in this lesson

A replica is added while a run is blocked on an external tool. Must its latency improve?

Compare the explanation

No. The added model capacity does not repair the external bottleneck. Scaling needs eligible queued work, measured capacity and post-change observation, with safe draining and bounded control decisions.

Carry the decision forward

Northwind can route admitted work without hiding capability differences. Page 38 asks whether that work is useful: build case-level acceptance evidence before using a smoother answer or a healthy endpoint as a release signal.