Full-Stack Practice Guide for AI Chatbot Assistants Based on Containerized Deployment

    This article provides a full-stack practice guide for building a complete AI chatbot system. It covers a monorepo architecture, a dual-token seamless refresh mechanism, SSE streaming responses, asynchronous voice recognition processing, and containerized deployment, offering a scalable and reliable engineering solution for small to medium teams looking to embed AI conversations into their applications.

    1. Why a Complete AI Chatbot System is Necessary

    With the widespread adoption of large language model (LLM) inference capabilities, an increasing number of products aim to embed “AI conversation” features, such as intelligent customer service, knowledge-based Q&A, and voice assistants. However, many teams fall into the same pitfalls during implementation: interface timeouts causing conversation interruptions, expired tokens forcing frequent re-logins, speech-to-text blocking the main thread, and concurrent requests overwhelming backend services. The root cause of these issues is not insufficient model capability, but rather an engineering architecture that has failed to keep pace.

    This article uses a typical “H5/mini-program universal AI chatbot system” as an example to thoroughly deconstruct its technical architecture and engineering practices. The system is maintained within a frontend and backend monorepo. The frontend is built on a modern component-based framework to construct a mobile chat interface, while the backend uses a lightweight Node.js service framework paired with an embedded database. It also introduces caching and message queue middleware to implement rate limiting and asynchronous task processing, ultimately achieving integrated delivery through container images. The overall solution holds strong reference value for small to medium teams.

    2. Overall Architecture Design: Layered Practices in a Frontend and Backend Monorepo

    The project organizes its code using a monorepo approach, primarily divided into two major directories:

    • ui/: The frontend project, responsible for chat interface rendering, streaming message display, voice recording, and image uploading interactions.
    • backend/: The backend project, providing REST APIs and streaming interfaces, handling authentication, session management, data persistence, and asynchronous task scheduling.

    The backend internally adopts a classic layered architecture with clear boundaries of responsibility:

    • Routes Layer: Solely responsible for route mounting, devoid of business logic.
    • Controllers Layer: Handles HTTP input validation and response encapsulation.
    • Services Layer: Orchestrates business logic, such as the complete chain of “create session - save user message - invoke model - stream write-back - persist AI reply”.
    • Repositories Layer: Encapsulates all read/write operations for the embedded database; the business layer does not directly concatenate SQL.
    • Middleware Layer: Centrally handles cross-cutting concerns like authentication, rate limiting, file uploading, and speech recognition encapsulation.
    • Queues and Workers: Defines queues and background consumers to move time-consuming operations out of the main request chain.

    The benefit of this layering is that each layer can be tested and evolved independently. For example, if a model provider needs to be replaced in the future, only the model invocation client and a small amount of orchestration code in the service layer need modification; routes and controllers remain completely unaffected.

    The frontend project is also clearly divided: the component directory is responsible for pure presentation, the custom Hooks directory consolidates reusable logic like authentication, session management, streaming response parsing, recording control, and scroll positioning, and the utility directory encapsulates a unified request layer. The request layer is split into two categories—a standard request module responsible for injecting Tokens and automatically refreshing and retrying on a 401 error, and a streaming request module specifically handling SSE connections and their reconstruction after authentication failure. The two are not coupled.

    3. Core Capabilities Breakdown

    3.1 Dual-Token Seamless Refresh Mechanism

    Mobile H5 pages are frequently embedded in various host environments where users might stay for long periods. A single, short-lived token will expire frequently, resulting in a poor experience. The system adopts an accessToken + refreshToken dual-token strategy:

    1. Silent login is automatically completed upon page load, and the server issues both a short-lived and a long-lived token.
    2. Each request carries the accessToken; if the server validation passes, it responds normally.
    3. When the accessToken expires and returns a 401, the frontend interceptor automatically uses the refreshToken to exchange for a new token, and replays the original request with the new token. The entire process is imperceptible to the user.
    4. Since streaming requests maintain persistent connections, their 401 handling logic is implemented independently—it catches the authentication failure, refreshes the token, and then rebuilds the SSE connection and resumes the context.

    Two details require attention during implementation: first, the refresh interface must implement concurrency control to prevent multiple requests from triggering multiple refreshes simultaneously (a singleton Promise can be used to cache the refresh process); second, the refreshToken itself must have an expiration and revocation mechanism to prevent long-term abuse if leaked.

    3.2 SSE Streaming Conversation Design

    First-token latency is the aspect of AI conversations that most impacts user experience. The system uses Server-Sent Events (SSE) to push model output to the frontend as an event stream, defining three types of events: delta (incremental content), thinking (reasoning process), and done (end marker):

    • delta event: Carries the generated text fragment for this round; the frontend appends and renders it character by character, formatted in real-time by a Markdown parser.
    • thinking event: Pushes the model’s reasoning process, which can be displayed in the UI as a collapsible panel to enhance transparency.
    • done event: Marks the end of the current response, prompting the frontend to stop the loading animation and refresh the session list after saving to the database.

    Compared to WebSocket, SSE is based on standard HTTP, is simple to implement, inherently supports reconnection semantics, and is friendly to reverse proxies, making it a pragmatic choice for unidirectional push scenarios. Engineering-wise, it is also necessary to note: the server must set response headers correctly and disable buffering; when a connection is interrupted, the server must promptly terminate the upstream model invocation to avoid invalid billing and resource waste.

    3.3 Session and Message Management

    The system provides a complete closed loop including session lists, historical message pagination, session deletion, message likes, and assistant message regeneration. The “regenerate” feature is an easily overlooked detail: it is not merely resending the user’s message, but rather invoking the model again based on the same context, replacing the old assistant message with the new result while preserving the ownership of feedback data such as likes. Persistence uses an embedded database with zero external dependencies; combined with a container volume mount, it ensures data is not lost, making it highly suitable for small to medium-scale deployments.

    3.4 Asynchronous Processing of Voice Recording

    Speech-to-text is a typical CPU-intensive task. If executed synchronously within the request thread, a single long audio recognition process might block the system for several seconds or more. The system’s approach is as follows:

    1. The frontend captures audio using the browser’s media recording capabilities and utilizes Web Audio APIs to standardize it into a WAV format with a unified sampling rate, masking encoding differences across devices.
    2. The upload interface only handles file reception and enqueues the task, immediately returning a task ID.
    3. A background Worker consumes the queue task, invokes a locally deployed open-source speech recognition engine to complete transcription, and writes the result back to the database.
    4. The frontend polls or receives a message push to obtain the recognition result.

    Meanwhile, temporary audio files are uniformly recycled by a scheduled cleanup task within the queue to prevent the disk from slowly filling up. This “receive and return, process asynchronously, check results” pattern is equally applicable to any time-consuming scenarios such as document parsing and image processing.

    3.5 Rate Limiting and Interface Protection

    Login, AI conversation, and speech recognition interfaces are the hardest hit areas for resource consumption and malicious attacks. The system implements fixed-window rate limiting based on an in-memory key-value store: using “user identifier + interface path” as the key, it counts the number of requests within the window period. If the limit is exceeded, it returns a clear status code and a retry prompt. The fixed-window algorithm is simple to implement; although it has the issue of traffic spikes at window boundaries, it is sufficient for small to medium traffic scenarios. If higher smoothness is required, it can be smoothly upgraded to a sliding window or token bucket algorithm without changing the storage layer.

    4. API Documentation and Collaboration Efficiency

    The backend integrates automated API documentation capabilities. Interface definitions are maintained as annotations alongside the code. After the service starts, accessing a specific documentation path allows viewing interactive docs and online debugging, while also providing structured documentation data for consumption by other tools. Maintaining documentation and code from the same source avoids the classic collaboration accident of “code changed but docs didn’t,” and allows the frontend to develop based on the documentation first, significantly shortening the joint debugging cycle.

    5. Containerized Deployment: The Key to One-Click Delivery

    The system provides image build files for both the frontend and backend, along with orchestration configurations:

    • Frontend Image: Uses multi-stage builds. The first stage installs dependencies and packages static assets, while the second stage uses a lightweight web server to host the artifacts, significantly reducing the final image size.
    • Backend Image: Based on a slim runtime base image, it installs production dependencies, copies source code, and includes the native binaries and model files required for speech recognition.
    • Orchestration Layer: Declares application services, caching services, and data volumes. Secrets and model service addresses are injected via environment variables. A single command can spin up the entire environment.

    The value of containerization goes beyond just “being able to run”; it lies in environmental consistency—development, testing, and production use the same image, completely eliminating the “it works on my machine” problem. Combined with general container platforms, logging services, and monitoring and alerting capabilities, it can further achieve rolling upgrades, health checks, and fault self-healing.

    6. Summary and Outlook

    Looking back at this AI chatbot system, the core philosophy of its technology selection is “sufficient and reliable”: using an embedded database to lower the operational threshold, SSE to balance experience and complexity, a message queue to isolate time-consuming tasks, fixed-window rate limiting to secure resource baselines, and container images to ensure delivery consistency. These practices do not rely on any specific vendor’s proprietary services; any team can build them independently based on the open-source ecosystem.

    On this basis, it can continue to evolve: introducing vector retrieval to implement knowledge base Q&A, migrating session data to a distributed database to support greater concurrency, replacing fixed windows with sliding windows for smoother rate limiting, and using object storage to host static resources like images and audio. The competition in AI applications is ultimately a competition of engineering capabilities. Only by polishing the infrastructure solidly can model capabilities truly translate into user experience.