Containerized Deployment of AI Chat Systems: Architecture and Practices

    This article explains how to containerize and deliver an AI chat system by separating frontend assets, online APIs, and asynchronous workloads into independently scalable units. It covers monorepo structure, dual-token authentication with silent refresh, streaming event semantics and rendering pacing, session and message data modeling, asynchronous image and voice processing, rate limiting and queues, container delivery details, and a pre-launch checklist. Readers will learn the architectural decisions and operational safeguards needed to run a conversational AI service reliably under real traffic.

    1. Why AI Chat Systems Need Containerized Delivery

    AI chat applications differ from traditional web apps in three ways: a high proportion of long-lived connections, many heterogeneous backend capabilities, and uneven resource consumption. A normal page request may finish in tens of milliseconds, while a streaming conversation can last several seconds or longer. Speech transcription is a classic CPU-intensive task, and sharing a process with online requests easily causes response jitter.

    This is where containerized delivery adds value. It splits three workload types—frontend static assets, online API services, and asynchronous task processing—into independently scalable units. Each unit scales according to its actual load instead of forcing the entire system to scale up together.

    For the architecture, a monorepo that maintains frontend and backend in the same repository is recommended. The frontend directory hosts the H5 chat interface, and the backend directory hosts the API service. Both share the same interface contract and documentation definitions. The benefit is that interface changes can be completed in a single commit, avoiding version drift where the frontend is released but the backend is not yet deployed. The cost is higher requirements for commit conventions and build pipelines, with a clear boundary between frontend artifacts and backend images.

    A typical directory layout looks like this:

    1. .
    2. ├── ui/ # H5 frontend
    3. │ ├── src/components/ # Chat interface components
    4. │ ├── src/hook/ # Auth, session, streaming, recording, scrolling
    5. │ └── src/utils/ # Request wrapper, endpoint config, streaming requests
    6. ├── backend/
    7. │ ├── clients/ # Model service clients
    8. │ ├── controllers/ # Input validation and response assembly
    9. │ ├── middleware/ # Auth, rate limiting, upload, transcription wrapper
    10. │ ├── queues/ # Queue definitions
    11. │ ├── repositories/ # Data access layer
    12. │ ├── routes/ # Route mounting
    13. │ ├── services/ # Business orchestration
    14. │ └── workers/ # Async task consumers
    15. ├── Dockerfile.frontend
    16. └── Dockerfile.backend

    2. Authentication Design: Dual Tokens and Silent Refresh

    The hard part of authentication on mobile is not “how to log in” but “how to keep the user logged in without them noticing.” H5 and mini-program session lifecycles differ significantly: mini-programs cold-start frequently, while H5 pages may be reclaimed by the system and then restored. A single-token scheme either sacrifices security (by extending validity) or sacrifices experience (by forcing frequent re-login).

    The dual-token scheme decouples the two concerns. The access token is short-lived and used only for business API authentication. The refresh token is long-lived and used only to obtain a new access token, with one-time rotation and invalidation tracking. The frontend injects the access token uniformly in the request interceptor. When authentication expires, it does not immediately redirect to the login page; it first attempts a refresh:

    1. // Normal request: inject token, refresh and retry once on failure
    2. async function request(url, options = {}, retry = true) {
    3. const res = await fetch(url, {
    4. ...options,
    5. headers: { ...options.headers, Authorization: `Bearer ${accessToken}` }
    6. });
    7. if (res.status === 401 && retry) {
    8. const ok = await refreshTokens();
    9. if (ok) return request(url, options, false);
    10. redirectToLogin();
    11. }
    12. return res;
    13. }

    Streaming endpoints need separate handling because the response body is continuously readable and cannot reuse the wrapper above directly. A practical approach is to perform a lightweight token check before establishing the stream; if the token is invalid, refresh first and then re-establish the stream. Also capture interruptions during stream reading to avoid showing the user “half a sentence.”

    3. Streaming Conversations: Event Semantics and Frontend Rendering Pace

    Streaming output essentially splits a complete answer into multiple incremental chunks that are pushed continuously. The server keeps the connection alive with a text event stream, and the frontend renders while receiving. To let the client distinguish different semantics, event types must be defined explicitly. There are three common types: incremental content events carry body chunks; reasoning process events carry reasoning summaries for collapsed display; and end events carry the session identifier and statistics, marking the end of the turn.

    The most error-prone part in practice is rendering pace. When chunks arrive much faster than the browser can paint, writing them one by one causes a large number of invalid reflows. A reasonable approach is to introduce a buffer queue and refresh the view in batches on a fixed time window. At the same time, the decision of “whether to auto-scroll to the bottom” should be delegated to the scrolling logic module: only follow when the user is near the bottom; otherwise preserve the reading position and show a new-message indicator.

    Markdown rendering must work with streaming increments. Unclosed code blocks, tables, and lists appear with abnormal styles in intermediate chunk states, so the renderer should tolerate incomplete syntax and perform a full correction once the end event arrives.

    4. Organizing Session and Message Data

    The data layer should use a lightweight embedded relational database with clear layered access: controllers handle only input and status codes, business orchestration happens in the service layer, and all SQL is centralized in the data access layer. The schema revolves around three core entities—users, sessions, and messages. The message table needs to record the role (user/assistant), content, associated session, creation time, and optional attachment references and feedback flags.

    Session list ordering should not rely on real-time computation of the “last message time.” Instead, maintain a redundant active-time field and update it when writing a message, avoiding a list query that degrades into an aggregate scan. Session deletion uses soft delete plus periodic cleanup, preserving the possibility of accidental-deletion recovery while preventing large tables from growing indefinitely.

    Message feedback (thumbs up/down) and regeneration are key interactions for improving usability. The key to implementing regeneration is: locate all messages after the target assistant message and mark them invalid, then re-initiate a streaming request with the same context, replacing the original content on success rather than simply appending a new message. Otherwise, history quickly becomes unreadable.

    5. Images and Voice: Asynchronization Is the Core Principle

    Image uploads should follow the path of “upload directly to object storage first, then submit the business record.” The business database stores only reference identifiers and metadata, avoiding binary content entering the relational database. The upload endpoint must restrict type and size and rewrite file names to prevent path traversal and overwrite risks.

    The voice input pipeline is longer: the frontend records in the browser, converts the captured data to a standard waveform format (fixed sample rate, mono, bit depth) through an audio processing endpoint, and then submits it to the backend. The backend does not wait for the transcription result in the request thread; it enqueues the task to an asynchronous queue, and an independent consumer calls local speech recognition to complete transcription. The result is written back and then retrieved by the frontend via polling or push notification. The benefit is that transcription latency fluctuations do not affect the chat endpoint’s response performance, and consumers can scale independently by CPU core count.

    1. Record → Standardize WAV → Upload → Enqueue → Consumer transcribes → Write back result → Frontend retrieves

    6. Rate Limiting and Queues: Isolating Instability at the Boundary

    Rate limiting should apply to “expensive and easily abused” entry points: login, chat, and voice submission. Fixed-window counting is simple to implement and low-cost, making it suitable as the first line of defense. For smoother behavior, a token bucket can be layered on top. The key point is that the rate-limiting dimension must include both account and source identifier to avoid being bypassed on a single dimension. Also return a clear retry hint so the client backs off instead of retrying tightly.

    Queues handle two types of tasks: voice transcription and temporary file cleanup. Temporary file cleanup is an easily overlooked hidden cost; if the upload directory has no lifecycle management, the disk can fill up within weeks. It is recommended to set expiration times for temporary objects and reclaim them in batches with scheduled tasks, while retaining necessary audit logs.

    7. Containerization and Delivery Essentials

    The frontend artifact is static assets. Packaging is completed in the build stage, and at runtime it is served by a static asset service or a content delivery network, keeping the image minimal. The backend image needs runtime dependencies and the model files required for local speech recognition. The models are large, so it is recommended to place them in a separate data volume or pull them during initialization, avoiding bloated image layers that slow down releases.

    All configuration is injected through environment variables, including the data directory, cache address, queue connection, model service endpoint, and keys. Keys must not be written into the image or repository; they should be provided by a key management capability or the deployment platform’s environment configuration. Health checks should distinguish liveness from readiness: return liveness success if the process is alive, and return readiness success only when dependencies (cache, queue) are available, avoiding repeated container restarts caused by dependency jitter.

    Logging and monitoring can use common categories: structured logs output to standard streams and are collected uniformly by the logging service. Key metrics include streaming connection count, first-chunk latency, queue backlog length, transcription failure rate, and authentication failure count. First-chunk latency is the most direct measure of chat experience and is more informative than average response time.

    8. Pre-Launch Checklist

    • Does dual-token refresh and rotation trigger only once under concurrent requests?
    • When a streaming connection is interrupted or the client disconnects, does the server correctly release resources?
    • Does rate limiting cover the three entry points—login, chat, and voice—with backoff hints?
    • Do queue consumers have failure retry and dead-letter handling, and are transcription failures visible to users?
    • Do uploaded files have type, size, and lifecycle limits?
    • Is the API documentation released with the code and kept consistent with the implementation?
    • Do containers run as non-privileged, and does unavailable dependency affect only the corresponding feature?

    Containerization does not end with putting services into images. It makes each workload type independently observable, independently scalable, and independently rollback-able. Once the four pipelines—authentication, streaming, asynchronous transcription, and rate limiting—are decoupled from each other, the AI chat system has the foundation to evolve continuously under real traffic.