manad #
The daemon for mana. The source of magic.
manad is a local LLM token load balancer. It sits in front of one or more
inference engines (llama.cpp, vLLM) and routes every token request to
the best available worker based on model intelligence, current capacity,
measured throughput (tokens/sec), and VRAM headroom.
It speaks exactly one protocol — the mana wire protocol — over exactly two transports: Unix domain sockets and WebSockets. In over socket, out over socket. That is the entire surface clients, agents, and peer manads see: no OpenAI-compat, no Anthropic-compat, no REST, no SSE. The only HTTP anywhere is inside the thin per-engine adapters, and only over UDS, where the engines (llama.cpp, vLLM) themselves speak HTTP on top of the socket — a quarantined detail that never crosses the mana surface.
Status: implemented. P0 (core + adapters, 92 unit tests), P1 (WS transport
matrix, live-capacity poller), P2 (UDP beacon discovery + federation) are
done and green. The balancer carries Olla-parity strategies
(round-robin, least-connections, priority, priority-capacity) with
config-order tie-breaking, verified by the side-by-side routing benchmark
(scripts/routing_bench.py) against a live Olla fork over the same 3 vLLM
replicas.
1. Design principles #
- One protocol, two transports. The mana wire protocol is one JSON framing/message layer written once; UDS and WebSocket are interchangeable byte streams underneath it, sharing all message code. UDS for local (agents, engines, co-located peers: permission-protected socket files, no ports) and WebSocket for remote (agents or peer manads across the network; TLS optional). A WebSocket listener binds a TCP port because that is what WebSocket is; manad itself speaks no HTTP — the WS listener speaks only the mana protocol.
- The core is pure. The balancer binary never touches an engine's native
API. It sees workers as mana sockets and nothing else. Engines are bridged
into the mana world by thin adapters (same binary,
manad adapt ...). This is what keeps the core dependency list tiny and the core testable against socket fixtures with no engine running. - Sovereignty. Clients, balancers, and engines are all components we own. A private protocol between owned components is a smaller attack surface than emulating vendor APIs, and it makes federation trivial (a manad is a mana socket).
- Tight codebase. Minimal dependencies by construction: no hyper, no reqwest, no yaml crate, no framework. The only HTTP in the entire tree is a ~300-line request/response client codec that lives inside the adapters and only ever talks to a same-host engine (see §4).
- Local-first decisions. Routing decisions are made on the box from live telemetry. A pluggable decision hook exists for a local decision model (the Jev slot, §6). Shipping prompts or summaries to a third party for routing is not a supported configuration.
2. Research summary #
2.1 Prior art #
olla(local fork of thushan/olla). HTTP-first LLM gateway: priority routing, failover, KV-cache-aware sticky sessions (FNV-64a hashed keys, TTL+LRU, purge on health transitions), circuit breakers, sub-millisecond endpoint selection with lock-free atomic stats. manad inherits the balancer feature checklist (sticky, circuit breaker, lock-free stats) and drops the HTTP/vendor surface.- Jev (TypeSafe "System One") and
prismhq/jev-router. Jev is not an LLM but a decision model: unstructured state in, type-safe structured decisions out, 70–500 ms, calibrated probabilities, no hallucinated structure — but it is a proprietary cloud API. jev-router's open-source shape: build a minimized request summary → filter candidates by capability → ask the decider → fall back to "cheapest eligible" rules. manad takes that shape with the decider local by default (a scoring function over live telemetry, plus a hook for a local decision model). No cloud routing. - RouteLLM (lm-sys) / LLMRouter (ulab-uiuc). Learned routers (matrix factorization, Elo, KNN, GNN) trained on preference data. They route on query difficulty and cost, not live capacity, and both need training pipelines. manad's v1 scoring is unsupervised; a trained per-model quality prior is a documented extension of the decision hook, not a dependency.
- SGLang Model Gateway (Rust). Prior art only, not a supported engine: its cache-aware routing (per-worker approximate radix trees over request prefixes), power-of-two-choices balancing, circuit breakers, consistent-hash rings for multi-model mode, and the documented 10–20 % cache-hit cost of unsynchronized gateway replicas. manad's affinity tree and policy set are modeled on it; the federation cost note informs the beacon design (§7).
- bet0x/vllm-router. Proved
unix:///abs/path.sockworker URLs and the full feature matrix over UDS (health, discovery, streaming, session affinity). Spec reference for the adapter's HTTP codec.
2.2 Backend transport facts (verified 2026-10) #
| Engine | UDS listener | Notes |
|---|---|---|
llama.cpp (llama-server) |
✅ native: llama-server --host /path/to/socket binds a UDS (cpp-httplib support; the unix:// URL form is already in server-http.cpp) |
adapter rides the engine's own UDS — zero extra hops |
| vLLM | ✅ native: vllm serve --uds /path (uvicorn socket binding; requested in vllm-project/vllm#13907, now in the CLI docs) |
adapter rides the engine's own UDS — zero extra hops |
SGLang is deliberately excluded: its server has no UDS binding (open request
sgl-project/sglang#14258), which would force a TCP+HTTP exception into the
adapter layer. If #14258 lands, an SGLang adapter is a drop-in addition (a
new adapt module; no core change).
Both engines expose Prometheus-style /metrics with GPU/KV-cache
utilization, which the adapter scrapes internally to produce the mana
capacity report (§7.3). Every engine connection is a UDS; there is no TCP
anywhere between manad and its engines.
3. Architecture #
mana wire protocol (JSON over a byte stream)
clients ── UDS /run/manad/mana.sock ──┐
agents ── UDS /run/manad/mana2.sock ─┤
remote ── ws://host:port/mana ────────┤ ┌─────────────────────┐
── wss:// (TLS, optional) ─────┴───────▶│ manad (core) │
│ ┌───────────────┐ │
│ │ balancer │ │
│ │ tier·load·tps │ │
│ │ ·vram·affinity│ │
│ │ sticky+breaker│ │
│ │ decision hook│ │
│ └───────────────┘ │
│ ┌───────────────┐ │
│ │ discovery │ │
│ │ (UDP beacon) │ │
│ └───────────────┘ │
└───┬──────────────────────────┘
pure mana, UDS or WS │
┌──────────────────────────┐ │
▼ ▼ ▼ ▼
peer manad (federation) mana socket mana socket
(manad core ↔ manad core) (adapter) (adapter)
┌────────┐ ┌────────┐
│ adapter│ │ adapter│
│llama.cpp│ │ vllm │
└───┬────┘ └───┬────┘
│ UDS, HTTP │ UDS, HTTP
┌───┴────┐ ┌───┴────┐
│llama- │ │ vllm │
│server │ │ │
│(--host │ │ │
│ /sock) │ │ │
└────────┘ └────────┘
Two roles, one binary:
manad serve— the core. Listens on UDS and/or WebSocket, balances, discovers peers, routes. Depends on no engine API.manad adapt <engine>— one per engine (or inside the engine's container). Listens on a mana socket; dials the engine with the most efficient local method; translates mana ↔ the engine's native API; scrapes engine metrics into the mana capacity report.
4. Adapters (the only HTTP in the tree, and only over UDS) #
Each adapter is small and shares one internal codec: a hand-rolled
HTTP/1.1 request/response + SSE client over a Unix domain socket. Roughly
300 lines, zero dependencies (no hyper, no reqwest). It exists because both
engines speak HTTP on top of their UDS — the socket is the transport, HTTP is
the on-socket framing the engines chose. It is quarantined: nothing outside
manad adapt ever imports it, and it only ever dials a same-host engine
socket. No TCP, no ports, no loopback — between manad and its engines it is
all UDS.
| Adapter | Engine dial | Translation |
|---|---|---|
manad adapt llamacpp |
UDS (engine's own --host /path.sock socket) |
mana chat → /v1/chat/completions (SSE → chunk frames); capacity from /metrics (kv cache used/size) |
manad adapt vllm |
UDS (engine's own --uds socket) |
mana chat → /v1/chat/completions; capacity from /metrics (gpu_cache_usage, KV token counts) |
Deployment note: if an engine runs in a container (the local convention for
llama.cpp/vLLM builds), run the adapter inside the container next to the
engine and mount its mana UDS to the host. The host's manad serve then sees
a uniform list of mana sockets regardless of how the engine is hosted.
5. Mana wire protocol #
JSON objects over any byte stream: WebSocket text frames, or raw UDS bytes length-framed (4-byte big-endian prefix per JSON object). One request → a stream of response objects on the same connection.
Request
{
"id": "req-01J...", // client-chosen, echoed back
"endpoint": "chat", // "chat" | "generate" | "embed" | "tokenize" | "admin"
"model": "qwen-27b", // logical model; balancer resolves to a worker
"payload": { ... }, // endpoint-specific, vendor-neutral (§5.1)
"hints": { // all optional; balancer may ignore
"session": "sess-abc123", // sticky key for KV-cache affinity
"priority": 0, // 0 = normal, higher = more urgent
"min_tps": 20, // reject workers slower than this
"min_tier": 2
}
}
Response (streaming)
{"id":"req-01J...","type":"chunk","token":"Hel","seq":0}
{"id":"req-01J...","type":"chunk","token":"lo","seq":1}
{"id":"req-01J...","type":"done",
"finish_reason":"stop",
"usage":{"prompt_tokens":12,"completion_tokens":3},
"worker":"llama-0", // observability: who served this
"ttft_ms":41,"tps":79.3}
Control frames
{"id":"req-01J...","type":"cancel"} // abort a running request
{"type":"ping"} → {"type":"pong"} // liveness (WS ping/pong also works)
{"id":"req-01J...","type":"error","code":"no_capacity","detail":"..."}
Admin ops (endpoint admin, payload {"op": ...})
| op | returns |
|---|---|
health |
core + per-worker health |
workers |
per-worker telemetry: state, queue depth, rolling TPS, TTFT, tier, transport, capacity report |
models |
unified model list across local + discovered workers |
stats |
per-worker / per-model aggregates (requests, tokens, error rates) |
peers |
discovered peers + their advertisements + last-seen |
config |
{patch} hot-reconfig of policy / worker list |
workers is the single source of truth for state and doubles as the
discovery beacon payload (§7) — there is no separate gossip protocol.
5.1 Vendor-neutral payload #
chat.payload is the intersection of what the three engines need, not a
copy of any vendor schema:
{
"messages": [{"role":"system|user|assistant","content":"..."}],
"max_tokens": 256,
"temperature": 0.7,
"top_p": 0.9,
"stop": ["\n\nHuman:"],
"tools": [ ... ], // passed through to the engine's function-calling
"stream": true
}
generate, embed, tokenize ride the same envelope under their endpoints.
Each adapter maps the payload to the engine's native request and maps streamed
engine output back to chunk frames.
6. Balancer and the decision hook #
6.1 Per-worker state (lock-free: atomics + bounded map, the olla pattern) #
Worker {
name, transport, // local-uds | local-ws | remote-ws | remote-uds
model, tier: 0..=3, // intelligence tier (config or learned, §9)
queue_depth, // in-flight requests (measured by this core)
tps_ema, ttft_ms_ema, // exponential moving averages, measured from chunks
vram_free_bytes, // from adapter capacity report (local) or beacon (remote)
kv_bpt, // KV bytes per token for this model (adapter-reported)
sessions_left: {8192: 14, 32768: 4, 131072: 1}, // live, §7.3
health: Healthy|Degraded|Down, // circuit breaker: N failures → open, half-open probe (wired into routing); proactive health check dials the adapter every health_check_interval_s
affinity_tree: RadixTree, // per-worker request-prefix tree (SGLang-MG style)
}
6.2 Scoring #
Eligible = model match ∧ health ∧ hint filters ∧ sessions_left(request_ctx) ≥ 1.
eta(w) = queue_depth(w) / max(tps_ema(w), 1) // seconds to drain the queue
score(w) = w_tier * tier(w)
+ w_load * (1 / (1 + eta(w)))
+ w_tps * tps_ema(w) / max_tps(pool)
+ w_vram * headroom_ratio(w) // vram_free / vram_total, or sessions_left ratio
+ w_aff * prefix_hit_ratio(w, req) // radix lookup
Defaults w_tier=4.0, w_load=3.0, w_tps=1.0, w_vram=2.0, w_aff=2.0, all
config-tunable. With one worker per model the scoring degenerates to a health
check, which is correct.
Sticky sessions: session → (worker, expire), FNV-64a hashed, TTL + LRU
bounded, purged when the pinned worker goes non-routable (inherited from
olla, which validated the design). A hit routes to the pinned worker unless
eta(pinned) > 2 × min_eta(eligible) — capacity failover. A miss selects by
score and inserts a sticky entry.
Telemetry: tps from streamed chunk timings (tokens ÷ wall time, EMA
α=0.2); ttft from request-accept to first chunk. The balancer is the source
of truth for what it sent; engine metrics (via adapter) are the source of
truth for VRAM/KV.
6.3 Decision hook (the Jev slot) #
The scorer is the default decider, behind an async trait:
trait Decider {
fn decide(&self, req: &Request, pool: &[WorkerSnapshot]) -> Decision;
// Decision::Scored → built-in scoring (default)
// Decision::Force(worker) → route to a specific worker
// Decision::Reject(why) → no worker eligible
}
Implementations:
ScoringDecider— built-in, zero cost, always available.ModelDecider— the jev-router shape with a local model: a minimized request summary + worker snapshot table → a small local LLM worker (declared in config, reserved from routing) returns{worker, confidence}. Bounded bymax_decision_ms(default 250); timeout falls back to scoring. The decision call itself goes out over mana, so the model can live on any discovered worker with spare capacity — the hook is transport-agnostic.RulesDecider— static config overrides (model X → worker Y), the "cheapest eligible" fallback from jev-router.
7. Discovery and federation #
7.1 Mechanism: one UDP multicast beacon #
No mDNS library, no gossip protocol, no consensus. One tokio::net::UdpSocket
joined to a multicast group (e.g. 239.255.255.123:40117, configurable).
Every beacon_interval (default 5 s) each instance broadcasts one small JSON
beacon; every instance listens. Discovery, capability advertisement, and
state sync are the same message.
{
"instance": "7f3a",
"epoch": 1042,
"transports": { "unix": "/run/manad/mana.sock", "ws": ["ws://10.0.1.4:40114/mana"] },
"workers": [
{
"name": "llama-0", "model": "qwen-27b", "tier": 3,
"tps": 79.3, "queue": 2, "health": "healthy",
"vram_free_bytes": 11811160064,
"sessions_left": { "8192": 14, "32768": 4, "131072": 1 }
},
{ "name": "vllm-a", "model": "gemma-31b", "tier": 3,
"tps": 61.0, "queue": 0, "health": "healthy",
"vram_free_bytes": 8589934592,
"sessions_left": { "8192": 6, "32768": 2, "131072": 0 } }
]
}
- Default on, disabled with
discovery.enabled: false(ormulticast_addr: "off"). - Peers unseen for 3× the interval drop out of the pool with a health transition (same circuit-breaker path as local workers).
- Multicast reaches the local segment; loopback multicast reaches co-located
instances. For peers beyond the segment, static
upstreams:entries (manad-core → manad-core over WS) remain — a remote manad's workers enter the pool the same way beacons do, minus auto-discovery. - Split brain is harmless: a physical worker is owned by exactly the instance whose adapters dial it; two instances can never double-book it. Session affinity survives peer churn because session keys hash identically on every instance.
7.2 Unified pool #
Remote workers enter the same balancer pool as local ones, marked
transport: remote, carrying peer-reported tps, queue, vram_free,
sessions_left. Scoring (§6.2) runs over local + remote uniformly, so a
request lands wherever capacity + tier + speed are best. If the local pool has
zero eligible workers, the request is forwarded to the best remote worker's
peer verbatim over mana (same id, via: [instance-ids] chain). If
nowhere is eligible: {"type":"error","code":"no_capacity"}.
7.3 The capacity model: VRAM room and sessions-left #
"VRAM room for context" and "sessions left at context size X" are computed quantities, not guesses:
vram_free_bytes = vram_total − weights_bytes − kv_in_use_bytes − reserve
sessions_left(ctx) = floor( vram_free_bytes / (ctx × kv_bpt) )
Inputs and where they come from:
| input | source |
|---|---|
vram_total |
adapter reports once at startup (engine reports device memory) |
weights_bytes |
adapter at startup (engine model info) |
kv_in_use_bytes |
adapter scrapes engine /metrics (KV cache used) on a slow tick (default 2 s) and ships it in workers/beacons |
kv_bpt |
adapter computes once: kv_used / ctx_in_use from a controlled warmup, or declared in config |
reserve |
config, default 5 % of vram_total |
- For local workers the core recomputes
sessions_leftfrom live numbers every scoring pass; for remote workers it trusts the peer's beacon value (the peer runs the same computation on its own live state). - The reported context sizes (the keys of
sessions_left) are configurable, default[8192, 32768, 131072]. - Eligibility uses
sessions_leftfor the requested context (interpolated from the table), so a worker that can still take small chats stays eligible for them while it is too full for a 128k session. - This is the answer to "how much room does that node have":
peers/workersadmin ops print the table, and the beacon carries it, so any client or tool on the network can answer the question.
8. Configuration (single JSON file, no env coupling) #
{
"listeners": [
{ "unix": "/run/manad/mana.sock", "mode": "0660" },
{ "ws": "127.0.0.1:40114", "path": "/mana",
"tls": { "cert": "/etc/manad/tls.crt", "key": "/etc/manad/tls.key" } }
],
"workers": [
{ "name": "llama-0", "mana": "unix:///run/engines/llama0.mana", "model": "qwen-27b", "tier": 3 },
{ "name": "vllm-a", "mana": "unix:///run/engines/vllmA.mana", "model": "gemma-31b", "tier": 3 }
],
"discovery": {
"enabled": true,
"multicast_addr": "239.255.255.123:40117",
"beacon_interval_ms": 5000,
"capacity_ctx_sizes": [8192, 32768, 131072]
},
"upstreams": [
{ "name": "rack-b", "ws": "ws://10.0.2.20:40114/mana" }
],
"policy": {
"weights": { "tier": 4.0, "load": 3.0, "tps": 1.0, "vram": 2.0, "affinity": 2.0 },
"sticky_ttl_s": 300,
"sticky_max": 10000,
"circuit_breaker": { "failure_threshold": 3, "probe_interval_s": 10, "max_retries": 2, "health_check_interval_s": 10 },
"vram_reserve_pct": 5
},
// Transport timeouts (Olla proxy.* parity). Defaults shown match the eris
// Olla deployment (config.yaml), not Olla's source fallbacks. The forward
// path keeps Olla's two distinct bounds: response_header_s is an absolute
// cap on time-to-first-frame (a long prefill is fine); read_s is the gap
// between frames, reset on each read (caps stalls, never a live stream).
"timeouts": {
"connection_s": 10, // dial + WS upgrade + mana handshake (Olla connection_timeout)
"response_header_s": 600, // time-to-first-frame (Olla response_header_timeout)
"read_s": 600, // per-frame gap, reset each read (Olla read_timeout)
"check_s": 5, // per capacity/health query (Olla check_timeout)
"idle_s": 120, // inbound client read gap, reset each frame (Olla http.Server idle_timeout)
"read_header_s": 10, // inbound WS-upgrade read, before the first frame (Olla http.Server ReadHeaderTimeout)
"write_s": 1800, // per-frame write to the client (Olla http.Server WriteTimeout)
"shutdown_s": 5 // graceful-shutdown drain budget on SIGTERM (Olla server.shutdown_timeout)
},
"decider": { "kind": "scoring" }
// or: { "kind": "model", "model": "small-router", "max_decision_ms": 250 }
// or: { "kind": "rules", "rules": [ { "model": "gemma-31b", "worker": "vllm-a" } ] }
}
JSON (not YAML) is deliberate: serde_json is already a dependency, a config
parser is not. manad check validates config + dials every worker socket.
Hot-reload of policy and workers via the admin config op.
9. Implementation plan #
Language: Rust. Single static binary, no runtime. sgl-router proves the
target (Rust balancer over heterogeneous backends) at production quality;
tokio gives UDS + TCP + WS + UDP on one event loop.
Dependencies (entire tree):
| dep | used by | why |
|---|---|---|
tokio |
core + adapters | net (uds/tcp/udp), io, sync, time |
tokio-tungstenite |
core | the only WebSocket implementation that is small and well-tested |
serde / serde_json |
everything | mana envelope + config |
fnv |
core | sticky keys, session hashing |
| (none) | adapters | HTTP/1.1+SSE client codec is hand-rolled, ~300 lines, quarantined to adapt |
No hyper, no reqwest, no yaml, no async-trait (the Decider trait is
synchronous over snapshots; ModelDecider spawns the mana call), no mDNS
crate (raw UDP multicast).
manad/
├── Cargo.toml
├── config.example.json
└── src/
├── main.rs # manad serve | adapt <engine> | check | bench
├── config.rs
├── core/
│ ├── listen.rs # UDS + WS listeners, connection supervisor
│ ├── proto.rs # mana envelope, length framing, validation
│ ├── balancer/
│ │ ├── state.rs # Worker, atomic telemetry, circuit breaker
│ │ ├── score.rs # scoring + hint filters + capacity check
│ │ ├── sticky.rs # session map, TTL/LRU
│ │ ├── affinity.rs # radix prefix tree per worker
│ │ └── decider.rs # Decider trait + scoring/model/rules
│ ├── capacity.rs # vram/kv math, sessions_left table
│ ├── discovery.rs # UDP multicast beacon in/out, peer pool
│ ├── forward.rs # remote forwarding over mana, via-chains
│ └── admin.rs # health/workers/models/stats/peers/config
└── adapt/
├── http.rs # the 300-line HTTP/1.1+SSE client codec (over UDS)
├── common.rs # adapter scaffold: mana in, engine out, metrics tick
├── llamacpp.rs
└── vllm.rs
Phases
- P0 — wire + one engine. mana protocol over UDS;
manad adapt llamacpp→ one llama-server;chatstreaming end-to-end; adminhealth/workers. Exit:manad benchstreams a prompt end-to-end at the engine's expected TPS, measured within 5 %. - P1 — full transport matrix + balancer. WS listeners/clients (in and
out), vLLM adapter over UDS, scoring, sticky, affinity, circuit breaker,
capacity report +
sessions_left; all admin ops. Exit: two llama.cpp servers + one vLLM balanced under concurrent multi-session load; sticky holds across turns;sessions_leftmatches a manual VRAM calculation. - P2 — discovery + federation + decision hook. multicast beacon,
unified pool, remote forwarding with
viachains;ModelDecider+RulesDecider. Exit: two boxes on one segment auto-discover, share one pool, and a killed local engine shifts traffic to the peer with no client-visible error; beacons show correct sessions-left tables on both. - P3 — hardening. load harness (sustained + burst), TLS on WS, Prometheus sidecar (optional, separate small binary so the core stays dep-free), packaging, docs.
10. Open questions #
tokenizeendpoint: cheap prompt token counts without generation (both engines have tokenize APIs). Include in P1? Leaning yes.- Tier assignment: config-declared (v1) vs. a one-shot local eval
micro-benchmark that writes tiers back into config. The eval fits
manad bench(P3+). - Beacon over untrusted networks: multicast beacons advertise topology
to anyone on the segment. Fine for a trusted LAN; for anything else,
discovery.enabled: false+ explicitupstreams:(optionally wss + a shared secret field, P3). - KV accounting accuracy:
kv_bptfrom warmup vs. declared. If engine metrics expose it directly (vLLM's block size × 2 × layers × kv heads), prefer the exact value; adapter picks exact-over-estimated.
11. Non-goals #
- No OpenAI/Anthropic/ollama compatibility on the client side. (Clients that must speak those need a translator in front of manad; that is a different program, and manad stays pure.)
- No SGLang: no native UDS binding upstream (sgl-project/sglang#14258). It
becomes a drop-in
adaptmodule the day that lands. - No TCP to engines, ever: the adapter layer dials UDS only.
- No model management: pulling, converting, storing. Workers have their models; manad routes.
- No HTTP server of any kind in the core (no REST admin, no REST metrics; admin is mana, metrics are an optional sidecar).
- No consensus, no replicated state, no multi-tenant authz. Trusted boxes, trusted segment.
- No cloud routing decisions, by design.