Hybrid Edge-Cloud Inference › Implementation: a routing + fallback pipeline
Language AI HandbookAll chapters The notebook simulates both model paths with controllable quality and latency. It measures routing on synthetic subgroups, gate exclusions, offline behavior, transferred bytes and remote serving spend. The code makes no model or network calls.
The simulation is deliberately simple, but its structure mirrors the production system: a gate that runs first, a router that scores within the gate's permissions, a serving step with fallback, and a logging step that records everything needed for per-slice evaluation.
Setup
PythonIn [2]Expand
import textwrap
from dataclasses import dataclass
from typing import Callable
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
rng = np.random.default_rng(7)
np.set_printoptions(precision=3, suppress=True)Simulating requests, difficulty, and both paths
The synthetic requests vary in length and difficulty. The router sees a noisy feature derived from hidden difficulty. The two generators give each request synthetic quality and latency values, with the edge score declining faster as difficulty increases.
PythonIn [3]Expand
@dataclass
class Request:
rid: int
n_tokens: int # prompt length
difficulty: float # hidden ground-truth difficulty in [0,1]
has_pii: bool # privacy-sensitive span present
language: str # 'en' or 'other'
def make_requests(n: int, rng: np.random.Generator) -> list[Request]:
reqs = []
for i in range(n):
n_tokens = int(rng.integers(20, 1200))
# difficulty increases with length and a random "hardness" trait
difficulty = np.clip(
0.15 + 0.0006 * n_tokens + rng.normal(0, 0.12), 0, 1
)
has_pii = rng.random() < 0.08
language = "en" if rng.random() < 0.85 else "other"
reqs.append(
Request(i, n_tokens, float(difficulty), bool(has_pii), language)
)
return reqs
requests = make_requests(2000, rng)ConsoleOut [4]Expand
Generated 2000 requests Mean prompt length: 605 tokens Fraction with PII: 0.066 Fraction non-English: 0.160
Our synthetic population has a spread of prompt lengths and a minority of privacy-sensitive and non-English requests. The ground-truth difficulty is hidden from the router; only the model-driven parts of the pipeline see it in simulation. This mirrors production, where difficulty is never observable directly and must always be inferred from proxies.
The two generators
Each path returns a synthetic answer score and latency. Both scores depend on difficulty, with a steeper decline on edge. The edge score includes a language penalty. Both latency expressions depend on prompt length. The cloud latency also includes a fixed network term.
PythonIn [5]Expand
def edge_generator(
req: Request, rng: np.random.Generator
) -> tuple[float, float]:
# Edge is fast, strong on easy/short, degrades on hard/long, weaker on non-English
lang_penalty = 0.05 if req.language == "other" else 0.0
base = 0.90 - 0.55 * req.difficulty - lang_penalty
quality = float(np.clip(base + rng.normal(0, 0.05), 0, 1))
latency_ms = (
20 + 0.08 * req.n_tokens + rng.normal(0, 4)
) # local prefill + decode
return quality, max(latency_ms, 5.0)
def cloud_generator(
req: Request, network_rtt_ms: float, rng: np.random.Generator
) -> tuple[float, float]:
# Cloud score has a smaller difficulty penalty and no separate language term.
base = 0.88 - 0.08 * req.difficulty
quality = float(np.clip(base + rng.normal(0, 0.04), 0, 1))
latency_ms = (
network_rtt_ms # round trip
+ 30
+ 0.05 * req.n_tokens # prefill at scale
+ rng.normal(0, 10)
) # serving jitter
return quality, max(latency_ms, 5.0)The two generators encode the core asymmetry: the edge's quality slope with respect to difficulty is steep (0.55), while the cloud's is shallow (0.08). For some easy requests, the simulated edge score is competitive. The wider gap on hard requests creates room for improvement if the router can identify them.
The privacy gate
The gate runs first and is deterministic. Here it enforces a policy rule: PII-bearing requests are redact_then_cloud_ok when redaction is enabled and local_only otherwise. Any request the gate marks local_only is ineligible for cloud routing regardless of the difficulty score.
PythonIn [6]Expand
REDACTABLE = True # PII may be eligible after redaction; no redactor runs in this example
def privacy_gate(req: Request) -> str:
if req.has_pii:
return "redact_then_cloud_ok" if REDACTABLE else "local_only"
return "cloud_ok"ConsoleOut [7]Expand
cloud_ok 1868 redact_then_cloud_ok 132
The gate count shows how many requests can be considered for cloud transfer without further action. A conditional verdict still needs verified redaction, and the simulated input contains no unconditional local-only requests with the flag enabled.
PythonIn [8]Expand
gate_order = ["cloud_ok", "redact_then_cloud_ok", "local_only"]
gate_series = (
pd.Series([privacy_gate(r) for r in requests])
.value_counts()
.reindex(gate_order, fill_value=0)
)
gate_counts_arr = gate_series.to_numpy(dtype=float)
gate_labels_arr = list(gate_series.index)
gate_frac_arr = gate_counts_arr / gate_counts_arr.sum()VisualizationOut [9]Expand

