LLM Service Architecture: Multi-Device Access and Engineering Best Practices
A reliable LLM application requires more than an accessible endpoint. This guide explains a four-layer architecture for multi-device access, covering browser-first clients, gateway controls, streaming responses, reliability, token-based cost management, security, and observability. It also provides a phased implementation roadmap and highlights common engineering pitfalls.
1. The Real Challenge: Building a Request Path, Not Finding an Endpoint
When teams begin deploying large language model applications, their first instinct is often to find a working access endpoint. From an engineering perspective, however, user experience and reliability depend on the entire path between the client and the model service: client compatibility, request authentication, key storage, long-running response streaming, retries and fallbacks, cost accounting, and log auditing.
Treating this as a matter of “finding a URL” typically exposes problems at three stages:
- Before launch, compliance requirements cannot be properly assessed.
- After launch, credentials may leak or usage may grow beyond control.
- During service disruptions, teams cannot determine whether the fault lies in the network, gateway, or model service.
The better approach is to treat it as a standard multi-device access and gateway governance architecture problem.
2. Overall Architecture: Four Layers
An access architecture that can evolve over time generally consists of four layers:
- Client layer: Browsers, desktop applications, phones, and tablets share the same business logic.
- Access layer: A unified domain endpoint, load balancing, TLS termination, and geographically proximate access.
- Gateway and business layer: Authentication, quotas, routing, caching, content safety, and protocol conversion.
- Model services and governance layer: Model calls, message queues for smoothing traffic spikes, logging, monitoring and alerts, and distributed tracing.
The central design principle is simple: clients must never hold long-lived model-service credentials. All model-service calls must pass through a gateway you control, which handles request signing and quota enforcement.
3. Multi-Device Support: Why Start with the Browser?
Responsive web applications provide the most straightforward way to support computers, phones, and tablets:
- One codebase covers multiple device types and operating systems without separate releases for every platform.
- Progressive Web App (PWA) capabilities enable offline caching of static assets and installation on the home screen, bringing the experience closer to a native application.
- Debugging and staged rollouts cost less, and frontend issues can be fixed without a full application release.
Introduce a desktop client only when system-level capabilities are required, such as local file indexing, global keyboard shortcuts, or persistent background operation. It should reuse the same gateway APIs.
Browser / Desktop / Mobile│ HTTPS + short-lived tokens▼Access layer (load balancing / nearby access)▼Business gateway(authentication · quotas · routing · caching · content safety)├── Message queue (traffic smoothing, asynchronous tasks)├── Cache (result caching / semantic caching)└── Model services (tiered routing)▼Logging · Monitoring and alerts · Distributed tracing
4. Streaming Responses: Designing for Long-Running Interactions
LLM interactions are sensitive to the time before the first output appears, while their total duration is difficult to predict. Three aspects of the request path deserve particular attention.
Protocol selection. Server-Sent Events (SSE) are commonly used for incremental text delivery. They are simple to implement and fit naturally into HTTP-based infrastructure and existing gateways. Use WebSocket when bidirectional interaction is required, such as interrupting voice output.
Layered timeouts and retries. Configure connection establishment, first-byte, and idle timeouts separately. Allow only limited retries during an idempotent request-establishment stage. Once streaming output has begun, do not retry blindly: doing so can cause duplicate charges and inconsistent content.
Backpressure and disconnection handling. When a client disconnects, the gateway must promptly cancel the upstream call. Otherwise, tokens may continue to be consumed after the user has left, creating hidden costs.
A simplified frontend streaming example:
const resp = await fetch('/api/chat/stream', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ messages, stream: true })});const reader = resp.body.getReader();const decoder = new TextDecoder();while (true) {const { done, value } = await reader.read();if (done) break;render(decoder.decode(value, { stream: true }));}
5. Reliability: Quotas, Circuit Breakers, and Fallbacks
- Quotas and rate limiting: Apply token-bucket rate limits at the gateway by user, tenant, and API endpoint. This prevents excessive traffic from a single source from overwhelming the service.
- Circuit breakers and fallbacks: Fail fast when upstream failures persist. Fall back to a smaller model or cached answers so that the service remains available with reduced capabilities rather than becoming completely unavailable.
- Asynchronous traffic smoothing: Place non-real-time workloads, such as batch summarization and offline labeling, in a message queue. Consumers process them with controlled concurrency.
- Elastic capacity: Deploy stateless gateway containers on a container platform and scale horizontally behind a load balancer. Use managed databases and object storage for stateful dependencies.
6. Cost Governance: Treat Tokens as Budget Units
Uncontrolled spending is often caused by missing usage measurement rather than high unit prices. Recommended controls include:
- Record input and output token counts, model tier, and duration for every call to create usage data that can be aggregated.
- Implement tiered model routing: send intent classification and format conversion to lightweight models, and reserve higher-capability models for complex reasoning.
- Use result caching and semantic caching to serve frequently repeated questions directly from cache.
- Set budget caps and alert thresholds for each business team or application. When a budget is exceeded, automatically reduce service capabilities rather than abruptly cutting off access.
7. Security, Compliance, and Observability
- Data minimization: Redact or replace sensitive data, such as phone numbers, government identification numbers, and secrets, with placeholders before sending it to a model.
- Content safety: Review both inputs and outputs, and retain the necessary audit logs after redaction.
- Secret management: Store credentials in a configuration service or secret management service, support rotation, and never include them in source repositories or frontend bundles.
- Observability: Send structured logs to a logging service. Monitor key metrics such as time to first token, failure rate, and token consumption, and use distributed tracing to locate bottlenecks.
In cloud deployments, these capabilities generally map to standard service categories: container platforms, object storage, message queues, logging, monitoring and alerts, and secret and configuration management. Baidu AI Cloud is one example of a platform whose services in these categories can be combined to build an access and governance foundation. Consult the official documentation for specific configurations and pricing.
8. Implementation Roadmap
| Phase | Goal | Deliverables |
|---|---|---|
| 1 | Establish the request path | Gateway proxy and browser access across devices |
| 2 | Make the service reliable and controllable | Rate limiting, circuit breakers, fallbacks, and quotas |
| 3 | Make costs measurable | Token accounting, tiered routing, and caching |
| 4 | Support compliance and auditing | Data redaction, audit logs, and credential rotation |
| 5 | Improve the user experience | Streaming rendering, PWA support, and offline caching |
9. Common Pitfalls
- Distributing long-lived credentials to clients effectively exposes a channel for generating charges.
- Measuring averages without tracking time to first token and tail latency creates a gap between reported performance and the user experience.
- Launching without usage measurement makes it difficult to attribute the monthly bill to individual business teams.
- Ignoring cancellation after disconnection leads to substantial wasted consumption.
- Leaving compliance review until the week before launch can force significant rework.
Conclusion
Multi-device availability is only the starting point. The lasting engineering value lies in four foundations: gateway governance, streaming request paths, cost measurement, and observability.
Building these capabilities in layers makes it possible to deliver LLM services reliably across devices while keeping compliance, operational control, and cost accountability in view.
