Web-Based AI Service Architecture: Best Practices

    This article explores the architecture and best practices for building web-based AI services. It covers the division of responsibilities between frontend and backend, unified entry points for multi-modal inputs, routing rule design, frontend processing for images, execution chains for complex queries, protocol selection (SSE vs. WebSocket), resource scheduling, and a pre-launch checklist.

    The main benefit of web-based services is accessibility. Users can open a browser and start using the service without installing a client or configuring a local runtime environment. For service providers, the browser unifies the client entry point, reducing compatibility and adaptation work across different operating systems.

    However, web-based services are not without trade-offs. The frontend must handle streaming rendering, long connections, and large file uploads, causing frontend complexity to rise as features increase. Therefore, during the initial design phase, it is crucial to clarify which logic belongs on the frontend and which belongs on the backend.

    2. Division of Responsibilities Between Frontend and Backend

    The frontend is responsible for session management, message rendering, streaming data reception, and input validation. Message rendering includes Markdown parsing, code highlighting, and image display. The frontend should remain lightweight; model invocation parameters, API keys, or routing rules should never be written into the page code.

    The backend handles model inference, context assembly, security auditing, and resource scheduling. Inference loads fluctuate significantly, so most teams deploy inference nodes on container platforms and use auto-scaling based on queue length or GPU utilization. The container platform can be from a mainstream cloud provider or a self-hosted Kubernetes cluster, depending on the team’s operational capabilities and cost structure. Auto-scaling only mitigates burst traffic; rate limiting and queue caps are still necessary. Otherwise, requests exceeding capacity will slow down response times for all users.

    3. From Fragmented to Unified Entry Points

    Early services often split daily chat, deep reasoning, and image understanding into independent pages, requiring users to determine which page to enter. This approach has two problems. First, users must understand the product’s model classification before they can ask a question. Second, if a task involves both images and reasoning, users must copy content between pages, risking the loss of context.

    A unified entry point consolidates these capabilities into a single input box, where the backend decides which model to call. The frontend can retain a model selection option for advanced users to manually specify, but the default behavior should be server-side dispatch.

    4. Routing Rule Design

    The unified entry point relies on a routing layer. Upon receiving a request, the routing layer first checks the content array in the message body to determine if it contains multimodal types like image_url. It then makes a decision based on session history, user permissions, and current model load. A practical routing table usually includes the following columns: input type, target model, maximum context length, timeout, and fallback strategy on failure.

    Here is a simplified request example:

    1. {
    2. "session_id": "web-uuid-1234",
    3. "messages": [
    4. {
    5. "role": "user",
    6. "content": [
    7. {"type": "text", "text": "Analyze the potential bottlenecks in this architecture diagram"},
    8. {"type": "image_url", "image_url": {"url": "https://files.example.com/upload/abc123.png"}}
    9. ]
    10. }
    11. ],
    12. "stream": true
    13. }

    In this example, the image is passed as an internal file address, and no Base64 string is directly embedded in the request body. The routing layer should perform the following validations:

    1. Check whether the type in content is within the whitelist (e.g., text, image_url).
    2. Check the image format, dimensions, and file size. Requests exceeding limits should return a clear error immediately.
    3. If the target multimodal model times out, retry once. If it still fails, degrade to a text model and state in the reply that the image could not be parsed.
    4. If the context exceeds the target model’s length limit, truncate older history messages before submitting the request.

    Degradation behavior must be visible to the user. If the model is changed silently, users might mistakenly assume the image has been analyzed, compromising the credibility of the conclusion.

    5. Frontend Processing for Multimodal Inputs

    A unified entry point requires the frontend to support drag-and-drop uploads and pasted screenshots. Before submission, the frontend should complete the following:

    • Restrict file types and sizes, accepting only formats declared as supported by the server.
    • Perform client-side compression for large images by reducing resolution or quality. Compression reduces upload size and transmission time.
    • Prioritize uploading via multipart form or direct upload to object storage, then pass the file address to the chat API.

    Base64 encoding increases data size by about one-third. Its advantage is that images can be sent in a single JSON payload, but the size increase offsets the benefits of compression. Use it only if the API explicitly requires Base64; otherwise, separate uploads are more appropriate.

    Images are user data, so privacy must be considered during processing:

    • Explain the purpose to the user before uploading and obtain explicit authorization.
    • Prompt users to be aware of sensitive information in screenshots (such as account numbers, phone numbers, or internal addresses) and provide blur or crop tools.
    • The server should re-validate the file type to prevent non-image files disguised as images.
    • Clearly define the image retention period, auto-delete upon expiration, and allow users to manually delete images in the session.
    • Do not log image content or raw Base64 strings.

    6. Execution Chain for Complex Problems

    Complex problems usually require step-by-step processing. Taking “Analyze the core algorithm of an open-source project and provide refactoring suggestions” as an example, the backend can execute in the following order:

    1. Decompose the problem and determine what types of information are needed.
    2. If external materials are needed, call search or document retrieval tools and record the sources returned by the tools.
    3. Reason using the retrieved results and the model’s existing knowledge.
    4. Output the conclusion, annotating which content comes from external materials and which comes from model inference.

    Each step should send a status event to the frontend, such as “Searching for materials” or “Analyzing code”. Tool calls may fail or return empty results. In such cases, the chain should record the failure reason and inform the model that the results are incomplete to prevent the model from fabricating content. During acceptance testing, prepare a set of test questions with standard answers to check the accuracy of conclusions, the traceability of cited sources, and whether failure scenarios provide clear prompts.

    7. Protocol Selection: SSE or WebSocket

    Streaming output typically uses SSE or WebSocket, and the choice depends on the communication direction.

    SSE is an HTTP-based one-way push where the server continuously sends events to the browser. It is simple to implement and can reuse existing HTTP gateways and authentication mechanisms, making it suitable for most “user asks, model replies word by word” scenarios. After a disconnection, the browser attempts to auto-reconnect, but the server must support resuming output based on event IDs; otherwise, users may see duplicated or missing content.

    WebSocket is a two-way long connection, suitable for scenarios where users frequently send interrupts, modify commands, or engage in real-time voice interaction during generation. The trade-off is more complex connection management, requiring manual handling of heartbeats, reconnections, and authentication refreshes.

    If the product only requires text streaming output, prioritize SSE. Only introduce WebSocket when stable two-way interaction is needed. Regardless of the protocol, a backpressure strategy must be set. When the client consumes data slower than the generation speed, the server should pause or limit output to avoid memory buildup.

    8. Resource Scheduling and Inference Optimization

    Long text generation consumes a large amount of VRAM. KV Cache stores the key-value vectors of historical tokens, avoiding repeated calculations. VRAM management methods like PagedAttention split the KV Cache into fixed-size blocks, reducing VRAM fragmentation and thereby increasing concurrency. Such optimizations are most effective for long-context, high-concurrency scenarios. In short-conversation, low-concurrency scenarios, the benefits are limited; teams should first run stress tests to determine if they are needed.

    Stress test results must specify the test conditions, including model size, hardware model, concurrency, input/output length, and measurement method. Latency or throughput numbers lacking this information cannot be directly used for capacity planning.

    9. Pre-Launch Checklist

    Before official rollout, you can verify the following items one by one:

    • Authentication: Verify login status for all APIs; use time-limited signed URLs for file addresses.
    • Rate Limiting: Set request frequency and concurrency limits per user and IP.
    • Timeout: Set timeouts for models, tools, and file uploads, and define failure prompts.
    • Logging: Record request IDs, durations, and error codes; desensitize user inputs and image content.
    • Canary Release: Open to a small percentage of users first, observe error rates and latency before expanding.
    • Cost: Monitor Token consumption and GPU time per session, and set budget alerts.

    10. FAQ

    How to select a web-based multimodal service?
    If image understanding is a high-frequency requirement, prioritize models that natively support multimodal input and keep a text model as a fallback path in the routing layer. If image requirements are low, launch the text entry first and gradually open up image capabilities through a separate upload button.

    What are common errors in multimodal web services?
    Common errors include: putting Base64 directly into all requests, not setting image size limits, not informing users during degradation, retaining raw images in logs, and exposing model keys in the frontend. These issues mostly appear in the early stages of launch. The earlier they are eliminated in the design phase, the lower the modification cost.

    How to choose between SSE and WebSocket?
    Choose SSE for text streaming output and WebSocket when frequent two-way interaction is needed. Before selecting, list the interaction directions, reconnection requirements, and existing gateway capabilities, then make the decision.