Deployment boundary
A Hivenet Router deployment currently consists of:- one router process
- one or more agent processes
- one inference backend behind each agent
- optional Prometheus, Grafana, Loki, and Tempo services
- optional OpenAI or Anthropic provider fallback
- on the same machine as the router
- on remote bare-metal or virtual machines
- in containers
- in Kubernetes or another scheduler
- across several infrastructure providers or locations
Main network surfaces
The router and agents use separate interfaces for clients, authentication, peer communication, and metrics.
The public HTTP server uses plain HTTP by default. Terminate TLS through a reverse proxy or another trusted ingress when clients connect over an untrusted network.
Streaming responses use server-sent events when the backend returns:
Router libp2p reachability
The router listens on:Using libp2p does not remove the need for network reachability.Agent hosts must be able to reach both the router’s gRPC authentication endpoint and the libp2p address returned during authentication.
Router architecture
The router brings several subsystems into one process.HTTP API
The Gin HTTP server exposes:- public liveness at
/health - authenticated client routes under
/v1/* - separately authenticated operator routes under
/admin/*
Agent registry
The in-process agent registry indexes live agents:- by peer ID
- by registered model
- its persistent libp2p peer ID
- its active agent-initiated transport connection
- model and capability
- engine and deployment metadata
- declared concurrency capacity
- current active-request count
- process and backend health
- last heartbeat time
- current session token
Policy executor
The policy executor owns:- the global routing policy
- optional per-model policy documents
- candidate evaluation
- fallback-chain progression
- per-step retry state
- per-model capacity wait queues
Request processor
The request processor consumes work from the router’s buffered request queue. It:- creates a routing session
- selects an agent
- acquires one declared capacity slot
- forwards the request over libp2p HTTP
- handles streaming or buffered responses
- records the result and observed latency
- retries or advances the fallback chain when appropriate
- releases the capacity slot
- wakes the next request waiting for that model
Provider fallback
Optional OpenAI and Anthropic adapters live inside the router process. They are used only when:- the local routing policy and fallback chain are exhausted
- the request requires the
llmcapability - the active policy declares a provider fallback
- the corresponding provider credential was available when the router started
HTTP middleware and route boundaries
Global HTTP middleware runs before route-specific authentication. The current high-level order is:- OpenTelemetry tracing
- RED request metrics
- trace-response headers
- request ID assignment
- audit logging
- application request logging
- panic recovery
- CORS handling
Model-discovery requests bypass quota admission. This lets a key using strict per-model quotas discover the models declared for it before sending an inference request.
Client authentication and administrator authentication use separate providers and credentials.
Agent architecture
An agent is a long-running bridge between the router and one inference backend. The agent is designed to survive transient failures. It does not require:- the inference backend to be ready at agent startup
- the router to be reachable at agent startup
- one uninterrupted connection for the process lifetime
Agent startup and registration
The normal agent lifecycle is:- Load or create a persistent Ed25519 libp2p identity.
- Poll the inference backend until it is ready.
- Use the configured model ID or discover one from the backend.
- Create a signed agent JWT.
- Authenticate with the router over TLS-protected gRPC.
- Receive a short-lived session token, router peer ID, and dialable router addresses.
- Initiate the libp2p connection to the router.
- Register the agent’s peer ID, metadata, and session over that connection.
- Start heartbeats, metric pushes, backend checks, and session renewal.
- Receive forwarded inference requests over the established agent-initiated transport.
Agent authentication bootstrap
Agent trust begins with one shared secret configured on the router and every agent. That secret is used in two independent ways.JWT authentication
The agent creates a one-hour HMAC-SHA256 JWT. The token contains standard claims such as:- subject
- issuer
- issued-at time
- expiration time
gRPC server identity
Both sides derive the same Ed25519 key material from the shared secret using HKDF-SHA256. The current derivation uses:Session token
After successful gRPC authentication, the router creates a random session token. The agent then uses that token for:- registration
- heartbeats
- routing-signal pushes
libp2p protocols
Hivenet Router uses two namespaced libp2p HTTP protocols.
libp2p encrypts peer streams with Noise.
Router management handlers
The router protocol contains:Agent inference handlers
The agent protocol receives the request selected by the router. The agent has a dedicated handler for:Heartbeats and routing signals
Agents send two separate updates.Routing signals
Routing signals carry the latest:- engine metrics
- hardware snapshot
LastSeen- process health
- backend health
Heartbeats
Heartbeats:- validate the current session
- update the agent’s last-seen time
- refresh its finite-lived peer address
- report backend health
- provide slower fallback delivery of hardware and engine snapshots
Backend health
The agent checks its local backend separately from router connectivity. The default check cadence is:Request lifecycle
The following sequence shows the main Chat Completions path.1. Global request processing
The router creates or validates:- the OpenTelemetry trace
X-Request-ID- audit context
- endpoint metrics
2. Client authentication
The/v1/* authentication provider resolves:
- tenant owner
- dynamic key ID where applicable
- model restrictions
- quota configuration
- no-auth mode
- static API-key mode
- dynamic API-key mode
3. Request-rate admission
Quota middleware applies either:- one flat tenant request bucket
- one strict per-model request bucket
4. Model authorization and admission
The handler:- parses the top-level
model - checks the key’s effective model allowlist
- computes one learned input estimate from message text, the Anthropic top-level
systemprompt, and raw tool-definition JSON - applies B1 request caps and B3 live pool-pressure shedding
- reserves the replica-scaled B2 occupancy budget and
max_inflightbackstop - on serverless policies, applies the key’s B4 occupancy share and token-per-minute caps
- checks the worst-case input plus requested output against the daily budget
- charges admitted prompt tokens
- preserves the original request bytes and headers
share × admit_budget_tokens × healthy replicas without the admit fraction. B4 is a per-key fairness control; B2 remains the pool-safety limit.
Reservation lifetime
An occupancy reservation stays attached to the request until it finishes:- Declared output is reserved up front through
max_completion_tokensormax_tokens. - Undeclared output grows the reservation as tokens stream.
- Exact backend input usage replaces the estimated input portion when available.
- Success, error, timeout, and client disconnect release the global and per-key reservations.
- Provider fallback releases them early as soon as routing leaves the local pool.
Count-tokens exemption
POST /v1/messages/count_tokens performs no generation and holds no KV cache. It skips B1 through B4 and the daily token budget, avoiding double charges for clients that count a prompt before sending it. The request-per-minute limiter still protects the endpoint.
5. Global request queue
The request is submitted to a buffered channel. The default capacity is:6. Processor concurrency
The request processor starts one goroutine for each queued request but limits concurrent agent forwards through a semaphore. The default maximum is:7. Policy selection
The policy session uses:- a model-specific policy when one claims the requested model
- otherwise the active global policy
- exact model registration
- process and backend health
- capability
- static
matchfields - earlier failures in the current step
- declared capacity
- dynamic
exclude_ifgates - strategy ranking
8. Capacity wait queue
When eligible agents exist but all are at capacity, the request can enter a bounded per-model FIFO queue. The default maximum is:- an agent releases a capacity slot
- a new agent registers for the model
9. Atomic slot acquisition
Selection and capacity acquisition are separate operations. After ranking the candidates, Hivenet Router calls an atomic slot-acquisition method on the selected agent. When another request claims the last slot first, selection repeats without:- marking the agent failed
- consuming one
max_triesattempt - advancing the fallback chain
10. libp2p forwarding
The router creates a namespaced libp2p HTTP client for the selected agent. It forwards:- the same endpoint path
- the original request body
- the original request headers
- W3C trace context
11. Response handling
For a non-streaming response, the router reads the completed body and can use backend usage information for token accounting. For a streaming response, the router pipes bytes to the client while a stream meter observes the output. For non-streaming responses, the selected agent’s capacity slot remains occupied until the complete response finishes, fails, or is cancelled. For streaming responses, the current implementation releases the agent capacity slot and router forwarding slot after response headers arrive and streaming begins, while backend generation can continue. Engine-level running and waiting metrics therefore provide the more reliable view of active streaming work.12. Result accounting
The processor records:- routed or failed request counters
- tenant success or failure
- input and output tokens
- selected deployment
- policy step
- router-observed RTT
- updated SRTT and RTTVAR
Failure and retry behavior
Failures fall into different architectural categories.Non-retryable request errors
Structured request-level errors stop immediately. Examples include:- invalid parameters
- context-length violations
- daily output-token rejection
Retryable agent or backend errors
A retryable failure:- records the failed agent in the current policy step
- increments that step’s attempt count
- excludes that agent from the next selection in the same step
- advances to the next step when
max_triesis exhausted
Connection-level failures
When the router’s view of an agent connection appears stale or disconnected, Hivenet Router can:- discard the stale peer connection state
- retry the request path once without consuming the policy try budget
- return the failure to the normal retry and fallback process when the connection is still unavailable
Provider fallback
When every local step is exhausted, an eligible LLM request may use the configured external provider fallback. If provider fallback also fails, the request ends with a backend error.Backpressure layers
Hivenet Router has several independent limits.
All values are configurable.
The effective request deadline is still controlled by the router. A longer client or agent timeout cannot extend a shorter router deadline.
Storage architecture
Hivenet Router uses two BadgerDB instances.In-memory database
The in-memory database is recreated with the router process.
Agents repopulate these records when they reconnect.
Persistent database
The persistent database uses:
The default entry lifetime for normal disk records is:
Hot-path counter state
Universal request counters are updated in process through atomic values and small per-agent locks. They are flushed to persistent history:- every 30 seconds by default
- when an agent is removed
- during graceful router shutdown
Warm start
When an agent registers with a peer ID found in persistent history, the router restores:- successful and failed request baselines
- token counters
- disconnect and health-failure history
- SRTT
- RTTVAR
State persistence summary
A router restart does not restore queued or in-flight requests.Clients receive a connection failure or timeout and must decide whether the operation is safe to retry.
Health and removal lifecycle
The router health monitor runs every:
When the router removes an agent, it:
- records a disconnection
- flushes that agent’s universal history
- removes its Prometheus registration and snapshot series
- closes the libp2p peer
- deletes the session
- removes live metadata and counter state
Sampling and update cadence
A routing signal can contain the same cached snapshot several times when its push interval is shorter than the underlying sampler interval.
Observability architecture
The router is the main observability aggregation point.Prometheus
The router exposes:- registration and health
- routing outcomes
- policy fallback and exhaustion
- queue depth and wait duration
- per-agent counters and latency
- engine snapshots and histograms
- GPU, CPU, and memory values
- tenant usage and quotas
- HTTP server and provider-client metrics
Audit records
The HTTP audit middleware writes one structured record after each audited request. Records can include:- request and trace IDs
- tenant and dynamic key ID
- model
- status and error code
- input and output tokens
- selected agent or provider
- source IP
- request duration
Distributed tracing
The router and agents can export OpenTelemetry traces through OTLP. Trace context is propagated:Correlation
The most useful correlation values are:- application logs
- router and agent logs
- audit records
- Prometheus series
- Tempo traces
Hot reload and state consistency
Hivenet Router can reload authentication and policy files on:Policy reload
The router can reload:- one global policy file
- a directory containing a global default and per-model policies
Authentication reload
Static client and administrator providers are also replaced atomically. In-flight requests already using the previous provider continue normally. An invalid auth file leaves the previous provider active. Switching between static and dynamic client-authentication modes requires a restart.Dynamic registry
When dynamic client authentication is active:- the dynamic registry is preserved during SIGHUP
- only the administrator provider is reloaded
- the registry is lost on process restart
Configuration that still requires restart
Examples include:- agent JWT secret
- gRPC-derived router identity
- provider fallback credentials
- network listen addresses
- storage path
- process-level queue and concurrency limits
- switching static and dynamic authentication modes
Trust boundaries
Hivenet Router separates several credentials and trust relationships.
These boundaries should not be collapsed into one credential.
For example:
- a client key should not call administration routes
- an administrator key should not be placed in a chat client
- the agent JWT secret should not be used as an HTTP API key
- provider credentials should remain inside the router deployment
Architectural limitations
The current design does not provide:- active-active router clustering
- replication of dynamic API keys or queues
- automatic inference-backend deployment
- automatic model loading through the public API
- translation between OpenAI and Anthropic request schemas
- automatic verification of agent metadata
- one ranking strategy beyond
least-loaded - arbitrary public proxy access to backend endpoints
- durable recovery of in-flight requests
- automatic pricing, energy, or carbon-aware routing
Source layout
The main implementation areas are:Next steps
Configuration reference
Review router and agent flags, environment variables, defaults, and precedence.
Error codes
Understand failures from the HTTP API, routing system, agents, and backends.
Performance characteristics
Review bottlenecks, measurements, capacity limits, and benchmarking guidance.
Architecture overview
Return to the shorter conceptual explanation of the system.