Most requests get the cloud_ok verdict. The PII-bearing requests receive a conditional verdict with REDACTABLE enabled. The notebook provides no redactor and keeps both PII-bearing categories on the device. To permit cloud transfer after redaction in a deployment, check that redaction succeeded on the actual payload.
The router: features, score, and threshold
The router uses token length, language, and a synthetic edge-confidence feature. We generate that feature by adding noise to a function of the hidden difficulty. A sigmoid maps a hand-set linear score into the unit interval. Treat it as a priority score for this simulation.
We sweep the threshold to trace the route-quality curve rather than hard-code an operating point.
PythonIn [10]Expand
def router_features(req: Request, rng: np.random.Generator) -> np.ndarray:
# Synthetic noisy confidence proxy.
edge_conf = np.clip(
0.75 - 0.35 * req.difficulty + rng.normal(0, 0.15), 0, 1
)
lang = 1.0 if req.language == "other" else 0.0
return np.array([1.0, req.n_tokens / 1000.0, lang, edge_conf])
def router_score(feats: np.ndarray) -> float:
# Hand-set weights for the example.
w = np.array(
[-1.2, 1.6, 0.7, -2.5]
) # longer, non-English, low-confidence -> cloud
logit = feats @ w
return float(1.0 / (1.0 + np.exp(-logit)))
score_rng = np.random.default_rng(42)
scores_by_request = {
r.rid: router_score(router_features(r, score_rng)) for r in requests
}ConsoleOut [11]Expand
Router score distribution: min=0.03 median=0.18 max=0.73
A higher score makes a request more likely to pass the cloud threshold. These weights assign higher scores to longer prompts, non-English prompts, and lower simulated confidence. Inspect the reported score distribution to see how many requests can be affected by changing the threshold. Whether their local answers are correct is a separate measurement.
End-to-end simulation with fallback
Apply the gate and threshold to each request. The simulation includes a pre-transfer availability check. If it declines a cloud-eligible request, the request stays on edge without an attempted upload. The notebook computes synthetic quality and latency for each path in a fixed order, and selects only the chosen path for reporting. Using the same seed for each policy gives each request the same potential outcomes and availability draw.
PythonIn [12]Expand
NETWORK_RTT_MS = 120.0 # representative mobile round trip
P_CLOUD_UNAVAILABLE = 0.02 # synthetic pre-transfer service unavailability
CLOUD_COST_PER_REQ = 0.0015 # serving $ / request in this separate simulation
BYTES_PROMPT_PER_TOKEN = 4
BYTES_COMPLETION_PER_TOKEN = 4
def simulate(
threshold: float, rng: np.random.Generator, network_up: bool = True
) -> pd.DataFrame:
rows = []
for r in requests:
g = privacy_gate(r)
score = scores_by_request[r.rid]
unavailable = rng.random() < P_CLOUD_UNAVAILABLE
edge_outcome = edge_generator(r, rng)
cloud_outcome = cloud_generator(r, NETWORK_RTT_MS, rng)
# Only unconditional approvals can leave the device.
want_cloud = g == "cloud_ok" and score > threshold
use_cloud = want_cloud and network_up and not unavailable
fallback = want_cloud and not use_cloud
if use_cloud:
q, lat = cloud_outcome
served = "cloud"
bytes_xfer = (r.n_tokens + 40) * BYTES_PROMPT_PER_TOKEN + (
50 + 20
) * BYTES_COMPLETION_PER_TOKEN
cloud_cost = CLOUD_COST_PER_REQ
else:
q, lat = edge_outcome
served = "edge"
bytes_xfer = 0
cloud_cost = 0.0
rows.append(
{
"rid": r.rid,
"difficulty": r.difficulty,
"gate": g,
"served": served,
"want_cloud": want_cloud,
"fallback": fallback,
"quality": q,
"latency_ms": lat,
"bytes": bytes_xfer,
"cloud_cost": cloud_cost,
"non_english": r.language == "other",
}
)
return pd.DataFrame(rows)ConsoleOut [13]Expand
Cloud fraction: 0.030 Mean quality: 0.624 Mean latency: 71.5 ms Cloud spend: $0.09 over 2000 requests Fallbacks: 0 requests hit the fallback path
At a 0.5 threshold, relatively few requests pass the score cutoff. The display counts successful cloud responses separately from requests that would have used the cloud but stayed on edge after the availability check. These fallback requests contribute their edge quality and latency. The simulation includes no post-upload failure or timeout costs.
Where the synthetic policy sends requests
Break down the same synthetic traffic by difficulty, language, and gate verdict to see what the aggregate hides. This exercise reuses the 2,000 generated requests. In a deployment, define the slices before evaluation and test the chosen thresholds on separate traffic.
With quality scores bounded between 0 and 1, a change confined to a slice that accounts for 5% of traffic moves the overall mean by at most 0.05, or five percentage points. A smaller shift in the mean can still hide a large loss inside the slice.
PythonIn [14]Expand
rng_rep = np.random.default_rng(11)
df = simulate(0.5, rng_rep)
hard = df.difficulty >= df.difficulty.quantile(0.75)
slices = pd.DataFrame(
{
"mean_quality": [
df.quality.mean(),
df[hard].quality.mean(),
df[df.non_english].quality.mean(),
df[df["gate"] != "cloud_ok"].quality.mean(),
],
"cloud_frac": [
np.mean(df.served == "cloud"),
np.mean(df[hard].served == "cloud"),
np.mean(df[df.non_english].served == "cloud"),
np.mean(df[df["gate"] != "cloud_ok"].served == "cloud"),
],
"p95_latency_ms": [
np.percentile(df.latency_ms, 95),
np.percentile(df[hard].latency_ms, 95),
np.percentile(df[df.non_english].latency_ms, 95),
np.percentile(df[df["gate"] != "cloud_ok"].latency_ms, 95),
],
},
index=["all", "hard (top quartile)", "non-English", "privacy-gated"],
)ConsoleOut [15]Expand
mean_quality cloud_frac p95_latency_ms all 0.624 0.030 114.733 hard (top quartile) 0.486 0.098 202.602 non-English 0.621 0.131 205.409 privacy-gated 0.620 0.000 110.288
The table shows the observed route mix for each slice. Interpret the pattern alongside the threshold, feature weights and unconditional transfer requirement.
Place each slice’s cloud fraction beside its mean quality. These describe one policy; changes in quality require a comparison on the same requests under competing policies.
PythonIn [16]Expand
slice_names_arr = list(slices.index)
cloud_frac_arr = slices["cloud_frac"].to_numpy(dtype=float)
mean_quality_arr = slices["mean_quality"].to_numpy(dtype=float)
pos_arr = np.arange(len(slice_names_arr))VisualizationOut [17]Expand

