Design a Query Router Between a Local Assistant and a Cloud LLM
Machine LearningModel answerLast updated
Design an end-to-end ML system that decides whether a natural-language query should go to a lightweight local assistant or a powerful cloud LLM.
Context
You are a machine learning engineer at a company that ships a voice and text assistant on mobile devices. The assistant has two backends:
- Local assistant (LA): runs fully on-device. Fast, private, and reliable for structured tasks — setting reminders, sending messages, controlling device settings, looking up contacts, playing media, managing calendars.
- Cloud LLM (CL): a large language model hosted in the cloud. Slower and more expensive, but far better at open-ended tasks — drafting text, explaining concepts, summarizing documents, creative brainstorming, multi-step reasoning.
Routing errors are not symmetric:
- Sending a device-control query to CL risks task failure, unnecessary latency, and exposing personal data to a third-party server.
- Sending an open-ended reasoning query to LA produces a poor or empty answer, degrading the user experience.
The system must balance task success, user satisfaction, latency, privacy, and inference cost.
What to design
Walk through the full system end to end. Your answer should address:
- Objective and metrics. What is the system optimizing for? What are the primary success metrics, guardrails, and the tradeoffs among them?
- Labels and ground truth. How do you define what the "correct" route is? How do you collect or construct training labels when you can only observe the outcome of the route that was actually taken?
- Features and model architecture. What signals does the router use? What kind of model (rules, classifier, LLM, hybrid)? How do you handle the on-device latency constraint?
- Hard cases. How do you handle ambiguous queries, queries with multiple intents, follow-up turns in a conversation, and low-confidence predictions?
- Offline evaluation. How do you measure router quality before shipping? What does calibration mean here and why does it matter?
- Online experiment. How do you run an A/B test to validate the router, and what makes this experiment tricky to interpret correctly?
You may assume queries arrive in English initially, but briefly discuss how the design generalizes to other languages and privacy-sensitive contexts.
Hints
Hint 1
Start by framing routing as a cost-sensitive decision rather than a plain classification task — the cost of routing a device-control query to the cloud is much higher than the reverse error, so your model and thresholds should reflect that asymmetry directly.
Hint 2
Logged outcomes are not unbiased labels: you only ever observe the result of the route that was taken. Think about how to recover the counterfactual — what would have happened under the other route — through annotation, sandboxed replay, or pairwise judgments.
Hint 3
Online experiments on a router face a selection-bias trap: treatment and control users receive different query distributions by construction. Think carefully about what your holdout unit should be and how to measure task success rather than engagement proxies.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing the Problem
A router is not just a classifier — it is a cost-sensitive decision policy. The right mental model is expected utility:
U(route | q) = P(success | q, route) · V
− λ_lat · latency
− λ_priv · privacy_risk
− λ_cost · inference_cost
The routes are {Local, Cloud, Hybrid, Clarify}. "Hybrid" means LA executes an action while CL generates content; "Clarify" means ask a short disambiguation question before routing. Getting the cost asymmetry right from the start shapes every downstream choice.
1. Objective and Metrics
Primary metric: task success rate — the query was completed without reformulation, manual fallback, or abandonment within ~30 seconds.
Secondary metrics: user satisfaction (thumbs, sampled surveys), and turns-to-success.
Guardrails (non-negotiable):
- p95 end-to-end routing latency ≤ 20 ms (the router itself, not the backend)
- Privacy egress rate: share of queries containing personal entities (contacts, calendar data) sent to the cloud without explicit consent → target near zero
- Clarification rate ≤ ~2% to avoid feeling annoying
- Cloud inference cost per 1k queries
- Safety incident rate
The key tradeoff: being more aggressive about sending queries to CL improves answer quality on reasoning tasks but increases latency, cost, and privacy exposure. Guardrails enforce a floor on the privacy and latency dimensions so you don't sacrifice them chasing satisfaction metrics.
2. Labels and Ground Truth
Logged routes are not labels. They reflect the existing policy and you only observe one outcome per query. Use three complementary sources:
Human annotation. Apply a rubric to consented ("Help improve the assistant") data plus synthetic examples:
- Needs device action, app control, or personal context → Local
- Open-ended generation or multi-step reasoning → Cloud
- Needs both → Hybrid
- Underspecified → Clarify
- Acceptable either way (e.g., "What is the capital of France?") → Both-OK, down-weighted in training since either route is correct
Pairwise counterfactual judgments. Replay sampled queries through both backends in a sandbox (simulate rather than execute device actions). Human raters or a calibrated LLM judge score each response. This yields soft per-route utility estimates rather than a single hard class label, which is what you actually need for training against the cost matrix.
Implicit signals as weak labels. Reformulations, "no, I meant…", barge-ins, and manual app opens are useful for mining errors and re-weighting hard cases. They are biased by the current policy, so don't treat them as ground truth.
Train on soft labels weighted by the cost matrix, not on argmax hard labels.
3. Features and Architecture: Tiered Hybrid
Stage 0 — Deterministic rules (high precision, zero latency, fully auditable):
- Explicit invocations ("ask the AI assistant to…") → Cloud
- High-precision device grammar matches (alarms, calls, timers) → Local
- Any query containing personal entities without cloud-consent → Local, unconditionally
- Safety and policy blocks
Stage 1 — On-device classifier:
- Model: a distilled multilingual transformer (~50–100M params, INT8 quantized), targeting ≤ 15 ms on mid-range hardware
- Input features:
- Query embedding + NLU outputs: domain, slot completeness, whether a handler exists
- ASR confidence and top-N transcription alternatives
- Modality (voice vs. typed)
- Device context: foreground app, screen state, locked status
- On-device personal-entity flags
- Conversation state: previous route, turn index
- Locale
- Output: calibrated probability distribution over {Local, Cloud, Hybrid}
Decision layer:
- Select
argmin_a Σ_y P(y|q) · C(a, y)using the cost matrix - Reject/clarify option: if max probability < threshold τ and expected error cost exceeds the cost of asking, surface a short disambiguation question
- Default to the reversible, private option (Local + "Want me to ask the AI?") when uncertain
- Siri-style escalation: if Local returns no handler, escalate to Cloud (with consent check)
Why not route with a large LLM? It adds latency, cost, and privacy exposure on every single query. A small calibrated classifier plus deterministic rules handles ~95% of traffic; the LLM is reserved for the uncertain tail.
4. Hard Cases
Ambiguous queries ("Tell me about my day"): lean on context features. Calendar context → Local. Philosophical question about the concept of a day → Cloud. Only clarify when both routes carry high predicted cost and they are close.
Multi-intent queries ("Write a funny birthday text to Mom and send it"): decompose into CL drafting → confirmation UI → LA sending. Always require confirmation before irreversible actions.
Follow-up turns: use sticky routing with a switching penalty in dialogue state. After a CL answer, "send that to John" goes to Local with the content passed as a payload. Track the prior route in conversation context.
Low-confidence predictions: default to Local (reversible, private), log for active learning, and monitor clarification rate to prevent the system from becoming intrusive.
5. Offline Evaluation
Test sets:
- A stratified, human-labeled golden set
- A long-tail and adversarial set: ASR errors, code-switching, ambiguous phrasing
- A multi-turn dialogue set
Metrics:
- Cost-weighted error (confusion matrix weighted by C(a, y))
- Precision of Cloud routing on device-control queries — this is the critical failure mode, needs a near-zero target
- PR curves per route class
- Expected utility under pairwise utility labels
Calibration: Reliability diagrams and Expected Calibration Error (ECE) per locale and per slice. Calibration is critical here because the decision layer uses raw probabilities in the cost-minimization step and for the reject threshold. A model that is accurate but overconfident will route too aggressively; one that is underconfident will over-clarify. Fit temperature scaling or isotonic regression per locale.
Slices to analyze: locale, voice vs. typed, ASR confidence, query length, domain, turn index, device type, consent status, new vs. returning users. An aggregate improvement can mask a regression in a critical slice — gate launches on the worst slice, not the average.
6. Online Experiment
Unit of randomization: user, not query. Randomizing by query mixes treatment and control within users, which contaminates both groups through learned behavior and cross-session effects.
What to measure: task success rate and satisfaction, not engagement. Router changes affect which backend handles a query, so raw session length or query volume are confounded — a better router may produce shorter sessions because tasks complete faster.
Selection bias trap: the treatment group sees a different routing distribution than control by construction, so the populations of queries that reach each backend are not comparable between arms. Measure the outcome at the user level, not the per-route level, to avoid this.
Holdback design: run a small holdback (e.g., 1–2%) on the old deterministic policy as a long-term baseline to detect novelty effects.
Guardrail monitoring: track privacy egress rate and safety incidents daily with an automated kill switch. Don't wait until the experiment ends.
Locale generalization: the classifier uses multilingual embeddings and per-locale calibration. For low-resource locales, start with rule-heavy Stage 0 and collect annotation data before enabling Stage 1. Privacy regulations (GDPR, etc.) may require keeping all processing on-device in certain regions — the tiered architecture handles this by never sending data to Stage 1 cloud services for those locales.