Distributed Mode
Distributed mode scales LocalAI across several machines. PostgreSQL holds the state and the node registry. Each worker attaches to the frontends over NATS, a WebSocket tunnel or P2P, and the frontends reach it by the route it has. The frontends broadcast messages to each other over PostgreSQL, and over NATS as well when the cluster has a NATS server. Unlike P2P and federation, distributed mode is for production deployments and Kubernetes. It gives you central management, health monitoring, and deterministic routing.
Distributed mode needs authentication and a PostgreSQL database. SQLite is not supported, because the node registry, the job store, and the other distributed state are PostgreSQL tables.
Architecture Overview


Frontends are stateless LocalAI instances. They receive API requests and route them to worker nodes with the SmartRouter. All frontends share state through PostgreSQL and reach each worker by the route it attached over (NATS, WebSocket or P2P).
Workers are generic processes that register themselves with a frontend. A worker has no fixed backend type. When a request arrives, the SmartRouter tells the worker to install the backend it needs, over the route the worker attached over.
Scheduling Algorithm


The SmartRouter uses idle-first scheduling with preemptive eviction:
- If the model is already loaded on a node, use it (per-model gRPC address).
- Drop any node without room to store the model on its models filesystem (see Disk headroom).
- If no node has the model, prefer nodes with enough free VRAM.
- When the model has a size estimate and no node has that much free VRAM, evict idle models on the one node where that makes room (fewest evictions first). The models that eviction protects (in-flight requests,
min_replicasfloors, pinned models and failover targets) are never evicted for it. Nodes that report no GPU memory at all (CPU-only workers) stay eligible, since their fit cannot be judged from VRAM. When nothing can make room, the request fails with503, aRetry-Afterheader andno node has enough free memory for model .... The model is never placed on a GPU node that is known to lack the room. The registry does not know the memory of each replica, so the plan charges each loaded replica an equal share of the node’s used VRAM; the worker’s next heartbeat reports the real figure. This strict fit does not apply when the estimate is read from a local model file (a GGUF file on the frontend). That estimate can be too high for some models, so it is advisory: the model goes to a node with that much free VRAM when there is one, and otherwise falls back as in step 5, without a refusal or an eviction for memory. The estimate uses the model’scache_type_kandcache_type_v. - A model with no size estimate (or an advisory one) falls back to idle nodes (zero models), then least-loaded nodes, then, if no node has capacity, evicts the least-recently-used model with zero in-flight requests to free a node.
- If all models are busy, wait (with a timeout) for a model to become idle, then evict.
The scheduler only plans an eviction while it chooses the node. The eviction runs after the frontend has claimed the load of the model on that node, and only if the model is still not loaded and the node still needs the room. A frontend that loses the claim to another frontend, or finds the model ready on another node, evicts nothing.
7. When two nodes fit equally well, the carrier weight breaks the tie (see Carrier weights). A node that a frontend reaches only over a data-limited public relay is a last resort.
8. Send the backend.install request, with the backend name and the model ID, to the worker. The worker starts a new gRPC process on a dynamic port.
9. The SmartRouter calls gRPC LoadModel on the model-specific port and records the result in the database.
Each model gets its own gRPC backend process, so one worker can serve several models at once (for example a chat model and an embedding model).
How workers attach, and the broadcast bus
A worker holds the routes that its operator gives it, and the frontends reach it on those routes. A worker can hold one route or, for NATS and WebSocket, both at once:
| Route | What it is | What you need |
|---|---|---|
NATS (nats) | A NATS broker. Frontends send control requests to the worker through it. | A NATS server, reachable from the frontends and the workers. |
WebSocket (tunnel) | The worker opens an outbound websocket tunnel to a frontend (/api/cluster/connect), and control requests and gRPC calls travel through it. | Nothing beyond the frontend. Workers need no inbound port. |
| P2P | The same tunnel, over a libp2p stream. See Workers over P2P. | A P2P invite. |
Request and reply between the frontends and the chat workers (the chat start, the replay of chat events, the background jobs of a turn) always go over the peer link between them, whatever route the workers use. See Request and reply between frontends and chat workers.
Workers never connect to PostgreSQL. A worker dials a frontend (or NATS) and nothing else. Only the frontends and the chat workers use PostgreSQL, for the shared state and the node registry, and as a broadcast bus: the channel on which a frontend tells the other frontends about job progress, gallery updates and cache hints.
The broadcast buses
The frontends and the chat workers broadcast to each other over two buses:
- PostgreSQL (
LISTEN/NOTIFY, a bus named pgbus). Every frontend and chat worker always listens on it. - NATS, when the cluster has a NATS server (the
nats.urlcluster setting, or--nats-url). Every frontend and chat worker that has it listens on it too.
Each broadcast goes on exactly one bus: on NATS when the cluster has a NATS server and the process that publishes is connected to it, on PostgreSQL otherwise. A message is never sent twice, so no subscriber sees it twice. Because every process listens on PostgreSQL, a process that lost NATS still reaches all the others.
A process that has a NATS server configured and cannot reach it does not hear what the other processes publish on NATS. It keeps listening and publishing on PostgreSQL, and its /readyz answers 503 with the status unavailable and the reason, so a load balancer stops sending it traffic. When NATS is back, it publishes on NATS again and /readyz answers 200. Messages that cross a change of bus are not ordered, so the shared state of the process (the replicated maps and the failover state) reads its tables again when the bus changes and when a bus reconnects. A NATS server that is down when a frontend starts does not stop the start: the frontend keeps retrying to connect and is not ready until it is connected.
How a deployment starts
A NATS server is optional. A frontend reads the NATS address from the nats.url cluster setting, else from its --nats-url flag (LOCALAI_NATS_URL). The first frontend that starts with the flag copies the address into the setting, without a user name, a password or a query string, so that every frontend uses the same server. A frontend whose --nats-url names another server than the stored one refuses to start and names both addresses.
- With PostgreSQL only (no NATS address in the flags and none stored), PostgreSQL is the only broadcast bus, and the workers attach over WebSocket or P2P. This has fewer parts to run, and workers behind NAT or a firewall need no open port. See Operational limits for the numbers.
- With a NATS address, the broadcasts go over NATS while a frontend reaches it, and the frontends reach the workers that hold NATS as well as the workers that hold a tunnel. Use NATS for large clusters, many frontends, and high-rate or large broadcasts.
A frontend reads the NATS address at start. To add a NATS server or to move to another one, store the address (see Save a NATS address) and restart the frontends. A NATS server that is down when a frontend starts does not stop the start: the frontend keeps retrying to connect, and it is not ready until it is connected.
The Workers page shows the broadcast bus of the frontend that serves the page in a pill under its title (NATS connected · 2 frontends, or PostgreSQL). The Cluster settings button opens a side sheet with the live frontends, the NATS address settings, the carrier weights and the joining choice. The same form is the Cluster group of Settings, which shows only when distributed mode is on.
How a frontend picks the route of a worker
Every worker reports in its heartbeat the routes it was given, the routes it holds now, and why it does not hold the others. The frontends route by that report only. For each call to a worker, the frontend uses the route that last worked for that worker, else NATS when the worker holds NATS and has an address, else the tunnel, among the routes that the worker holds and that the frontend has. A call goes to the next route only when the first one shows that the worker received nothing (no responder on NATS, no tunnel). It never goes to another route after a timeout or an answer of the worker, so a call is never run twice. Unloading a model and deleting its files reach each worker on its own route. A worker holds at most one tunnel, over a websocket or over P2P. The health monitor judges each worker by the routes it holds, never by a setting of the cluster: see Node health and routes.
An MCP tool call that does not name an agent worker goes to an agent worker on NATS first (the queue group), and to an agent worker that holds a tunnel when no agent worker on NATS takes it. A call that names an agent worker goes on the routes of that worker: the NATS subject of the node (mcp.<node>.tools.execute, mcp.<node>.discovery), or its tunnel.
The Workers page lists every machine of the cluster in one roster, with a chip for each connection it holds: NATS, WebSocket (the tunnel over a websocket) or P2P, each with its state. A P2P chip says the path (direct, hole-punched or relayed, with the round trip when it is known) and is marked Limited when the relay limits the data or the time of a connection. A connection that fails is a warning chip with the reason the worker gave. The inspector beside the roster shows the health of each connection of the chosen worker. A model-split worker is a row of the same roster, marked Model-split.
Prerequisites
- PostgreSQL (with the pgvector extension recommended for RAG). It holds the node registry, the job store, auth, the cluster settings, and the shared state. It is also a broadcast bus between the frontends, and the only one without NATS, so size it for that (see Operational limits).
- A NATS server, only if you want workers on NATS or NATS for the broadcasts. A deployment can start without one and add it later.
- All services must be reachable from each other, through the network or the configured URLs.
- Every frontend and chat worker needs a peer address that the other frontends and chat workers can reach, with or without NATS. It is found at start from the route to the database; set
LOCALAI_PEER_ADDRESSwhen that one is wrong (see Peer link). A process without one answers503on/readyz. - A session-level
LISTENconnection from every frontend and chat worker to PostgreSQL, with or without NATS. A connection pooler in transaction mode (for example PgBouncer in its default mode) breaksLISTEN, and a frontend then fails to start. Point the frontends directly at PostgreSQL, or use a session-mode pool.
Quick Start with Docker Compose
The easiest way to try distributed mode on one machine is the provided Docker Compose file:
This starts PostgreSQL, NATS, a LocalAI frontend, and one worker node. The frontend has a NATS URL, so the frontends broadcast over NATS and the worker holds NATS and the WebSocket tunnel. When you send an inference request, the SmartRouter installs the needed backend on the worker and loads the model. See the file for GPU support, shared volumes, and more workers.
To try PostgreSQL as the only broadcast bus, remove the nats service, the depends_on entries that name it, and every LOCALAI_NATS_URL line from the file. The frontends then broadcast over PostgreSQL, the worker holds only its WebSocket tunnel, and it needs only LOCALAI_REGISTER_TO and the registration token. The frontend sends chat starts to the chat worker over the peer link, as it does with NATS (see Request and reply between frontends and chat workers).
The compose file starts PostgreSQL, NATS, Garage as S3-compatible object storage (with a one-shot step that creates its bucket and access key), a frontend, a model worker, an agent worker and a chat worker. The frontend and the chat worker store the chat files in Garage, and the frontend sends unattended chat turns to the chat worker. Its credentials are examples: change them, and the rpc_secret in examples/distributed/garage.toml, for anything beyond a local test.
Use docker-compose.distributed.yaml for quick local testing. For production, run PostgreSQL (and NATS, if you use it) as managed services, and run frontends and workers on separate hosts.
Frontend Configuration
The frontend is a standard LocalAI instance with distributed mode enabled. These flags are added to the local-ai run command:
| Flag | Env Var | Default | Description |
|---|---|---|---|
--distributed | LOCALAI_DISTRIBUTED | false | Enable distributed mode. Needs PostgreSQL. NATS is optional. |
--instance-id | LOCALAI_INSTANCE_ID | auto UUID | Unique instance ID for this frontend |
--peer-address | LOCALAI_PEER_ADDRESS | (found from the route to the database) | host:port at which the other frontends and chat workers dial this one. A frontend publishes it so that a replica that does not hold the connection of a worker can reach the replica that does, and so that chat starts, chat replay and background jobs reach it. A frontend or chat worker that has none is not ready (/readyz answers 503). Set it when the address found from the route to the database is not the one the other frontends should use. The link carries the credential of the replica and every request that it relays, so by default it is clear text. Use --peer-tls when the replicas sit behind TLS. |
--peer-tls | LOCALAI_PEER_TLS | false | Dial the other frontends over wss and not ws. Every frontend must then be reachable over TLS at the address it publishes with --peer-address, for example behind a reverse proxy that terminates TLS. A frontend that serves the API over TLS itself (--tls-cert, --tls-self-signed) dials wss without this flag. LocalAI warns at start-up when it publishes an address that is not on the local host and the link is clear text. |
--peer-tls-ca | LOCALAI_PEER_TLS_CA | (system roots) | PEM file with the certificate authority that signs the certificate of the other frontends. Use it with a private CA. See Peer link. |
--nats-url | LOCALAI_NATS_URL | (empty) | NATS server URL (e.g., nats://localhost:4222). Optional. With a URL, the frontends broadcast over NATS while they reach it, and reach the workers that hold NATS. Without one, PostgreSQL is the only broadcast bus. The URL is copied into the nats.url cluster setting. See How a deployment starts. |
--registration-token | LOCALAI_REGISTRATION_TOKEN | (empty) | Optional shared token that a worker may use to register. It is used for registration only: after that a worker holds its own credential, and no other node route accepts the shared token. It also seeds the token that authenticates the data plane between the frontends and the workers (see Join tokens). Workers can join with join tokens instead, so you can leave it empty |
--registration-require-auth | LOCALAI_REGISTRATION_REQUIRE_AUTH | false | Fail startup when distributed mode is enabled but the registration token is empty (node endpoints and worker file-transfer would otherwise be unauthenticated) |
--distributed-require-auth | LOCALAI_DISTRIBUTED_REQUIRE_AUTH | false | Umbrella switch. Implies both --nats-require-auth and --registration-require-auth - one knob to lock down the NATS bus and the registration/file-transfer layer. Set this in production instead of the two granular flags. |
--auto-approve-nodes | LOCALAI_AUTO_APPROVE_NODES | false | Auto-approve new worker nodes (skip admin approval) |
--distributed-shared-models | LOCALAI_DISTRIBUTED_SHARED_MODELS | false | Assert that every node mounts the same models directory at the same path (a shared volume). When true, the router skips file staging entirely and workers load models directly from the shared path instead of re-downloading them. See Shared models directory. |
--distributed-disk-headroom-check | LOCALAI_DISTRIBUTED_DISK_HEADROOM_CHECK | true | Reject worker nodes that lack free space to store the model, at scheduling time rather than partway through staging. When false, node selection ignores free disk; the check still runs and warns when it would have rejected every node. Also toggleable at runtime via the distributed_disk_headroom_check setting. See Disk headroom. |
--distributed-chat-workers | LOCALAI_DISTRIBUTED_CHAT_WORKERS | false | Send the turns of triggers, agent jobs and connector messages to chat workers. When no chat worker listens, the turn runs on this frontend. |
--chat-worker | LOCALAI_CHAT_WORKER | false | Run this instance as a chat worker instead of a frontend for the unattended chat runs. |
--chat-worker-max-turns | LOCALAI_CHAT_WORKER_MAX_TURNS | 32 | On a chat worker, the most turns it runs at once. 0 means no limit. |
--chat-start-timeout | LOCALAI_CHAT_START_TIMEOUT | 30s | How long a frontend waits for a chat worker to start a turn, and how long the worker gives the start. |
--auth-enabled | LOCALAI_AUTH | false | Must be true for distributed mode |
--auth-database-url | LOCALAI_AUTH_DATABASE_URL | (required) | PostgreSQL connection URL |
--backend-install-timeout | LOCALAI_NATS_BACKEND_INSTALL_TIMEOUT | 15m | How long the frontend waits for a worker to acknowledge a backend install before considering the request stalled. It applies to every route. Raise it when workers pull large backend images over slow links. If a worker takes longer than this, the operation shows as “still installing in background” in the admin UI and clears once the worker finishes. |
--backend-upgrade-timeout | LOCALAI_NATS_BACKEND_UPGRADE_TIMEOUT | 15m | Same as the install timeout, applied to backend upgrades (force-reinstall). |
--model-load-timeout | LOCALAI_NATS_MODEL_LOAD_TIMEOUT | (derived from checkpoint size) | Pins the deadline for the LoadModel gRPC call the frontend issues to a worker. Leave it unset: by default the deadline is derived from the checkpoint’s on-disk size (see below), which is what the worker actually spends its load time reading. Set it only to pin a specific budget: the value is then used verbatim, including when it is shorter than the derived one, so an operator who wants fast failure gets it. |
| (env only) | LOCALAI_MODEL_LOAD_STALL | 5m | How long a running cold load may make no progress (no new phase, file or bytes) before a request starts a load of the same model on another node that matches the model’s rule, instead of waiting for it. Set to 0 to always wait for the running load. See Requests for a model that is still loading. |
| (env only) | LOCALAI_MODEL_LOAD_WAIT | 60s | How long an inference request waits for a model that is still cold-loading onto a worker before it is answered with 503, a Retry-After header and live staging progress. The request is served the moment the model becomes ready, so a model already most of the way staged needs no client retry. Set to 0 to wait as long as the load takes: only safe when no ingress or load balancer with an idle timeout sits in front. See Requests for a model that is still loading. |
--node-heartbeat-checkpoint | LOCALAI_NODE_HEARTBEAT_CHECKPOINT | 60s | Minimum gap between durable heartbeat writes for a worker node. A beat that only carries a fresher timestamp is kept in memory until this interval elapses instead of being written to PostgreSQL; every reported field is compared against the value last written rather than merely tested for presence, so a node’s first beat, a changed total VRAM / total disk / GPU vendor, and a free VRAM / RAM / disk reading that has moved more than 256 MiB from the written value all still write immediately, and a node that is not active is never suppressed. Set it below the worker’s --heartbeat-interval to restore a write per beat. See Heartbeat writes and stale-node detection. |
--stale-node-threshold | LOCALAI_STALE_NODE_THRESHOLD | 5m | How long a node may go without a durable heartbeat before the health monitor marks it offline. Because --node-heartbeat-checkpoint holds back a beat that only carries a fresher timestamp, this has to stay comfortably wider than that interval: raising the checkpoint without raising this marks healthy, beating nodes offline. Neither the per-model gRPC health check nor request-time failure reads last_heartbeat, so neither is affected by this knob. See Heartbeat writes and stale-node detection. |
--drain-timeout | LOCALAI_DRAIN_TIMEOUT | 10m | How long a drained worker keeps the models it serves while their replacements load on other nodes. After it, what is left on the node is removed. A drain request can set its own deadline with ?timeout=. |
--model-config-resync-interval | LOCALAI_MODEL_CONFIG_RESYNC_INTERVAL | 30s | How often each frontend compares its model configs with the shared models directory, to apply a change whose NATS message it missed. A frontend that missed a message serves the old config for at most this long. See Model configs across frontends. |
--expose-node-header | LOCALAI_EXPOSE_NODE_HEADER | false | When enabled, inference responses carry an X-LocalAI-Node header with the ID of the worker node that served the request. Coverage spans the OpenAI-compatible endpoints (chat completions, completions, embeddings, audio transcriptions, audio speech / TTS, image generations, image inpainting), the Jina rerank endpoint (/v1/rerank), the VAD endpoints (/v1/vad, /vad), and the Anthropic Messages (/v1/messages) and Ollama (/api/chat, /api/generate, /api/embed) shims. Useful for debugging, observability and load-balancer attribution. Off by default: the node ID reveals internal cluster topology and should not be exposed on a public endpoint. Best-effort: under heavy concurrency for the same model across multiple replicas, the header may reflect a recent routing decision rather than this exact request’s. Acceptable for observability and debugging. |
Add-ons
Every local-ai run process is its own add-on owner by default. With several
frontend replicas, run the owner as one separate workload with its own volume, and
start the frontends with --addons-role=frontend, so they forward add-on requests
to it and hold no add-on state. The library sources and the backend library
installs also go through the owner: a frontend follows the owner’s sources and
installs backends on its own node. See
Running the owner as its own workload.
The owner must join distributed mode with the same --nats-url, registration token
and PostgreSQL database as the frontends. Then it takes part in the leader locks and
sends model loads to the workers. An owner without these settings loads models in its
own process (backend not found) and polls the connectors next to the leader
frontend (Slack messages answered twice). See
The owner in distributed mode.
The model load deadline scales with the checkpoint
The LoadModel deadline starts after the backend is installed and the model files are staged, so it covers only the worker backend’s own checkpoint read and pipeline init. That work is proportional to the bytes on disk, which makes any fixed deadline a model-size cliff rather than a timeout: a 70 GB video checkpoint on a Jetson Thor worker failed reproducibly against the old fixed 5m default (rpc error: code = DeadlineExceeded after 953.5s of wall clock, roughly 11m of which was backend install and staging), and simply raising the constant would only move the cliff to the next larger model while making a genuinely wedged small model hang for the whole inflated duration.
So the deadline is derived per model:
budget = 5m + 20s per GiB of checkpoint, capped at 6h| Checkpoint | Derived budget |
|---|---|
| 2 GB | 5m40s |
| 70 GB | 28m20s |
| 600 GB | 3h25m |
The per-GiB rate is deliberately pessimistic (it corresponds to reading weights at about 54 MB/s, below what any supported storage sustains) because the two errors are not symmetric: a budget that is too long costs only failure latency on a load that was going to fail anyway, while a budget that is too short causes a guaranteed false failure on a load that was perfectly healthy.
The size is measured from the model files on the frontend’s disk, over the same set of paths that get staged to the worker. If those files are not present locally (a backend handed a bare HuggingFace repo id fetches its own weights on the worker) there is nothing to measure and the budget stays at the plain 5m default. Pin LOCALAI_NATS_MODEL_LOAD_TIMEOUT for those models if their load is slow.
A model can set its own budget with load_timeout in its config (a duration such as 40m). It wins over both the derived budget and LOCALAI_NATS_MODEL_LOAD_TIMEOUT for that model:
When the budget is exceeded, the error names the phase, the budget, where the budget came from (the model’s load_timeout, LOCALAI_NATS_MODEL_LOAD_TIMEOUT or the checkpoint size) and the settings that change it, instead of surfacing a bare context deadline exceeded.
Load phases and their deadlines
A cold load is judged by its progress, not by one deadline for the whole load. It runs in phases, and each phase has its own budget. The clock restarts when the next phase starts, so the time an earlier phase took never counts against a later one:
Phase (state) | What runs | Budget |
|---|---|---|
pending | Node selection and replica allocation. | The starting budget of the load, max(backend-install-timeout + model-load-timeout + 5m, 25m), 25m with the defaults. |
installing | The worker installs the backend, starts its process and waits for the first gRPC health check. | LOCALAI_NATS_BACKEND_INSTALL_TIMEOUT + 1m (16m with the defaults), and never more than the starting budget. The install’s own timeout fires first, so its error reaches the caller. |
staging | Model files go to the worker. | A 5-minute stall window that restarts every time staging does real work (see below). |
loading | The backend’s LoadModel call. | The model’s load_timeout, else LOCALAI_NATS_MODEL_LOAD_TIMEOUT, else the budget derived from the checkpoint size (see above). A backend that reports load progress extends it while the progress moves; see Load progress from the backend. |
When the LoadModel call returns, the load is done and the job ends. The phase, when it started and its budget are on the load job, in the 503 body and in GET /api/models/{id}/load-status (state, phase_started_at, phase_budget_seconds), and the chat shows them while a reply waits for the model.
When a phase runs out of budget, the load fails with an error that names the phase and its budget (for example the loading phase did not finish within its budget of 28m20s). The worker stops the backend process of that load, so a backend that spins inside LoadModel does not keep the node busy, and the job is released: a request can then load the model on another node at once, and on the same node after the stop window.
The worker does not use the I/O or the CPU time of the backend process to extend a deadline. Both are unreliable signals: a checkpoint on a network filesystem reads in bursts the worker cannot see, and a thread that spins on the CPU is not progress. The worker reports one hint from the I/O of the process on Linux, weights_read, which is true when the process read from storage and then stopped reading for a while. It only helps to read a load that is stuck after its weights were read, and it changes no deadline.
The phase state lives on the load job row in the database, so every frontend reports the same phase (the job row is shared state; the frontend that owns the load writes it).
Load progress from the backend
A backend can report how far its LoadModel has got through the optional LoadProgress gRPC call. While a load runs, the worker asks for it every 2 seconds and sends the value to the frontend with each renewal of the load. Progress that advances counts as progress of the loading phase: it pushes the deadline out by the full phase budget. Progress that stops moving does not, so a backend that stops at 99% still fails when the phase budget runs out after the last advance. A backend that does not implement the call answers UNIMPLEMENTED and keeps working; its load has the plain phase budget.
The value is in load_progress (percent) in the 503 body and in GET /api/models/{id}/load-status, and the chat shows it as a progress bar while a reply waits for the model.
| Backend | Reports load progress |
|---|---|
llama-cpp (and its CPU and GPU variants) | Yes: llama.cpp’s own load progress, over the text model, a draft or MTP model and the multimodal projector. |
| Every other backend | No: the loading phase has its budget only. |
The cold-load lock ceiling
The router also bounds how long a single cold load may hold the per-model advisory lock, so a worker that dies mid-install cannot pin every other replica’s request for that model. That bound is the sum of the phase budgets above, and it is based on progress rather than on wall-clock time: no phase can go silent for longer than its budget.
While model files are staging, however, the deadline extends every time staging does real work, and expires only once staging has been silent for a 5-minute stall window. Real work means uploaded bytes, and also the resumable-upload verify phase: when a shard is already present on the worker from an earlier attempt, the frontend HEADs it and hashes the local copy to confirm it matches, then skips the transfer. That phase uploads nothing at all, on a 70 GB model resuming with 56 GB already staged it ran for six-plus consecutive minutes at ~45s per shard, so hashing counts as progress too. Otherwise a resumed transfer would be mistaken for a wedged one. Staging time is a function of checkpoint size and available bandwidth, not a constant: a 70 GB model at 26 MB/s needs about 45 minutes, and a 600 GB checkpoint needs hours. A fixed ceiling would therefore be a model-size cliff, every increase just moves the cliff to the next larger model. Extending on progress means a large model transfers for as long as it legitimately needs, while a worker that dies mid-transfer still releases the lock within the stall window.
An absolute cap of 24h ends the hold even if progress keeps arriving, so a degenerate peer trickling a few bytes at a time, or a backend that reports a tiny load progress forever, cannot pin the lock forever. No configuration is needed for either value; both are sized well above any legitimate transfer.
Requests for a model that is still loading
A cold load in distributed mode is a long-running background job: install the backend, stage multi-GB model files to the worker, then load the checkpoint. Staging a 35.7 GB GGUF onto a fresh worker takes roughly twenty minutes on a fast LAN, far longer than any HTTP request can be held open.
So the load does not run on the request. The first request for an unloaded model chooses a node, then claims a durable model load job for the model on that node (that claim takes milliseconds and is the only part that holds the job’s advisory lock), and the job then runs in the background on the frontend replica that claimed it. Every other request for the same model, on any replica, attaches to that job as a waiter:
- It is served the moment the model is ready, with no client-side retry. A model already 90% staged usually needs no second request.
- Load jobs are kept per model and node. A slow load on one node never blocks a load of the same model on another node: the replica reconciler skips the nodes that already run or hold a load of the model, chooses a different node for each load it needs, one after the other, and then runs the loads in parallel, up to what
min_replicasneeds, and counts the loads in progress toward the floor. A request waits on the load that is furthest along on a node that matches the model’s rule. It starts a load on another matching node only when there is no such load, or when that load made no progress (no new phase, file or bytes) forLOCALAI_MODEL_LOAD_STALL(default5m). A checkpoint load reports no progress while the backend reads its weights unless the backend reports load progress (see Load progress from the backend), so a load that stays inloadinglonger than that without it counts as stalled. When no other node can take the model, the request keeps waiting on the stalled load. - It is also served by any ready replica of the model on a node that matches the model’s rule, checked on every poll (every 2 seconds). When another node finishes first (for example a replica the reconciler loaded), the request is served from it and stops waiting; the job it waited on keeps running.
- It never starts a duplicate load and never blocks on the database lock. (Before this split, concurrent requests blocked on
pg_advisory_lockfor the whole load and were killed by the PostgreSQL role’sstatement_timeout(SQLSTATE 57014) so from the operator’s seat the model simply never loaded.) - If the load fails, the waiter gets the real cause (
worker out of disk), not an anonymous timeout. - If the client disconnects, the load keeps going. It belongs to the job record, not to the request.
- The owner of a job holds a 30 second lease, which it renews on every heartbeat. The database clock decides whether a lease has expired, so a frontend with a wrong clock cannot expire a live lease or keep a dead one. If an owner cannot renew for a whole lease, it stops its own load.
- If an owner dies, its job is marked failed once the lease runs out, with or without a new request. A request that arrives then reads the cause. The model is held for a 2.5 minute stop window, because remote work may still run. After that the next request starts a new attempt. No manual cleanup is needed.
- A failure that is known to have ended the remote work (an error from the backend, or a failure before a node was chosen) is kept for 15 seconds only, so every waiter reads the same cause and the next request can retry.
- Each attempt has its own generation. If a job is replaced, the old owner notices at its next heartbeat and stops its load. Its late writes to the job and to the replica table are rejected.
- If the job table cannot be read, a cold load fails instead of running without a job. Models that are already loaded keep serving, because routing to a loaded replica does not read the job table.
When the wait budget (LOCALAI_MODEL_LOAD_WAIT, default 60s) runs out, the request is answered with 503, a Retry-After header, and a body that says exactly where the load is:
The error envelope keeps OpenAI clients working unchanged; loading is additive, so a client that understands it renders progress instead of an error. eta_seconds is derived from the job’s own observed transfer rate and is omitted rather than guessed until enough bytes have moved for that rate to mean anything, a confidently wrong ETA on a twenty-minute wait is worse than none. state is one of pending (choosing a node), installing, staging (transferring files) or loading (the worker is reading the checkpoint). When the model loads on several nodes at once, the body, load-status and the operations list of the UI report the load that is furthest along: a running load before a failed one, then the later phase, then the higher progress.
The chat UI renders this state inline and retries automatically once the model reports ready. Poll GET /api/models/{id}/load-status for the same loading object at any time. When {id} is a model alias, it reports the load of the target model, and model in the response names the target. The user’s model allowlist applies to the alias name, as it does for inference. When {id} is a failover chain, it reports the load of the chain target that is furthest along, or of the pinned target when the chain is pinned. The allowlist applies to the chain name. As for inference, load-status and load-cancel ignore a :latest suffix when they look up the model, but the allowlist applies to the name as sent. When the user’s model allowlist does not include the model, load-status answers 404, the same as for a model with no load.
An agent chat turn (the chats and agents of the web UI, triggers, jobs and connectors) waits for the load as well. Each 503 with model_loading, and each 503 or 429 with a Retry-After header, makes the turn wait for the Retry-After time (at least 1 second, at most 60 seconds, 5 seconds when the header is absent) and send the request again. These answers do not count as model failures. A spent quota (429 with quota_exceeded) and a model held after a failed load (503 with model_loading and a loading.state of failed) still end the turn at once, with the cause of the failure. The turn waits at most LOCALAI_CHATS_MODEL_LOAD_WAIT in total (default 15m). After that it ends with the reason “the model is still loading” when the last answer was a load in progress, and you can try again later. When the last answer was another 503 or 429 (no node with room for the model, a model upgrade, a model at capacity), the turn ends with the message of that answer instead. Other 5xx answers still count as failures, and four in a row end the turn.
A frontend replica that dies mid-load does not wedge the model: the job row carries a lease, and a job whose lease ran out is failed and then released. The lease is renewed on a timer, not on byte progress, because a checkpoint load legitimately transfers zero bytes for many minutes.
The worker bounds the work it runs
The frontend owns the job row, but the real work runs in a backend process on a worker. The worker therefore watches each load too. A load is an operation named by the job’s generation:
- The install request carries the operation id and the longest the load may run, as a duration, so a worker clock that is wrong changes nothing. The backend starts in its own process group.
- The frontend renews the operation every few seconds and completes it when the load finishes. The worker kills the whole process group when no renewal arrives for 90 seconds, or when the deadline passes. A backend that already reports
READYis never killed: a lost completion message must not destroy a model that serves. - A stop names the operation, the process key and, when known, the address and process instance. The worker refuses unless they all match its own records. There is no fallback to “any running backend”. A stop for a load that already finished leaves the serving model alone.
- A worker that is killed cannot stop its backends. It records each backend’s process group in a small file under its data directory, and the next worker kills every group listed there before it serves (Linux and Windows; the start time of the leader guards against a recycled pid; Windows has no process groups, so there the worker kills the recorded process and the processes it started). A new incarnation, reported on the next heartbeat, then confirms the failed loads on that node. The worker also skips a gRPC port that something already listens on, and a readiness answer only counts while the worker’s own backend process is alive.
- If the worker answers a renewal with “unknown operation” three times in a row, the frontend fails the load at once instead of waiting for the load budget. The worker lost the operation, so the work is gone.
When a load fails after remote work may have started (a timeout, a cancel, a lost lease), the owner stops the operation immediately. An acknowledged stop shortens the hold to the 15 second report window. A silent worker keeps the hold at the stop window (2.5 minutes), and the reconciler retries the stop on every pass until the worker answers or the window ends. Nothing needs manual cleanup.
| Setting | Value | Meaning |
|---|---|---|
| Lease TTL | 30 s | How long a job’s lease lasts after each renewal |
| Worker kill TTL | 90 s | No renewal for this long: the worker kills the operation |
| Stop window | 150 s | How long a failed load holds the model if the worker never confirms |
| Report window | 15 s | How long a failure with confirmed-ended work is kept |
A failed job holds its node, not the whole model. A request for a model whose only matching nodes are held answers 503 with Retry-After set to the seconds until the hold ends, and the real cause in the body; a matching node without a hold can take a new load at once.
Cancelling a load
POST /api/models/{id}/load-cancel (admin only) cancels one load attempt. The body names the exact attempt, as GET /api/models/{id}/load-status reports it:
| Status | Meaning |
|---|---|
200 | state: stopped (the worker confirmed) or state: gone (no such load any more, even when another load of the model runs, for example on another node) |
202 | state: stopping. The cancel is recorded and the stop is pending. The model is released after retry_after seconds regardless. |
400 | The body is not {"job_id": "..."} |
404 | Unknown model, or the server is not distributed |
409 | A different attempt replaced the one named on its node while the cancel ran. The body carries its current_job_id. |
When {id} is a model alias, the load of the target model is cancelled. The load is shared, so this also affects requests that use the target or another alias of it. When {id} is a failover chain, the attempt named by job_id is cancelled under whichever target has it. The chain can then try its next target, which can start another load.
The call is idempotent. A repeat retries the stop and never extends the hold. A load that has not been placed on a node yet can be cancelled too. Unloading a model on a node, draining a node, and removing a node all cancel the loads placed there through the same stop path, and an unload still unloads the loaded replicas. The replica rows of a cancelled attempt are removed as soon as the worker confirms the stop. The cancel_model_load tool of the assistant calls the same service.
load-status also reports job_id, lease_expires_in, cancel_requested, last_error, stopping, stop_deadline and retry_after. A database error is a 503, never an empty answer.
Rolling upgrades
Upgrade the frontends first. The first frontend of this version that starts moves the key of the model_load_jobs table from the model alone to the model and the node, keeping the rows. An older frontend that still runs during the upgrade claims a model without naming a node, so it does not see the loads of a newer frontend on a node, and the two may load the model on the same node once; finish the frontend upgrade before relying on per-node loads. A worker that predates operations ignores the new request fields and does not report reports_operations. The frontend then treats the node as legacy: it cannot confirm a stop, so a failed load holds the model for the 45 minute load deadline, as it did before leases existed, and never longer. For such a node the stop, including a cancel, is sent by exact process address, never by model name. If the address is not known, no stop is claimed, and the model is held for the 45 minutes. A new worker that gets an install from an older frontend tracks it as an anonymous operation: it kills it at its deadline only, never for missing renewals.
Backend upgrades need workers that serve backend.upgrade. A frontend never falls back to a forced backend.install for a worker that does not serve the upgrade subject. Such a worker fails the upgrade with an error that says the worker is too old. The node stays healthy, and a queued upgrade for it waits, without counting a failed attempt, and is tried again every 15 minutes. This is a hard break for old workers: upgrade the workers with the frontend.
A worker keeps its backend build until the new one starts. On backend.upgrade the worker stops the processes of the backend, installs the new build, and starts it once under a process of its own, with the same readiness check (30 seconds) as a model load. Only when it answers does the worker delete the previous build. When it does not, the worker puts the previous build back and registers it. In both cases it then starts the processes it stopped again, on the build that is in place, with no model loaded (the next load uses them). None of this talks to NATS, so it works the same on a worker that holds only a tunnel.
The answer of the worker says what happened, on every route (NATS, and the tunnel over a websocket or P2P): code (the error_key of the step that failed), rolled_back, verified (the new build answered), cause (the last output of a build that did not start, at most 512 bytes), and restarted_process_keys. The frontend keeps the outcome of each node: in the job status, each entry of nodes has a status (success, error, rolled_back, unconfirmed or queued) and an error_key. The job has rolled_back: true when every node that failed rolled back. A rolled back upgrade is not retried by the reconciler, because the same build would fail the same way.
An upgrade whose reply never arrives (a timeout, or a tunnel that drops after the worker took the request) is unconfirmed: it is not reported as failed or as updated, the job has unconfirmed: true, and the queued intent stays until the reconciler or a check of the node settles it.
The new reply fields are a hard break too: frontend and workers must run the same version. A frontend reads an older worker’s failed upgrade as unknown.
Broadcast size limit
A broadcast is a message that goes to every frontend replica, such as a job progress event or a gallery update. Every carrier now refuses a broadcast with a payload above 8 MiB. The call fails with ErrPayloadTooLarge, and nothing is sent. The limit is the same for every carrier, so a deployment keeps its behavior when the carrier changes.
This matters only if your NATS server sets max_payload above 8 MiB. The default of the NATS server is 1 MiB, and a message above the server limit was always refused. Keep max_payload at 8 MiB or lower.
NATS JWT authentication (recommended for production)
By default, NATS connections are anonymous: any client that can reach port 4222 may publish control-plane subjects such as nodes.<id>.backend.install. Enable JWT auth to scope workers to their own node subjects and give the frontend a dedicated service credential.
| Flag | Env Var | Description |
|---|---|---|
--nats-account-seed | LOCALAI_NATS_ACCOUNT_SEED | Account signing seed (SU...). The frontend mints a per-node user JWT at registration (nats_jwt in the register response). |
--nats-service-jwt | LOCALAI_NATS_SERVICE_JWT | User JWT for the frontend (and optional fallback for agent workers) to publish install/upgrade and related subjects. |
--nats-service-seed | LOCALAI_NATS_SERVICE_SEED | User signing seed (SU...) paired with the service JWT. |
--nats-worker-jwtttl | LOCALAI_NATS_WORKER_JWT_TTL | Lifetime of minted worker JWTs (default 24h). |
--nats-require-auth | LOCALAI_NATS_REQUIRE_AUTH | Fail startup if JWT credentials are missing when distributed mode is enabled. |
NATS TLS / mTLS (optional)
Use tls:// in --nats-url / LOCALAI_NATS_URL for encrypted transport. When the server uses a private CA or requires client certificates, set:
| Flag | Env Var | Description |
|---|---|---|
--nats-tlsca | LOCALAI_NATS_TLS_CA | PEM file to verify the NATS server (private CA) |
--nats-tls-cert | LOCALAI_NATS_TLS_CERT | Client certificate for NATS mTLS |
--nats-tls-key | LOCALAI_NATS_TLS_KEY | Client private key (required with --nats-tls-cert) |
The same env vars apply to backend workers and local-ai agent-worker. If the server cert is already trusted by the OS, tls:// alone is enough.
Worker register response (when minting is enabled and the node is approved):
Workers connect with that JWT and seed automatically (shown once; store securely). Override with LOCALAI_NATS_JWT / LOCALAI_NATS_USER_SEED if needed. Set LOCALAI_NATS_REQUIRE_AUTH=true on workers when the bus requires credentials.
When LOCALAI_NATS_REQUIRE_AUTH=true and no static credentials are provided, a worker that registers while still pending admin approval keeps re-registering (with backoff) until an admin approves it and the frontend mints its JWT - it does not start unauthenticated. This retry is bounded: if the node is never approved (or no credentials are minted) after a large number of attempts, the worker exits non-zero so the failure is visible (a crash-looping or failed worker) rather than hanging silently. Minted worker JWTs are also refreshed automatically before they expire (the worker re-registers at ~75% of the JWT lifetime), so long-running workers survive past LOCALAI_NATS_WORKER_JWT_TTL; the NATS connection picks up the new JWT on its next reconnect. If refresh fails persistently, the worker exits (to restart and re-acquire) rather than drifting toward an expired, unrenewable JWT. Statically configured (LOCALAI_NATS_JWT) and service (LOCALAI_NATS_SERVICE_JWT) credentials are used as-is and not refreshed.
Generate operator/account material with scripts/nats-auth-setup.sh (requires nsc). The frontend user it creates may publish and subscribe on the subjects the frontends use for the gallery, caches, state, chats and the Open Responses cancel (responses.>). Configure the NATS server with account resolver JWTs before enabling LOCALAI_NATS_REQUIRE_AUTH.
LOCALAI_AUTH (HTTP users/sessions) and NATS JWTs are separate: end-user API keys do not connect to NATS. HTTP registration still uses LOCALAI_REGISTRATION_TOKEN.
Optional: S3 Object Storage
For multi-host deployments where workers don’t share a filesystem, S3-compatible storage enables distributed file transfer (model files, configs):
| Flag | Env Var | Default | Description |
|---|---|---|---|
--storage-url | LOCALAI_STORAGE_URL | (empty) | S3 endpoint URL (e.g., http://garage:3900) |
--storage-bucket | LOCALAI_STORAGE_BUCKET | localai | S3 bucket name |
--storage-region | LOCALAI_STORAGE_REGION | us-east-1 | S3 region |
--storage-access-key | LOCALAI_STORAGE_ACCESS_KEY | (empty) | S3 access key |
--storage-secret-key | LOCALAI_STORAGE_SECRET_KEY | (empty) | S3 secret key |
--storage-accept-blob-backend | LOCALAI_STORAGE_ACCEPT_BLOB_BACKEND | (empty) | Accept a planned switch of the Files blob backend to filesystem or objectstore. Set it for one start only. See Shared filesystem for Files |
When S3 is not configured, model files are transferred directly from the frontend to workers via HTTP - no shared filesystem needed. Each worker runs a small HTTP file transfer server alongside the gRPC backend process. This is the default and works out of the box.
For high-throughput or very large model files, S3 can be more efficient since it avoids streaming through the frontend.
Shared models directory
If every node (frontend and workers) mounts the same models directory at the same path - for example a shared volume or network filesystem, as shown in the “Shared Volume Mode” section of docker-compose.distributed.yaml - the model files are already present on each worker at their canonical path. In that case staging is wasted work: it copies files that already exist into a per-model subdirectory the worker then loads from, which shows up as a re-download of a model you already have.
Set LOCALAI_DISTRIBUTED_SHARED_MODELS=true (or --distributed-shared-models) on the frontend to skip staging entirely. The router then leaves the model’s absolute paths untouched and the worker loads them directly from the shared volume.
This flag is a contract you assert: all nodes must mount identical paths. LocalAI doesn’t check it. The .volume-id check at startup covers only the Files blob folder (see Chats deployment). Leave it off (the default) when workers have independent models directories - the frontend stages files to them over HTTP (or S3) as described above.
Which files are staged
The frontend stages the files that the model config names (parameters.model, mmproj, draft model, LoRA adapters and similar fields). It also stages every other file that the model declares:
- The
files:of the gallery entry or import-page (/app/import-model) import that installed the model. LocalAI records these in._gallery_<name>.yamlnext to the model config. - The
download_files:of the model config.
A backend can read files that the config does not name. For example, llama.cpp opens all shards of a split GGUF (<name>-00002-of-00004.gguf and the rest) from the directory of the first shard. The worker cannot see the frontend’s models directory, so it gets only the files that the frontend stages.
If you write a model config by hand and the model has files like these, list them under download_files:. If you do not, the worker gets only the first shard and the load fails with failed to load GGUF split.
The file sizes used for the load deadline and for the disk headroom check include all of these files.
Model artifact staging
For managed Hugging Face artifacts, the controller resolves the repository and
downloads every selected file. Workers receive the committed snapshot through
the existing directory stager. They never receive HF_TOKEN and do not contact
Hugging Face for managed artifacts.
With LOCALAI_DISTRIBUTED_SHARED_MODELS enabled, workers use the shared
absolute snapshot path and skip transfer. Otherwise, the controller stages the
complete snapshot tree to each worker before loading the backend.
Every controller and worker must have enough disk space for its own snapshot copy unless shared-models mode is enabled. Account for temporary partial files during installation as well as the committed snapshot.
The worker HTTP file transfer server is authenticated by a data plane token that the frontend derives from LOCALAI_REGISTRATION_TOKEN and hands to the worker at registration. If the frontend has no registration token, the token is empty and the server fails open - anyone who can reach the port gets read/write access to the worker’s models/staging/data directories (a remote model-poisoning / exfiltration vector). The worker logs a loud warning at startup in this case. Always set LOCALAI_REGISTRATION_TOKEN in distributed mode, and set LOCALAI_DISTRIBUTED_REQUIRE_AUTH=true (frontend and workers) to make a missing token or missing NATS credentials a hard startup error rather than a silent fail-open. Firewall the file-transfer port (gRPC base − 1) so only the frontend can reach it.
Automatic backend updates
With Update backends automatically on (auto_upgrade_backends), one
frontend installs the newer backends on the workers. Every six hours the
frontends compete for a database lock and the one that holds it checks and
installs. A frontend that does not hold the lock never installs, so two
frontends never start the same update at once.
Every frontend still checks for updates on its own, once after start and again
after each backend operation, to fill its own list of available updates. That
list is kept in the memory of the frontend, so two frontends can show a
different list for a short time. A check you start from the UI, or with
POST /backends/updates/check, refreshes only the frontend that answers it,
on any frontend whether or not it holds the lock, and it installs nothing.
GET /backends/updates answers from that frontend’s own list and shows when it
was checked (see Checking for backend updates). A standalone server has
no lock and installs after any check.
The same frontend writes the update items of the inbox: the digest of the updates that need a person, the result of the pass and the notice of a check that keeps failing (see Updates in the inbox). The mode is single runner, on the same lock, so there is no new lock key. The items are rows of the shared database, and every frontend streams a new one to its clients through the bus; the browser push and the Telegram forward run on the frontend that stores the item, so they happen once in the cluster. Failover is safe: a new leader that finds the same updates changes nothing, because the items are keyed and an unchanged item is not written again. The count of failed passes that delays the failed-check notice is kept in the memory of the leader, so a new leader starts it again from zero. Add-on items are written by the add-on owner (see Add-ons). Limit: the two-frontend rules are tested with the in-process bus and a shared store; the lock itself needs PostgreSQL and is tested elsewhere.
Model updates in a cluster
The model update check and the upgrades of gallery models work across frontends like this:
- The state lives in the shared models directory. The frontends share that directory. Each model has its gallery file (
._gallery_<name>.yaml) there, with where it came from, the hold flag and the journal of its last upgrade. The check writes its result to one file,._model_updates.json. Every frontend buildsGET /api/models/updatesfrom these files, so every frontend gives the same answer. There is no per-frontend list in memory. A hold or an edit shows at once; what the galleries offer is as of the last check. - The check is single runner. Every six hours the frontends compete for the advisory lock
KeyModelUpdateCheck, and the one that holds it checks. A Check now that reaches a frontend while another one checks waits (at most 60 seconds) for that check’s result file. A standalone server uses a lock of its own process. - An upgrade runs on the frontend that took the operation. That frontend holds a PostgreSQL advisory lock of the model for the whole upgrade, and touches the journal every 30 seconds. An install holds the same lock while it writes the config and the gallery file, and a hold or Remove old version holds it while it runs. A second upgrade of the same model, on any frontend, is refused as busy for as long as the first runs, however long its download takes. The lock is the proof that the frontend still runs: the database frees it when the session of a dead frontend ends (about 30 seconds). Mode: single runner per model, through that lock.
- The notifications (the digest of the models that need you, the end of an upgrade, the removal of an old version) are rows of the shared notification store. The frontend that runs the check or the upgrade writes them. The digest is set, not added: when a hold or the end of an upgrade changes it on another frontend, that frontend writes the same digest again, so there is still one row for each administrator.
If a frontend stops during an install or an upgrade, another frontend ends the change within about three minutes. Every frontend looks once a minute for a running journal whose model lock it can take and that was not touched for 90 seconds; it never touches a journal whose lock another frontend holds. An install is finished (the new config is on disk) or undone. An upgrade that had not stopped the model removes its staged files and ends failed; from the stop on, the old version is put back and loaded again if it was loaded. Every frontend then reads the config again.
At start, before the database is ready, a frontend ends only its own journals, and only when LOCALAI_INSTANCE_ID is set: a generated instance ID changes at every start, so no journal can be told apart as its own. Set LOCALAI_INSTANCE_ID to a stable value on each frontend to end its own interrupted changes before it loads the model configs.
An upgrade replaces the replicas as the upgrade strategy of the model says, and each worker downloads its own files (see Upgrade strategy). In a mixed-version cluster, an older worker does not know model.prefetch. It does not fail the upgrade: over HTTP staging it gets the new files from the frontend at its next load, as it did before. With object storage, an older worker keeps using the copy in its cache, which can be the old file under the same key; upgrade the workers before you upgrade models (see Upgrade strategy). Upgrade the workers to get the worker-side download.
Watching Backend Installs
While a worker downloads a backend, the Activity tab of the notification
panel shows real-time progress: a percentage, and, when the install targets
several workers, a roll-up of how far the fan-out has got, Node 3 of 5.
Per-file byte counts are not on the tab; they are in the per-node detail
below.
The per-node detail is on the Admin → Activity page (Activity). When an install targets more than one worker, an N nodes tag appears on the operation card, with one row per worker showing:
- A status pill: Queued (gray), Downloading (blue), Worker busy (yellow), Done (green), or Failed (red).
- The file currently being downloaded with current/total bytes and percentage.
- A thin per-node progress bar.
- Any error returned by the worker.
The yellow Worker busy pill means the worker took longer than
--backend-install-timeout to acknowledge but is most likely still
working in the background. The admin UI clears it as soon as the worker
finishes; no action is required from the operator.
If a worker is running an older LocalAI release that does not report progress, its row in the breakdown will still show terminal status (queued / done / failed / worker busy) but no per-file progress.
The Record on that page - what model and backend installs and removals have finished - is read from PostgreSQL rather than from the replica’s memory. Every replica reports the same record, it survives restarts, a replica added by a scale-out or a rolling deploy reports it in full, and Clear history clears it for every replica.
Worker Configuration
Workers are started with the worker subcommand. Each worker is generic - it doesn’t need a backend type at startup:
This worker holds one route: the WebSocket tunnel to the frontend. Add --nats-url to also hold the NATS route. The routes are the choice of the operator; see Workers and routes.
| Flag | Env Var | Default | Description |
|---|---|---|---|
--addr | LOCALAI_ADDR | (empty) | Address where this worker is reachable (host:port). The port is the base for gRPC backends. A worker on the tunnel only with no address binds its backends to loopback. See Worker profiles. |
--grpc-max-port | LOCALAI_GRPC_MAX_PORT | 65535 | Highest port the worker may assign to a backend gRPC process. Each backend gets its own port, allocated upward from the base port, so the width of [base port, this] caps how many backends this worker can run at once (see Backend gRPC port range) |
--prompt-cache-disk | LOCALAI_PROMPT_CACHE_DISK | true | Keep the prompt cache of long llama.cpp prompts on the local disk of this worker, under the root that --prompt-cache-path or --data-path gives. false turns it off on this worker only. The other settings (time to live, cap, quota, marks) and the clears come from the frontends over the control channel; the worker runs the defaults until it gets them. See Disk Prompt Cache |
--prompt-cache-path | LOCALAI_PROMPT_CACHE_PATH | (empty) | Directory of the disk prompt cache of this worker. It must be on a local disk. On a network disk, or when it is not writable, the cache is off on this worker. See Worker setup |
--data-path | LOCALAI_DATA_PATH | (empty) | Data directory of this worker. The disk prompt cache goes under it, in prompt-cache. Empty: the cache uses <models path>/../data/prompt-cache when that is on a local disk, else it is off. In a container, mount a local volume here |
--advertise-addr | LOCALAI_ADVERTISE_ADDR | (auto) | Address the frontend uses to reach this node (see below) |
--http-addr | LOCALAI_HTTP_ADDR | gRPC port - 1 | HTTP file transfer server bind address |
--advertise-http-addr | LOCALAI_ADVERTISE_HTTP_ADDR | (auto) | HTTP address the frontend uses for file transfer |
--ephemeral-staging-byte-limit | LOCALAI_EPHEMERAL_STAGING_BYTE_LIMIT | 0 (automatic) | Maximum bytes held by request-input staging across the worker’s HTTP staging directory and S3 cache. Automatic mode uses the smaller of 10 GiB and 10% of filesystem capacity. |
--ephemeral-staging-min-free-bytes | LOCALAI_EPHEMERAL_STAGING_MIN_FREE_BYTES | 0 (automatic) | Free filesystem space preserved while staging request inputs. Automatic mode uses the larger of 1 GiB and 5% of filesystem capacity. |
--register-to | LOCALAI_REGISTER_TO | (empty) | Frontend URL for self-registration. Required unless --join is given |
--join | LOCALAI_JOIN | (empty) | Join the cluster over P2P with a worker invite link instead of --register-to and a registration token. See Workers over P2P |
--p2p-identity | LOCALAI_P2P_IDENTITY | <models path>/../data/p2p/identity.key | Key file of the P2P identity of the worker: of a worker that joins with --join, and of the host that model-split workers attached to this node connect to. Keep it: the frontend knows the worker by it |
--split-server | LOCALAI_SPLIT_SERVER | false | Declare this worker a split server: it may serve model-split workers. An administrator can also turn it on or off on the Workers page; that choice wins over the flag |
--p2p-listen | LOCALAI_P2P_LISTEN_MADDRS | TCP and QUIC on every interface, random ports | Listen addresses of the P2P host of the worker. Model-split workers attached to this node connect to it; a fixed, open port gives them a direct path |
--p2p-bootstrap | LOCALAI_P2P_BOOTSTRAP_PEERS_MADDRS | (public bootstrap peers) | Peers the P2P host connects to at start, addresses that end in /p2p/<peer ID> |
--allow-open-relay | LOCALAI_ALLOW_OPEN_RELAY | false | With --join: redeem an invite that names an open relay, which anyone can use |
--node-name | LOCALAI_NODE_NAME | hostname | Human-readable node name |
--registration-token | LOCALAI_REGISTRATION_TOKEN | (empty) | Shared registration token of the frontend, if it has one. Used to register only |
--join-token | LOCALAI_JOIN_TOKEN | (empty) | Single-use join token that an admin minted. It replaces the registration token for registering. The worker keeps the own credential that it gets in its state directory (<models path>/../data/node-credential.json), so a restart needs no token |
--registration-require-auth | LOCALAI_REGISTRATION_REQUIRE_AUTH | false | Refuse to start the HTTP file-transfer server when the worker has no data plane token, that is, when it has neither a registration token nor a frontend that hands one over (it would otherwise fail open) |
--distributed-require-auth | LOCALAI_DISTRIBUTED_REQUIRE_AUTH | false | Umbrella switch implying both --registration-require-auth and --nats-require-auth |
--heartbeat-interval | LOCALAI_HEARTBEAT_INTERVAL | 10s | Interval between heartbeat pings |
--shutdown-abort-wait | LOCALAI_SHUTDOWN_ABORT_WAIT | 30s | On SIGTERM, how long the worker waits for the loads it aborts to end (their processes exit and their downloads stop) before it drains. A load that did not end in this time is released by the frontend after its stop window. See Worker shutdown |
--shutdown-request-wait | LOCALAI_SHUTDOWN_REQUEST_WAIT | 30s | On SIGTERM, how long the worker waits for the requests in flight on its models before it deregisters. See Worker shutdown |
--shutdown-timeout | LOCALAI_SHUTDOWN_TIMEOUT | 60s | On SIGTERM, the bound of the drain, the wait for requests and the deregistration together. Stopping the backends comes after it |
--routes | LOCALAI_WORKER_ROUTES | (derived) | Routes this worker holds, comma separated: nats, tunnel, or both. When empty: nats when --nats-url is set (never with --join), and always tunnel. See Workers and routes |
--nats-url | LOCALAI_NATS_URL | (empty) | NATS server URL. With it the worker holds the NATS route. With --routes nats and no URL, the worker uses the NATS address that the frontend hands over |
--nats-jwt | LOCALAI_NATS_JWT | (empty) | Optional override for the nats_jwt returned at registration |
--nats-user-seed | LOCALAI_NATS_USER_SEED | (empty) | Optional override for nats_user_seed from registration |
--nats-require-auth | LOCALAI_NATS_REQUIRE_AUTH | false | Require NATS JWT+seed (from registration or env) |
--nats-tlsca | LOCALAI_NATS_TLS_CA | (empty) | PEM file for NATS server CA |
--nats-tls-cert | LOCALAI_NATS_TLS_CERT | (empty) | Client certificate for NATS mTLS |
--nats-tls-key | LOCALAI_NATS_TLS_KEY | (empty) | Client private key for NATS mTLS |
--backends-path | LOCALAI_BACKENDS_PATH | ./backends | Path to backend binaries |
--models-path | LOCALAI_MODELS_PATH | ./models | Path to model files |
--vram-budget | LOCALAI_VRAM_BUDGET | (empty) | Cap the VRAM this node advertises for model placement, as a percentage (e.g. 80%) or an absolute amount (e.g. 12GB). Empty uses all detected VRAM. See Per-node VRAM budget. |
--vram-total | LOCALAI_VRAM_TOTAL | (empty) | Total VRAM this node reports, as an absolute amount (e.g. 40GB). Replaces GPU detection; use it when the detected VRAM is wrong. LOCALAI_VRAM_BUDGET is then resolved against this total. Empty uses detection. See Per-node VRAM budget. |
--max-active-backends | LOCALAI_MAX_ACTIVE_BACKENDS | (empty) | Models kept loaded on this node (0 = no limit). Empty uses the cluster setting. See Per-node memory limits. |
--model-swap | LOCALAI_MODEL_SWAP | (empty) | true or false: unload the least recently used idle model on this node to make room for another. Empty uses the cluster setting. |
--memory-reclaimer-threshold | LOCALAI_MEMORY_RECLAIMER_THRESHOLD | (empty) | Memory use (0 to 1) above which idle models on this node are unloaded. Setting it turns the memory reclaimer on for this node, even when the cluster setting leaves it off. Empty uses the cluster setting. |
Advertise address: The --addr flag is the local bind address for gRPC. The --advertise-addr is the address the frontend stores and uses to reach the worker via gRPC. If not set, the worker auto-derives it by replacing 0.0.0.0 with the OS hostname (which in Docker is the container ID, resolvable via Docker DNS). Set --advertise-addr explicitly when the auto-detected hostname is not routable from the frontend (e.g., in Kubernetes, use the pod’s service DNS name).
HTTP file transfer: Each worker also runs a small HTTP server for file transfer (model files, configs). By default it listens on the gRPC base port - 1 (e.g., if gRPC base is 50051, HTTP is on 50050). gRPC ports grow upward from the base port as additional models are loaded. Set --advertise-http-addr if the auto-detected address is not routable from the frontend.
Join tokens
A worker joins with a join token that an admin mints. It is the safe default: the token expires, it works once, and it does not stay on the worker.
- Single use and short. A token is good for 10 minutes and one registration. For Kubernetes or Compose, where several replicas start together, an admin can ask for up to 100 uses (the default for that case is 5) and up to 24 hours.
- Stored as a hash. The frontend keeps only a SHA-256 of the token, compares it in constant time, and spends a use with one atomic update, so two workers that race for the last use cannot both join. A caller that sends many tokens that are not valid is throttled by its address. A token is never written to a log or to the API trace.
- Revocable, and visible. The list shows each token as
unused,partly_used,used_up,expiredorrevoked, with the uses left, the connections it allows and who minted it. - Connections. A token can allow only
nats, onlywebsocket, or both. A worker that asks for another connection is refused, also when it registers again. Workers over P2P keep the worker invite. - Approval. A node that joins with a token waits for an admin to approve it, as before. A token can carry
auto_approve, and the cluster settingjoin_auto_approvesets its default. Both are off unless you turn them on.
After it joined, the worker holds its own credential. The frontend returns it once, in the answer to the registration, and stores only its hash. The worker keeps it in its state directory (<models path>/../data/node-credential.json, mode 0600) and presents it for the heartbeat, drain, deregister and models routes, and to register again after a restart. So a restart needs no join token, and a node cannot act on another node. A new registration with a join token or with the registration token replaces the credential, and the old one stops working at once; LocalAI also ends the tunnel session of the old one. A worker whose credential is lost (for example its state directory is deleted) joins again with a new join token.
Upgrade. This is a hard break for old workers: a worker that predates join tokens sends the shared registration token for its heartbeat, and the frontend now refuses it. Upgrade the workers with the frontend. A worker that registers again gets its own credential.
Add a worker
On the Workers page, press Add worker. Choose the connections (NATS is offered when it is set up, P2P when sharing is on), then copy the command of the tab that fits: the install script, Docker, Docker Compose, Kubernetes or a manual start. The page mints the token for you, hides it on the page, and puts it in the command when you copy. It counts down to the expiry, lets you choose how many workers may use the token and for how long, and waits for the worker to appear in the roster. Or mint a token with the API:
The answer holds the plain token once, and a ready-to-copy command for each way to run a worker, built from the external URL of the frontend (LOCALAI_BASE_URL, or the request host when it is behind a trusted proxy set with --trusted-proxies):
| Method | What it runs |
|---|---|
install_script | curl -fsSL '<frontend>/join.sh?t=<token>' | sudo sh: installs the binary with the checksum check of install.sh, writes a systemd unit (Linux) or a launchd daemon (macOS), keeps the settings in a file that only root can read, and starts the service. It is safe to run again. |
windows | irm '<frontend>/join.ps1?t=<token>' | iex from an elevated PowerShell: installs the binary and a Windows service. |
docker | docker run with LOCALAI_REGISTER_TO and LOCALAI_JOIN_TOKEN, and volumes for /models, /backends and /data |
docker_compose | A compose file with one worker service and the same volumes |
kubernetes | kubectl apply -f '<frontend>/join.yaml?t=<token>': a Secret with the token and a StatefulSet named localai-worker with a volume for the state directory, and GPU limits as comments |
manual | LOCALAI_REGISTER_TO=... LOCALAI_JOIN_TOKEN=... local-ai worker |
The three scripts are public, but each answers only for a token that exists and is not expired, revoked or used up (otherwise 404, the same for every case). Serving a script does not spend the token. The query routes=nats,websocket limits the connections of the worker within what the token allows. A script holds the token: do not share it. The shell script never prints the token and never puts it on a command line.
To remove a worker that the install script set up, see the note it prints at the end: systemctl disable --now localai-worker, remove /etc/localai/worker.env, the unit and the state directory, and delete the worker on the Workers page.
The scripts use the installer at https://localai.io/install.sh and https://localai.io/install.ps1. For a host with no internet access, serve a copy and set LOCALAI_INSTALL_URL before you run the script.
The join token API
All routes are for an admin only and answer 503 when distributed mode is off. The schema is in the swagger UI.
| Route | Purpose |
|---|---|
POST /api/cluster/join-tokens | Mint a token. Body (all optional): ttl_seconds (up to 86400), uses (up to 100), routes (nats, websocket), label, auto_approve. Returns the plain token once and the commands. |
GET /api/cluster/join-tokens | List the tokens and their state. The secret is never in the list. |
DELETE /api/cluster/join-tokens/{id} | Revoke a token. A worker that already joined keeps its own credential; delete the node to end that. |
PUT /api/cluster/settings with join_auto_approve | The default of auto_approve for new tokens. |
These routes are not exposed as tools of the LocalAI Assistant: a token is a credential and must not pass through a chat.
Workers over P2P
A worker on another network (a laptop, a machine behind NAT, a box at another site) can join with a one-time worker invite instead of a URL and the registration token. The frontend must run P2P in mode share (Connect and share; see P2P).
On the Workers page, press Add worker, choose P2P and continue: the page makes the invite. The API is
POST /api/p2p/inviteswith{"kind": "worker"}. A worker invite has no QR code.On the new machine, run the command that the page shows:
The worker finds the frontend by its peer ID and connects directly, by hole punching, or through a relay. It redeems the invite, prints a phrase, and registers. The node waits for approval whatever
--auto-approve-nodessays: compare the phrase and the peer ID with the person who runs the machine, then approve it.
What the worker keeps and does:
- It keeps its P2P identity (
--p2p-identity) and a record of the frontend underdata/p2p/pairs/. A restart with the same command does not redeem the used invite again. - It registers, heartbeats and drains over P2P HTTP. The frontend knows it by its peer ID, so it needs no registration token, and the node is pinned to that peer: a registration under its name from another peer or with the registration token is refused (409), and the tunnel accepts it only from its peer. A paired worker may act only on its own node.
- Its tunnel is one P2P stream per lane (
/localai/tunnel/1/inferenceand/localai/tunnel/1/bulk), with the same yamux sessions as the websocket tunnel. The bulk lane (model files) needs a path without a data limit, so a public relay never carries it; a relay that you run does. - It is tunnel-only: it holds the P2P tunnel and never attaches to NATS (see How a frontend picks the route of a worker). A NATS URL on such a worker is ignored with a warning, and
--routes natsis refused at start. To put it on NATS, restart it with--register-to, the registration token,--nats-urland--addr. - Revoking the device under Cluster, Sharing closes its connections, and the node stops heartbeating.
Several frontends: the invite names a peer ID, and the worker always reaches the frontend that runs it (see P2P with several frontends). The other frontends reach the worker through the peer link, as for a websocket tunnel.
Disabling backend installation on workers
A worker installs a backend the first time the frontend schedules a model
that needs it. On workers that must run only pre-installed or system-path
backends, set LOCALAI_DISABLE_BACKEND_INSTALL=1 on the worker: it then
refuses frontend install and upgrade requests for backends it does not have,
and a model that needs a missing backend fails to load on that node with a
clear error instead of pulling an image. Set the same variable on the
frontend so its own install and upgrade endpoints refuse as well, each
process enforces the switch for the backends it owns. Model installs on the
frontend are judged against the workers’ backends, so a model whose backend
is installed on any healthy worker, under its own name or an alias, is still
accepted; a worker marked unhealthy does not count until its heartbeat
returns. See
Disabling backend installation.
Ephemeral request-input storage
Workers reserve local capacity before accepting per-request audio, image, and other ephemeral inputs. The limit covers both direct HTTP staging and the worker’s S3 download cache. A request is rejected before inference when accepting its input would exceed the byte limit or the configured free-space headroom. One request-scoped cleanup operation releases all exact input keys and their reservations after inference, while a one-hour recovery sweep removes abandoned files after crashes. The sweep runs at startup and every 15 minutes, preserves active requests, and considers the newest file in each request directory.
Set both capacity variables to positive byte counts when a worker needs fixed limits. Leaving either value at zero selects its filesystem-based default. These settings apply only below the two ephemeral roots; model, data, and configuration files are excluded.
Worker Health Probes
The worker’s HTTP server (base port - 1, default 50050) exposes two unauthenticated probes:
| Endpoint | Meaning |
|---|---|
/healthz | Liveness. 200 whenever the process is up and serving. Deliberately independent of readiness, so a brief NATS outage does not trigger a restart storm across every worker. |
/readyz | Readiness. 200 only when the worker is registered, its NATS connection is live, and every backend process it is currently serving answers a short TCP dial on its gRPC address; 503 otherwise. A worker holding no backends is ready, because idle is a healthy state, and so is one whose backends are still starting up. |
/readyz reports something the frontend cannot see on its own. The node registry’s status and last_heartbeat are driven by an HTTP heartbeat to the frontend, which is a different network path from NATS. A worker can keep heartbeating while its NATS link is dead, and so appear healthy in the registry while being unable to receive any work. The local probe closes that gap.
The same applies to the data path. A worker can hold a live NATS link while the backend processes it believes it is running have died, so it reports healthy while every load routed to it fails. /readyz therefore also dials the recorded gRPC address of each backend the worker is serving, and a worker whose backend port refuses connections drops out of rotation instead of absorbing work it cannot serve.
Only backends in the middle of their lifecycle are dialled. A backend that is still starting is skipped until its gRPC server has answered a health check, which can take 10 to 15 seconds on a slow node, and a backend that is stopping is skipped from the moment shutdown begins. Neither a cold start nor an ordinary shutdown makes a worker report 503, so a Kubernetes readinessProbe at the usual 10s period does not pull a worker out of rotation every time it loads a model.
The container image’s HEALTHCHECK detects worker mode and probes this endpoint automatically; no HEALTHCHECK_ENDPOINT override is needed. Set HEALTHCHECK_ENDPOINT only to pin an explicit URL.
Worker Address Configuration
The simplest way to configure a worker’s network address is with a single variable:
| Variable | Description |
|---|---|
LOCALAI_ADDR | Reachable address of this worker (host:port). The port is used as the base for gRPC backend processes, and port-1 for the HTTP file transfer server. |
Example:
For advanced networking scenarios (NAT, load balancers, separate gRPC/HTTP ports), the following override variables are available:
| Variable | Description | Default |
|---|---|---|
LOCALAI_SERVE_ADDR | gRPC base port bind address | 0.0.0.0:50051 |
LOCALAI_GRPC_MAX_PORT | Highest port assignable to a backend gRPC process | 65535 |
LOCALAI_HTTP_ADDR | HTTP file transfer bind address | 0.0.0.0:{gRPC port - 1} |
LOCALAI_ADVERTISE_ADDR | Public gRPC address (if different from LOCALAI_ADDR) | Derived from LOCALAI_ADDR |
LOCALAI_ADVERTISE_HTTP_ADDR | Public HTTP address (if different from gRPC host) | Derived from advertise host + HTTP port |
Backend gRPC port range
Every backend process a worker starts listens on its own gRPC port, allocated
upward from the worker’s base port (LOCALAI_SERVE_ADDR, default 50051).
LOCALAI_GRPC_MAX_PORT sets the top of that range. The width of
[base port, LOCALAI_GRPC_MAX_PORT] is therefore a hard cap on how many
backend processes one worker can run concurrently.
Set it when the worker shares a host with other services and you need to keep the rest of the ephemeral range clear, or when you want a worker’s backend count bounded explicitly rather than by whatever the host happens to allow:
Leave it unset (the default) and the worker may use anything up to 65535.
Budget headroom above your real concurrency. When a backend stops, its port is held briefly before it can be reused, so a worker with heavy start/stop churn has more ports tied up than it has running backends at any instant. If the range does fill, backend starts fail with:
no free gRPC port in range: 50051-50150 is fully consumed by 100 running
backend(s) and 12 port(s) still in quarantine; raise LOCALAI_GRPC_MAX_PORT to
widen the rangeRaise LOCALAI_GRPC_MAX_PORT (or reduce how many models you schedule onto that
worker). A value above 65535 is clamped, and a value below the base port is
ignored in favour of the full range, so a typo degrades the setting rather than
wedging every backend start on the node.
NVIDIA GPU support
When running workers in a container, two runtime settings affect how VRAM usage is reported back to the frontend:
NVIDIA_DRIVER_CAPABILITIESmust includeutility. Without it, the NVML library (and thereforenvidia-smi) is not available inside the container. CUDA compute still works, but the worker cannot query free VRAM and the Nodes page will show the node as fully used. SetNVIDIA_DRIVER_CAPABILITIES=compute,utilitywhen using the NVIDIA runtime. For Docker Compose withdriver: nvidia, usecapabilities: [gpu, compute, utility]on the device reservation. Docker derives driver capabilities from this reservation, so includecomputefor CUDA libraries such aslibcuda.so.1. Theutilitycapability alone enables monitoring but does not provide CUDA libraries.Run the container with
init: true(ordocker run --init). The worker process becomes PID 1 in the container and cannot reap zombies on its own. Without an init,nvidia-smicalls can fail intermittently withwaitid: no child processes, which briefly clears free-VRAM metrics.
Unified memory devices (Jetson, DGX Spark / GB10, Thor): these SoCs
share one physical RAM between CPU and GPU. LocalAI detects them via
/sys/devices/soc0/family and /sys/devices/soc0/soc_id (no nvidia-smi
required) and reports system-RAM figures as VRAM. Free VRAM therefore tracks
MemAvailable in /proc/meminfo. Workers report RAM metrics independently
from VRAM on every registration and heartbeat. On unified-memory nodes, the
available RAM and available VRAM values should therefore track each other
closely; on discrete-GPU nodes they can change independently.
Windows workers
A worker can run natively on Windows (amd64). It serves the llama.cpp backend, the only backend with a Windows build. A model that the scheduler places on a Windows worker and that needs another backend fails on that node with “this backend has no Windows build”, so use node labels to keep such models on Linux or macOS workers. The worker reports the GPU and VRAM through nvidia-smi for NVIDIA GPUs and through DirectX (DXGI) and the “GPU Adapter Memory” performance counters for other GPUs. The frontend and the workers can run on different operating systems. To run the worker as a Windows service and for the other limits, see Distributed mode and workers on Windows.
CPU telemetry
Backend workers report host-wide CPU telemetry in GET /api/nodes and
GET /api/nodes/:id:
| Field | Meaning |
|---|---|
cpu_logical_cores | Logical processor count, sampled at registration |
cpu_usage_percent | Utilization across the whole host, clamped to 0..100 |
cpu_load_1 | One-minute system load average |
default_threads | Thread count the worker uses for a model that sets no threads: its physical cores, capped by its CPU limit. Sent at registration |
Utilization and load are sampled at registration and again at each worker heartbeat (every 10 seconds by default). The frontend persists heartbeat samples on the normal heartbeat checkpoint cadence; CPU movement alone does not force an extra database write. If a sample fails, the worker omits all CPU fields and the frontend keeps the last successful reading.
Workers from releases that predate CPU reporting remain compatible. Their
cpu_logical_cores value is zero, which means unknown rather than a zero-core
machine. Fleet capacity excludes those workers from CPU totals and reports
them as unknown. The dashboard derives available CPU as idle logical-core
equivalents:
idle cores = cpu_logical_cores * (1 - cpu_usage_percent / 100)Node Labels
Workers can declare labels at startup for scheduling constraints:
| Variable | Description | Example |
|---|---|---|
LOCALAI_NODE_LABELS | Comma-separated key=value labels | tier=premium,gpu=a100,zone=us-east |
Labels can also be managed via the admin API (see Label Management API below).
The system automatically applies hardware-detected labels on registration:
gpu.vendor– GPU vendor (nvidia, amd, intel, vulkan)gpu.vram– GPU VRAM bucket (8GB, 16GB, 24GB, 48GB, 80GB+)node.name– The node’s registered name
How Workers Operate
Workers start as generic processes with no backend installed. When the SmartRouter needs to load a model on a worker, it sends a backend.install request, over a route that the worker holds, with the backend name and model ID. The worker:
- Installs the backend from the gallery (if not already installed)
- Starts a new gRPC backend process on a dynamic port (each model gets its own process)
- Replies with the allocated gRPC address
- The SmartRouter calls
LoadModelvia direct gRPC to that address
Workers can run multiple models concurrently - each model gets its own gRPC process on a separate port. For example, an embedding model on port 50051 and a chat model on port 50052 can run simultaneously on the same worker.
When the SmartRouter needs to free capacity, it can unload models with zero in-flight requests without affecting other models on the same worker.
Managing nodes in the WebUI
With distributed mode on, the Cluster group of the Administration sidebar holds the cluster: Workers, Placement (with a Rules view and a Failover view) and Sharing. A single-node install shows This machine instead and never draws the cluster pages. With P2P on, a single-node install also has Cluster, with Sharing alone.
Nodes lists every worker in a sortable table: name, role, state in words, GPU or system memory, loaded models, last heartbeat and version. Switch between comfortable and compact rows, between List, Map and Running models, and filter to Needs attention (waiting for approval, not answering, or low GPU memory, system memory or models disk). The Map draws this instance, the message bus and database, and each worker; a dashed line is a worker that gets no traffic. It is not drawn on a phone. When a backend has a newer version, an Update button on the page asks first, then sends the update to the nodes that differ from the rest of the cluster, or to the nodes you selected.
A worker stops the running processes of a backend before it installs the new version, so every update that touches a node shows a confirmation. It lists each node, the versions, and the models that stop on it. The model list comes from the backend each model was loaded with, as the registry recorded it. It can be empty or name another backend, so an empty list for a node reads “No loaded model recorded”, not “none stop”. A model starts again when a request needs it. The nodes update one after another, and the dialog shows each result when it ends. A node is updated only when its operation ended without an error and a new check shows the node on the new version. A node that fails does not stop the others, and Retry runs only the failed ones. Stop after this node keeps the nodes that have not started from starting.
The same confirmation opens from the Nodes action of a backend on the Updates tab (/app/updates/backend/<name>). That page lists every node that has the backend, with its version, the models that use it and its state. A node that differs from the rest of the cluster is shown as “Differs from the cluster”, not as behind, because it can be newer. The page is for administrators and is only offered when more than one node has the backend.
The Running models view groups replicas by model. Its View logs… action opens logs directly when there is one placement. When a model has several, it opens the row so you can choose the logs of one replica.
Add a node (/app/nodes/add) explains how a machine joins: a registered worker (by the server address or with a P2P invite) or a model-split worker. Another LocalAI instance is not a node: add it as a remote and group it under Federation. It prints the command to run on the new machine with a Copy button, and updates the page when the machine appears. On a single-node install it starts with the command that turns distributed mode on.
Open a node for node-scoped work. The page shows its state, VRAM, RAM, models disk, CPU and in-flight requests, and has tabs for Models (replica logs, unload), Backends (update, delete), Logs, and Capacity and labels (replica capacity, labels). Drain… shows what the drain would change before it does anything; Remove… asks for the node’s name. Update in the Backends tab is offered only for a backend that has a newer version on this node, and asks first like the bulk button. A node that stopped answering says so and shows the last figures it reported.
The “what happens if I drain this node” list is a preview worked out in the browser from the node list, the loaded replicas and the placement rules. The server does not compute it, and the scheduler also weighs free memory and disk when it loads a model, so the preview never claims a model will fit.
Node Management API
The API is split into two prefixes with distinct auth:
/api/node/ - Node self-service
Used by workers themselves (registration, heartbeat, etc.), exempt from global auth. Registration takes a join token (join_token in the body), the shared registration token (token, when the frontend has one), or the own credential of a node that registers again (Authorization: Bearer). It returns the credential of the node once (node_token). Every other route takes that credential, for its own node only.
| Method | Path | Description |
|---|---|---|
POST | /api/node/register | Register a new worker |
POST | /api/node/:id/heartbeat | Update heartbeat timestamp |
POST | /api/node/:id/drain | Drain self. The worker sends it when it shuts down, with {"shutdown":true,"loads_ended":true} once it stopped its loads (see Worker shutdown) |
GET | /api/node/:id/models | Query own loaded models |
POST | /api/node/:id/split | Report the P2P host and the model-split workers of the node; the answer says whether the node is a split server and lists the workers attached to it and the relays that admit it. A node that registered with the token is bound to the first peer it reports; another peer gets 409 until the node registers again |
DELETE | /api/node/:id | Deregister self |
The shared registration token is refused on every route of this table except register.
/api/nodes/ - Admin management
Used by the WebUI and admin API consumers. Requires admin authentication.
| Method | Path | Description |
|---|---|---|
GET | /api/nodes | List all registered workers |
GET | /api/nodes/:id | Get a single worker by ID |
GET | /api/nodes/:id/models | List models loaded on a worker |
GET | /api/nodes/models | List loaded model replicas on healthy workers |
DELETE | /api/nodes/:id | Admin-delete a worker |
POST | /api/nodes/:id/drain | Drain a worker. ?force=true removes its models at once; ?timeout=15m sets the deadline. Answers with status, immediate, drain_deadline and leaving_replicas |
POST | /api/nodes/:id/resume | Cancel the drain of a worker: it is healthy again and its models stay |
POST | /api/nodes/:id/approve | Approve a pending worker node |
POST | /api/nodes/:id/backends/install | Install a backend on a worker |
POST | /api/nodes/:id/backends/upgrade | Update (force-reinstall) a backend on a worker. Answers 202 with a job ID; the worker stops the running processes of the backend first. Answers 404 not_installed or 409 no_update at once when there is nothing to do, and 409 stale when the optional expected_to is no longer the available build (see Starting an upgrade) |
POST | /api/nodes/:id/backends/delete | Delete a backend from a worker |
POST | /api/nodes/:id/models/unload | Unload a model from a worker. Cancels a load of that model on the worker first. |
POST | /api/models/:id/load-cancel | Cancel one load attempt ({"job_id": "..."}) |
POST | /api/nodes/:id/models/delete | Delete model files from a worker |
PUT | /api/nodes/:id/vram-budget | Set a VRAM budget for a worker ({"value":"80%"}) |
DELETE | /api/nodes/:id/vram-budget | Clear the admin VRAM budget of a worker (the worker’s own budget, else the cluster one, applies again) |
GET | /api/nodes/:id/limits | The memory limits a worker runs with, and the source of each (override, worker, cluster or default) |
PUT | /api/nodes/:id/limits | Override some memory limits of a worker (max_active_backends, vram_budget, memory_reclaimer_threshold, model_swap); a key left out keeps its value |
DELETE | /api/nodes/:id/limits | Clear every memory limit override of a worker |
PUT | /api/nodes/:id/split-server | Declare a worker a split server ({"split_server":true}), or clear it, which detaches its model-split workers |
DELETE | /api/nodes/:id/split-server | Hand the split server declaration back to the --split-server flag of the worker |
The Nodes page reads GET /api/nodes every five seconds and renders 50 workers at a time. Bulk drain, resume and remove run with bounded concurrency, so the page stays usable for fleets with thousands of registrations. Selecting the visible page or a group does not discard selections elsewhere; selections are removed only when a later poll confirms the worker no longer exists.
The list never fetches backend inventory, and the Running models and Map views stay lazy: the first use of either makes one controller database request that is kept until the page is left. A node’s backends are read only when its page opens.
Use a model row’s actions menu in Running models to stop that model across the fleet. LocalAI sends one controller shutdown request for the model, which stops all loaded placements; the browser does not contact workers individually. The view refreshes the running-model inventory after both successful and failed shutdown attempts because a failed request can still have stopped some replicas.
Model sizing in the WebUI
The model gallery answers “will this model run here” against the cluster, not against the frontend. A distributed frontend is usually a GPU-less pod, so sizing models against its own memory would report that a fleet of GPU workers can only run the smallest CPU build.
The budget is the largest single healthy backend node, not the sum of the fleet: a model loads into one node, so four 16GB workers do not add up to a home for a 40GB model. A node’s operator-set VRAM budget caps its contribution, since the scheduler would refuse a load above that ceiling anyway, and a GPU node wins over a CPU node holding more system RAM. The gallery names the node its verdict belongs to (“Fits on dgx-01”).
GET /api/resources and GET /api/models carry this as an additional cluster
object; their existing aggregate and ram* fields keep reporting the
frontend’s own hardware, which is what the resource monitor shows. The object is
absent in single-node mode, and also whenever the registry cannot be read, in
which case every sizing surface falls back to the local host:
Variant selection (GET /api/models/variants/:id) uses the same reading, and
judges backend compatibility against the union of the capabilities present in
the cluster, so a CUDA-only build is offered when any worker can run it.
Context size and threads of the node that runs the model
The frontend reads the model configuration, and it fills two values that the configuration does not set from its own hardware: the automatic context size (from the GGUF file and the memory of the host) and the thread count (the physical cores of the host, capped by its CPU limit). The frontend is often a pod without a GPU, so these values fit the frontend and not the worker.
When the router has chosen a node for a load, it chooses both values again for that node, the same way the node would choose them for itself:
- Context size. A model with no
context_sizegets the window that fits the GPU of the node (its VRAM budget when one is set), or its system memory when it has no GPU. The router reads the GGUF header of the model file on the frontend. - Threads. A model with no
threadsgets thedefault_threadsthat the worker reports, when the frontend detected its own default too.
A value that you set is always sent as it is: context_size or threads in the
model configuration, and --threads / LOCALAI_THREADS or a saved threads
setting on the frontend. A worker from a release that does not report
default_threads, or a node that reports no memory, gets the frontend’s value,
as before.
Model configs across frontends
Every frontend keeps its own in-memory copy of the model configs in the shared models directory. When a frontend installs, edits, toggles or deletes a model, it writes the change to the directory and publishes a message on NATS. The other frontends reload the directory when they receive it.
A gallery install or delete publishes this message as soon as the new config is in place, before the frontend preloads model files. The preload can take minutes on a large models directory, and other frontends do not wait for it. If the preload fails, the operation reports the error, but the config change stays applied on every frontend.
NATS keeps no history of these messages. A frontend that is disconnected when a message is published never receives it. To recover, each frontend also reloads the models directory:
- every
--model-config-resync-interval(default30s), when a config file changed since its last pass, and - after each NATS reconnect.
The pass is the same reconcile that a NATS message triggers, so it is idempotent. Only models whose file changed get a new configuration revision. A pass over an unchanged directory reads the config files and does nothing else.
Distributed-state mode: each frontend derives this state from the shared directory, so there is no leader and nothing to replicate. The only per-frontend memory is a hash of the config files from its last pass, which only saves work. The consequence is a bounded delay: a frontend that missed a message serves the previous config for at most one interval.
Two limits apply:
- Models loaded with
--config-fileexist only on the frontend that loaded them. A reload of the models directory keeps them, and a config-file model wins over a directory file with the same name, as it does at startup. - The reload is strict: if any config file in the directory does not parse, the frontend keeps its current configs and logs the error once. It retries on each pass until the file is fixed. This keeps a half-written file from looking like a deleted model.
GGUF header cache shared by file
Frontends that mount the same data volume share one GGUF header cache file, header-cache.json, in the data path. A header that one frontend has read is used by the others. This is the shared-by-file mode, and it requires that every frontend mounts the same data volume.
A frontend that sets --instance-id keeps its own file, header-cache-<id>.json, and does not share it. Use this when a frontend should start warm after a restart without sharing its entries.
With a ReadWriteOnce volume, all frontends that share the cache must run on one node. Sharing across nodes needs a ReadWriteMany volume or a shared store, and this mode does not support it.
Model configuration revisions
Distributed mode assigns a config_revision to each validated model configuration. It hashes the persisted semantic configuration, including fields such as context_size and parallel settings. YAML formatting, comments, and map order do not change it.
The first request for a model establishes its current revision and replay information. The replica reconciler uses only replay information that matches the current revision. This lets min_replicas recover after an ordinary worker failure without restoring an old configuration.
When you save a valid model edit, LocalAI makes replicas from the old revision ineligible immediately. New requests cannot route to those replicas. This rule applies to raw YAML edits, structured patches, renames, disabled models, and changes from another frontend.
The edit response includes these fields:
config_revisionidentifies the saved semantic configuration.pending_cleanupcounts old replicas that still need cleanup when the response returns.
LocalAI sends an acknowledged stop request for each exact backend process. If a worker or NATS is unreachable, LocalAI keeps the replica in the unloading state and retries with durable backoff. The saved edit remains successful while cleanup is pending.
Workers must support the exact model-stop protocol. Upgrade all workers before you rely on revision cleanup. An older worker cannot acknowledge the request, so its stale replica remains unloading until cleanup succeeds or the worker re-registers.
Worker re-registration removes stale live-replica rows, but it preserves the current model revision and matching replay information. A temporary worker outage therefore does not make an old revision routable. The reconciler can restore the current revision after the worker becomes healthy.
The responses from GET /api/node/:id/models and GET /api/nodes/:id/models include these replica fields:
| Field | Meaning |
|---|---|
config_revision | Hash of the persisted semantic model configuration that created the replica. Routable replicas match the current revision. |
effective_options_hash | Hash of the final node-specific load options after defaults and file staging have been applied. Different hashes can be valid on heterogeneous workers when config_revision matches. |
state | Replica lifecycle state, such as staging, loading, loaded, or unloading. Only eligible loaded replicas receive requests. |
cleanup_error | Last exact-stop error. This field appears while cleanup is pending. |
cleanup_next_retry_at | Time of the next durable cleanup attempt. This field appears after a failed attempt. |
model.unload releases model memory inside a running backend. It does not replace the exact process stop that configuration cleanup requires. The backend.stop operation remains an administrative backend operation.
backend.stop is acknowledged
backend.stop is request-reply. The worker answers with what it terminated, so the controller can tell a stop that worked from one that matched nothing or failed outright.
This matters for POST /api/nodes/:id/models/unload, which stops the backend after unloading the model. The stop used to be fire-and-forget, so the endpoint answered 200 as soon as the message left the frontend, including when the backend was still running and still holding its VRAM. It now returns an error when the worker reports that the stop failed.
Two outcomes are deliberately not errors:
- Nothing matched. The worker reports an empty stopped-process list, logged as
backend.stop matched no running process. Stopping a backend that is not running leaves the caller in the state it asked for, and eviction and cleanup paths stop already-gone models routinely. - No answer. A worker built before this reply performs the stop and never responds. The controller waits 15 seconds, logs
Worker did not acknowledge backend.stop, and assumes delivery, so a fleet mid-upgrade keeps working. A transport failure is reported rather than assumed.
On a mixed fleet, every stop against a worker that predates the reply costs the full 15-second wait before falling back. Upgrading the workers removes the delay.
Memory settings across frontends
The settings of Settings → Models in memory (models kept loaded, eviction, Swap models when memory is full, the watchdog, the memory reclaimer and the GPU memory budget) are cluster settings in distributed mode. They are stored once in the database and every frontend applies the same values. The keys and names do not change: POST /api/settings takes them as in single mode.
- Where they live. A save through any frontend stores the memory keys in the
cluster_shared_settingstable and sends them to the other frontends over the bus, so a request served by another frontend sees the new values at once. The other keys of the same request follow Other settings across frontends. - Precedence. Every frontend runs the same memory settings: the stored value of a key, else its built-in default. A frontend’s
runtime_settings.jsonis not read for these keys; a frontend that finds them there logs a warning at start and ignores them. A frontend’s environment (for exampleLOCALAI_MAX_ACTIVE_BACKENDS) only adds the keys that the store does not hold yet, when the frontend starts: the first frontend that sets a key wins. When a later frontend starts with a different value in its environment, it logs a warning and uses the stored value. Change the values in Settings, not in the environment. Single mode is unchanged: there the environment wins over the file. - Revisions.
GET /api/settingsreturnsmemory_scope: "cluster"andmemory_revision. A save may send thatmemory_revisionback: when another admin saved in between, the answer is409and nothing is stored. A save withoutmemory_revisionmerges its keys over the stored ones, so two admins who change different keys at the same time both keep their change. The Settings page sendsmemory_revisionwith every save of a memory setting. On a409it says that the settings changed, loads the values in force and asks you to apply your change again. - Where they act. The scheduler applies the model limit, model swap, the eviction order, the eviction retries and eviction of busy replicas when it places a model. The replica reconciler applies the idle unload (
watchdog_idle_*, also to models with no scheduling rule; a rule’smin_replicas, pinned models and warm failover targets stay) and the memory reclaimer (one idle replica per node and tick while the node’s memory use is above its threshold). The sweeps run in the reconciler’s pass, under its advisory lock, so one frontend runs them at a time. While a node’s reclaimer is on, placement keeps(1 - threshold)of its GPU memory free. - Distributed state. Shared (
syncstatemapsettings.memorywith the database as the store). A frontend re-reads the store every 30 seconds and after a reconnect of the bus, so a missed update is repaired. A frontend that cannot open the store logs an error and keeps its local values, like single mode.
Other settings across frontends
Most other runtime settings are cluster settings too: a save through any frontend is in force on every frontend. They include the API keys of Settings → API Keys, CORS and CSRF, the P2P mode with p2p_public_dht and p2p_bootstrap_peers (each frontend still runs its own host with its own identity, see Several frontends), the galleries and the official libraries, the default context size, the chat tools (chats_host_exec, the web tools, the LocalAI tool groups, the egress settings), the limits of chats, loops, triggers and plugins, sharing, incognito, collections and the branding text. The source code holds the full list (ClusterSettingKeys in core/config/setting_scopes.go); a test fails when a new setting has no scope.
Some settings stay with each frontend, in its own runtime_settings.json, because they describe the process or its host:
| Setting | Why it stays on the frontend |
|---|---|
threads | The default follows the cores of the host. |
artifact_download_concurrency, max_concurrent_backend_operations, max_concurrent_model_operations | They limit the work of this process. |
prefer_development_backends | The backend resolver reads it once, when the process starts. |
debug, enable_backend_logging | The logs of this process. |
enable_tracing, tracing_max_items, tracing_max_body_bytes | Each frontend keeps its own trace buffer in memory. |
vram_persistent_cache, collections_db_path | Files on the disk of the host. |
mitm_listen | A listener on the host. |
p2p_relays, p2p_relay_paired | The relay manager of each frontend’s P2P host keeps this list. |
p2p_relay_mode, p2p_relay_rate_limit, p2p_mdns | The relay service and the local network announce of each host. |
logo_file, logo_horizontal_file, favicon_file | Set by the branding upload, not by POST /api/settings. The uploaded files stay on the frontend that took the upload. |
Where they live. In the same
cluster_shared_settingstable as the memory settings, in a document of their own (runtime) with its own revision. Each frontend also keeps a copy of the last document it applied incluster_settings_cache.jsonin its configuration directory (mode0600). A frontend that starts while the database cannot be reached runs with that copy, not with the built-in defaults.Secrets. The document holds the API keys of Settings → API Keys and
collections_database_urlas they are inruntime_settings.jsontoday: in clear, in the database. Restrict access to the database as you restrict access to the configuration directory. The keys ofLOCALAI_API_KEYand--api-keysstay with the frontend that has them and never reach the database; each frontend adds them to the cluster’s keys.Upgrade. At its first start in a cluster, a frontend offers the cluster settings of its
runtime_settings.jsonand of its environment to the store. It does not change the file, so a rollback to a release without cluster settings still finds them there; in distributed mode the frontend ignores those keys in the file. A frontend that already holdscluster_settings_cache.jsonhas started in the cluster before and does not offer its file again; when the store holds no settings yet (a new or emptied database), it offers that cache instead. The cache is written only after the frontend has offered its settings: when that fails, the frontend keeps its own settings and offers them again at the next attempt. A key the store does not hold yet is added. For a key the store holds already, the stored value wins, with a warning in the log, with these exceptions for the security settings:- A security value that is not stricter than its default is never added: one frontend cannot turn on, for example, the host bash for the whole cluster. The cluster keeps the default until an administrator changes it in Settings, and the log names the keys.
- When the file of the frontend holds a stricter value than the store, the stricter value is stored, so an upgrade never loosens a frontend.
- The API keys are not tightened this way: a stored list can lack a key because an administrator removed it, so a file never adds keys to a stored list. Two different API key lists are not merged; the stored list wins and the log names
api_keys. Check the API keys after the upgrade.
The security settings and their strict values are
api_keys(a list over no list),corson (only the origins ofcors_allow_origins),chats_host_exec(off, then empty, thenask, thenon: empty isoffwith accounts andaskwithout),chats_egress_ceilingandchats_egress_default(offor empty, thenregistries, thenall),csrffalse(the field holds “disable CSRF”, sofalsekeeps the protection on),p2p_mode(off, thenconnect, thenshare),p2p_public_dhtoff, and off forchats_egress_allow_private,chats_web_allow_private,mcp_connectors_allow_private,chats_localai_admin,client_jobs_allow_all_tools,automations_skip_approvals,plugins_user_installs,shared_pages_enabledanduser_page_shares_enabled.Some other settings guard the instance too but have no order:
cors_allow_origins,galleries,backend_galleries,official_libraries,chats_web_ports,chats_egress_ports,chats_egress_extra_registries,chats_egress_allowed_hosts,chats_tool_providers,plugins_model_tiers,incognitoandincognito_max_level. For these the stored value wins at the upgrade, like for any other setting, and the log names the keys where a frontend’s file differs. Check them after the upgrade.Precedence. In standalone mode the environment and the flags win over
runtime_settings.json. In distributed mode they do not win over the cluster settings: the environment of a frontend adds the keys that the store does not hold yet, when the frontend starts, and for a key the store holds the stored value applies. A key that the store does not hold takes the value of the environment, of a flag or the default, never the value ofruntime_settings.json. One exception keeps a frontend from being loosened: a security setting that the environment or a flag sets to a stricter value keeps that value on that frontend, whatever the cluster says. This also holds for a value equal to the default, for exampleLOCALAI_P2P_MODE=offorLOCALAI_DISABLE_CSRF=false. The flags and variables that count are--cors,--disable-csrf,--p2p-mode,--chats-host-exec,--automations-skip-approvals,--disable-shared-pages,--disable-user-page-sharesand--disable-local-ai-assistant, and their variables. Edits of the cluster keys inruntime_settings.jsonare ignored in distributed mode. Single mode is unchanged.Add-ons. When add-ons are enabled, the add-on owner holds
chats_egress_*,chats_tool_providersandauto_upgrade_addons. They are not stored in the cluster settings, and a value of them in the cluster settings does not apply. The assistant changes them through the owner when the owner runs in the same process, and refuses them otherwise, asPOST /api/settingsdoes.Revisions.
GET /api/settingsreturnssettings_scope: "cluster"andsettings_revision. A save may sendsettings_revisionback and gets409when another admin saved in between, as formemory_revision. A save that holds both memory settings and other cluster settings checks both revisions before it stores either, so a409leaves both unchanged.Database not reachable at start. A frontend that cannot attach the cluster settings at start runs with its cached cluster document (or, before its first join, with its file) and tries again, after 1 second and then after twice the delay each time, up to every minute. Until it attaches, a save of a memory setting or another cluster setting gets
503, so the change is not stored on that frontend alone; a save of the frontend’s own settings works.Distributed state. Shared, like the memory settings: the same
syncstatemap and store, re-read every 30 seconds and after a reconnect. A frontend of an older release ignores theruntimedocument.
Disk prompt cache across nodes
The disk prompt cache keeps long llama.cpp prompts on disk so that a model reload starts warm. Each part has one owner:
| What | Owner |
|---|---|
| Cache files | Each worker, on its own local disk, under --prompt-cache-path, else <data path>/prompt-cache, else <models path>/../data/prompt-cache when that is local (see Worker setup). A worker whose root is on a network disk or not writable runs without the cache, and Settings shows why. Its backends write them and its own cleaner deletes them. Frontends never touch them, and no shared storage is used. |
Settings (prompt_cache_disk*) | The cluster. They are memory settings (see above): stored once in cluster_shared_settings, applied on every frontend, and sent to every worker with the control verb promptcache.sync. A worker does not read them from its environment; LOCALAI_PROMPT_CACHE_DISK=false on a worker can only turn its tier off. |
| Clears and the purge of a deleted user or device | The cluster. Written to the purge log (table prompt_cache_purges) and sent to every online worker at once. A worker that was offline gets the clears it missed when it is back. The log keeps a clear for 30 days; a worker that missed a clear that the log dropped deletes all its entries older than that clear. |
| Usage | Each worker answers promptcache.usage. GET /api/prompt-cache lists every worker and a total. |
Table prompt_cache_node_sync records, for each worker, the last clear it applied, the settings it runs and its process. One frontend at a time (advisory lock) checks every 30 seconds, and at once after a change of the settings, which workers are behind, and sends them what they miss. A worker that restarted gets the settings again. A clear of everything or of one model deletes only entries last used before the clear was asked for, so a clear sent twice or late deletes nothing newer. A worker older than the verbs is listed as not answering, and keeps its cache until the time to live.
Per-node memory limits
Five of the cluster memory settings can differ per worker: models kept loaded (max_active_backends), the GPU memory budget (vram_budget), the memory threshold (memory_reclaimer_threshold), model swap (model_swap) and eviction for memory (distributed_memory_eviction, see Eviction for memory). For each node the value in force comes from, highest first:
- an admin override for that node (the Limits pane of the node on the Nodes page,
PUT /api/nodes/:id/limits, or theset_node_limitsassistant tool). It survives worker restarts until it is cleared; - the worker’s environment (
LOCALAI_MAX_ACTIVE_BACKENDS,LOCALAI_VRAM_BUDGET,LOCALAI_MEMORY_RECLAIMER_THRESHOLD,LOCALAI_MODEL_SWAP,LOCALAI_DISTRIBUTED_MEMORY_EVICTION), reported when the worker registers. A worker that registers again (after a restart) replaces this value, never the admin override; - the cluster setting (Settings → Models in memory);
- the default.
A memory threshold set for one node (by an admin override or by the worker’s environment) also turns the memory reclaimer on for that node, even when the cluster setting leaves it off. To stop the reclaimer on such a node, clear its threshold.
A worker that reports unified memory (a GB10, a Thor, Apple silicon) reclaims memory at a threshold of 0.90 while the cluster settings do not name the memory reclaimer: the GPU and the system share one pool there, and a full pool starves the host.
GET /api/nodes/:id/limits returns each value with its source. A worker that sends "want_limits": true in its heartbeat gets the same object back as limits in the reply.
Eviction for memory
The scheduler sizes a model before it places it. When the size comes from the model’s own weight file (a local GGUF), the number is only a guide: it is too high for some models (hybrid and shared-KV layouts, input embeddings kept on the host). So the scheduler prefers a node with that much free GPU memory, but when no node has it, it does not refuse the load: it places the model as it would without a size, which can put it beside the models already loaded on a full node.
Eviction for memory lets the scheduler unload idle models on a node to make room in that case. It has three layers:
- The cluster switch: the runtime setting
distributed_memory_eviction(Settings → Models in memory → Unload idle models to make room for new ones, flag--distributed-memory-eviction, environmentLOCALAI_DISTRIBUTED_MEMORY_EVICTION). Default off. It is a memory setting, so it is stored once for every frontend. - The node’s value:
alloworneverfor one node, orinheritto use the cluster switch. An admin sets it withPUT /api/nodes/:id/limits({"distributed_memory_eviction":"never"},"inherit"clears it) or theset_node_limitsassistant tool. A worker sets it withLOCALAI_DISTRIBUTED_MEMORY_EVICTION=allow|never(alsotrue|false), reported when it registers. An admin value wins over the worker’s, and survives worker restarts. A worker that does not report the value uses the cluster switch. - The eviction settings decide how it evicts: a model of the same concurrency group first, then the least recently used idle model (the largest first with
size_aware_eviction), as many as the size needs and no more. Pinned models, models below a rule’smin_replicas, and nodes withmodel_swapoff are left alone. The memory threshold (memory_reclaimer_threshold) is kept free.
For each candidate node the value in force is: the node’s value when it has one, else the cluster switch, else off. GET /api/nodes/:id/limits shows the value in force and its source.
GET /api/nodes shows the value in force of each node as distributed_memory_eviction: {"allowed": true, "source": "override"}, where source is override (an admin set it for the node), worker (the worker reported it), or cluster (the node follows the cluster switch).
On the Workers page. The roster has a column Make room with one tag for each node: Allowed · cluster, Allowed · this worker, Never · this worker or Never · cluster. The word after the dot says where the value comes from: the cluster switch, or this worker. A tag with the accent colour means the node overrides the cluster. A line above the roster says if the cluster switch is on and how many nodes override it. To change one node, choose it in the roster and use Unload idle models to make room in its panel (a bottom sheet on a phone): Inherit follows the cluster switch and clears the value an admin set, Allow and Never set it for this node. The choice is saved as soon as you make it, with a message in the corner. Only an administrator can change it. The panel also says in one sentence why the node has its value, and What do Inherit, Allow and Never mean? explains the three choices.
Never only stops the scheduler from unloading a model to make room for a new one on that node. The Models kept loaded settings and the other eviction settings still apply there, so a node with Never can still unload a model to stay within its limit.
A model that serves a request is never unloaded for this, even with force_eviction_when_busy. When the idle models of a node cannot free enough, nothing is unloaded and the model loads as it would with the switch off: eviction for memory never refuses a load. Each eviction is logged at info level with the model, the node and the models it unloaded, and every administrator gets a notification such as “Unloaded old-model on gpu-a to load new-model”. This holds for every eviction the scheduler makes for GPU memory, also for a size that is a limit.
When a load fails because a node ran out of memory and eviction for memory is off on that node, the error the request gets (and the log) says so and names the two ways to turn it on: the cluster switch, or allow for that node. The message of any other failure, or of a node where eviction is on, is unchanged.
A size from another source (the gallery, or a remote file) is not a guide but a limit: such a model already goes only where it fits, after evicting idle models if that makes room, and the request gets 503 when no node can hold it. The switch does not change that.
Per-node VRAM budget
Each worker advertises its detected VRAM, and the SmartRouter uses that number when picking a node with enough free memory. You can cap the VRAM a node offers for placement so it never gets scheduled beyond a chosen limit, leaving headroom for other workloads on that machine.
There are two ways to set the cap:
- At the worker: start it with
--vram-budget/LOCALAI_VRAM_BUDGET(see Worker Configuration). - From the frontend, live: set it per node in the node capacity editor on the node detail page, or via the admin API:
The value accepts the same formats as the standalone budget: a percentage (80%) or an absolute amount (12GB, 12GiB, 12000MB, or raw bytes). It is a hard ceiling: the budget keeps total - budget of the node’s VRAM out of reach, so the free VRAM the scheduler sees is the reported free VRAM minus that reserve. A node with a 12GB budget on 24 GB that already uses 4 GB has 8 GB left for new models, not 12. A budget can only lower the number, never raise it above the hardware. When no admin budget and no worker budget is set, the GPU memory budget of Settings → Models in memory applies to each worker (see Per-node memory limits). An admin-set node budget is sticky across worker restarts: it is stored in the node registry and reapplied when the worker re-registers, so it wins over whatever the worker reports on reconnect. For the underlying semantics and the standalone equivalent, see VRAM Budget.
The Nodes page draws the VRAM bar of a node with a budget against the budget, and shows the detected total next to it, so an idle node with a 40GB budget reads 0 of 40 GB in use, not 148 of 188 GB.
Budget and total are different settings. LOCALAI_VRAM_BUDGET is the share of the node’s VRAM that LocalAI may use. LOCALAI_VRAM_TOTAL is how much VRAM the node has, and replaces what GPU detection found. Use the total when detection is wrong (see Troubleshooting), and the budget to keep headroom. With both set, the budget applies to the total: LOCALAI_VRAM_TOTAL=40GB with LOCALAI_VRAM_BUDGET=80% offers 32 GB for placement.
Runtime state: none is added. The worker reads the total at start and reports it on registration; the frontend stores it in the node registry with the other node fields, so every frontend sees the same figure.
Disk headroom
Model weights are staged onto the worker’s disk before the backend loads them, so a node needs free space as well as free VRAM. Each worker reports the capacity of the filesystem backing its models directory (--models-path), not the root filesystem, on registration and on every heartbeat. Those figures appear as total_disk and available_disk in the nodes API and as Models disk free on the node detail page.
Before placing a model, the SmartRouter removes any node whose models filesystem cannot hold it. The requirement is derived from the model’s actual on-disk size plus a small margin (5%, at least 1 GiB), rather than a fixed percentage of the node’s disk, a fixed threshold would take a small-but-usable node out of rotation for models it could comfortably store. When the model’s size cannot be determined locally (a bare HuggingFace repo id that the worker fetches itself), the node only has to clear a 2 GiB floor.
If no node has enough space, the request fails immediately with a capacity error naming the requirement and each node’s free space, for example:
scheduling longcat-video-avatar-1.5: no node has enough free disk for the model:
need 73.5 GB free on the models filesystem, but nvidia-thor has 0 B free of 937.0 GBThis is deliberately a scheduling-time verdict. Without it, a worker with a full disk still reported status: healthy, accepted the staging request, transferred tens of gigabytes and only then failed with no space left on device, minutes after a decision that could never have succeeded.
Workers that predate this feature (or whose disk reading fails) report total_disk as 0. Such nodes are treated as unknown, not full, and stay in rotation, so a rolling upgrade never empties the candidate pool. A full disk is distinguishable because it reports a non-zero total_disk with available_disk at 0.
Low disk does not mark a node unhealthy. Disk is compared per model rather than against a global threshold, so a node that is too small for one model remains a valid target for smaller ones. The check is also skipped entirely in shared-models mode, where nothing is staged to the worker at all.
Turning the check off
The check is on by default. To disable it, start the frontend with --distributed-disk-headroom-check=false / LOCALAI_DISTRIBUTED_DISK_HEADROOM_CHECK=false, or toggle Settings → Distributed → Disk headroom check in the WebUI (distributed_disk_headroom_check via POST /api/settings). The runtime setting takes effect on the next placement, with no restart; the env/CLI flag only sets the value LocalAI boots with, and both write the same underlying value, so the last change wins.
Disabling means warn, do not block. Node selection goes back to ignoring free disk (the pre-check behaviour), but the check still runs, and when it would have rejected every node it logs a warning naming the shortfall:
WARN No node has room to store this model, but the disk-headroom check is DISABLED;
scheduling anyway — staging will most likely fail with ENOSPC
model=longcat-video-avatar-1.5 knob=distributed-disk-headroom-checkThe alternative (skipping the check outright) was rejected because it reproduces the condition that made the original bug expensive: the cluster was doing something that could not work and said nothing about it. The escape hatch exists for setups where the size estimate is wrong (deduplicating or compressing filesystems, a backend that fetches its own weights rather than using the staged copy), and in exactly those cases the operator needs to see what LocalAI thought was wrong. Disabling is logged once at startup as well.
The LocalAI Assistant can also set a node budget conversationally through the set_node_vram_budget MCP tool.
Node Approval
By default, new worker nodes start in pending status and must be approved by an admin before they can receive traffic. This prevents unknown machines from joining the cluster.
To approve a pending node via the API:
The Nodes page in the WebUI shows pending nodes with an Approve button, and so does the node’s own page and the Add a node page once the machine has registered.
A worker that joins with a worker invite always waits for approval the first time, and keeps its approval when it registers again from the same peer.
To skip manual approval and let nodes join immediately, set --auto-approve-nodes (or LOCALAI_AUTO_APPROVE_NODES=true) on the frontend. This is convenient for development and trusted environments.
Node Statuses
| Status | Meaning |
|---|---|
pending | Node registered but waiting for admin approval (when --auto-approve-nodes is false) |
healthy | Node is active and responding to heartbeats |
unhealthy | The HealthMonitor found no live route to the node: it heartbeats, but neither NATS nor its tunnel is live (see Node health and routes), or it missed heartbeats while auto-offline is off. Status only: nothing of the node is deleted, and it becomes healthy again when a route is live |
offline | Node is temporarily offline (graceful shutdown or stale heartbeat). The node row is preserved so re-registration restores the previous approval status without requiring re-approval |
draining | Nothing new is placed on the node. Its loaded models keep serving until replacements load on other nodes, then leave. See Draining a node |
Draining a node
Drain a node before you take it out of service: maintenance, a GPU lease, a new image. A drain does not drop the models of the node. It replaces them first:
- The node gets the status
drainingat once. No new model is placed on it, by a request or by the reconciler. - Its loaded models keep serving. A replica on the draining node has the lowest preference: a request goes to it when no healthy node has the model, or when it runs fewer requests than the least busy replica on a healthy node. On a tie, the healthy replica wins.
- The reconciler does not count a replica on a draining node. A model with a scheduling rule gets replicas on other matching nodes up to its
min_replicas(or one per matching node withspread_all), with the usual placement rules (node selector, memory fit, model limits). A model with no rule (or a rule with no floor) gets one replacement when the replica on the draining node is its last one and the model is in use: it is pinned, a request runs on it, or it served a request within the idle window. The replacement goes to a healthy node that matches the node selector of the rule; when none matches, nothing is placed and the replica serves until the deadline. A model that is not in use is not replaced. - A replica leaves the draining node, and its backend is stopped, when the model has enough replicas on healthy nodes, once the requests that run on it finish. A replica on an
unhealthynode does not count, because it takes no requests. An idle replica that no model needs leaves on the next reconciler pass. - At the drain deadline (
--drain-timeout, default10m, or?timeout=of the request) whatever is still on the node is removed, also when no replacement could be placed.
A drain is never a window with zero replicas for a model that has a replacement: the old replica serves until the new one is loaded.
Loads that run on the node when the drain starts are cancelled, because a model must not land on a node that leaves.
Force. POST /api/nodes/:id/drain?force=true takes the models of the node out of routing at once, as drain did before this change. The reconciler then places replacements for the rules on its next pass. Use it when the node must stop serving now.
A node that does not answer. An unhealthy or offline node drains at once: there is nothing on it to wait for. A draining node that stops answering loses its models when the health monitor sees no live route that carries work and a heartbeat older than --stale-node-threshold (5m by default), so it is not routed to until the drain deadline. Before that, a request that reaches one of its replicas finds the backend dead in the health check before the request is sent, and that replica is removed then.
Resume. POST /api/nodes/:id/resume (or Resume on the Nodes page) cancels the drain. The node is healthy again and the models still on it stay. A worker that registers again (it restarted) also ends the drain of its node.
Status. GET /api/nodes and GET /api/nodes/:id show status: draining, drain_deadline and leaving_replicas, the number of loaded models still on the node. The Nodes page shows Draining, the count and the deadline. The assistant tool drain_node (actions drain and resume) does the same as the API.
Recommended sequence for external tools (a GPU lease tool, a maintenance script, a cluster autoscaler):
POST /api/nodes/:id/drain(with?timeout=if the default does not fit).- Poll
GET /api/nodes/:iduntilleaving_replicasis0. - Stop the worker. A worker that is stopped earlier is safe, but its models are removed when it goes, and a model that had no replacement yet is not served until one loads.
Worker shutdown
A worker that gets SIGTERM (or a node.stop from the frontend) shuts down in this order:
- It refuses new backend installs and upgrades at once. A load sent to it fails with
the worker is shutting down; the frontend marks the nodedraining, so placement skips it, and answers the request with503andRetry-After. The next attempt loads the model on another node. - It aborts the loads in progress: it cancels their downloads, kills their backend processes, and waits until the processes exited and the installs returned, for up to
--shutdown-abort-wait(30s) in total. A load that is still downloading has no process yet; it does not start one after this point. A stop the frontend sends for a process that is already being stopped is acknowledged as soon as that process exited, or answered “already stopping” after 5 seconds, before the frontend stops waiting for the reply. - It drains its node through
POST /api/node/:id/drainwith{"shutdown":true}, and adds"loads_ended":truewhen every load ended in step 2. The frontend cancels the load jobs of the node and, when the worker vouched that the loads ended, releases them at once instead of holding the model for the 150 second stop window. A request or the reconciler then loads the model on another node within seconds. A load that did not end in the abort wait is released after the stop window, as for a worker that died. - Its loaded models keep serving the requests in flight for up to
--shutdown-request-wait(30s). New requests go to other replicas when there are any. The reconciler starts the replacements of the drain in this window. - It deregisters (
offline): the frontend removes its replicas, and the reconciler places what is still missing. - It stops its backends: each gets a bounded
Free()call and is then stopped.
Step 2 is bounded by --shutdown-abort-wait (30s), and steps 3 to 5 by --shutdown-timeout (60s). The total shutdown time is at most the sum of the two bounds (90s with the defaults) plus the stop of the backends, which runs one backend after the other: up to 5 seconds of Free() for each, plus the time its process takes to exit. Step 2 takes seconds in practice: a killed process group exits at once.
Kubernetes
LocalAI ships no manifests for the workers; these are the settings that fit the shutdown above.
terminationGracePeriodSeconds: cover the abort wait, the shutdown timeout and the stop of the backends. With the defaults (30s+60s), use at least120; with several large backends per worker,150. A pod killed before the end loses the acknowledgement of its loads, and the frontend then holds those models for the stop window.preStop: not needed. The worker handlesSIGTERMitself (steps 1 to 6). Use apreStophook that callsPOST /api/nodes/<node id>/drainwith an admin key only if you want the drain to start before the pod receivesSIGTERM, for example to give replacements more time than--shutdown-request-wait. The hook time counts againstterminationGracePeriodSeconds.- Rolling updates of GPU workers:
maxUnavailable: 1andmaxSurge: 0. A surge pod usually cannot get a GPU, and taking down more than one worker at a time can remove every replica of a model. - PodDisruptionBudget:
maxUnavailable: 1on the worker pods, so a node drain of the cluster does not take several workers down at once. - Redeploying on every image: a rollout restarts each worker, and every model that worker held is loaded again somewhere. A load in progress is aborted and starts again on another node. When the CD redeploys workers on every build, a large model can be reloaded many times a day; pin the worker image, or roll out workers on a schedule.
Where the state lives: the drain is the status and drain_deadline columns of the node in PostgreSQL, and the replica rows. Every frontend reads the same drain, and the reconciler pass that moves the replicas runs on one frontend at a time under its advisory lock. Nothing of a drain is kept in the memory of a frontend.
Node health and routes
The HealthMonitor judges each node by the routes that node holds, whatever routes the other nodes use. It never reads the carrier setting of the cluster. For each node it looks at:
| Route | Live when |
|---|---|
heartbeat | The last heartbeat is younger than --stale-node-threshold. It shows that the worker process runs and carries the route report, but it does not carry work. |
nats | The last route report of the worker lists NATS in attached, and the heartbeat that carried it is fresh. |
tunnel | A frontend holds the WebSocket or P2P tunnel of the worker. A tunnel that dropped less than the reconnect grace ago (one minute) is reconnecting and still counts while the heartbeat is fresh. When no frontend has a record of the tunnel, the route report of the worker decides. |
A node is healthy while one of its nats or tunnel routes is live:
- A node that loses one route and keeps another stays
healthy. The lost route is shown asdown, with the reason the worker gave, and the frontend logs it once. - A node whose heartbeat is stale while a frontend still holds its tunnel stays
healthy. The heartbeat is shown asdown. - A node that heartbeats and has no live route is marked
unhealthyonce it has been so for the reconnect grace (one minute). A tunnel that has been gone for longer than the grace already counts, so a tunnel-only node is marked at once. A route that comes back inside the grace changes nothing, so a reconnect does not make the node flap. The node is not probed while it isunhealthy, and nothing of it is deleted. - A node with a stale heartbeat and no live route follows the stale rules: it is marked
offline(orunhealthywith auto-offline off), as described below. - A node that has not sent its first route report is judged by its heartbeat alone.
A worker sends no heartbeat while it holds no route, so a worker that loses its only route goes stale and is marked offline after --stale-node-threshold. Each frontend that runs the health checks counts the grace on its own. A frontend that has not checked the node for three check intervals starts the grace again, which delays the mark.
GET /api/nodes and GET /api/nodes/{id} return route_state for each node: a list of {route, transport, state, reason} entries, where route is heartbeat, nats or tunnel, transport is websocket or p2p for the tunnel, and state is live, reconnecting or down. The LocalAI Assistant tool list_nodes returns the same list as routes. On the Workers page, the Connections column of the roster shows one chip per route with its state, and the reason when you point at it.
Heartbeat writes and stale-node detection
Workers beat every --heartbeat-interval (default 10s). Writing each beat straight
to PostgreSQL means roughly 52,000 UPDATEs a day against a table that holds one row
per node. With autovacuum healthy that is merely wasteful. With autovacuum blocked –
by a long-lived idle transaction, for example – the dead tuples accumulate, and a
six-row table has been observed growing to 460 MB, at which point scanning it cost
867 ms and the queries that place models began timing out.
So the frontend checkpoints the write. A beat that carries nothing but a fresher
timestamp is held in memory until --node-heartbeat-checkpoint (default 60s) has
elapsed since that node’s last durable write. These beats still reach the database
without waiting:
- the node’s first beat after the frontend starts, or after it was seen offline
- any beat from a node that is not active (
pending,offline), because such a node recovers only when the health monitor sees a fresh timestamp - a GPU vendor, total VRAM or total disk that differs from the stored value, since those are hardware facts and a change to one is a real event
- a free VRAM, free RAM or free disk reading that has moved more than 256 MiB, because the scheduler places against those figures
CPU utilization and load follow the scheduled checkpoint instead of making a heartbeat material. They are dashboard observations and do not affect model placement, so persisting every fluctuation would defeat write suppression.
Every figure is compared against the value last written, not against the previous beat. A worker reports its disk capacity on every single beat, so testing whether a field is merely present would make every real beat look like a change and suppress nothing. Measuring from the written value also means a reading that walks away in sub-256 MiB steps still writes once the total distance crosses the threshold, rather than drifting arbitrarily far from the figure the scheduler is reading.
The consequence is that last_heartbeat is up to one checkpoint interval behind
reality by design. The stale-node threshold therefore defaults to 5 minutes
(it was 60 seconds before checkpointing existed): the health monitor waits that long
without a fresh timestamp before it marks a node offline. It is configurable with
--stale-node-threshold / LOCALAI_STALE_NODE_THRESHOLD, and an operator who widens
--node-heartbeat-checkpoint must widen this to match, or the beats that checkpointing
suppresses will read as a dead node.
Marking a node offline from a stale heartbeat now takes up to five minutes. This is
the slowest of the three ways a dead worker is noticed, not the only one. The per-model
gRPC health check still probes each loaded model on the health-monitor interval
(default 15s) and removes replicas whose backend has died, and a request routed to a
gone worker still fails and is retried elsewhere at request time. Neither of those
paths reads last_heartbeat, so neither is slowed by this change.
To go back to a durable write per beat – on a database with plenty of write headroom,
or while debugging heartbeat delivery – set LOCALAI_NODE_HEARTBEAT_CHECKPOINT to a
value below the worker’s heartbeat interval, for example 1s.
Operations: do not share a database with the vector store
Give the control plane a PostgreSQL database of its own. Sharing one with the agent vector store, or with anything else that holds long transactions, is the fastest way to reproduce the 460 MB node registry described above.
PostgreSQL computes the removable-tuple cutoff per database, not per table. One
transaction left open anywhere in the database – a stalled embedding batch, an idle
BEGIN from a connection pool, an abandoned psql session – pins that cutoff for
every table in it. Autovacuum still runs, finds nothing it is allowed to reclaim,
and moves on. The node registry is six rows rewritten tens of thousands of times a
day, so it is the table that pays: it bloats into hundreds of megabytes, a sequential
scan starts costing the best part of a second, and model placement begins timing out
while the vector store that caused it looks perfectly healthy.
Concretely, these two must point at different databases:
| Variable | What it holds |
|---|---|
LOCALAI_AUTH_DATABASE_URL | Auth and the distributed control plane - nodes, replicas, load jobs |
LOCALAI_COLLECTIONS_DATABASE_URL | Collections and their embeddings |
Different databases on the same PostgreSQL server is enough; they do not need separate servers. Different schemas in one database is not enough, because the cutoff is per database.
To detect it before placement starts failing, watch the
localai_control_plane_oldest_xmin_age gauge, exported on the frontend’s OpenTelemetry
meter. It reports how many transactions have elapsed
since the oldest snapshot still held open against the control plane’s database. Under
normal load it stays small and flat. A line that climbs without coming back down means
something is holding a transaction open and autovacuum has stopped reclaiming the node
registry; find it with:
Grant pg_read_all_stats to the role LocalAI connects as (GRANT pg_read_all_stats TO localai;), or make it a superuser. PostgreSQL blanks backend_xmin and xact_start in
pg_stat_activity for sessions owned by other roles, so without that grant both the
gauge and the query above see only LocalAI’s own sessions – and the transaction that
wedges the horizon is typically the co-located vector store connecting as a different
role, which is exactly the case they exist to catch.
Agent collections across frontends
Collections (the /api/collections routes) are shared state: every frontend shows the same list. With the postgres vector engine, the database is the source of truth for which collections exist. Each frontend keeps the collections it has opened in memory, but only as a cache:
- Listing a collection set reads it from the database.
- A request for a collection that this frontend has not opened yet checks the database before it answers
404, and opens the collection if it exists. A collection created through one frontend is therefore usable through any other one at once. - A frontend re-checks a cached collection at most every 5 seconds, so a collection removed through another frontend stops being served within that time.
- Creating or resetting a collection publishes an event on the message bus, so the other frontends re-check immediately.
This needs LOCALAI_COLLECTIONS_VECTOR_ENGINE=postgres and LOCALAI_COLLECTIONS_DATABASE_URL. With another vector engine there is no shared registry, and each frontend keeps its own list. Per-user collections (authentication enabled) are not yet coordinated this way.
Agent Workers
An agent worker is a dedicated process that runs the MCP servers of your models, for example stdio servers that need docker. The frontend sends it MCP tool calls and discovery requests over its routes: NATS, the WebSocket tunnel, or both. It needs no database and runs no model.
Agent workers:
- Handle MCP tool discovery and execution requests from the frontend
- Close their MCP sessions when a backend stops
The routes of an agent worker follow the same flags as a backend worker (--routes, LOCALAI_WORKER_ROUTES), with other defaults: nats when --nats-url is set, and tunnel when a registration token is set, because the token guards the control server that the tunnel reaches. With neither, the agent worker holds NATS with the address that the frontend hands over. On NATS an agent worker answers in the agent-workers queue group and on the subjects of its own node. An agent worker over P2P is not supported.
The agent worker does not run chat turns. To run the turns of triggers, connectors and agent jobs away from the frontends, use chat workers. The options LOCALAI_AGENT_SUBJECT, LOCALAI_AGENT_QUEUE, LOCALAI_MCP_CI_JOB_TIMEOUT, LOCALAI_API_URL and LOCALAI_API_TOKEN are still accepted by local-ai agent-worker and ignored. LOCALAI_MCP_CI_JOB_TIMEOUT is live on the server command (local-ai run, also used by frontends and chat workers) and is ignored only on local-ai agent-worker. LOCALAI_AGENT_JOB_RETENTION_DAYS is read by local-ai run.
In docker-compose.distributed.yaml, the agent worker mounts the Docker socket so it can run MCP stdio servers (e.g., docker run commands). It keeps its own credential in /data, so mount a volume there too:
The container does not run LocalAI as root. Its entrypoint adds the group that owns /var/run/docker.sock to the user of LocalAI, so the agent worker can use the socket. Access to the Docker socket is equal to root access on the host. When root owns the socket with group root, as on Docker Desktop, the user cannot join that group: set LOCALAI_RUN_AS_ROOT=true there. See Container user and permissions.
Backend workers also install backends. Mount a volume on /backends of each worker, so that a recreated container does not download them again.
Chat Workers
A chat worker runs the turns of the chats that no person starts at the keyboard: trigger runs, agent jobs and connector messages. Use one to keep this work off the frontends that serve your users.
A chat worker is a local-ai run instance with the same configuration as a frontend (database, NATS, models, storage and data path), plus --chat-worker. The chat-worker-1 service in docker-compose.distributed.yaml is an example. It needs the same NATS credentials as a frontend, and a peer address that the frontends can reach, because they send it the chat starts over the peer link. Turn on the routing on the frontends with --distributed-chat-workers:
How it works:
- The frontends keep the trigger runner, the connectors and the job host, each on the frontend that holds its leader lock. When one of them starts a turn, the frontend sends the start over the peer link to a live chat worker that it picks from the node list, with or without NATS. The chat worker takes it, claims the turn in the database and runs it. It replies whether the turn started or whether the message waits behind a running turn.
- The turn’s live events and a stop travel on the same subjects as between two frontends, so a user who watches the chat sees it through any frontend, and a stop or a run limit reaches the worker.
- The notification center runs in every process, a chat worker included, on the same store. A notification stored by one process reaches the streams of every frontend over the message bus. Its state is shared (rows in the database) and live-only on the bus; see Storage and clusters.
- A message that a person sends to the chat while the worker runs it waits in the database, and the worker gives it to the model at its next request.
- When no chat worker listens, the frontend runs the turn itself. When a chat worker does not answer in time, or refuses the start, the run fails: the worker may have started the turn, and running it again could send the message twice. The time a start may take is
LOCALAI_CHAT_START_TIMEOUT(default30s). Raise it when a slow database makes starts time out, and set the same value on the frontends and the chat workers. - The frontend that watches a job or a trigger run stops it at its limit (
LOCALAI_MCP_CI_JOB_TIMEOUTfor a job). If that frontend is gone, the chat worker stops the turn one minute after the same limit, so it cannot run on without a bound. The same bound applies to the next turn that the worker starts from messages that arrived after the last model request. SetLOCALAI_MCP_CI_JOB_TIMEOUTto the same value on the frontends and the chat workers. - A chat worker runs at most
LOCALAI_CHAT_WORKER_MAX_TURNSturns at once (default32). Every turn on it counts, also the sub-agents of its turns. When it is full it refuses a start that would begin a turn. A message for a chat whose turn already runs is still taken, because it only waits. The frontend then sends the start to another chat worker; the run fails, with an error that says the worker is full, only when every worker it tried (up to three) is full. Nothing runs on the frontend then. - A chat worker that dies leaves its turn claimed. The frontends’ reaper ends it as interrupted, as for a frontend that dies, and nothing retries it.
- A chat worker shows in the node list as an
agentnode with the labelsnode.role=chat-workerandnode.instance(the instance ID that the frontends reach it by over the peer link), namedchat-and its instance ID (LOCALAI_INSTANCE_ID), or its host name when the ID is generated. It registers itself through the database, is approved at once, sends a heartbeat every 10 seconds and goes offline when it stops. Models are never scheduled on it. Draining it from the node list does not stop it from taking starts: stop the process instead. - A chat worker starts no triggers, connectors or jobs and runs no conversion of old data. It still serves the HTTP API: its turns reach the models through it, and the health probes use it. Do not put it behind the load balancer of your users.
What stays on the frontends:
- The chats that a person starts, and their sub-agents.
- A start that carries files, such as a connector message with a photo or a job with attachments. The files are saved before the turn starts.
- Sub-agents follow their parent: the sub-agents of a turn that runs on a chat worker run on that worker.
Request and reply between frontends and chat workers
A chat start, the replay of the events of a turn to a client that reconnected to another frontend, and the background jobs of a turn that runs on another node are request and reply between processes. With or without NATS, they go over the peer link between the two processes (/api/cluster/peer), the link that also carries the requests for a worker whose tunnel another frontend holds. NATS never carries them. Every frontend and chat worker needs a peer address that the others can reach: it is found at start, and LOCALAI_PEER_ADDRESS sets it when the one found is wrong. A frontend or chat worker that has none is not ready: /readyz answers 503 with the status unavailable and a reason that names LOCALAI_PEER_ADDRESS. Workers that run models open no new port for this.
- A chat start goes to a live chat worker that the frontend picks from the node list. When that worker cannot be reached, or is full, the frontend tries another one (up to three). Each try may spend only its share of
LOCALAI_CHAT_START_TIMEOUTto reach its worker, so a worker that does not answer leaves time for the others. When the start has been sent and no answer comes back, the run fails and nothing is retried: the worker may have started the turn, and a second start could send the message twice. When no chat worker can be reached, the frontend runs the turn itself, as it does when none is live. - The replay asks the frontend that runs the turn and waits up to 2 seconds. On a slow link that also carries large model file transfers to a worker, the answer can take longer, and the client then reads the transcript instead of the missed events.
- A turn reaches a background job on another node. When that node does not answer, the tool call says so and the job stays as it is. A job is marked lost only when its node does not know the job. A node that does not answer is never taken as a node that left the cluster, because a live frontend whose heartbeats stall for a while looks the same, so the job of a node that left stays listed as running.
- Chat events, notifications and stops are broadcasts (see The broadcast buses), and they work with or without NATS.
MCP in Distributed Mode
MCP servers configured in model configs work in distributed mode. The frontend routes MCP operations to agent workers, over NATS or their tunnels:
- MCP discovery (
GET /v1/mcp/servers/:model): routed to agent workers which create sessions and return server info - MCP tool execution (during
/v1/chat/completions): tool calls are routed to agent workers by request and reply
vLLM Multi-Node (Data-Parallel)
A single vLLM model can span multiple GPU nodes via data parallelism: the head node serves the OpenAI API and runs the local DP ranks, follower nodes run vanilla vllm serve --headless and speak ZMQ directly to the head. LocalAI’s role is starting the follower processes and surfacing them in the admin UI; the cross-rank tensor traffic is vLLM’s own.
This mode is operator-launched - the head config and each follower’s invocation must agree on the topology (data_parallel_size, data_parallel_size_local, data_parallel_address, data_parallel_rpc_port). The SmartRouter does not place follower ranks automatically.
Head node configuration
The head runs the existing single-node vLLM gRPC backend. Set engine_args to publish the DP topology vLLM expects:
The head will start its 2 local ranks, listen on 10.0.0.1:32100, and wait for the remaining 2 ranks to handshake.
Follower nodes
Each follower runs local-ai worker vllm with matching topology, an explicit start rank, and the head’s address (the old name, local-ai p2p-worker vllm, still works):
--register-to is optional but recommended - it makes the follower visible in the admin UI as an agent-type node tagged with node.role=vllm-follower. Without it the worker just runs vLLM and exits silently when vLLM does. The role label discourages SmartRouter from placing other models on the follower; pair it with model selectors like {"!node.role":"vllm-follower"} if you also run regular LocalAI models on the same fleet.
Worked example: 2-node Kimi-K2.6 deployment
Two A100 nodes (10.0.0.1, 10.0.0.2), 8 GPUs total, data_parallel_size=8 with 4 ranks per node:
A curl http://10.0.0.1:8080/v1/chat/completions ... against the head will then dispatch across all 8 ranks.
Intel Arc / XPU notes
vLLM XPU supports DP (vllm/platforms/xpu.py:198 handles world_size_across_dp > 1; ranks bind to xpu:{local_rank} in xpu_worker.py:62, with xccl as the collective backend). Each rank still needs a distinct discrete GPU - the iGPU on a hybrid host is not a viable second device.
Older XE-HPG GPUs (e.g. Arc A770) need to bypass the cutlass attention path:
docker-compose.vllm-multinode.intel.yaml at the repo root is the Intel equivalent of docker-compose.vllm-multinode.yaml - uses /dev/dri passthrough, ZE_AFFINITY_MASK to pin each rank to one device, and latest-gpu-intel images. Run via ./tests/e2e/vllm-multinode/smoke.sh --intel.
Caveats
- Tensor parallel within a node only. vLLM v1 does not support TP across nodes; combine
tensor_parallel_size(within a node, viaengine_args) withdata_parallel_size(across nodes). - Followers don’t host LocalAI gRPC. The follower process is vanilla vLLM, so
/api/backend-logs/<modelId>does not stream follower output. Usejournalctl/kubectl logs/ compose logs for the follower’s stderr. - Network reachability. The head’s
data_parallel_rpc_portplus a range of ZMQ ports (typicallydata_parallel_rpc_port..+N) must be reachable from every follower. Open them in your firewall / security group. - Topology must match exactly. A mismatch in
--data-parallel-sizebetween head and any follower will hang the handshake. Check the head’s vLLM logs forwaiting for N DP ranksif startup stalls.
ds4 Layer-Split Distributed Inference
The ds4 backend (DeepSeek V4 Flash) supports layer-parallel distributed inference: a single model that is too large for one machine is split by transformer layer across several machines. Each machine must have the GGUF present locally, but loads only its own slice of the layers. This lets you run a model whose weights exceed any single host’s memory.
This is not routed through the SmartRouter: it is a model-internal split, configured manually (Phase 1). It is unrelated to the NATS/PostgreSQL distributed mode described above.
Topology


ds4 uses a coordinator/worker split:
- The coordinator owns tokenization, sampling, the prompt, and a low layer range (e.g.
0:19). It is LocalAI’s ds4 backend and listens on a host/port. Workers dial into it. - One or more workers own higher layer ranges (e.g.
20:output). Each worker loads only its slice and dials the coordinator to register the range it can serve. The last worker normally owns the output head. - Activations flow through the connected slices and back to the coordinator. The route is “ready” only once the coordinator plus all connected workers cover every layer.
This dial direction is the inverse of the llama.cpp RPC model, where the main server dials out to a list of rpc-server workers. With ds4 the workers dial in to the coordinator.
Coordinator setup
The coordinator is a normal LocalAI ds4 model whose YAML carries distributed options::
| Option | Meaning |
|---|---|
ds4_role:coordinator | Enables distributed coordinator mode. Without ds4_role, the backend behaves as a normal single-node ds4 model. |
ds4_layers:0:19 | The coordinator’s own layer slice (inclusive). |
ds4_listen:0.0.0.0:1234 | Address that workers dial into. |
ds4_route_timeout:60 | Optional. Seconds the coordinator waits for the worker route to form before returning an error on a request. Defaults to 60. |
Worker↔coordinator traffic is plaintext and unauthenticated: there is no TLS or auth on this channel. Bind ds4_listen to an address on a trusted/private network only; using 0.0.0.0 exposes the coordinator on every interface. Run the layer split exclusively over a network you control.
Once the model is loaded, the coordinator serves requests exactly like a single-node ds4 model: generation goes through the ordinary inference path and is transparently routed across the layer slices.
Worker setup
On each worker machine (with the GGUF present locally), start a worker pointed at the coordinator:
local-ai worker ds4-distributed resolves the ds4 backend and execs the packaged ds4-worker binary, passing everything after -- straight through.
Layer-range semantics
- Ranges are inclusive:
0:19is layers 0 through 19. N:outputmeans layer N through the final layer plus the output head. The last worker normally owns the output head.- The coordinator and all connected workers together must cover every layer. Until they do, the coordinator returns a gRPC
UNAVAILABLEerror on inference requests (so a worker that starts slightly after the coordinator is tolerated: once it connects and the route is complete, requests succeed). The wait is tunable viads4_route_timeout.
ds4 layer-split inference is manual setup. You place the coordinator config and start each worker yourself. You must split the layer ranges by hand so that they cover the whole model. The coordinator is not found automatically over P2P.
Scaling
Adding worker capacity: Start additional worker instances pointing to the same frontend. They self-register automatically:
Multiple frontend replicas: Run multiple LocalAI frontends behind a load balancer. Since all state is in PostgreSQL and coordination is via NATS, frontends are fully stateless and interchangeable.
Model Scheduling
Model scheduling controls where models are placed and how many replicas are maintained. In the React WebUI it has its own page, Placement (Admin → Cluster → Placement, the Rules view, at /app/scheduling). Each rule is written as a sentence, shows the nodes the model is loaded on now, and opens in a side sheet that previews which nodes the draft rule could use. The preview is worked out in the browser from the node list and labels; the scheduler also checks free memory and disk when it loads a model. A deleted rule can be taken back for a few seconds. A rule combines two optional features:
Node Selectors
Pin models to nodes with specific labels. Only nodes matching all selector labels are eligible:
Without a node selector, models can schedule on any healthy node (default behavior).
Placement is strict. A load, from a request or from the replica reconciler, only goes to a node that matches the rule that governs the model:
- When no matching node is healthy, the request fails with
503and aRetry-Afterheader. It never falls back to a node the selector excludes; use failover chains to serve the model elsewhere. - When the rule cannot be read (for example during a database timeout), the
request fails with the same retryable
503. It is not treated as “no rule”. - A selector that is not valid JSON blocks placement instead of matching every node.
Every cold-load placement logs one Placed cold load line with the node, the
key of the governing rule and its selector.
In the WebUI, the node selector field completes what you type against the labels your cluster actually reports: start typing a key and the matching label keys appear inline, then the value field offers only the values that key takes. A key no node reports yet is still accepted as typed, so you can write a rule before labelling the nodes for it.
Replica Auto-Scaling
Control the number of model replicas across the cluster:
| Field | Description |
|---|---|
min_replicas | Minimum replicas to maintain (0 = no minimum, single replica default) |
max_replicas | Maximum replicas allowed (0 = unlimited) |
Auto-scaling is only active when min_replicas > 0 or max_replicas > 0.
The Replica Reconciler runs as a background process on the frontend:
- Scale up: Adds replicas when all existing replicas are busy (have in-flight requests)
- Scale down: Removes idle replicas after 5 minutes of inactivity
- Maintain minimum: Ensures
min_replicasare always loaded (recovers from node failures) - Eviction protection: Models with auto-scaling enabled are never evicted below
min_replicas - Backoff: A scale-up that fails is retried after 30 seconds, doubling up to 10 minutes. A load that another owner is running (for example one that a request started) is not a failure: the reconciler retries on its next pass. A node that becomes schedulable (it registers, is approved, recovers or is resumed after a drain) ends every backoff, so the next pass tries again at once. The backoff and the set of nodes it compares against are kept in memory by each frontend (documented per-instance state): the reconciler pass runs on one frontend at a time, and a frontend that takes over starts with no backoff, which is safe.
- Restart-safe: Per-model load metadata (backend type +
ModelOptions) is persisted in themodel_load_infosPostgreSQL table on the first successful dispatch, so a frontend restart or rolling upgrade does not require a fresh inference request to repopulate state before the reconciler can scale up replacement replicas.
All fields are optional and composable:
- Node selector only: pin model to matching nodes, single replica
- Replicas only: auto-scale across all nodes
- Both: auto-scale on matching nodes only
With a node selector, the reconciler counts only the replicas on matching nodes.
A replica on a node that does not match, for example one loaded before the
selector changed, does not count toward min_replicas, so the reconciler loads
another replica on a matching node. The reconciler does not unload the replica
on the other node; unload it yourself when you no longer need it.
Upgrade strategy
upgrade_strategy says how an upgrade of a gallery model (POST /api/models/upgrade/{name})
replaces the replicas that run it (see Model updates for the upgrade itself):
| Value | What an upgrade does |
|---|---|
stop_and_start (default) | Stops every replica on every node, switches the files and the config, then loads one replica of the new version as the load check. When the check fails, the old files and config come back and the old version loads again. The reconciler brings the model back to min_replicas afterwards. |
canary | Accepted and stored, but not available yet. The upgrade stops and starts the model, and the upgrade’s status and note in GET /api/models/updates say so. |
An update that omits upgrade_strategy keeps the stored value. A model with no
rule upgrades with stop_and_start. A standalone server has no rules and always
stops and starts the model. The model is unavailable from the stop until the
new version has loaded.
During the switch, the frontend that runs the upgrade publishes a placeholder revision of the model in the node registry. This stops every replica, and no frontend and no reconciler pass can load the model until the frontend publishes the revision of the new configuration. The same happens when a change of the weights leaves the configuration, and so its revision, as it was: an old replica cannot survive the upgrade and pass the load check in place of the new version.
Each worker downloads its own files. While the frontend downloads the new
files of an upgrade, every worker that runs the model downloads them too
(model.prefetch, a request on the node’s control subjects) and checks each
sha256. After the frontend switches its files, each worker puts its copy in
place, and every other worker drops its old copy of the changed files, so its
next load gets the new ones. With object storage, the frontend also deletes
the changed keys, so the next load uploads the new file, and it sends the
sha256 of each file that a gallery install manages with every load: a worker
whose cached copy has another sha256 (it was offline, its commit timed out, or
it was busy with another download) downloads the file again. A worker that
cannot download a file (a wrong checksum or no route to the source) gets it
from the frontend at its next load; this never fails the upgrade. An older
worker that does not know model.prefetch gets the file from the frontend
over HTTP staging; with object storage it ignores the sha256 and keeps the
copy in its cache, so upgrade the workers before you upgrade models. With LOCALAI_DISTRIBUTED_SHARED_MODELS
the workers read the shared models directory and nothing is sent. A first
install still sends the files from the frontend.
A cancel of the upgrade during the download returns at once: the frontend does not wait for the workers. A worker that is still downloading finishes that download in the background, and its staged copy stays beside the model file until the next upgrade of the model replaces it.
Scheduling a model alias
model_name accepts a model alias as well as a
model. A rule keyed by an alias governs whatever model that alias currently
points at, and keeps governing it after you repoint the alias:
This makes an alias a stable deployment slot: the placement policy belongs to the slot, and the model filling it can change without rewriting the rule. The WebUI lists aliases in the model picker on the Placement page, tagged with the model each one resolves to.
Each frontend resolves the alias from its own copy of the model configs, and a frontend that has not yet reloaded a repointed alias still resolves it the old way (see Model configs across frontends). The rule’s stored target therefore follows the alias only through frontends whose copy of the alias config matches the configuration revision the cluster accepted. A frontend that is behind uses the stored target, for the replica reconciler and for the router’s own placement, and does not write it, so two frontends cannot overwrite the rule’s target against each other, and a frontend that is behind cannot reload the model the alias used to point at.
Two constraints follow from replicas being shared. A single load of llama3
serves both production and any request that names llama3 directly, so only
one rule can decide where it runs: a rule whose target is already governed by
another rule is rejected with 409 Conflict naming the rule that has it. And a
rule keyed by an alias that resolves to nothing (its target was deleted, or it
points at another alias) is rejected, since it would govern nothing loadable.
A rule can still end up inert if the pair is created some other way, for example
by a declarative seed or by repointing an alias onto a model that already has a
rule. The rule that governs is the one keyed by the model’s own name, or failing
that the oldest one; the rest are listed as Shadowed in the WebUI and carry
"shadowed": true in GET /api/nodes/scheduling.
Declarative per-model scheduling (unattended installs)
In distributed mode you can declare per-model scheduling at startup, instead of using the WebUI/API. Config is authoritative: it is re-applied on every boot and overwrites the listed models (models not listed are left untouched).
| Variable | Description |
|---|---|
LOCALAI_MODEL_SCHEDULING | Inline JSON list of scheduling entries |
LOCALAI_MODEL_SCHEDULING_CONFIG | Path to a YAML file with the same list |
Entry fields: model_name (required), node_selector (a label map; omit it to
match every node), the optional upgrade_strategy, and then one of two replica modes (they are mutually
exclusive):
replicas: all- static spread: place exactly one replica on every matching node, proactively, regardless of load, and keep it in sync as nodes join and leave. Use this for “run model X everywhere (with this label)”.min_replicas/max_replicas- elastic auto-scaling: keep at leastmin_replicasrunning, and burst up tomax_replicasonly when all replicas are busy, scaling back down to the minimum when idle.max_replicas: 0means no upper bound (grow to cluster capacity). To enable this mode you must setmin_replicas >= 1ormax_replicas >= 1- an entry with onlymax_replicas: 0(and noreplicas: all) does nothing.
Net effect at a glance:
| Config | Behavior |
|---|---|
replicas: all | One replica per matching node, placed immediately, tracks join/leave |
min_replicas: 1, max_replicas: 0 | Always >=1, bursts to cluster capacity under load, back to 1 when idle |
min_replicas: 2, max_replicas: 4 | Always >=2, bursts to at most 4 under load |
node_selector constrains which nodes a model may use; with no selector the
model may use all healthy nodes. So “spread model X across all nodes” is just
replicas: all with no node_selector. replicas: all targets one replica per
matching node; with the default per-node cap of one replica per model this lands
exactly one on each node (see the note below about LOCALAI_MAX_REPLICAS_PER_MODEL).
YAML example (scheduling.yaml):
Inline equivalent:
Notes:
- Because the config is authoritative, each listed model’s entire scheduling
row is replaced on every boot, including the optional prefix-cache routing
overrides (
route_policy,balance_abs_threshold,balance_rel_threshold,min_prefix_match). For a model you manage via this config, set those fields here too if you need non-default values; values set only through the API are reset on the next restart. Models not listed in the config are never touched. replicas: allplaces one replica per matching node by relying on the default per-node cap of one replica per model. If you raiseLOCALAI_MAX_REPLICAS_PER_MODELon a worker above 1, the target count can be met by stacking replicas on fewer nodes rather than spreading one to each.
Label Management API
| Method | Path | Description |
|---|---|---|
GET | /api/nodes/:id/labels | Get labels for a node |
PUT | /api/nodes/:id/labels | Replace all labels (JSON object) |
PATCH | /api/nodes/:id/labels | Merge labels (add/update) |
DELETE | /api/nodes/:id/labels/:key | Remove a single label |
Scheduling API
| Method | Path | Description |
|---|---|---|
GET | /api/nodes/scheduling | List all scheduling configs |
GET | /api/nodes/scheduling/:model | Get config for a model |
POST | /api/nodes/scheduling | Create/update config |
DELETE | /api/nodes/scheduling/:model | Remove config |
Comparison with P2P
| P2P / Federation | Distributed Mode | |
|---|---|---|
| Discovery | Automatic via libp2p token | Self-registration to frontend URL |
| State storage | In-memory / ledger | PostgreSQL |
| Coordination | Gossip protocol | NATS messaging |
| Node management | Automatic | REST API + WebUI |
| Health monitoring | Peer heartbeats | Centralized HealthMonitor |
| Backend management | Manual per node | Dynamic via NATS backend.install |
| Best for | Ad-hoc clusters, community sharing | Production, Kubernetes, managed infrastructure |
| Setup complexity | Minimal (share a token) | Requires PostgreSQL + NATS |
Cluster settings
The cluster settings are shared by every frontend through the database: the NATS addresses and the carrier weights. Read and store them with the local-ai cluster settings command, the admin API, or the Cluster settings of the Workers page.
Save a NATS address
Store the address of the NATS server in the cluster settings. The frontend that serves the request checks that it reaches the server, and refuses an address that it cannot reach.
If workers must use another address than the frontends (for example a public name), also set --nats-worker-url. When it is empty, workers use the nats.url address. An address must not contain a user name, a password, or a query string. NATS credentials stay on each frontend (see NATS JWT authentication).
A deployment that started with --nats-url already has this address stored. The frontends read the address at start, so restart them after you store a new one.
The admin API
Both routes are for an admin only. They answer 503 when distributed mode is off. The full schema is in the swagger UI of your server (/swagger/index.html).
| Route | Purpose |
|---|---|
GET /api/cluster/settings | nats_url, nats_worker_url, carrier_weights (the weights in force) and carrier_weights_default. It also returns bus, the broadcast bus of the frontend that answers (bus: nats or postgres, nats_configured, nats_connected), read from the connection of that frontend, and replicas, the live frontends (id, version, last_seen). |
PUT /api/cluster/settings | Store the fields that you send. An empty string clears a setting. A nats_url that the serving frontend cannot reach is 422. carrier_weights is an object with some or all of nats, websocket and p2p: a key that is left out stays, null puts the default back, an unknown key or a value that is not a whole number from 0 to 1000 is 400. |
The LocalAI Assistant has get_carrier_weights and set_carrier_weights for the carrier weights; the second asks for your confirmation first.
Carrier weights
A hybrid cluster attaches NATS, WebSocket and P2P workers at the same time, and the SmartRouter sends requests across all of them as one pool. A carrier weight decides between two nodes that fit a request equally well but that a frontend reaches over different carriers.
| Carrier | Default weight |
|---|---|
nats | 100 |
websocket | 50 |
p2p | 25 |
A weight is a whole number from 0 to 1000. A higher weight wins. 0 means: use that carrier only when nothing else fits. The weight of a node is the highest weight among its routes, so a worker that holds both NATS and a WebSocket tunnel counts as NATS by default.
The weight is a tie-break and nothing more. It never changes which node wins when fit differs. The router ranks the candidates as it always did, and the weight is read only after the earlier keys leave nodes equal:
- For a model that is already loaded: fewer requests in flight first, then the weight, then the least recently used replica (so equal-weight replicas still rotate), then free VRAM.
- For a new load: free VRAM (or an idle node, or the least loaded node) first, then the weight, then the node id. The last key keeps the order stable, so the same state gives the same node.
So a node with more free VRAM, or less load, wins over a node with a higher weight. Nodes that report exactly the same free VRAM, such as identical machines, are where the weight shows.
Set the weights
Every frontend reads the weights from the shared cluster settings, so a change through one frontend reaches all of them within a few seconds. No restart is needed.
The same fields are in PUT /api/cluster/settings (carrier_weights), in the Connection preference sliders of the cluster settings, and in the Assistant tools get_carrier_weights and set_carrier_weights.
State mode (see the distributed state rules): the weights are shared cluster settings in the database. Each frontend keeps what it read for up to 2 seconds, so two frontends can disagree for that long after a change. Nothing else is held in memory.
Data-limited relays are a last resort
A P2P worker can be reached over a public relay that limits the data it carries. The worker reports this, and the router treats such a node (one whose only route is a limited relay) as a last resort:
- It is used only when no other candidate fits. For a model that is loaded on several nodes, the replica behind the relay comes last. For a new load, the other nodes are tried first, and the relay node only when none of them can take the model without evicting another.
- It is never chosen for a placement that needs model files pushed to it, because that would send the whole model through the relay. A placement needs no push when every node mounts the same models directory (
LOCALAI_DISTRIBUTED_SHARED_MODELS), when the files go through S3 object storage that the worker reads itself, or when the model has no local file. If the relay node is the only candidate and the placement needs a push, the request fails with a503and a message that says why.
The weight of a node does not change this rule. A relay node with the top weight is still a last resort.
Workers and routes
A worker holds the routes that its operator gives it, and the frontend does not change them. A worker never connects to PostgreSQL.
| Worker started with | Routes it holds |
|---|---|
--register-to | The WebSocket tunnel to that frontend. |
--register-to and --nats-url | NATS and the WebSocket tunnel, NATS first. |
--join (a worker invite) | The P2P tunnel only. A NATS URL is ignored. |
--routes nats | NATS only. Without --nats-url the worker uses the address that the frontend hands over. |
--routes tunnel | The tunnel only, whatever --nats-url says. |
Each route is attached on its own. A route that cannot be attached (a NATS server that is down, a frontend that refuses the tunnel) is tried again in the background, with a wait that grows from 1 to 30 seconds, and the worker serves on its other routes meanwhile. A route whose credential cannot be renewed is attached again. The backend processes keep running through all of it.
Every heartbeat reports the routes (routes), the routes that the worker holds and is connected on (attached), why each other route is not held (route_error, for example nats: connecting), and, for a tunnel, its transport (websocket or p2p) and the P2P path. The Nodes page and GET /api/nodes show them as attached, follow (the routes the worker was given) and follow_error, and route_state says which routes are live (see Node health and routes). A worker sends no heartbeat while it holds no route, so a worker that nobody can reach goes stale.
Worker profiles
| Profile | How to start it | Address |
|---|---|---|
| NATS and tunnel | --register-to and --nats-url. | The worker registers its address (--addr, --advertise-addr, or the host name and the base port). Its backends bind all interfaces, because the frontends dial them on NATS. |
| NATS only | --routes nats. | As above. |
| Tunnel only | --register-to alone, or --join. | None is needed. Without --addr or --advertise-addr its backends and file server bind to loopback, so no port is open, and the frontend drops the address. |
A route can fail to attach for these reasons, shown in follow_error:
- The NATS server cannot be reached, or the credential of the node is not minted yet (for example, the node waits for approval).
- The NATS server asks for a client certificate, and the worker has none. The frontend cannot hand over certificate files. Set
LOCALAI_NATS_TLS_CERTandLOCALAI_NATS_TLS_KEYon the worker. - The frontend refuses the tunnel, for example while the node waits for approval.
Credentials per route
A worker registers once at start to get its node ID, with no credential. Then each route registers again and asks for its own credential only ("routes": ["nats"] or "routes": ["tunnel"] in the body of POST /api/node/register):
- For
nats: the worker NATS address (nats.worker_url, elsenats.url), the CA certificate of the server as PEM, and the per-node JWT and seed when JWT authentication is on (nats_jwt,nats_user_seed). The JWT is minted only for an approved node. It is refreshed before it expires by a registration that asks fornatsonly. - For
tunnel: a per-node tunnel token (tunnel_token), sent once. A registration for the tunnel replaces the previous token and ends the tunnel session that used it. A heartbeat never mints a token.
A worker that joined over P2P never gets a NATS credential, whatever it asks for. The handover crosses the network under the registration token, so use https for --register-to unless the frontend is on loopback.
Peer link
Several frontends can share the tunnels of the workers. A worker is connected to one frontend. A request that arrives at another frontend goes over a peer link to the frontend that holds the tunnel. The same link carries the chat starts, the chat replay and the background jobs between the frontends and the chat workers, with or without NATS (see Request and reply between frontends and chat workers). It also carries the P2P requests of frontends that share a P2P identity to the one that runs it (see P2P with several frontends).
| Flag | Env | Meaning |
|---|---|---|
--peer-address | LOCALAI_PEER_ADDRESS | host:port at which the other frontends and chat workers dial this one. By default LocalAI finds it from the route to the database. Set it when that address is wrong, for example in Kubernetes or behind NAT. A frontend or chat worker that publishes none cannot be reached by the others: it logs a warning and /readyz answers 503. |
--peer-tls | LOCALAI_PEER_TLS | Dial the other frontends over wss. |
--peer-tls-ca | LOCALAI_PEER_TLS_CA | PEM file with the CA that signs their certificate. By default the system roots are used. |
The link carries the credential of the frontend and the requests that it relays. Without --peer-tls it is clear text, and LocalAI logs a warning at start-up when the published address is not on the local host. If a reverse proxy ends TLS in front of each frontend, use --peer-tls, and set --peer-address to the TLS address of that frontend.
A frontend that serves the API over TLS itself (--tls-cert or --tls-self-signed) dials the other frontends over wss without --peer-tls, because the peer link uses the API listener. The other frontends must also serve TLS, and their certificates must be valid for the address that they publish. The system roots verify them unless you set --peer-tls-ca. A --tls-self-signed certificate is different on each frontend and no root verifies it, so for several frontends use --tls-cert with certificates from one CA, and pass that CA with --peer-tls-ca.
Security of the carriers
- Per-node credentials. Each worker has its own credential for the node routes (heartbeat, drain, deregister, models, split report), minted at registration and stored as a hash. A worker can act on its own node only. Each worker also has its own tunnel token. It is stored as a hash (SHA-256) and compared in constant time, and it is rotated at each registration. Each frontend has its own peer credential. The shared registration token never opens a tunnel or a peer link. It only allows a worker to obtain its own credential, and it is optional when workers join with join tokens.
- Open registration. With no registration token, a registration with no join token and no credential is accepted and waits for approval, as it always did; it cannot replace the credential of a node that already has one. With no registration token and
--auto-approve-nodes, anyone who can reach a frontend can register a node, get a tunnel, and receive the requests sent to workers. LocalAI logs a warning once (Worker registration is open) but does not refuse to start. Set a token, or turn off automatic approval.--distributed-require-authmakes the missing token a start-up error. - Admin only. The cluster settings routes need an admin user, and each change is logged with the name of the admin (
Cluster settings changed). - Websocket. The tunnel upgrade happens after bearer authentication. The tunnel reaches only the loopback ports of the worker that its backends use.
- Worker control plane. A worker serves its control plane to callers on its own host only, unless it has a data plane token: the one that the frontend derives from the registration token and hands to the worker at registration (so a worker that joined with a join token never sees the registration token). A frontend with no registration token has no data plane token, and a worker then serves the file-transfer port with no token; set a registration token on the frontend, and
--distributed-require-authon both, to close it. A frontend reaches it through the tunnel. - NATS secrets stay on the frontends. Operator keys and TLS key files are files or environment values on each frontend. They never enter the database. The CA certificate (public) is handed to the workers.
- Cluster settings are shared by all frontends, so they cannot hold credentials: an address with a user name, a password, or a query string is refused.
Rolling upgrades and rollback
Upgrade the frontends and the workers together. A release with worker routes (see Workers and routes) does not work with frontends or workers of an earlier release: a worker asks for the credential of each route, and an earlier frontend does not mint one per route; an earlier worker expects the frontend to name a carrier, and a frontend of this release names none. Mixed versions and rolling upgrades across this release are not supported.
- Removed with this release: the
/api/cluster/carrierroute, thelocal-ai cluster carriercommand, the--carrier-prepare-timeout,--carrier-transition-windowand--carrier-max-drainflags, theswitch.*cluster settings and thelocalai_carrier_*metrics. Each worker holds the routes its operator gives it, and the frontends listen on every bus they have. - The database is cleaned at start. A frontend drops the
cluster_carriertable, theready_epoch,ready_reason,availabilityandavailability_atcolumns of theinstancestable, theattached_epochcolumn ofbackend_nodes, and the storedswitch.*settings. Nothing reads them. - Rollback to an earlier release is not supported. Downgrade the frontends and the workers together only to a release that has worker routes.
- A NATS-only deployment sees these additions after the upgrade: the tables
cluster_settings,instances,node_connections, andbus_messages; one write per frontend per heartbeat; the/api/cluster/connectroute, which refuses everyone until a worker holds a tunnel credential; and the Cluster settings of the Workers page.
Observability
LocalAI exports these metrics through OpenTelemetry (Prometheus on /metrics):
| Metric | Type | Meaning |
|---|---|---|
localai_pgbus_published_total (label path) | counter | Broadcasts published through the database: inline or spill. |
localai_pgbus_dropped_total (label stage) | counter | Broadcasts this frontend received and lost: listener, subscription, or resolve. |
localai_pgbus_spill_purged_total | counter | Spilled broadcast rows deleted after the retention time. |
localai_pgbus_reconnections_total | counter | Times the LISTEN connection was lost and opened again. |
Log lines to watch (frontend): Broadcasts use the NATS server of the cluster when it is reachable, and PostgreSQL otherwise, Cluster settings changed, The NATS URL was refused: this replica cannot reach it. Worker: The worker attached a route, The worker could not attach a route; it keeps its other routes and tries again, A route of the worker ended and will be attached again.
Operational limits
The numbers come from a benchmark of the pgbus and the tunnel on one machine (4 PostgreSQL cores, loopback). Treat the ratios as a guide and the ceilings as rough. Measure your own deployment.
- Broadcast ceiling. pgbus carries about 16,000 messages per second of 200 bytes with a p99 latency under 10 ms. With 20 listening frontends, or messages of 2 to 8 KiB, the ceiling is about 8,000 per second. Realistic cluster rates (hundreds per second for 200 workers) use a few percent of this. A NATS server is far above it.
- Large broadcasts. A payload that does not fit in a PostgreSQL notification (about 8 KB) goes through a table row (the spill path). The spill path is fine up to about 1,000 messages per second of 64 KiB. It loses messages above about 2,000 per second, because delivery is at most once. The frontends read spilled rows with up to 8 concurrent readers, which reduces this loss. Keep large payloads rare.
- Delivery is at most once on both buses. Anything that must survive a gap lives in a table.
- Broadcast size limit. Every carrier refuses a payload above 8 MiB (
ErrPayloadTooLarge). Keep the NATSmax_payloadat 8 MiB or lower. - Tunnel latency. A tunnel adds about 0.1 ms per call. Token streaming runs at the same rate as a direct connection.
- Large transfers. A bulk transfer used to delay small calls on the same tunnel session (head-of-line blocking). Bulk data now uses its own lane of the tunnel, so inference calls are not held behind a model upload.
- Cost of one tunnel session. About 46 KB of heap and 6 goroutines (both ends together). With 64 KiB websocket buffers it is about 306 KB. 200 workers cost a frontend a few megabytes.
- Database connections. Every frontend and chat worker holds one
LISTENconnection, with or without NATS. - Not measured. The reconnect storm at scale, PostgreSQL on another host, behind a pooler, with many frontends, and TLS on the websocket.
FAQ
Does a NATS URL that I save take effect at once? No. The serving frontend checks that it reaches the server, and every frontend reads the address at start. Restart the frontends.
Can both buses run together? Yes. Every frontend and chat worker listens on PostgreSQL, and on NATS too when the cluster has a NATS server. Each broadcast goes on one of them (see The broadcast buses). Workers are a separate matter: each worker holds the routes its operator gave it, and a P2P worker or a WebSocket worker is reached in a cluster that has NATS (see How a frontend picks the route of a worker).
Can I use --nats-url and keep my old setup? Yes. With --nats-url the frontends broadcast over NATS and reach the workers that hold NATS. The flag is copied to the nats.url setting (without credentials in the address).
Do I still need --nats-url on workers? Only on a worker that should hold the NATS route. A worker with --register-to alone holds the WebSocket tunnel. --routes nats without a URL uses the address that the frontend hands over.
What if I never use NATS? Run PostgreSQL only. PostgreSQL is the only broadcast bus between the frontends, and workers attach over WebSocket or P2P. Workers still never connect to PostgreSQL.
Why is my tunnel-only worker not on NATS? Its operator gave it no NATS route. Restart it with --nats-url (and --addr when its host name is not reachable from the frontends).
Troubleshooting
Add-on owner logs backend not found, or Slack messages are answered twice:
- The owner is not in distributed mode. Give it the same
--distributed,--nats-url, registration token and--auth-database-urlas the frontends - Check that only one connection uses each Slack app
Worker not registering:
- Verify the frontend URL is reachable from the worker (
curl http://frontend:8080/api/node/register) - Check that
--registration-tokenmatches on both frontend and worker, or that the join token is valid (GET /api/cluster/join-tokensshows its state). A heartbeat refused with 401 means the worker has no credential for the node: register it again with a new join token - Ensure auth is enabled on the frontend (
LOCALAI_AUTH=true)
A worker shows follow_error:
- The text names each route that the worker does not hold, and why (for example
nats: connecting). See Worker profiles. - The worker serves on its other routes and tries the failed route again, with a wait of up to 30 seconds. Fix the reason and the route attaches without a restart.
The frontend log says it cannot reach NATS, or the NATS URL is refused:
- Saving a NATS URL (
PUT /api/cluster/settings) is refused with422when the serving frontend cannot reach the server with its own credentials. Check the address, the TLS files (--nats-tlsca,--nats-tls-cert,--nats-tls-key), and the JWT credentials on that frontend. - A frontend that loses the NATS server stays up and keeps retrying. It broadcasts over PostgreSQL and answers
503on/readyzuntil NATS is back. A worker that holds only NATS cannot be reached meanwhile (nothing is reaped). A worker that also holds a tunnel is reached on the tunnel.
NATS connection errors:
- Confirm NATS is running and reachable (
nats-server --signal ldmor check port 4222) - Check that
--nats-urluses the correct hostname/IP from the worker’s network perspective
PostgreSQL connection errors:
- Verify the connection URL format:
postgresql://user:password@host:5432/dbname?sslmode=disable - Ensure the database exists and the user has CREATE TABLE permissions (for auto-migration)
- Check that pgvector extension is installed if using RAG features
Node shows as unhealthy or offline:
- The HealthMonitor marks nodes offline when heartbeats are missed. Check network connectivity between worker and frontend.
- A node that is
unhealthywith a fresh heartbeat has no live route. Look at itsroute_state(the Connections column of the Workers page, orGET /api/nodes): the reason of eachdownroute is the one the worker reported, for examplenats: connectingfor a NATS server it cannot reach, or a tunnel that is gone. The node becomeshealthyagain as soon as one route is live. - Verify
--heartbeat-intervalis not set too high - Offline nodes automatically restore to healthy when they re-register (no re-approval needed)
InsightFace reports a missing MiniFASNet file after staging:
- Gallery models such as
insightface-buffalo-muse a virtual primary name and load their files through options. The frontend derives the worker’s model directory from successfully staged companion files or directories, so relative options resolve inside the model’s staging directory. - If logs show matching hashes for the staged files but InsightFace still reports a bare filename such as
MiniFASNetV2.onnxas missing, upgrade the frontend to include this path-resolution fix. Re-uploading the same files does not correct the directory passed to the backend.
Backend not installing:
- Check the worker logs for
backend.installevents
Model staging repeatedly fails with HTTP 416 after all bytes have arrived:
- An interrupted upload can leave a full-size file marked as unfinished (
.sha256.target). On retry, the worker verifies the file’s SHA-256 and finalizes it if it matches, without rewriting the model. Corrupt content fails integrity validation and is removed. - Upgrade the affected worker to get this recovery behavior. Older workers can repeatedly reject retries from byte zero with
Content-Range start 0 does not match current file size. File size alone is not proof that an upload is valid.
Requests still report an old context size or another old load option:
- Query
/api/nodes/:id/modelsfor every worker that hosts the model. - Confirm that every routable replica has
state: loadedand the same currentconfig_revision. - Treat a different
effective_options_hashas diagnostic information. Node-specific defaults can cause valid differences. - Check
cleanup_errorandcleanup_next_retry_aton replicas in theunloadingstate. - Check connectivity to the worker and NATS when cleanup reports a timeout or no responder.
- Upgrade the worker when it does not support the exact model-stop request.
- Stop and restart the stale backend only as an operational recovery action. LocalAI keeps it non-routable while durable cleanup is pending.
A model cannot be scheduled on a node that looks free (no replica slot ... all models busy, cannot evict):
- A replica row in
stagingorloadingholds its slot: slot allocation counts every state exceptunloading. If a worker drops out mid-transfer, that row never reachesloaded, and eviction only ever considersloadedreplicas, so on a node with one replica slot per model the model became unschedulable there. - The reconciler now reclaims a replica row stuck before serving when no load job is still driving it, and the freed slot is immediately reusable.
- Each replica row names the load attempt that made it. Liveness is decided by that attempt’s job lease, not by elapsed time. Staging a large checkpoint legitimately runs for a long time without touching the replica row, so a transfer whose owner still renews its lease is never reclaimed however long it takes. A row is reclaimed when its attempt has no job: the job was released after a failure, or another attempt replaced it.
Reconciler: reclaimed a replica slot held by a load nobody is drivingnames each row reclaimed this way.
A request fails with nats: no responders available for request:
- The chosen worker was not subscribed on the bus when the frontend tried to install the backend on it. A node’s status comes from its HTTP heartbeat, which is a separate channel: a worker that stops stays
healthyuntil that heartbeat ages out. - The scheduler now checks that a node still answers on the bus before it commits to it, marks one that does not as unhealthy, and picks another. A request should therefore see this only when no reachable node is left.
- Only a no-responders answer counts as absent. A worker that answers slowly stays eligible, because excluding it would cost capacity that is really there.
- Check the worker process is running and its NATS connection is up.
Scheduled node is not answering on the busin the frontend log names each node demoted this way.
A worker fills its own disk over time:
- A request that carries a file (an image, an audio clip, a video) stages that file below the worker’s HTTP staging or S3 cache
ephemeral/directory. The frontend releases each request-owned input when inference finishes, and the worker reserves capacity before accepting it. - A one-hour recovery sweep runs at startup and every 15 minutes to reclaim inputs left by interrupted requests. It preserves active reservations and uses the newest file timestamp in each request directory.
- Releases before request-owned cleanup existed can leave a legacy backlog. Delete the affected
ephemeral/directory once, as the user the worker runs as; capacity admission and recovery cleanup keep new staging bounded. - A request that produces a file (speech, sound, an image, a video, a 3D asset, an audio transform) has the backend write it to an output file on the worker:
localai-output-*.tmpin the HTTP staging directory, orlocalai-staging-*.tmpbelow the S3 cachestaging-tmp/directory. The frontend removes that file from the worker once it has fetched it, and also when the request fails. A sweep at startup and every 15 minutes removes output files older than six hours, which catches a file that a frontend could not remove (it stopped mid-request, or it predates this release). The sweep looks only at files with these names directly in those two directories. - Releases before the output cleanup existed can leave a backlog of output files. The sweep removes the ones older than six hours after the worker is upgraded.
- Staged model files are not touched by this. They live beside the ephemeral directory and are not per-request scratch.
- A worker whose volume is genuinely full reports
creating backend process state directory under ...: no space left on devicewhen a backend starts.
Requests fail with stale model config revision although nobody edited the model:
- A model’s stored revision must describe its persisted configuration. Releases before this fix also hashed the per-request prediction parameters, so the first request after a restart pinned the revision to its own
temperature,top_p,stopand similar values. Every later request that sent different values was then rejected. - Upgrade the frontend replicas first. After the upgrade the revision is stamped when the configuration is loaded, so it no longer depends on the request body.
- Each frontend now reconciles the stored revisions against the configuration on disk at startup, and republishes any that disagree, so a drifted revision heals on the next restart. Only models that actually drifted are republished, because republishing quarantines the replicas loaded under the old revision.
- A model that has never been served has no stored revision and is left alone; its first request establishes one.
- On a release without that reconciliation, clear the row once per affected model so the next request establishes the correct revision:
DELETE FROM model_config_states WHERE model_name = '<model>';Saving any edit through the API or the WebUI has the same effect.
Port conflicts on workers:
- Each model gets its own gRPC process on an incrementing port (50051, 50052, …)
- The HTTP file transfer server runs on the base port - 1 (default: 50050)
- Ensure the port range is not blocked by firewalls or used by other services
- Verify the backend gallery configuration is correct
- The worker needs network access to download backends from the gallery
Routing pipeline
Loaded replicas are selected through a filter, scorer, and picker pipeline. The initial pipeline applies the load guard as an eligibility filter, scores eligible replicas using prefix-cache affinity and cold-placement order, then picks the highest score with a deterministic node/replica tie-break.
Per-model scheduling fields configure the initial pipeline:
route_policyenablesprefix_cachescoring or selects theround_robinfloor.balance_abs_thresholdandbalance_rel_thresholdconfigure the load eligibility filter.min_prefix_matchcontrols when prefix affinity contributes the highest score.scorer_weightsenables or weights named scorers. The initial scorer isprefix_cache; setscorer_weights: {prefix_cache: 0}to disable its contribution while retaining the load filter and deterministic picker.
The pipeline accepts additional independently weighted scorers and alternate
pickers without coupling them to SmartRouter. This is the extension point for
queue depth, precise KV utilization, latency, and fairness signals.
Prefix-cache-aware routing
The scheduling algorithm supports prefix-cache-aware routing: bias each request toward the replica that already holds the relevant KV/prefix cache (multi-turn conversations and shared system prompts), so backends reuse cache instead of recomputing it. A router-side radix tree maps prompt-prefix hashes to nodes, with longest-prefix match, a load guard that preserves round-robin behavior under imbalance, and NATS sync across frontends. It is purely a routing-layer hint (no backend changes) and never routes worse than round-robin.
When the load guard must route away from a warm replica, the frontend emits a forced-disturb event. These events and the reset sent after a successful pressure-triggered scale-up are broadcast over NATS, so the rolling autoscale threshold is cluster-wide rather than per frontend. The Prometheus counter localai_prefix_cache_forced_disturb_total{model="..."} records events at their originating frontend; sum it across frontend replicas to inspect cluster pressure without counting the NATS copies.
Backends can report exact KV-cache residency on the prefixcache.residency
NATS subject. The JSON event contract is:
operation is store, remove, or clear. store adds the announced
shallow-to-deep chain for one model replica, remove removes only that exact
announced chain, and clear removes all reported residency for that model
replica (and may omit chain). Producers must generate the chain with exactly
the same windowing and hashing algorithm as the router; hashes from a different
chain algorithm are not compatible and will never match requests correctly.
Reported events populate the exact-residency provider, but the guessed provider
remains the routing default until a backend producer is available.
Open work on routing, taken from a survey of SGLang, vLLM production-stack, Ray Serve, llm-d, AIBrix, and NVIDIA Dynamo, is tracked in the routing epic (#10063):
- Reported/precise KV-event mode (#10064): subscribe to actual backend KV-cache events for exact residency instead of inferring it from routing history.
- Multi-tier cache-overlap scoring (#10065): credit GPU/CPU/disk cache tiers separately.
- Load-shaping (#10067): anti-herding (softmax/temperature) and dispatch-time freshness.
- Prefill/decode disaggregation routing (#10068): route prefill and decode to separate pools with KV transfer.
- Per-user fairness (VTC) (#10069): balance per-user token usage against pod load.
- Minor tuning + MCP parity (#10070): per-model TTL override, probabilistic LRU updates, and MCP scheduling-config tool parity.
Per-model worker environment
A model’s env map is sent with each backend installation as a complete
per-process snapshot. The worker applies it only to that model replica’s child
process, on top of the worker’s inherited environment; it never changes the
frontend or worker daemon environment. Models sharing a backend executable can
therefore use different credentials or runtime settings without sharing them.
An empty string is an explicit value, not an instruction to remove a variable.
When a slot is installed again with changed overrides (including removal of the last override), the worker restarts its child rather than reusing a process with stale settings. Removing an override restores the worker’s inherited value, if one exists. Unload/reload a running model after changing its environment; this is not live environment mutation of an already loaded child.
This requires updated frontends and workers. Legacy install requests omit the snapshot and retain legacy reuse behavior; older workers ignore the added field and cannot provide per-model environment isolation. Upgrade workers before relying on this feature. Environment snapshots may contain secrets and travel over the control transport: restrict NATS access and enable its authentication and TLS for untrusted networks. They are not secret-store references.
Install coalescing is per frontend instance and includes a keyed identity of the snapshot, so concurrent installs with different environments do not share an install reply. The worker owns process-local snapshots; they are rebuilt from model configuration on each install, not persisted as a new cluster state store.
Workspace Files without S3
Workspace Files uses configured S3 for every role; otherwise it uses the direct
filesystem adapter at the existing DataPath/chats/blobs. There is no additional
workspace path or boolean setting. This selection does not change global
model/input staging. The add-on owner honors the same S3 settings even without
distributed services, and remains an owner rather than joining the control plane.
Distributed metadata still requires the same shared PostgreSQL database. Without S3, mount the same existing DataPath/backing storage on every Files consumer: frontends, the add-on owner and optional chat workers. Ordinary inference workers need no Files mount. PostgreSQL owns metadata and references; immutable blobs are shared, while scratch and caches are local and disposable. No DataPath and no S3 means Files is disabled, not backed by authoritative temporary storage.
Use compatible UID/GID, permissions and trusted writers. LocalAI does not recursively chmod/chown existing trees. Platform path aliases are resolved, but symlinks inside the canonical blob tree are rejected. Same-node local/RWO storage requires enforced co-placement, with no cross-node failover claim. Multi-node use requires coherent shared storage (typically RWX), atomic same-filesystem rename, cross-client visibility and durable file/directory sync semantics. Equal path strings do not prove shared mounts. Shared volume and datastore identity are not verified at startup; no startup probe certifies these deployment guarantees.
PostgreSQL/direct-FS publication and purge coordination is automatic for all participants, including the separate owner. Blob ingest holds the revision lock, serializing metadata writers; blocked operations must honor cancellation and orphan cleanup has a bounded 30-second context. S3 remains an alternative. See Shared filesystem for Files for the full storage and durability contract.
No automatic migration occurs: existing filesystem paths stay put and configured S3 workspaces remain on S3. Switching populated metadata requires a separately planned copy and verification, with all consumers switching together. Mixed S3/local/shared backends can yield missing content.
Chat apps, MCP servers and Projects in a cluster
Chat apps, MCP servers and Projects keep state in a cluster as the sections below say. The user pages are Chat apps and connections, MCP servers and Projects.
Multiple frontends and readiness
In a multi-frontend deployment, connector discovery and calls go to the frontend that owns the add-on runtime over the private, peer-authenticated add-on carrier. You can create and test bindings from another frontend; it does not need its own Slack or Telegram runtime. Poll leadership is unchanged: the polling frontend and notification sender can reach the runtime owner without owning it themselves. Connector access still requires Connectors, not the separate Add-ons permission. Existing agent permissions and sender allowlists still apply.
A healthy owner with no running connector kinds returns an empty list. An unreachable, unready or fenced owner returns an error instead: an empty list is not an outage signal. Check that the connector add-on is running and that the frontends can reach the configured private carrier before trying discovery again.
If discovery fails or the platform explicitly refuses a token, creating a binding fails without saving it. Once discovery succeeds, a temporary outage during token verification retains the existing permissive save behavior; use Test when the platform is available again. An authorization denial or explicit token refusal during replacement leaves the stored binding unchanged. Binding calls use the owner’s stored token. LocalAI does not replay a forwarded send automatically after a transport failure, since the platform may already have received it.
Telegram’s legacy binding resolution remains compatible with existing bindings. It is not a fallback for discovering other connector kinds or for owner outages.
Connections: storage and clusters
Bindings, the read position in Telegram’s updates, the sender log and the chat of each sender are stored with your chats: in the database, in JSON files under the data path, or in memory when there is no data path (then nothing survives a restart). The JSON store is for one process.
| State | Mode | How |
|---|---|---|
| Bindings, offsets, sender log, sender chats, the key | Shared | Rows in the database. |
| Which frontend reads the bot | Single runner | The frontend that holds the advisory lock (KeyChatsConnectors). When it stops, another takes the lock and continues from the stored offset. Add-ons run on the process that owns the add-ons, and the loops run only where the add-on answers. |
| The upstream account of a binding, and which of two twin bindings answers | Shared | The account is stored with the binding. The oldest enabled binding of the same account answers; every frontend derives that from the stored bindings, so no claim is needed. A frontend remembers in memory only when it last asked an add-on for an account that the add-on did not tell, to ask again after 10 minutes. |
| Where the next message is read from | Shared | The offset is stored with the binding. Core passes it to the add-on’s poll call and stores the offset that the answer names. |
| The reply being sent for a turn | Per instance | The frontend that took the message sends the answer, edits its working message or sends its draft, and sends its files. If it dies, the answer is lost; the message is not repeated. |
| The preview budget of a binding | Per instance | The time of the next edit or draft is kept in memory by the frontend that sends the replies. Replies of one binding run on the leader, so one budget covers them. |
| Draft IDs | Per instance | A counter in the process that sends the replies gives each turn a new draft ID. Two frontends could give the same ID, but a draft only lives in one chat for one turn. |
| The chats of the answers (thread mode) | Shared | Each answer’s message IDs are stored with the chat of each sender, so a reply finds its chat on any frontend. |
| Slack Socket Mode links and their queues | Per instance | The Slack add-on process keeps one link per polled binding, acknowledges each event at once and queues it until the next poll. An event that is queued when the process stops is lost. The followed threads and the “Working…” messages are kept there too. |
| The language of each sender | Per instance | With reply_language set to auto, the frontend that takes a message keeps the last clear language of the sender and of the chat in memory for 24 hours. A trigger that runs on another frontend does not know it and uses English. The interface language of the owner is stored with the binding, so it is the same on every frontend. A fixed language is stored with the binding and works everywhere. |
| Shares of a binding | Single runner | The grants are records in the policy store of the add-on owner, the one process that writes them, keyed by the binding ID; the binding itself is not copied. A call through a shared binding is admitted on the owner, which is also the only process that opens the sealed tokens, so a revocation cancels it there. Other frontends ask the owner for the listing, the record of a binding and its removal. |
Files marked by attach_file | Per instance | The marks live in the process that runs the turn and are sent by the process that sends the replies. A turn that ends on another frontend than the one that sends the answer loses its marks; the agent then sees no error, and the person asks again. |
MCP servers: storage and clusters
| State | Mode | How |
|---|---|---|
| The connectors and their sealed secrets | Shared | Rows in the database (JSON files under the data path for one process). |
| The sealing key | Shared | The key of the Telegram connectors. |
| Open MCP sessions | Per instance | Each frontend opens its own sessions, lazily, for its own users’ calls, and closes them after 10 idle minutes and when a connector is edited, switched off or deleted. A frontend notices an edit made on another by the record’s update time at the next use. A session is never shared between users. |
Local commands (stdio) | Refused | They would run on whichever frontend served the request. |
Remote connectors connect from the frontend that runs the turn, not from an agent worker, so a server must be reachable from every frontend.
Projects: storage and clusters
| State | Mode | How |
|---|---|---|
| The folder, manifest, files and memory of a project | Shared | Ordinary files in your home, in the same store as your other files. |
| The index of your projects (id, slug, status) | Shared, rebuilt | A table of rows in the database, or a JSON file for one process. It is a cache of the folders: it is rebuilt from the manifests at each list, and a row that disagrees with its folder is corrected. |
| Anything else | None | A frontend keeps nothing in memory. Each request reads the index and the folders, so every frontend of a cluster gives the same answer. |
In distributed mode the projects are stateless per request. If you lose the index, nothing is lost: the next list rebuilds it from the folders.