Requests can belong to several slices. A privacy-gated request stays on edge in this simulation, regardless of its score. Each displayed p95 describes its own slice under the measured policy.
The cloud path in this simulation includes a fixed 120 ms network term per cloud-served request. To estimate how routing changes a slice’s p95 latency, compare both policies on the same requests with matched simulated conditions and recompute the quantile for each policy. Path compute and request composition can also change the tails.
The route-quality curve
Sweep the threshold and plot mean quality, mean latency and serving spend against the fraction of requests served in the cloud. Compare the three plots at the same cloud fraction to choose a candidate operating point.
The curve characterizes the routing system: two systems with different routers, different edge models, or different traffic mixes will have differently shaped curves, and the shape tells you which lever to pull.
PythonIn [18]Expand
thresholds = np.linspace(
0.0, 0.30, 19
) # sweep across the region where the score distribution has mass
curve_rows = []
for t in thresholds:
local_rng = np.random.default_rng(11)
d = simulate(float(t), local_rng)
curve_rows.append(
{
"threshold": t,
"cloud_frac": float(np.mean(d.served == "cloud")),
"quality": float(d.quality.mean()),
"mean_latency_ms": float(d.latency_ms.mean()),
"cloud_spend": float(d.cloud_cost.sum()),
"bytes_mb": float(d.bytes.sum() / 1e6),
}
)
curve = pd.DataFrame(curve_rows)
plot_curve = curve.sort_values("cloud_frac", ignore_index=True)VisualizationOut [19]Expand

VisualizationOut [20]Expand

VisualizationOut [21]Expand

Across the sampled thresholds, larger cloud-served fractions correspond to higher mean quality and latency. Each successful cloud request has the same fee in this simulation, so serving spend rises proportionally.
Start with thresholds that meet the quality floor and fit the serving budget. Compare their latency, then check the candidate operating points on the traffic slices your application needs to serve. The plot uses one seeded population, and a different mix of requests can move the operating point.
Offline behavior
Simulate a full network outage using the same request scores and potential outcomes as the online run. Compare how many requests finish locally and how their mean score changes.
PythonIn [22]Expand
off = simulate(0.5, np.random.default_rng(11), network_up=False)
assert off["served"].eq("edge").all()
assert off["fallback"].equals(off["want_cloud"])ConsoleOut [23]Expand
Served on edge: 1.000 Unconditionally eligible requests above threshold: 61 Mean quality offline: 0.612
All requests are served on-device during the outage. The count in the second row measures preflight cloud intent: the gate returned cloud_ok and the score exceeded the threshold. The two assertions check that every request finishes on edge and that every request with cloud intent takes the fallback path. The intent count includes requests the online availability check might already send to the edge. Compare outcomes on this shared workload before measuring the policy on a different traffic mix.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!