Layered Routing and High Availability Design for LLM Web Services

    This article explores the architectural design of large language model (LLM) web services, focusing on three core areas: layered routing between fast and expert modes, a unified multimodal input entry, and high availability mechanisms across deployment and resource scheduling. It provides actionable engineering solutions and validation methods for each component to ensure stable and efficient service delivery.

    The design of layered routing and high availability for LLM web services revolves around three core aspects: layered routing for fast and expert modes, a unified multimodal entry, and a high availability mechanism spanning deployment and resource scheduling. This article elaborates on these three main threads, providing solutions that can be directly adapted into engineering code and explaining the validation methods for each step.

    1. Layered Routing for Fast and Expert Modes

    The complexity of user queries varies significantly. Daily chats require minimal time-to-first-token (TTFT) latency, whereas code debugging, legal clause interpretation, or medical data analysis require longer reasoning chains and larger models. If all requests are routed to a single large model, costs will rise rapidly, and computing power during off-peak hours will be wasted. Therefore, most platforms split web services into two modes:

    Dimension Fast Mode Expert Mode
    Applicable Scenarios Chatting, simple Q&A, rewriting & polishing Code debugging, domain-specific queries, long-text analysis
    Model Type Smaller parameters or quantized/distilled models Large-parameter models with reasoning chains enabled
    Latency Target Example: TTFT p95 < 1 second Example: TTFT p95 < 5 seconds (excluding queue time)
    Queueing Strategy No queue; direct rate limiting when capacity is exceeded Enters queue when cluster load exceeds threshold; queue timeout configured
    Billing & Rate Limiting Free users rate-limited by requests per minute Billed by request count or tokens; daily quota cap
    Degradation Plan Switch to a smaller backup model when capacity is insufficient Automatically downgrade to Fast Mode and notify user on queue timeout or excessive length

    The latency values in the table above are only examples; actual targets should be based on your own stress testing results.

    The routing layer must determine the request destination based on the user’s selected mode and the current system load. The following code is runnable, with the queue interface injected by the caller. In practice, it can be integrated with a message queue or task scheduling service:

    1. from dataclasses import dataclass
    2. from typing import Optional
    3. QUEUE_LOAD_THRESHOLD = 0.85 # When cluster load (between 0 and 1) exceeds this value, Expert Mode requests enter the queue
    4. QUEUE_TIMEOUT_S = 60 # If not scheduled within 60 seconds, the task is marked as timed out
    5. @dataclass
    6. class RouteResult:
    7. status: str # "routed" or "queued"
    8. model_type: Optional[str] = None # Target model type for routing
    9. task_id: Optional[str] = None # Task ID returned when queued
    10. message: str = ""
    11. def route_chat_request(user_input: str, selected_mode: str,
    12. system_load: float, queue) -> RouteResult:
    13. if selected_mode == "fast":
    14. return RouteResult(status="routed", model_type="lite_distilled")
    15. if selected_mode == "expert":
    16. if system_load <= QUEUE_LOAD_THRESHOLD:
    17. return RouteResult(status="routed", model_type="large_reasoning")
    18. # The queue must provide three methods: enqueue, get_status, and cancel
    19. task_id = queue.enqueue(user_input, timeout_s=QUEUE_TIMEOUT_S)
    20. return RouteResult(status="queued", task_id=task_id,
    21. message="Peak hours detected. Queuing in progress, please wait.")
    22. return RouteResult(status="routed", model_type="default")

    A few points to note here:

    1. system_load should come from real-time metrics of the monitoring system, such as GPU utilization or the ratio of pending requests to capacity, not just CPU usage.
    2. After returning queued, the frontend should poll queue.get_status(task_id) using the task_id. Timed-out or canceled tasks must return a clear error status rather than leaving the page spinning indefinitely.
    3. When the user actively leaves the page, queue.cancel(task_id) should be called to avoid occupying a queue slot.

    2. Engineering Details for a Unified Multimodal Entry

    Early web services often implemented image understanding as a separate “Visual Mode” toggle. Users had to switch modes before uploading an image, which easily caused context loss during the transition. A unified entry approach places text and images in the same input box, with the backend organizing them into a single message. The frontend does not need to determine the modality but must complete pre-upload checks and data encapsulation.

    1. Image Preprocessing Rules

    The frontend should complete the following processing before uploading:

    • Format: Only accept JPEG, PNG, and WebP. Prompt users to convert for other formats directly on the frontend.
    • Size: Reject uploads if the original file exceeds 10MB. This value is an example and should align with the request body limits of the model API used.
    • Dimensions: Scale proportionally if the longest edge exceeds 2048 pixels. Most vision models yield minimal understanding benefits from oversized images, while significantly increasing transmission and computation overhead.
    • Compression: Encode the image as JPEG with a quality parameter of about 0.8. If it still exceeds the limit after compression, prompt the user to crop it.

    2. Choice of Transmission Method

    There are two common ways to transmit images with requests, each with trade-offs:

    Method Pros Cons
    Base64 Embedded Simple implementation, no extra storage dependency Data volume increases by about one-third; limited by request body size
    Object Storage URL Small request body, suitable for large images and repeated references Requires extra storage and signed URLs; must handle link expiration and access permissions

    In practice, traffic can be split by size: small images (e.g., under 1MB) use Base64 embedding, while large images are uploaded to object storage first, and a signed URL is passed in the request. The specific threshold should follow the documentation of the model API used.

    3. Unified Payload Structure

    Below is an example structure. Field names are for illustration only; actual implementation should follow the API specifications used:

    1. {
    2. "mode": "expert",
    3. "client_request_id": "a3f9c2e1-7b5d-4e8a-9c01-2d6f8b4e7a10",
    4. "messages": [
    5. {
    6. "role": "user",
    7. "content": [
    8. {"type": "text", "text": "What is wrong with the circuit diagram in this image?"},
    9. {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "..."}}
    10. ]
    11. }
    12. ]
    13. }

    client_request_id is used for idempotency control. When the frontend retries after a network timeout, the server can identify it as the same request, avoiding duplicate generation and billing.

    4. Server-Side Validation and Error Handling

    Frontend validation is only the first line of defense; the server must validate again. The server should determine the actual format via the file header magic numbers, not just the extension, otherwise forged files can bypass checks.

    Suggestions for handling common error codes:

    • 413 (Payload Too Large): The frontend should resubmit using an object storage URL, or prompt the user to compress the file.
    • 415 (Unsupported Media Type): Prompt the user to convert the format; do not auto-retry.
    • 429 (Too Many Requests / Rate Limited): Retry using exponential backoff with jitter, up to 3 times.
    • 5xx (Server Error): Retry once. If it still fails, prompt “Service temporarily unavailable, please try again later,” while preserving the user’s input content.

    3. High Availability and Canary Releases During Model Iteration

    Version upgrades for large models are usually accompanied by adjustments to computing clusters, inference framework updates, and weight replacements. Prolonged service outages reported publicly have varied causes, potentially related to full-link stress testing, weight hot-swapping, or inference framework upgrades. For architects, a more practical assumption is: any release can cause issues, and the system must be able to stop losses quickly when problems arise.

    1. Observation and Rollback for Canary Releases

    New model versions should first receive a small amount of traffic, such as 10%. This percentage is just a common starting point; the key lies in the accompanying observation window and rollback conditions. It is recommended to:

    • Observation Window: The canary phase should last at least two hours and cover a complete traffic peak. Looking at data for just a few minutes makes it hard to spot issues like queue backlog.
    • Core Metrics: Monitor at least the abnormal rejection rate (proportion of 5xx and 429), TTFT p95, generation speed (tokens output per second), and the rate of negative user feedback.
    • Rollback Thresholds: The values below are examples and should be set based on pre-release baseline data. Trigger a rollback if the abnormal rejection rate is 0.5 percentage points higher than baseline, TTFT p95 is 20% higher than baseline, or generation speed is 20% lower than baseline. Any condition met triggers rollback.
    • Rollback Speed: Use feature flags to switch traffic back to the old version, aiming to complete within 5 minutes. The rollback process must be rehearsed before release, recording the actual time consumed.

    After all metrics meet standards, gradually increase traffic to 100% in stages, repeating the same observation at each stage.

    2. Multi-Cluster DR and Upgrade Draining

    Deploy at least two inference clusters, with a global load balancer distributing traffic based on health check results. When upgrading a cluster, first remove it from the load balancer, wait for existing requests to be processed (i.e., drain), and then perform the upgrade. During the upgrade, the backup cluster’s capacity must be able to handle all traffic from the drained cluster; otherwise, draining will result in user request rejections.

    Container platforms, logging, and monitoring services are common infrastructures for implementing these capabilities. When selecting these, pay attention to whether they support label-based canary releases, metric aggregation by cluster, and alert response latency.

    3. Session Persistence

    User conversation history should be saved in an independent database, indexed by session ID. After the frontend refreshes the page, it can fetch historical messages by session ID to restore the conversation.

    Note that after model hot updates, the internal format of messages may change, such as the structure of tool call records or reasoning content. Historical messages should include a format version number. Upon reading, the server performs compatibility conversion based on the version number; otherwise, old sessions may not continue normally under the new model.

    4. Resource Isolation Between Consumer and Enterprise Tiers

    “Consumer free tier for acquisition, Enterprise pay-as-you-go” is a common business model for many LLM platforms. Both user types share GPU computing power, but they must be prioritized at the scheduling level; otherwise, sudden traffic spikes from free users will squeeze the resources of paid APIs.

    1. Consumer Tier Limitations

    Consumer tier users are typically subject to the following restrictions:

    • Rate Limiting: Limit requests per minute by account or IP.
    • Queueing: Enter normal priority queues during peak hours.
    • Quota: Downgrade to Fast Mode after free quota is exhausted, or prompt to upgrade.

    2. Enterprise Tier Guarantees

    Enterprise API users are authenticated via API Keys and billed by quota. In scheduling, a weighted priority queue can be used. For example, set the weight of high-priority Enterprise requests to 3, Expert Mode Consumer requests to 2, and Fast Mode Consumer requests to 1. Weights are examples and should be adjusted based on business SLA requirements.

    Pure priority scheduling can easily cause low-priority requests to remain unprocessed indefinitely. Therefore, a minimum resource share must be reserved for the Consumer tier, such as guaranteeing at least 10% processing capacity per scheduling cycle, to prevent free users from starving entirely.

    For large clients with strict latency requirements, dedicated line access or exclusive inference instances can be provided to achieve more stable latency and throughput.

    3. Acceptance Criteria

    Whether resource isolation is effective must be verified through stress testing, not just by looking at architecture diagrams. It is recommended to define the following metrics:

    • Enterprise tier availability target, e.g., 99.9% monthly.
    • Enterprise tier TTFT p95 remains within target range even when Consumer tier traffic reaches several times the normal level.
    • Consumer tier queue wait time has a clear upper limit; if exceeded, a clear prompt is returned.

    5. Summary and Checklist

    Layered routing, unified multimodal entry, and resource isolation for LLM web services all need to be grounded in verifiable metrics. Before going live, you can check item by item:

    1. Routing Degradation: Simulate full cluster load. Expert Mode requests should return a clear status after queue timeout, or automatically downgrade to Fast Mode and prompt the user. During validation, all timed-out requests should have corresponding status codes or prompt text.
    2. Canary Rollback: Rehearse a rollback in the staging environment, recording the time from trigger to traffic switching back to the old version. This duration should be less than the set target value, e.g., 5 minutes.
    3. Resource Isolation: Apply burst traffic to the Consumer tier during stress testing. The Enterprise tier’s availability and TTFT p95 should remain within SLA bounds. If not met, check the weight configuration and minimum guaranteed share.

    Validating these three items one by one is more effective for ensuring the stable availability of web services than simply scaling up model parameters.