Building a Custom LLM Chat Client: Multi-Device Synchronization Practices

    This article explores the process of building a custom LLM chat client, covering architecture choices, server-side proxy implementation, streaming output, authentication, multi-device data synchronization, data migration, and observability. It provides practical code examples and design patterns to help developers securely wrap model APIs into a stable, user-friendly interactive experience while maintaining full control over session data.

    1. Background and Problem Definition

    Large Language Model (LLM) services are typically provided as APIs, requiring callers to hold access credentials and pay based on usage or subscription plans. For general users, the raw format of these APIs is not user-friendly. What most people actually need is a ready-to-use chat interface where conversation history can be saved, migrated, and synchronized across different devices.

    Around this requirement, there are three common demands:

    1. Usage Continuity: Users want to retain their familiar interaction methods and historical sessions even if the service provider adjusts rate limits or strategies.
    2. Data Control: Conversations often contain personal or business information. Users want to know exactly where their data is stored and who can access it.
    3. Customization: Teams may need to integrate capabilities like permission management, content auditing, prompt templates, or knowledge base retrieval.

    Therefore, the core problem of building a custom chat client can be summarized as: how to wrap the model API into a stable interactive experience while ensuring key security, and allowing session data to flow according to explicit rules.

    2. Architecture Choice

    The first decision in a self-hosted solution is whether the browser should call the model API directly. The differences between the two approaches are as follows.

    Dimension Frontend Direct Connection Server Proxy
    Key Exposure Risk High; keys are distributed with frontend code Low; keys are stored only on the server
    Deployment Complexity Low; can be just static files Medium; requires running a backend process
    Access Control Difficult to implement Can be handled uniformly at the proxy layer
    Usage Statistics & Rate Limiting Depends on the model service provider Can be implemented independently at the proxy layer

    Conclusion: If keys need protection or multiple users share the service, a server proxy should be adopted. If it is only for local interaction logic verification by an individual, the risk of frontend direct connection is manageable, but you should still avoid writing keys into distributable files.

    A typical architecture consists of four parts:

    • Frontend Interface: Handles input, message list rendering, streaming display, and local caching.
    • Proxy Service: Handles authentication, parameter validation, request forwarding, and usage logging.
    • Session Storage: Saves conversation and version information, supporting multi-device reads.
    • Model Service: Provides inference capabilities externally, exposing standardized APIs to the proxy service.

    3. Three Deployment Forms

    3.1 Locally Run Static Page

    Place the frontend build artifacts in a local directory and open them in a browser. This form is suitable for personal learning and offline debugging. The limitation is that local pages cannot be accessed by other devices, and history is only stored in the current browser’s storage by default.

    3.2 Static Site Hosting

    Deploy the build artifacts to a static hosting service, allowing any device to access them via a domain name. In this case, the frontend should not contain any long-term credentials; all requests requiring keys should pass through a proxy. Under this form, the frontend’s main job is display, and the security boundary is determined by the proxy layer.

    3.3 Full Frontend and Backend Service

    Deploy both frontend and backend simultaneously, with the backend handling model calls, user identity, and session storage uniformly. This is the recommended solution for team scenarios, offering the most room for expansion, but it requires taking on operations, monitoring, and backup workloads.

    4. Key Management and Server Proxy

    Key leakage is the most common security issue in self-built chat applications. The following principles should be followed:

    1. Keys should only be stored in server-side environment variables or dedicated key management services, never in source code or version control.
    2. Assign independent credentials to different environments and different users for easy individual revocation.
    3. The proxy layer should authenticate every request to prevent anonymous API calls.
    4. Limit the size of a single request and the maximum length of model output to control costs.

    Below is a minimal proxy example implemented using the standard library to illustrate the forwarding process. Production environments still need to add authentication, timeout retries, and structured logging.

    1. import os
    2. import urllib.request
    3. from http.server import BaseHTTPRequestHandler, HTTPServer
    4. UPSTREAM_URL = os.environ["UPSTREAM_URL"]
    5. API_KEY = os.environ["UPSTREAM_API_KEY"]
    6. MAX_BODY_BYTES = 64 * 1024
    7. class ChatProxy(BaseHTTPRequestHandler):
    8. def do_POST(self):
    9. if self.path != "/api/chat":
    10. self.send_error(404)
    11. return
    12. length = int(self.headers.get("Content-Length", 0))
    13. if length <= 0 or length > MAX_BODY_BYTES:
    14. self.send_error(413)
    15. return
    16. body = self.rfile.read(length)
    17. req = urllib.request.Request(
    18. UPSTREAM_URL,
    19. data=body,
    20. headers={
    21. "Content-Type": "application/json",
    22. "Authorization": f"Bearer {API_KEY}",
    23. },
    24. method="POST",
    25. )
    26. with urllib.request.urlopen(req, timeout=60) as resp:
    27. payload = resp.read()
    28. self.send_response(200)
    29. self.send_header("Content-Type", "application/json")
    30. self.end_headers()
    31. self.wfile.write(payload)
    32. if __name__ == "__main__":
    33. HTTPServer(("127.0.0.1", 8080), ChatProxy).serve_forever()

    There are three points worth noting in this example. First, the key is read via environment variables, and the code contains no plaintext. Second, the request body has a size limit to avoid resource exhaustion from oversized inputs. Third, the service only listens to the local address; external access requires a reverse proxy with additional authentication.

    5. Frontend Implementation of Streaming Output

    When the model generates content word by word, waiting for the complete result before displaying it causes noticeable latency. A common practice is to have the server return data in chunks or event streams, while the frontend renders as it receives.

    The following example shows how to read chunked data in the browser. The specific data format depends on the documentation of the service used; here, we assume the common convention of “each line starts with data:“.

    1. async function streamChat(messages, onToken) {
    2. const res = await fetch("/api/chat", {
    3. method: "POST",
    4. headers: { "Content-Type": "application/json" },
    5. body: JSON.stringify({ messages, stream: true }),
    6. });
    7. if (!res.ok) throw new Error(`Request failed: ${res.status}`);
    8. const reader = res.body.getReader();
    9. const decoder = new TextDecoder();
    10. let buffer = "";
    11. while (true) {
    12. const { value, done } = await reader.read();
    13. if (done) break;
    14. buffer += decoder.decode(value, { stream: true });
    15. const lines = buffer.split("\n");
    16. buffer = lines.pop(); // Keep the incomplete last line
    17. for (const line of lines) {
    18. if (!line.startsWith("data: ")) continue;
    19. const data = line.slice(6);
    20. if (data === "[DONE]") return;
    21. onToken(data);
    22. }
    23. }
    24. }

    Two details need to be handled during implementation. First, network packet segmentation may split a single line of data into two segments, so you must retain the unfinished fragment for the next round of processing. Second, rendering should be batched and updated per frame to prevent every character from triggering a page reflow, which would cause UI lag.

    6. Login and Authentication Design

    For multi-user or multi-device access, it is necessary to clarify “who is using it.” Common solutions include:

    • Self-built Account System: Store credentials using password hashing and issue session tokens after login. Passwords should be processed with a salted slow hashing algorithm and never stored in plaintext.
    • Third-Party Identity Protocols: Adopt standard OAuth 2.0 or OpenID Connect flows, where the identity provider handles authentication, and the application only receives identity assertions.
    • Token Mechanism: Use short-lived access tokens paired with refresh tokens to reduce the impact scope if a token is leaked.

    Regardless of the method, the following constraints should be met: token validity periods should be controlled, the server should be able to invalidate tokens upon logout, and sensitive operations should require re-authentication.

    7. Session Data Model and Multi-Device Synchronization

    Multi-device synchronization is a core capability of chat applications. The design requires defining the data model first, then determining the synchronization strategy.

    7.1 Data Model

    It is recommended to split a session into two layers: “session metadata” and “message list,” recording version numbers and update times separately to facilitate incremental synchronization.

    1. {
    2. "id": "conv_8f3a21",
    3. "title": "API Design Review Notes",
    4. "createdAt": 1763999046000,
    5. "updatedAt": 1764002646000,
    6. "version": 12,
    7. "messages": [
    8. { "id": "msg_001", "role": "user", "content": "Please list the review points." },
    9. { "id": "msg_002", "role": "assistant", "content": "Here are the review points..." }
    10. ]
    11. }

    Messages use independent IDs for deduplication and location tracking. The version number increments with each modification, used to determine if local data is outdated.

    7.2 Synchronization Strategy

    Synchronization is usually divided into three steps:

    1. Pull Incremental: The client saves the cursor from the last sync and requests the server to return sessions changed since that point.
    2. Local Merge: Compare version numbers. If there are no uncommitted local changes, overwrite directly; if both ends have changes, enter conflict resolution.
    3. Push Changes: Submit locally added or modified data with the base version number. The server validates the version consistency before writing; otherwise, it returns a conflict.

    There are two common strategies for conflict resolution. “Last-Write-Wins” is simple to implement but may lose earlier modifications. “Keep-Duplicates” generates a copy of the conflicting session for the user to choose to keep or merge, which is safer for data but has slightly higher interaction costs. For conversation records, which are primarily append-based, message-level merging can be prioritized—taking the union by message ID and only prompting a conflict if the same message is modified on both ends.

    7.3 Local Cache

    The browser can use a local database to save sessions, allowing users to browse historical content even offline. Caching requires attention to capacity limits and should provide a clear entry point for clearing sensitive data. If the device is shared, the local cache should be cleared upon logout.

    8. Historical Data Migration

    When migrating existing user conversation records to a new system, follow the four steps: “Export, Validate, Import, Verify.”

    1. Export Phase: Preserve the original structure and timestamps to avoid information loss from secondary conversion.
    2. Validation Phase: Check required fields, role enumeration values, and encoding formats. Remove empty messages and log abnormal entries.
    3. Import Phase: Write in batches by session, recording a checkpoint after each successful batch so it can resume from the breakpoint upon failure.
    4. Verification Phase: Compare the number of sessions and messages before and after import, and sample-check key content.

    A full backup of the original data should be made before migration. For data containing personal information, masking must be applied in the migration logs.

    9. Observability and Cost Control

    The usage of chat applications is strongly correlated with model calls, requiring basic monitoring at the proxy layer:

    • Request Metrics: Record request volume, response latency, and error code distribution to detect failures.
    • Usage Metrics: Count input and output scales by user or project to provide a basis for quotas and billing.
    • Rate Limiting: Use token bucket or sliding window algorithms to limit the request frequency of individual users and prevent abnormal traffic from consuming quotas.
    • Log Masking: Do not record complete conversation content or access credentials in logs; only retain necessary request identifiers.

    Alert thresholds should be set based on business baselines, such as triggering an alert when a single user’s daily usage exceeds several times the historical average.

    10. Implementation Suggestions and Checklist

    Before deployment, confirm each item using the checklist below:

    • Model access credentials exist only in server-side environment variables or a key management service.
    • The proxy interface has authentication and rejects anonymous requests.
    • There are upper limits on request body size, message count, and output length.
    • Streaming output correctly prompts the user upon network interruption and allows recovery.