Running multiple replicas
Read this page before scaling the backend out. It covers what you configure, what you see and what it costs. The design behind it (PostgreSQL as the arbiter, the cluster library, generations) is in the cluster architecture.
Coordination:Clustered declares that a replica is one of a fleet. It turns on the coordination only a fleet needs:
- the Matter bridge's live-state relay
- the plugin roll's census of live replicas
- the membership reads behind the status page
- the default of observation replication
- the device-model job worker's start-up recovery scope and idle poll
- the
Cluster:LeaseTtlallowance in the redescribe deadline - the replica-id conflict check
A single replica with the setting unset or false takes the direct path for these. Host-build comparison, owned work, held mutexes, requests between replicas and how configuration reaches every replica do not depend on the setting. The cluster library runs them at every replica count.
Scaling out
Helm. Scale out in two upgrades. First set coordination.clustered=true while replicaCount=1 and let that rollout finish. Then raise replicaCount to N, so the existing replica already runs with coordination before peers join.
Compose. Set COORDINATION_CLUSTERED=true and REPLICA_ID=reeve-backend in .env and run docker compose up -d backend. When it is healthy, apply docker-compose.multi.yml to start the peers. The base file defaults the id to reeve-backend and passes COORDINATION_CLUSTERED=false when the variable is unset. The overlay sets it to true and gives each peer its own id.
Move Docker workloads first. The Docker workload provider is supported on a single backend only. Before either step, move every workload off Docker (switch it to Manual, or reinstall it on Kubernetes), set the workload provider to Automatic and drop docker-compose.docker-workloads.yml. A clustered backend refuses to start otherwise (see the Docker workload provider).
Frontend fleet. The chart's replicaCount sizes the backend fleet and, unless overridden, the frontend fleet. Set frontend.replicaCount to scale the stateless SPA independently. Frontend pods prefer separate nodes by default, and frontend.affinity replaces that preference. The top-level affinity applies to backend pods only.
What becomes mandatory
| Requirement | Why |
|---|---|
Coordination:Clustered=true on every replica |
Turns on the fleet-only coordination listed above. Unit kinds, held mutexes, plugin connection leases, MQTT availability leadership and fire de-duplication work the same without it (single-node ownership costs). |
A non-blank REPLICA_ID or Workflow:Engine:ReplicaId, unique to each replica |
Recovery boot state, MQTT membership, workflow run state and cluster membership use this one identity. Start-up refuses a host without either setting, clustered or not, and names both in its error. Duplicate ids make replicas overwrite the same membership entry and can make both believe they own exclusive work (replica identity). |
Redis reachable, and the same RateLimiting:KeyPrefix on every replica |
Every rate-limit budget counts in Redis. Replicas on different prefixes or Redis instances each grant the full budget. Redis is mandatory on every deployment, a single replica included (Redis in a cluster). |
ForwardedHeaders:Enabled=true (the chart's default), the ingress inside the trusted networks (the private ranges unless forwardedHeaders.trustedNetworks is set), and every proxy in front of the ingress counted in forwardedHeaders.forwardLimit, trusted and passing the client address on |
Otherwise the per-address sign-in and 2FA limits and the failed-login lock see the ingress's address for every client. One client can then spend every user's budget, and one person's wrong passwords block everyone. Every replica must carry the same trust configuration, or the lock counts differently on each. See configuration. |
| Migrations applied once | Leave boot migration on and rely on the initializer lock, or set Database:Startup:RunMigrationsOnStartup=false on the serving replicas and run one migrate-only job. |
| Session-affine routes for both database pools | Object-storage admission uses session-level advisory locks on the dedicated gate pool, outside caller transactions, and on the application pool inside joined transactions. A statement error can leave a lock on that physical session, so a transaction-pooling proxy must not reassign either session without clearing advisory locks. Use direct PostgreSQL or session pooling for Database:ObjectStoragePool and Database:Pool. |
transaction_timeout and statement_timeout at 0 |
The cluster library refuses connections where either is non-zero (database session settings). |
| The same shutdown timings on every replica | One replica's wait covers its peers' budgets (timings). |
| A fixed fleet size | Set Workloads:PluginRoll:FleetSize (rendered by the chart) on every replica that may lead a plugin update. The chart ships no autoscaler (a plugin update reloads one replica at a time). |
Clustered=false with several replicas
Coordination:Clustered=false with several backend replicas is a misconfiguration, and the most expensive one on this page. A deployment can have the right pod count, a reachable Redis and a working real-time backplane and still be broken because the setting is missing. Unit kinds, held mutexes and fire de-duplication still work, because the cluster library handles them at every replica count. The fleet-only coordination is off, though:
- Plugin rolls use a fleet of one, whatever
FleetSizesays, so a roll reloads only the replica that leads it. - Observation replication defaults to off.
- The device-model job worker frees at start the running jobs claimed under its own host name, and polls every five minutes when idle.
- The replica-id conflict check does not run.
- A plugin instance that fails to start on one replica has its sources recorded Offline for the whole fleet, although its peers still run it.
This list is not complete. The host-build check still compares every replica.
Several unclustered backends on one database is a state the Docker provider cannot survive, because each one drives its own daemon. The peer monitor reports it, and enabling clustering then makes the Docker refusal apply.
The coordination health check reports a live peer on an unclustered replica once that peer's lease has kept being renewed for Coordination:PeerGrace (3 minutes). The brief overlap of old and new pods in a rolling update is therefore not reported.
Requests between replicas
A request one replica sends another travels over the cluster library's member ask, at every replica count. Examples are a flow step submitted to a replica that does not run the flow, a flow's end, a manual redescribe, a replica's logs and a recovery restart. The Matter bridge's commissioning verbs, its resync and the question of which replica holds its link use the library's keyed ask, which reaches whichever replica holds the matter-bridge-link unit.
Each request and its answer are sealed with the replicas' shared Data Protection key ring before they reach Redis, and a handler's failure carries no text. The relay uses the Redis channels reeve:ask:q:* and reeve:ask:r:* and the keys reeve:ask:c:*, which a Redis ACL must allow.
A replica is running while its member row reads joining or active with a valid lease, or fenced (the process lives and will be readmitted). A stopped replica (a draining row), a crashed one (an expired lease) and an id with no row are not running. A request for a flow's owner is sent only while the owner reads as running, and names the owner's process, so a new process under the same replica id answers that the flow's process is gone. In either case the replica that receives the next step adopts the flow.
A stopping replica takes no new request. It lets the requests it took from peers finish for up to a quarter of its shutdown timeout, cancels the rest and waits a sixteenth more. Only then does the library's own drain start. That drain waits out the requests running at its start (up to ProxyReadTimeout) and ends by writing draining. Until then, and for as long as it is fenced, the replica keeps its flows and their steps answer FLOW_OWNER_BUSY.
An owner that crashed inside its lease reads as running until the lease expires. An owner cut off from Redis keeps renewing its lease in PostgreSQL, so it reads as running for as long as it is cut off.
A flow step sent to either is withdrawn when the owner has not taken it within 5 s, and answers a retryable FLOW_OWNER_BUSY. The first submit after a crashed owner's lease has expired adopts the flow. A cut-off owner keeps it, and its steps run again once its Redis is back.
Only flow steps have this 5 s bound. Other requests wait their whole answer budget before they end untaken.
Two cases are refused rather than supported:
-
A step that runs past the
/apiproxy timeout. A polling step's single submit may run for up toConfigFlow:PollingSubmitTimeoutMs(180 s), but the/apiproxies (the frontend image, the Compose balancer and the chart's ingress) cut the request at 120 s. The step then gets a 504 with no error code from the proxy, which the web application does not retry. A plugin keeps each poll short by running a long operation in the background and answering the poll at once. -
An exit while fenced. The library writes
drainingonly fromjoiningoractive. A replica that stops or crashes while fenced therefore keeps itsfencedrow, and the row reads as running until the same id joins again. This happens when a pod is replaced while its replica is fenced: on a DeploymentREPLICA_IDis the pod name, so a new pod is a new id, and a StatefulSet pod removed by a scale-down never returns. Until then:- the replica-status alerts for it never clear
- applied-snapshot activation waits for it for at most 5 minutes after its lease ended
- the plugins and secrets boxes read incomplete
- its removal from the Cluster tab answers 409
- the flows it owned answer
FLOW_OWNER_BUSY
Once the pod is gone, delete the row:
DELETE FROM reeve_cluster.member WHERE replica_id = '<id>' AND state = 'fenced';Run the DELETE only once the pod is gone. Deleting the row of a fenced replica whose process still runs makes it read as gone, so peers may adopt its flows. The same statement without the
statefilter is the housekeeping for rows that aredrainingor expired and whose pod is gone. The library never deletes member rows, so under a Deployment each pod replacement leaves one.
Manual device redescribe uses the member ask on every deployment. The claiming replica first asks its local plugin instance. After NotOwner, or with no local instance, it tries the other running members in turn.
TargetGoneandNotTakenmove to the next peer, and so does a peer that also answersNotOwner.- No owner before the job deadline produces
failed/no-ownerafter retry backoff. NoAnswerand relay failure leave the job running so lease recovery can retry it.- With no running peer (always so on a single node),
NotOwnerproducesfailed/unreachableand a missing instancefailed/plugin-not-running.
Load balancing without session affinity
The ingress needs no session affinity. Plain round-robin works, and so does a controller with no cookie persistence at all, such as Cilium's Gateway API implementation. The web application and the companion app open the hub WebSocket directly instead of negotiating a connection id first, so one connection is one request, and the Redis backplane carries every group and broadcast to whichever replica holds the socket. The route to the backend must pass WebSocket upgrades, because nothing falls back to server-sent events or long polling.
Everything else a client does across requests (sessions, OIDC, passkey and TOTP challenges, config and repair flows, plugin OAuth, widget previews) is held in Redis, PostgreSQL or a signed cookie, whatever the replica count. Every named rate-limit budget is shared by all replicas through Redis, and every second-factor attempt, challenge and one-time token is spent atomically there. See authentication.
Clients that negotiate need affinity
The hubs still answer the SignalR negotiate call (offering the WebSocket transport only). A script built on a stock SignalR client, or a companion build that negotiates, connects fine against one replica or behind a sticky balancer and fails with an unknown connection id behind a round-robin one. Keep cookie affinity on the ingress until every such client is updated. The chart sets none. On ingress-nginx, add it under ingress.annotations:
ingress:
annotations:
nginx.ingress.kubernetes.io/affinity: "cookie"
nginx.ingress.kubernetes.io/affinity-mode: "persistent"
nginx.ingress.kubernetes.io/session-cookie-name: "reeve-affinity"
nginx.ingress.kubernetes.io/session-cookie-path: "/"
nginx.ingress.kubernetes.io/session-cookie-samesite: "Lax"
Config and repair flows across replicas
A config or repair flow runs every submit on the replica that started it, because a plugin may keep the flow's work in memory. A replica that receives a submit forwards it over the member ask and returns the owner's answer. A replica that is stopping starts no new submit and finishes the ones it has taken, for up to a quarter of Hosting:ShutdownTimeoutSeconds, then cancels them and answers 500. Once its member row reads draining, which follows the library's own drain, its flows continue on whichever replica receives their next submit.
| Answer | Meaning | Client behaviour |
|---|---|---|
503 FLOW_OWNER_BUSY |
The owning replica is stopping, fenced (it continues its flows once readmitted) or not yet serving relayed submits; it did not take the submit within 5 s (crashed inside its lease, or cut off from Redis); the cluster roster could not be read within 2 s; or a step finished on a replica after a peer adopted its flow, in which case the step is not written and does not end the flow. | The web application retries for 249 s, which covers the chart's default 214 s grace period (the longest a stop can last) and the 30 s lease of a replica killed before it wrote draining. The window does not grow if you raise the grace period. Only a 503 the receiving replica decides itself carries Retry-After. |
503 PLUGIN_TYPE_NOT_LOADED |
The replica running the flow has not loaded its plugin type within Plugins:TypeCatchUpTimeout. The flow is kept. |
Retried the same way. If it persists, that replica needs a restart. |
504 FLOW_OWNER_NO_ANSWER |
The owner took the submit and did not answer in time. It may still finish the step. | Not repeated. |
504 with no error code |
From the proxy, for a step that ran past its 120 s. | Not retried. |
410 |
A submit for a flow that finished or was aborted on another replica. Only a flow's start creates its state, so nothing is written. |
The Compose multi-replica stack
deploy/docker-compose.multi.yml adds two peers (backend2, backend3) and a balancer in front of all three.
| Topic | Behaviour |
|---|---|
| Balancing | The balancer (deploy/balancer/nginx.conf) is plain round-robin with no affinity, so one browser's consecutive requests land on different replicas, as behind an affinity-free ingress. The frontend's nginx proxies to the name backend, which the overlay links to the balancer for the frontend alone. Docker's embedded DNS is re-read every 5 s, so a recreated replica is found on its new address. The X-Reeve-Upstream header carries the address of the replica that answered. |
| Retries | A 503 of an idempotent method (a GET) is resent to another replica, up to three tries. A POST or PATCH is never resent, and a timeout is not retried. When every replica answers 503, the client sees that 503. A 503 never ejects a replica from rotation (max_fails=0), or a fleet-wide 503 would answer 502. deploy/scripts/balancer-retry-check.sh runs the real balancer configuration against stub replicas to check this. |
| Readiness | nginx open source counts only connect errors and timeouts as failures, so a replica that listens but fails /health/ready stays in rotation. The client then sees the replica's own refusal (replica_not_serving). |
| Timeouts | /api/ and / are read for 120 s, the budget the cluster library sizes its action and acknowledgement timeouts inside. /hubs/ and /ws/ stay open for an hour. The balancer adds no request-size limit of its own. The frontend's nginx enforces them. |
| Forwarded hops | The balancer appends itself to X-Forwarded-For, so the replicas unwind two forwarded hops (the frontend's nginx and the balancer) from TRUST_SUBNETS. Unset, that trusts loopback and the private ranges, which also trusts every other container reachable on them (workload sidecars, the Docker gateway). Narrow it to the project network's own subnet if that matters. Every replica carries the same trust. |
| No Docker workloads | No replica has the Docker socket, the docker group or the reeve-workloads network. The Docker workloads overlay is for a single backend, so leave it out. Workloads run on the Manual provider with the adapter on the host. |
| Per-replica state | Each replica owns its plugin root, and the first backend keeps the base file's reeve-plugins volume. Every replica carries the same set of Android passkey origins (AUTHENTICATION__WEBAUTHN__ANDROIDOWNBUILDORIGIN, generated with mobile/tools/apk-key-hash.sh). |
| Shutdown | Each peer sets stop_grace_period: 214s and Hosting__ShutdownTimeoutSeconds: "204", 10 s apart as the chart's grace period is, so a stop that begins saving at the host's deadline finishes before the container is killed. |
| Test intervals | The overlay shortens the observation-replication intervals (poll 100 ms, idle and hint intervals) and sets the followers to Polling for the multi-replica observation test. Do not copy these values. The product defaults are 250 ms and 60 s. |
What trails a change made on another replica
Plugin install and instance changes, config and repair flows, the recovery restart, workflow deletion, the object-storage switch, safe-mode sign-in, the identity-provider session refresh and the second-factor counters hold on any replica. The behaviours below remain per replica. Cookie affinity hides some of them from the user who made the change, but not from anyone else, so adding it does not fix them.
| Area | Effect behind round-robin |
|---|---|
| Replica-count consumers | The plugin roll and the device event sink read the declared count. Observation shares use live membership after their first successful refresh. Workload session relays, Matter bridge frame relays and defaulted cluster-port warnings run on every replica. The Matter live-state relay, forwarder and owner-side primary-database probe run only with Coordination:Clustered on. |
| Matter bridge | State and button presses behind round-robin are in the Matter bridge guide. |
| Zigbee2MQTT shared ingest | With SharedIngest and no last_seen, an identical repeat inside 10 s can be lost, because its copies alternate between replicas. |
| Device and energy access | Every access check (device reads, lists and commands, camera media, analytics and utility meters) and every realtime push is decided from the access configuration state, which each replica rebuilds when an access change is applied. A role, override, time window or user-status change is honoured on a replica once the write that made it is acknowledged. A replica that does not serve (starting, or fenced) refuses an access check with ReplicaNotServingException and sends no push. |
| Automations and helpers | An automation or trigger edit wakes every replica's trigger sync when the automation or workflow generation holding it is applied there, so arming follows within moments. A replica that has not applied it yet waits for the generation or for the next 30 s cycle of the owning path (the trigger host's for leader-owned trigger types, the replica's own for feed-driven ones). In that window the old trigger's fires start no run. A webhook served by the trigger leader can keep the previous secret or enabled state for at most the 30 s sync. A workflow, inputs or debug-mode edit applies from the next run without re-arming. A helper edit or a device rename re-wires every serving replica's helper graph once the write is acknowledged. |
| Egress allowlist | Follows the egress generation applied by each serving replica. |
| Plugin instance page | Loaded and pending build, update-available and blocked-outcome fields (Requires restart, Rejected, Backend too old) describe the replica that served the page, and its health badge names that replica. Reload completion is reported only after that same replica reports healthy or running. A workload the operator switched to Manual keeps its Docker binding, so its logs and status are unavailable on every replica of a clustered stack until it is reinstalled on Kubernetes or run on one backend. |
| Install remedy badges | Remedy bookkeeping is in memory, per replica, one slot per instance. Requires restart is fixed by a restart. Backend too old (the installed version declares a host range this backend is outside) is not, because the version comparison gives the same answer next boot. It carries the declared bound and the running host version, and clears on a successful start after a backend upgrade or on a newer install judgement. Rejected (registration refused) refuses again next boot, but a restart clears the badge. |
| Cross-replica commands | Opening a Matter bridge pairing window, rotating its code and removing a fabric answer 200 only once the bridge's own report shows the result, whichever replica served the call and whichever holds the bridge link. A resync answers 200 once the link holder has requested the rebuild. A replica that holds the link unit without a live link answers 400. When no replica holds the unit (as on a single node in safe mode), the call waits up to 10 s and answers 503. A 504 means the bridge did not report in time and the outcome is unknown. A 503 with Retry-After: 1 means no replica held the link, or its holder was busy or unreachable, so nothing ran. A plugin configuration change, disable or uninstall is answered once every serving replica has applied it. |
| Device source removal notice | When an operator removes a device source or a whole device, the replica that served the DELETE tells the owning plugin (if it implements IDeviceSourceRemovalHandler) once the removal has committed, from a detached task bounded to 30 s. A replica that stops between the commit and the call, a timeout or a plugin failure leaves the plugin untold, and nothing retries. |
| Plugin permission grants | A permission change reaches every replica through the plugin_grant generation, in effect on a serving replica when the write is acknowledged. Each replica reloads every instance of that type that disagrees with the row, rebuilds disagreeing plugin alert subscribers and re-arms disagreeing armed WASM triggers. Until the reload runs, the replica does not dispatch to a disagreeing facade. The convergence repeats at doubling intervals (Plugins:TypeCatchUpRetryDelay up to Plugins:TypeCatchUpRetryMaxDelay) until everything agrees. A reload that failed after it stopped the instance is left to the recovery sweep (Plugins:InstanceSweepInterval, 60 s). An armed WASM trigger waits one more trigger cycle. An unreadable grant row keeps the old grant until the database answers. A start whose grant identity could not be resolved runs on an empty grant until the next generation or restart corrects it. The reload is a stop and start, so a plugin holding work between calls loses it. |
| Object-storage backend switch | Writes are refused from the moment a switch is accepted, while reads continue from the source through the claim. Cutover changes the active backend only after all storage leases drain, and long leases postpone a drain to a later scan. |
| Camera viewer budget | Held slots in PostgreSQL, counted inside the statement that grants one, so replicas do not over-admit outside a fence or a rolling update. A database error or an unknown commit still admits the viewer (the limiter degrades open). A replica that is not serving refuses it. |
Single-node ownership costs
Owned work and held mutexes run through the cluster library at every replica count, a single node included, whatever Coordination:Clustered says. A single node pays for that as follows.
Unit kinds start after the replica serves. The placer puts every kind on the only replica one placement pass (2 s) after it serves, not at boot. A fence stops them at its first step, and they start again at the first placement pass after readmission, so a PostgreSQL outage long enough to fence the replica stops them for its length.
No mutex is granted before the replica serves or while it is fenced, and its holder loses it at drain start. A Single workflow run triggered during start-up, a fence or a drain is skipped (see the workflow run lock). The workloads engine leads only once the replica serves, its units stop for the length of every fence and from drain start, and switch-to-manual answers 409 "Another replica is currently coordinating…" while the replica does not serve. A plugin install or update start waits out its lock budget and then answers 409 install_in_progress.
Every keyed fire pays a claim, and every Parallel or Queued run a slot. The workflow library is told it has peers at every replica count. A single node therefore claims each fire that carries a key in Redis (the window claim, which also collapses a repeat of the same key inside the window) and takes a PostgreSQL slot for each Parallel or Queued run, renewed every 10 s while it runs. A Parallel or Queued run that would start during a fence or a drain is refused its slot.
A plugin connection lease is refused whenever the replica is not serving. Plugin instances start only after the replica first serves, but a fence or a drain later refuses leases again, and a database error reaches the plugin as an exception from the acquire. A plugin must retry the acquire on a bounded interval, because one that reads null as final never opens its connection. A lease whose holder crashed is free after at most 30 s, the mutex's time to live.
The MQTT status topic reads offline for the takeover window. Only the leader's connection carries the broker-side Will, so a process crash of the leader leaves the topic offline, and a clean stop publishes offline before the leader releases. The leader also publishes offline when it loses leadership (a fenced replica included) and releases the mutex only once its link is down. A peer polls for the mutex about every 5 s, then reconnects with the Will and publishes online. The topic therefore reads offline from the leader's end until a replica has taken over, at every replica count, including a single node restarting.
A late offline does not stay. While it leads, a connection watches its status topic and publishes online again whenever it sees the Will payload there. The broker's delayed Will for a dead leader (up to one and a half keep-alive periods after a node loss) or a resumed leader's step-down therefore leaves the topic online.
The mutex is per broker and topic. Two instances on different brokers that share a topic name each have a leader. Reeve's Home Assistant discovery plugin uses homeassistant/status, a topic Reeve stands in for. A real Home Assistant on the same broker writes its own offline Will there with the same payload, so the leader answers it with online and every device that listens to the topic republishes its discovery each time. Do not share that topic between Reeve and a real Home Assistant.
A leader the broker cannot reach lets go. Its mutex is released when its link drops or a connect is refused, so a peer that can reach the broker takes over.
How coordination works
PostgreSQL arbitrates ownership, liveness and held slots, so a partition collapses to one question for each replica: can it reach the database? There are two exceptions:
- Fire de-duplication, trigger cooldowns and the baby monitor's claims are window claims on the cluster library's Redis claims with the
Grantpolicy. While Redis does not answer, each replica that sees an event runs it and a cooldown admits. Rate limits stay on Redis through the host's own store and fail closed. - Config and repair flows keep their state and recorded owner in Redis, and a step write lands only while the writing process is still the recorded owner.
Locks that guard owned work (plugin operations, plugin connections, the MQTT availability leader, workflow runs, the workloads engine) are held mutexes. A mutex is a slot with a 30 s time to live (ClusterMutex:TimeToLive), renewed every 10 s (ClusterMutex:RenewInterval), that fires Lost at fence step 0 and at drain start. The time to live minus the cluster safety margin must allow two renewals, or start-up refuses the options.
Session advisory locks remain only for the boot steps (BootLock: the database initializer and the demo seed) and the object-storage admission gate. These run before the replica serves or outside its fence. They need a database session that belongs to their client: connect directly or through a pooler in session mode. Under transaction pooling the lock stays on a pooled server session after the client closes, so a second replica can land on it and also acquire. Npgsql has no multiplexing. A ConnectionStrings__PrimaryDatabase that sets Multiplexing=true is refused when it is parsed, so the backend does not start. Remove the keyword.
The database initializer creates the first data-protection key before any replica loads its key ring, under a transaction-scoped advisory lock. Serving replicas also run this check at boot when migrations are disabled. The lock makes concurrent replicas create at most one replacement when all stored keys have expired or been revoked. A serving replica that cannot reach PostgreSQL fails through the counted boot-failure path rather than starting with a private key ring.
Each replica is a member of the cluster library, which holds its lease and its status sections. Reeve elects no coordinator and keeps no assignment map. Work that must run on one replica is a unit kind registered with the cluster library, which places it. Placement is best-effort and correctness is hard: churn at the placement layer can cause a brief gap or a duplicated attempt, never double execution.
Placed unit kinds
These unit kinds are registered on every replica and placed by the cluster library.
| Group | Kinds |
|---|---|
| Workloads and devices | the presence sweep (which also keeps the session-outage streaks), the observation sweep, the orphan sweep, the system-plugin bootstrap, device-history-orphan-sweep, workload-storage-class-seed |
| Plugins and repositories | the plugin artifact store repair, the blueprint and widget repository syncs, plugin-repository-sync, resource-index-sync, the OAuth token refresh, demo-content-seed |
| Automations | the workflow journal reconcile, the helper time tick, the trigger host, the baby monitor |
| Matter | the Matter bridge link (matter-bridge-link) |
| Alerts and status (leader jobs) | alert-maintenance, alert-delivery, cluster-workload-alert, replica-status-alert, replica-id-conflict-alert |
| Maintenance and secrets (leader jobs) | config-flow-reconciliation, command-cleanup, device-model-retention, onboarding-session-maintenance, plugin-grant-restore, secret-reference-refresh, trusted-keys-revalidation |
| Periodic (leader jobs) | discovery-cleanup, blueprint-validation, media-plane-path-sweep |
| Storage | object-storage-migration |
| Configuration (leader jobs) | applied-snapshots, applied-snapshot-retention |
The library also places three convergent units of its own: reeve.once-sweeper, reeve.command-sweep and reeve.primitive-retention (which deletes slot rows 24 h after they end).
The placer assigns a kind to one serving replica, moves it when that replica drains, and starts it again elsewhere within the library's failover bound after a crash. A unit whose feature is off is still placed and does nothing. A start that throws is logged and retried with a growing backoff (1 s up to 30 s) until the replica loses the kind. The kinds a replica holds are in its reeve status section (HeldUnitKinds), refreshed every 3 s, and the Cluster tab lists them under each replica ("Runs ..."). The list is advisory: during a hand-over a kind can appear on two replicas for a moment. A replica in safe mode is offered none of the kinds that need a plugin or skip in safe mode (see a replica in safe mode).
Leader jobs. Each alert, status, maintenance and periodic kind has one owner that runs its loop. A single node starts them one placement pass after it serves, and the replica-id conflict alert is registered on every node, clustered or not (at one replica it finds no conflict). Every replica still writes its own buffered alert raises every 10 s and at shutdown. Only the snooze expiry and the purge belong to alert-maintenance.
Each job asks the library whether the replica still owns the kind immediately before an effect outside the cluster (a send, an announcement, a delete, a validation, a fetch of an index, a call to the media plane, a fetch from the secret store). A replica whose stop has begun therefore does none of them, but a pass already past that check finishes. A pause longer than the member lease between that check and the effect can still produce one stale effect. A delivery row the old owner had claimed keeps its claim until it expires and is then sent by the new owner.
| Job | Schedule |
|---|---|
config-flow-reconciliation, onboarding-session-maintenance |
One interval after the owner takes the kind, then every interval |
command-cleanup, device-model-retention |
Once at the start of the tenure, then every minute |
plugin-grant-restore |
Once at the start of the tenure, then every 15 seconds |
trusted-keys-revalidation |
Once at the start of the tenure, then every 30 seconds. It revalidates the installed signatures only when the hash of the trusted and revoked keys differs from the last one it revalidated, and is the only writer of that hash. A key write through the API wakes it (a hint on the cluster bus), so the recorded verdicts follow within seconds. A failing pass is retried on the same list after 30 seconds, then after twice as long, to at most 15 minutes, and a changed list runs at once. |
secret-reference-refresh |
One pass when the owner takes the kind, then its interval pass and every requested pass |
discovery-cleanup (daily), media-plane-path-sweep (hourly) |
Once at the start of the tenure, then on the interval. The media-plane sweep also wakes when its owner applies a media_plane change. |
resource-index-sync |
25 s after the tenure starts, then on the interval |
plugin-repository-sync |
20 s after the tenure starts, then every Plugins:SyncIntervalHours (6 h) |
device-history-orphan-sweep |
One minute after the tenure starts, then on the interval. A device removal on any replica publishes a hint on the cluster bus. |
blueprint-validation |
At its configured hour of the day, so a hand-over does not repeat it |
workload-storage-class-seed |
Once per tenure. It offers workloads.defaultStorageClassName to the workload settings, which take it only while they have never been saved. |
Secret reference refresh on demand. POST /api/secrets/references/refresh on any replica is run by the owner.
- On the owner, the call waits for the pass that serves it and answers
503if the kind is lost before that pass finishes. On any other replica it answers202once the request is published. - A request that reaches the owner while a pass runs is served by one more pass after it, so a call can be held for up to two passes. Past the proxy read timeout of 120 s the browser sees a
504while the refresh still completes. - If no replica owns the kind at that moment, the request is lost and the new owner's first pass refreshes.
- Every replica also refreshes its own cache of the references it holds when the owner publishes changed candidates and when its bus connection is restored, and restarts its local instances that use a rotated secret.
Demo content is seeded by a durable cluster command of the kind demo-content-seed, not inside the request that asks for it. Any replica writes the command row and the kind's owner runs it. A run interrupted by the owner's loss is run again by the next owner, and every step resumes from what the previous attempt left. The run goes on once the plugin instance runs on the owner, and its devices count as synced only when they appear in the database within 30 s. When the instance cannot run there, the outcome says why. Any replica answers a run's progress from the same row, long-polling up to 2 s, and the row is kept for the library's command retention (24 hours).
The object-storage migration runs on the owner of object-storage-migration, and a backend switch asked of any
replica wakes that owner's loop. A new owner resumes whatever the former one left, and a snapshot interrupted midway
is rebuilt from its first statement. The owner's writes are fenced: each chunk (5000 rows of the snapshot's delete,
500-row batches, every progress save of 100 objects, every status save) is a transaction the database refuses once
another replica has taken the kind, and a refused pass ends quietly. The claim and the cutover hold the storage drain
for up to 30 s, which does not fit a fenced transaction (limited to 5 s), so they are ordinary transactions guarded by
a compare-and-set on the migration's status. An abort asked of any replica marks the migration failed directly, and
the owner's next status or progress save finds the row finished and ends its pass without writing.
The OAuth token refresh checks ownership immediately before every refresh request. A refresh rotates the refresh token at the identity provider. Once the request is sent, the send, the read of the answer and the save of the rotated token proceed even if the stop begins meanwhile, because aborting would lose the token. The client's 10 s timeout bounds this, so the hand-over may overrun the stop budget by that long.
The trigger host stops firing its schedule-driven and inbound triggers when the stop begins and disarms them when it loses the kind. Triggers fed by a per-replica ingest feed stay armed on every replica.
The Matter bridge link holds the tenure itself. How its commands behave across replicas is in the Matter bridge guide.
The workloads engine
The workload library's reconciler, watch plane, retained-volume scan and repairs run under a leader the library elects itself. That leadership makes a node the leader of nothing else: the node that leads plugin communication does not have to lead the workloads. The host's own workload units (presence, orphan and observation sweeps, system-plugin bootstrap) are placed by the cluster library as above.
The leadership is a held mutex with the key workloads-engine. It is taken only once the replica serves, and renewed every 10 s. It ends at its time to live after a crash, so failover after a lost node takes up to about 35 s (the 30 s time to live plus the engine's 5 s retry). A fence ends it at fence step 3. The engine stops its units on Lost, and the overlap is the units' stop time beyond that step, including the container actions and workload row writes of the passes in flight. A draining replica loses it at drain start: the engine stops its units first, then resigns, and only then can a peer lead. After readmission the engine elects again.
A replica that has begun shutting down hands its unit kinds over at the start of its drain, while they still run, and the library places them on a peer within its failover bound.
The workflow run lock
The workflow run lock is a cluster mutex. A Single or Restart run holds one for its length, and the four workflow sweeps (execution history, version retention, debug-session retention and the compilation sweep) take it for one pass.
- A replica gets the lock and claims a keyed fire only while it serves, at every replica count. In a cluster, a fire it sees during its start-up, a fence or its drain is claimed and run by a serving peer that saw it too. A fire only that replica sees is not run: an event its own plugin connection ingested before closing, or a keyed fire of a leader-owned trigger between its drain start and the trigger host's stop. On a single node such a fire is dropped.
- A Cron or Sun fire carries no key and is not claimed, but a draining owner is refused the run lock or run slot its mode needs, so its run does not start.
- A draining replica's lock reads invalid at the start of its drain. Its run ends at its next heartbeat (at most 10 s later plus its cancel time) and releases the key. A peer starts a run only after that release, so there is no overlap.
- A fenced replica's run ends at its next heartbeat too. Its non-dispatch steps can therefore overlap a peer's run by up to 10 s after the fence's first step plus the step's cancel time. Dispatch is refused from fence step 4.
- A sweep already running when its lock is lost finishes its pass. A crashed replica's run lock frees after the mutex's 30 s time to live.
Failover and overlap bounds
These are the cluster library's defaults, which Reeve keeps: LeaseTtl 30 s, PlacementInterval 2 s, RenewTimeout 3 s, StopBudget 5 s and FencedTransactionTimeout 5 s. The chart renders LeaseTtl, RenewTimeout and StopBudget explicitly and leaves PlacementInterval and FencedTransactionTimeout to the library.
| Event | Unit kinds | Held mutexes |
|---|---|---|
| Crash or node loss | Started on a peer within LeaseTtl + 3 × PlacementInterval + FencedTransactionTimeout, 41 s |
Free at the slot's time to live, at most 30 s after its last renewal |
| Fence | Stopped at fence step 0. The member lease is released at step 3, at most RenewTimeout after step 0, or runs out within LeaseTtl when the release goes unanswered. A peer takes the kind at its next placement pass. |
Lost fires at step 0. The slot ends with the lease at step 3 when the release is answered. When it goes unanswered, the member row stays active and the slot ends at its time to live. |
| Drain | Handed over from drain start: a peer takes the kind once the unit's stop returned, or after StopBudget |
Lost fires at drain start. The slot stays held until the holder disposes it, so a peer acquires only after the holder has stopped. |
| Pause past the lease, then resume | The kind has moved on. One effect whose ownership check passed before the pause can still happen. | The mutex reads invalid at resume, on the monotonic clock. One effect whose check passed before the pause can still happen. |
A readmitted replica takes new tenures. The units it held start again only if the placer gives them back, and a mutex that read invalid stays invalid, so its holder acquires a new one.
What can overlap a peer after a fence. A peer can start once fence step 3 has passed. Work on the fenced replica that has not stopped by then overlaps it:
- a unit with an effect outside the cluster (the Matter bridge link, the OAuth refresh, alert delivery, the recovery override announcement, the secret fetch): one call already past its ownership check
- the workloads engine: its units' stop time beyond step 3, with the container actions and workload row writes of the passes in flight
- the workload lock: the rest of one provider switch
- a plugin connection: its close time when it observes
Lost, or its poll interval plus its close time when it pollsIsStillOwnedAsync - the MQTT availability leader: one publish
- a
Singleworkflow run: up to 10 s of non-dispatch steps after step 0, plus the step's cancel time - the workflow library's sweeps: the rest of one pass
- a plugin install, update, sync or retention pass, a broadcast apply on one replica, or the creation of an instance under the update-start lock: one step
- a config or repair flow: nothing, because a step that finishes after a peer adopted the flow is not written
At a drain the mutex holders do not overlap, because each releases only after its effects stopped. A unit whose stop runs past StopBudget can overlap its successor by one call already past its check.
What the database holds
The cluster library keeps owned work in its own schema, reeve_cluster. Read it for diagnosis and never write it, except for the documented delete of a member row above.
| Table | Content |
|---|---|
reeve_cluster.owned |
One row per unit kind, keyed by the kind's name. owner_replica and owner_epoch name the holder and are null while the kind is free. token is the fencing token, drawn anew for every tenure. |
reeve_cluster.slot |
One row per held slot. A mutex is a slot with a limit of one. key is the slot's key (workloads-engine, plugin-conn:…, WorkflowRunBudget_…, workflow-run-slot:…, camera-viewer:…, camera-event-media:…, oidc-refresh:…). holder_replica and holder_epoch name the holder, and expires_at is its time to live, which each renewal pushes out. A slot counts only while expires_at is ahead and the holder's member row, in that epoch, is active or draining. A crashed holder's row stays until the next acquire of that key deletes it. |
reeve_cluster.member |
One row per replica: epoch, state (joining, active, draining, fenced) and lease |
reeve_cluster.member_status |
Each replica's status sections, written once per renew interval |
The host registers no Redis slot, so the library's Redis maxmemory-policy check does not apply to it. The meter Reeve.Cluster reports reeve_cluster_owned_takeover_duration_seconds, reeve_cluster_owned_release_overdue, reeve_cluster_slot_acquires_total, reeve_cluster_slot_renewals_total and reeve_cluster_slot_held (see observability).
Database session settings
transaction_timeout must be 0 for the database role, the database and the session. Neither the Compose stack nor the Helm chart sets it. The cluster library checks every physical connection it opens and refuses one with a non-zero value (TransactionTimeoutNotZero). A replica that migrates at start fails its boot migration. With Database:Startup:RunMigrationsOnStartup=false the migrate-only job fails instead, and a replica that does not migrate never joins and stays unready. A fenced write on Reeve's own connection checks the same.
statement_timeout must be 0 for the same role, database and session, and for the application role too. The library refuses a non-zero value on its own connections with StatementTimeoutNotZero, and the application's fenced, claim and slot transactions refuse at begin.
Clear both with ALTER ROLE … RESET and ALTER DATABASE … RESET, and do not set them in the connection string. A server-level value (postgresql.conf or ALTER SYSTEM) is not cleared by either. The check reads the session's effective value, so reset it at the server too. Fenced transactions need PostgreSQL 18 or later.
Leave idle_in_transaction_session_timeout unset for the Reeve role, or above your longest upload. A storage call keeps its transaction open for the whole transfer, and the timeout would fail it after the object landed.
How configuration reaches every replica
Configuration is written to PostgreSQL, and the same transaction appends an entry to the cluster library's change log. This covers users, roles and access overrides, plugin installations, instances and grants, devices and their sources, helpers, automations and triggers, workflows, utility meters, the egress allowlist, OIDC, media-plane, workload and Matter bridge settings. Every replica's applier reads the log, rebuilds the state of each changed type from one database snapshot, and publishes it as a new generation. Requests read the generation they pinned when they were admitted. Background work pins one per action and does nothing while the replica does not serve.
A write is answered once every serving replica has applied it. The next request, on any replica, sees it. What follows the answer is the work a generation starts rather than holds: plugin instance starts and reloads, trigger arms, the Matter exposure gate's rebuild, the egress allowlist's install, the utility-meter index, the device ownership index, the workload-settings view, the OIDC metadata cache and the plugin type registry. Until a replica has done it, a request or background dispatch to a plugin instance the write retired is answered as though the instance were not running, and a fire from a retired trigger starts no run. The Matter gate and the egress allowlist keep their previous contents for that moment.
A write waits for the slowest serving replica. A crashed replica is waited for until its lease runs out, so a write can take up to AckTimeout (51 s with the shipped timings) after a crash. A replica whose applier stops progressing for ReconcileTimeout plus ApplyStallLimit (45 s) fences itself and stops being waited for. When the wait runs out, the write answers 202 with write_unconfirmed: it is committed, but not every replica has confirmed it. The web application and the companion show a notice and re-read. In the web application, an error answer that carries Reeve-Replication: unconfirmed gets the same notice.
A replica fences itself on its own facts: its lease could not be renewed, its applier stalled, an attempt hung, a fatal fault occurred, or the database moved to a new timeline after a failover. It never fences because a peer is ahead of it. reeve_cluster_fences_total counts fences by trigger. A fenced replica refuses requests (see readiness and degradation) and rejoins with a full load.
A type whose load keeps failing keeps its replica in Loading. At start-up the process retries the load without listening until Hosting__StartupTimeoutSeconds (300 s) ends it with exit code 75, and the startup probe or the restart policy starts it again. On a rejoin after a fence, readiness reports loading.failed. The Error log names the type, the attempt's elapsed time against ReconcileTimeout, and the first unapplied entry. When no replica has acknowledged that entry yet, open a skip from it with the skip command. When peers have already applied it, the fault is this replica's own, a skip is refused, and only a release that fixes the reconciler helps. Safe mode runs the reconcilers too, so it is not a way out.
Timings
The values are the same on every replica and sized for a Raspberry Pi 4. The chart renders them from its cluster block, and the code carries the same defaults for the Cluster:* options. The shutdown pair is set by the chart and the Compose files. The compiled Hosting:ShutdownTimeoutSeconds default is 204 s (valid range 5 to 600), so a deployment that sets neither only needs a grace period above it. Give every replica the same values, because one replica's wait covers its peers' budgets.
| Option | Value | What it bounds |
|---|---|---|
Cluster:LeaseTtl |
30 s | How long a crashed replica holds a write |
Cluster:ReconcileTimeout |
15 s | One reconciler attempt, a full load included |
ApplyStallLimit, AckTimeout |
30 s, 51 s (derived) | With ReconcileTimeout, how long an applier may stall before it fences (45 s), and the longest a write waits |
Cluster:ProxyReadTimeout |
120 s | The shortest read timeout of any proxy in front of a replica |
Cluster:ActionTimeBudget |
55 s | The longest a writing handler is declared to take (not enforced). ReadIndexTimeout + this + AckTimeout must stay below ProxyReadTimeout. |
Hosting:ShutdownTimeoutSeconds, grace period |
204 s, 214 s (Compose); 199 s after a 5 s preStop sleep, 214 s (chart) | Both must cover the member-request drain, 5/16 of the timeout (64 s), and then the library's drain, StopBudget + ProxyReadTimeout + 2 × RenewTimeout = 131 s: 195 s in all |
The shutdown budget must fit the drain. The member-ask dispatcher drains first, for a quarter of the host shutdown timeout plus a sixteenth of cancel grace, and then the library drains. The host shutdown timeout is one budget shared by every hosted service, and the orchestrator's kill deadline (the pod's terminationGracePeriodSeconds, Compose's stop_grace_period) must exceed it. The chart's render-time guard sizes the timeout and the grace period for both. Lowering either below those figures truncates the drain.
With a PostgreSQL standby, the library waits for synchronous replication before it acknowledges. When the standby is asynchronous, every replica logs a warning (readiness is not affected). See PostgreSQL with a standby. The proxy rules (resend only a 503, read for at least ProxyReadTimeout) are in deployment. A release inside the build's window upgrades by a rolling update. A full-stop release is a full stop.
What changes when you scale out
| Area | Behaviour |
|---|---|
| Plugins | Every in-process plugin loads on every replica. A plugin holding a long-lived connection must take a connection-ownership lease before connecting and self-fence when it loses it. A follower is healthy with a follower annotation, not degraded. |
| Device commands | The plugin instance resolves from a replica-local map. A workload's commands to a non-owning replica are written as durable rows and the owner delivers them on its own socket: reliable, with real latency. An in-process plugin whose connection lives on another replica passes the command to its connection-lease holder over the member ask, and the call fails fast when there is no holder (plugins). |
| Plugin updates | An update's plugin roll reloads one replica at a time and waits for Workloads:PluginRoll:FleetSize live replicas before each turn (below). |
| Plugin code | Reload, hot-registration and the three install markers (Requires restart, Rejected, Backend too old) are per replica, written by the replica that served the install. Install and uninstall reach every replica through the plugin_type generation, in effect on a serving replica when the write is acknowledged, or within Plugins:TypeCatchUpTimeout of it for an artifact still being pulled. A failed or cut-off apply is retried at doubling intervals until it succeeds. Instance create, delete, enable, disable and edit reach every replica through the plugin_instance generation. A replica asked for an installed type it has not loaded yet loads it on the spot and answers once it has. One that cannot within Plugins:TypeCatchUpTimeout answers 503 with Retry-After. A replica that could not hot-register says so, and rolling the deployment converges plugin code. Each replica's convergence stops instances whose row is disabled or gone and restarts a copy whose row an operator's edit has moved on, and until it has, it does not dispatch to the stale copy. An edit that reaches a replica during its own plugin-roll turn is refused there and leaves that replica's copy stopped. The next generation or the recovery sweep (Plugins:InstanceSweepInterval) starts it again. A plugin's own writes to its settings row advance no revision and restart nothing. |
| Plugin workflow blocks per replica | Each replica swaps or retires a native plugin's blocks itself. The plugin's admin page lists every counted replica with the block outcome of its last update (Swapped live, After restart, Not swapped) and of the uninstall (Waiting for live runs, Blocks removed, Kept until restart, with the count of runs still going). These come from the serving replica's records and the peers' last state reports. No report means the peer recorded nothing for the plugin, or runs an older build. When the members cannot be read, only the serving replica is shown. Runs that use this plugin opens the executions list filtered to the plugin's live runs, where each can be cancelled. Once none is left, a replica that kept the blocks still needs its restart to drop them. |
| A replica that missed an uninstall | Uninstall writes a durable type tombstone together with the installation-row deletion, and every replica's plugin_type generation carries it. The replica's sweep matches factory and WASM registrations to a manifest in the reportable install root, re-reads the tombstone under the type's locks and deletes the artifact before eviction. A reinstall that lands first wins, unreadable state changes nothing, and a removal that meets a busy lock or fails is retried. It keeps directories newer than the tombstone cutoff. It does nothing when the install root is missing or overlaps the bundled one. Both log a warning, and the directory is then removed by hand with a restart. |
| An uninstall interrupted midway | The tombstone commits with the removed installation rows, so every replica can finish local artifact deletion and type eviction if the origin crashes after the commit. The cluster's stored object copy is deleted after local files. A crash before that cleanup strands the object, because object storage has no uninstall sweep. A retry can answer 404 because the installation rows are already gone. |
| Plugin artifacts | Per-replica storage self-heals at boot from the recorded installed set, reading the cluster's own copy in object storage before the plugin's repository and re-populating that copy whenever it falls back. An unreachable source costs a plugin only when there is no usable object either, which includes an installation record that carries no digest. A plugin neither source can produce is absent, never a failed boot. The repair of an artifact the cluster holds no copy of runs every 6 hours on the owner of plugin-artifact-store and skips an artifact whose install lock is held. A drain whose put outlasts the stop budget leaves the lock held until the old owner disposes, so the new owner's first pass skips that artifact (an Information line names it). A fence between the owner's lock check and its put can leave one stray object after a peer's uninstall, which nothing reads. |
| Config, options, action and repair flows | Every submit runs on the process that started the flow, whichever replica receives it (config and repair flows). |
| Automations | Schedule-driven and inbound trigger types fire once cluster-wide, only from the replica that holds the trigger-host kind, armed on its own 30 s cycle. While no replica holds the kind, none runs them. Feed-driven triggers (state change, device event, geofence) run on every replica's own 30 s cycle and fire from whichever replica sees the event. The trigger-scoped claim collapses duplicate fires using the armed trigger identity, at every replica count. |
| Egress allowlist | A committed edit is loaded by the egress reconciler on every replica. |
| Deleting a workflow | Every replica cancels the runs it holds when its workflow pass applies the delete, and each cancelled run is audited once, by the replica that held it. A peer that has not applied the delete keeps its run until the run's next attempt, which the database refuses, so the run ends as a failure without its audit entry. |
| Expression-derived helpers | The dependency graph comes from the helper and device states of the generation an evaluation reads. The cycle check on save reads PostgreSQL under a graph-wide advisory lock, so two edits on different replicas cannot save a cycle together. Evaluating one helper is serial cluster-wide (a per-helper advisory lock is held through the read, compare and write), so replicas that both see a device change do not both emit it, and a later evaluation never writes an older value over a newer one. The debounce is per process. |
| Peer plugin calls | Resolve through the replica-local plugin map and do not cross replicas. |
| Recovery restart | Stops exactly the replica it names, and answers 202 only once that replica has confirmed it reset its failure count and is stopping. A fenced or safe-mode replica is reached too. An unnamed restart reads the roster of running replicas. It restarts this replica when the roster holds no other, and otherwise answers 400 (RECOVERY_RESTART_TARGET_REQUIRED), so name an id from GET /api/admin/recovery/status. A roster that cannot be read within 2 s answers 503. An id no running replica has is a 404. A replica that did not take the request is a 503, one that did not answer in time a 504, and one whose handler failed a 502. A replica that is not running cannot have its streak reset from the Cluster tab, but it self-heals into safe mode on its next boot attempt, after which "Exit safe mode and restart" works. A retry after a 504 that names the same id restarts the new process if the first one has already relaunched. A script that restarts a multi-replica deployment should read the replica ids from GET /api/admin/recovery/status first and always send replicaId. It should retry a 503 after its Retry-After, treat a 504 or 502 as an unknown outcome and reload the status before trying again, and stop on a 404. |
| A replica in safe mode | See below. |
| The workflow debugger | The paused run lives in the memory of the replica that executes it. A step, resume or kill arriving on another replica is published on the cluster bus and applied by the replica holding the run, and its pause events reach every replica's hub through the backplane. A command lost to a Redis disconnect does nothing: the run stays paused until the command is sent again or the orphan timeout kills it. A replica that dies mid-run takes the run with it. |
| Sign-in and second-factor limits | Every attempt counter, challenge and one-time token, and every named rate-limit budget, is counted or consumed in one atomic step in Redis or PostgreSQL, so requests spread across replicas get no more tries than one replica allows. The named budgets and the failed-login gate fail closed while Redis does not answer. The global concurrency cap and the workload handshake limiter are per replica, because they guard that replica's own connection pool and crypto work. |
| Object-storage backend switch | Decided in the database on every storage call (object-storage backend switch). |
| Plugin object storage | Shared across replicas but last-write-wins with no version precondition. Pair it with a lease when mutual exclusion matters. A filesystem backend makes it per replica. |
| MQTT client ids | Must be replica-unique (replica identity). |
| Telemetry | No replica is elected to write it (telemetry de-duplication). |
| Shared subscriptions | Nothing shards by default. Zigbee2MQTT shards its device-state stream only with SharedIngest=true, which needs last_seen enabled on the bridge: a sharded burst reaches replicas out of order, and without the bridge's timestamp a cumulative counter reads as reset and is billed again. Its share group carries the plugin instance id. Its retained bridge, device-list and availability topics stay broadcast, and a retained state is not replayed to a shared subscription after a reconnect. Home Assistant MQTT discovery subscribes its retained discovery configs on every replica, so any replica can send a command, and ingests state on the one replica holding the instance's ingest lease. The holder gives the lease up once its broker link has been down for 15 s, and another replica takes over within about a minute. WASM MQTT subscriptions stay broadcast. A subscription the broker refuses is logged at warning and retried after 5 s, then at a doubling delay capped at 5 min. A broker without shared-subscription support may grant a $share filter that never matches, which nothing reports. |
| A device's push | Who may receive it is read at broadcast time from the access state of the generation the push reads. A revoked or disabled user is out of the audience on every serving replica once the change is acknowledged. A replica that does not serve skips the push. |
| Replica status reports | See replica identity and status. |
| The admin hub | Each replica rechecks its tracked admin connections when it applies an access change and every 5 s. With a working database, removal is within one backstop interval. During a database outage, a connection is removed after RecheckGrace has elapsed since its last successful check. Checks run one at a time, so with a stalled database removal can take RecheckGrace plus one check timeout per tracked admin connection. AdminPermissionRevalidation:Interval and CheckTimeout must be from 1 ms to about 49.7 days, and RecheckGrace may be zero but not negative. |
| Adapter observations | A sidecar's session terminates on one replica, so only that replica's plugin hears its frames. With observation replication on, the frames a plugin opts into also reach the other replicas through Redis (observation replication). |
A plugin update reloads one replica at a time
The update's leader sends one replica at a time its turn. The replica claims it in PostgreSQL, reloads, and releases the claim, and the next turn follows its report. The peers go first, ordered by replica id, and the leader goes last. While a turn runs the other replicas keep serving, so an adapter refused by the reloading replica connects to another one. A failure halts the walk with the rest of the fleet on the old version, until an operator retries or gives up (a plugin update that halts).
FleetSize is per-process configuration, resolved when the leader adopts a roll and not stored in the roll row. Set the same value on every replica that may lead. If values differ, a leadership change can change the target and therefore the fleet wait. The target is configuration alone: FleetSize on a clustered host, one on an unclustered host (which warns if a larger value is configured). Membership never changes it. The chart renders the effective replica count on a clustered host and ships no autoscaler.
A clustered host without FleetSize refuses to start a plugin update (fleet_size_unset, 409) before anything is installed, pinned or adopted. It also warns at start-up and reports the plugin-roll-fleet health check degraded. A roll already in flight when the setting is missing continues against a target of one, and a new value takes effect after the leader restarts.
The census is the cluster library's leased members that are not fenced or draining, each peer with the process id of its reeve status section. A member read fault, a result missing this replica, or a counted peer whose section is missing or more than 45 s old fails the census, and the roll then waits with "the census could not be read". Each stage call rereads membership before selecting a turn, so it never sends a turn to an absent id.
Below the target, the stage waits for enough live members, with no overall fleet-wait timeout. Above it, the stage processes every member in the current census.
With FleetSize 1 (one replica, the chart's default) a turn may fence the only replica serving. A crashed pod remains in the census until its lease runs out (Cluster:LeaseTtl, 30 s), so it can hold the roll for at most that long. A stopping replica is written draining only at the end of its drain, so until then it is counted: a turn sent to it is declined and re-sent, and nothing is lost.
An instance that another operation (a permission-grant reload, a configuration restart) was restarting while the new version arrived can come back on the previous build. The replica's activation of the new version reloads it once more onto the installed version, so no pod restart is needed.
The options are in configuration.
Replica identity and status
Every process needs a replica id: REPLICA_ID, else Workflow:Engine:ReplicaId. The host refuses to start without one, or with one too wide for the workflow column. The same id serves workflow rows, MQTT identity, recovery and cluster membership. A process also draws a process id at start, so a restarted pod that reuses its replica id is a different process. A clustered host refreshes its replica-id claim and withdraws it on a graceful stop, so a second live process under the same id raises the "Replica id conflict" alert and an ordinary restart does not. On a Deployment the chart sets REPLICA_ID to the pod name. On a StatefulSet it is the stable pod name.
MQTT. Client ids are derived from the replica id, the plugin instance and the connection's role, so they are distinct per replica and per connection. The broker disconnects the older of two connections that share an id, so a fixed id across replicas is a permanent reconnect storm. A shared subscription group is named after the connection's role, the same on every replica. Connections use clean sessions, a 15 s keep-alive (a half-open link is detected in about 1.5 times that) and a bounded connect timeout. A TLS broker is trusted only through the operator-supplied CA, and a wrong or missing CA fails closed. Retained Will and Birth status topics belong to the replica holding the plugin's mutex, so a peer dropping its connection does not flip a shared status to offline.
Status reports. Each replica publishes its reeve section of the cluster status registry (PostgreSQL, every 3 s) from memory and bounded plugin-health reads. A source not yet observed reads unknown, never empty. The report interval is validated: two reports must fit in the roster's 45 s staleness window, and the interval must cover the plugin-health reads. A section older than 45 s, or unreadable, is no report, and the replica reads as silent. The roster always includes the replica answering the operator.
The owner of replica-status-alert reads the sections every 30 s and raises the plugin-fault, secret-provider, unresolved-reference and safe-mode alerts while any live report shows the condition. A replica that stops reports nothing after 45 s and, once the reader has seen it silent for two minutes, stops holding an alert open. An alert clears only on a report that says the condition is gone, and never while a known replica has not reported. A pass that cannot read the cluster status changes nothing, and after a gap the replicas report again at different moments, so clears wait until each has reported. A replica that has just restarted reports what it does not know yet as unknown, which keeps the alert as it is. The owner also waits two minutes after it takes the kind before it treats a silent replica as gone. The details are in alerts.
Redis in a cluster
Redis is mandatory on every deployment. Start-up aborts if it does not answer PING within Redis:StartupWaitSeconds or reports a version below 8.4 (waiting for it does not count as a failed boot). Reeve keeps these in Redis:
- plugin install broadcasts and cluster-bus hints, and the member-ask relay
- OAuth state (15-minute TTL, with the PKCE verifier), repair-flow sessions (sliding TTL), config-flow state and widget preview sessions
- sign-in challenges, second-factor counters and rate-limit counters
- workload adapter presence (the ground truth for session liveness)
- telemetry last values and copy claims
- window claims for fire de-duplication and cooldowns
- observation-replication streams
Failure behaviour differs by feature:
| Feature | While Redis does not answer |
|---|---|
| Rate limits, failed-login gate | Fail closed |
| Fire de-duplication, trigger cooldowns, baby monitor claims | Admit (Grant): each replica that sees an event runs it |
| Telemetry de-duplication | Fails open: duplicate rows, no lost readings (below) |
| Workload presence | A read for one instance propagates the fault, so a Redis blip is never read as "offline" and healthy sockets are not force-closed. Fleet-wide presence reads and writes swallow faults. |
| Workload handshake limiter | Fails open |
| OAuth, repair and config flows | Cannot resume on a peer replica |
| Cross-replica frame delivery | Commands to a device whose adapter session another replica holds fail for the length of the outage, with or without observation replication |
| Cluster-bus subscriptions | A subscription made during the outage logs Cluster bus: Redis disconnected; subscription to channel … deferred until reconnect at Warning and subscribes when Redis returns. A subscribe that times out while connected logs failed to subscribe to channel …; retrying and is retried from 5 s, doubling, capped at 5 min. Once subscribed, a component that mirrors database state re-reads it. Hints published meanwhile are not replayed. |
Redis Cluster is supported: Reeve avoids multi-key commands, and observation keys share an {instanceId} hash tag. The redis health check is degraded-tagged: Degraded on a failed ping, Unhealthy after three in a row, and it never pulls a replica out of rotation.
Protect Redis. It holds sessions, flow state and device observations. The chart's built-in Redis has no password by default, and plugin workloads run in the release namespace by default, so a plugin's container can reach it and read session ids. Set redis.builtin.passwordSource and networkPolicy.enabled (which then admits only the backend pods to the built-in Redis), or use an external Redis that requires authentication and let nothing but the backend reach it. See Redis.
Telemetry de-duplication
No replica is elected to write telemetry. A row's key is derived from the reading: the device's own timestamp when it lies within TelemetryIngest:SourceTimeWindow (two minutes) of capture, plus source, metric and value. A duplicate insert is skipped, so a timestamped reading delivered to several replicas is stored once. A plugin must never time a broadcast reading with its replica's clock, or every replica stores its own row.
Change-only storage compares each reading with the last value the cluster stored for that series, kept in Redis, so a value that returns to an earlier one is stored however delivery was split. The last value moves only after the rows commit. A record nothing has written for half its day-long life is rewritten unchanged, so it cannot expire under a device that keeps re-sending one value (one write per half-life). A replica stopped between the commit and that move leaves it one value behind, so a return to that value is not stored until the series changes again (at most a day).
Readings with no usable timestamp are recorded at each replica's capture time, so only the first replica to claim the copy within TelemetryIngest:CopyDedupWindow (3 s) stores it.
- The claim is the value together with the value before it in that replica's own ordered stream. A claim owner may re-claim its own key, so every repeat in that replica's stream is stored.
- A failed batch releases its claims.
- A claim is held for
TelemetryIngest:CopyClaimCommitWindow(30 s) while its batch commits, and is shortened afterwards to expire one dedup window after the reading arrived. A replica killed mid-batch holds its claims for that window. - A copy arriving after the claim expires may be stored again.
- A replica starting mid-stream claims against the shared last stored value until its own stream establishes a predecessor.
When Redis fails, the store fails open at once while disconnected and skips Redis for five seconds after a failure (each attempted operation bounded to 500 ms). Ingest continues, repeated change-only values can add rows, and cross-replica copy suppression is unavailable for that time. reeve_telemetry_dedup_store_failures_total counts failures and skipped calls.
Observation replication
A workload adapter holds one session, on one replica, and that replica's plugin builds its view of the devices from the adapter's frames. Every other replica's copy of the plugin sees none of them. Observation replication gives them those frames.
Workloads:ObservationReplication:Enabled controls whether this path runs. Unset, it follows Coordination:Clustered. Set Workloads__ObservationReplication__Enabled=true or false to override that, including on a single replica. The chart leaves it unset and relies on its Coordination__Clustered value, and the Compose multi-replica overlay turns coordination on.
- The owner appends the frame kinds a plugin opts into to one Redis stream per workload instance. Kinds the plugin does not list, such as the Matter adapter's key-value store, never leave the owner's process.
- Every other replica polls the streams of the instances its plugins follow and hands the frames to the plugin's observer, in order. The owner keeps calling the ingestor, and commands, replies and every side effect stay on the owner.
- Loss is reported, never assumed away. A replica that cannot vouch for its view tells the plugin through a gap, and the plugin falls back to what it does without replication until a checkpoint closes the gap.
Nothing here engages on a single replica, and correctness does not depend on the numbers below. A budget that is too small makes history shorter and gaps more frequent, but does not make any replica act on wrong state. The options and their defaults are in configuration. Every budget and limit is a default an operator may override, and the chart's Redis maxmemory is only the chart's default too.
Membership and the budget. The observation budget uses live cluster membership, refreshed in the background once
the cached view reaches InstanceCountCacheSeconds (10 s). Writers continue with the cached share meanwhile. A join
or leave can leave replicas with different derived budgets for at most that interval plus the bounded membership read.
A draining replica leaves the count but can keep reading until shutdown, overstating the budget by at most
ReaderMaxReplyBytes for that peer. A crashed replica can stay counted for the membership lease, understating it by
the same amount. An explicit TotalBudgetBytes does not vary with membership. Until the first refresh completes, the
share assumes one instance and one replica. A refresh that exceeds InstanceCountRefreshTimeoutMilliseconds counts as
a failed read, logged once per outage, and failed reads keep the last successful count. When replication is disabled,
calculating the share makes no membership read.
Plugin reloads and replicated sessions
A session resolves its opt-in once, when it opens, so a reload ends the sessions of the plugin it reloads, on each replica, by itself. There is nothing to do after installing a plugin update. The replica doing the reload declines new registrations for that plugin's workload instances, closes the sessions it owns, waits for the ones that replicate observation to finish closing, swaps the assembly and lifts the refusal. The adapter reconnects on its own, and the session that comes back resolves its opt-in against the loaded plugin. An instance with the opt-in off has no replication state to drain, so its close is ordered but not awaited.
You see a short burst of refusals in the gateway log, and one session recycle per workload instance of that plugin:
Declining the workload session for instance 0c73170d…: the plugin instance … is being reloaded on this
replica. The adapter will reconnect.
A plugin update reloads one replica at a time, so an adapter the reloading replica refuses reconnects to another one. An install that is not an update, a configuration edit and a WASM activation reload every replica at once. The recycle is then fleet-wide, and observation stops for the assembly swap plus the adapter's reconnect delay. Each refusal counts as a failed attempt on the adapter side and advances its jittered backoff (500 ms doubling toward a 30 s cap), so the gap is longer than the swap itself and still shorter than a pod restart.
If a session will not close, the reload goes ahead anyway after Workloads:Gateway:InstallEvacuationTimeoutSeconds (15 s) and names the instance that was still live. Its owner will not vouch for the rest of that session.
Three things make a reload proceed without that protection, and each says so at warning level. Grep the gateway log of the replica that reloaded before you conclude a reload was clean:
| What happened | What the log says |
|---|---|
| The workload instances could not be read, so nothing was fenced | Reloading plugin instance … WITHOUT fencing its workload sessions |
| A session would not finish closing inside the evacuation timeout | Reloading with workload instance … still live after … |
The reload outran Workloads:Gateway:InstallFenceMaxHoldSeconds (120 s) and the fence lifted under it |
The registration fence for plugin instance … expired before its reload finished |
A clean reload logs Fenced N workload instance(s) of plugin instance … for its reload and nothing else. That line is the only positive evidence: without it, a reload that fenced nothing reads exactly like one that fenced everything.
An assembly swap is not the only thing that replaces a plugin object. Editing an instance's configuration does it too, on the replica the operator used and on every peer that applies the change, and so does activating a WASM plugin. All three take the same fence, so expect one session recycle per workload instance when you edit a live integration.
A WASM activation can trip the fence's deadline routinely. It holds a fence for every instance of that plugin type that is running or enabled (a row that is down can already own a session) and then stops and starts them in sequence, so one slow instance spends InstallFenceMaxHoldSeconds on behalf of all of them. A burst of expired-hold warnings naming different instances of one plugin type after a WASM install means the deadline needs raising for a fleet that size, not that any one instance misbehaved.
Reading the metrics
behind_owner_seconds depends on the reader mode. With Polling at the default 250 ms interval, mean lag is near half a second. Quiet Adaptive and Interrupt readers can add up to the 5 s idle interval when a hint is lost. Alert on the trend, not the absolute value: a view that keeps falling further behind is a Redis or sizing problem.
behind_owner_seconds does not measure how slow the owner's plugin is. It is the age of the owner's cursor (Redis time minus the last time the owner touched its high-water mark), and the heartbeat touches that mark every second whether or not a frame moved. reeve_workload_observation_publish_delay_seconds measures each frame from its arrival at the gateway to its append to the stream, so it carries the owner's dispatch time, which the stream waits for. Read the two together: publish_delay_seconds says how long the owner took to rule on a frame, and behind_owner_seconds how far a follower trails the owner's cursor once it was published.
reeve_workload_observation_incomplete. Page on side="owner", which answers "is the owner's own view holed". A reader that may not restore a checkpoint (the session owner following its own instance outside a handover) reports 0 on side="replica". One that is draining, and may restore, reports what it finds. A plugin install ends the sessions of the plugin it reloads, so the sessions that come back have nothing against them. A side="owner" that stays at 1 after an install points to a real problem, unless one of the three warnings above is in that replica's log, in which case that reload ran wholly or partly unfenced.
side="owner" has one blind spot. It is reported when a session's handover runs, and a session whose consumer could not be resolved within two seconds at open has no handover, so an instance can hold a live session with neither side reporting. It logs at warning: Resolving the observation consumer of workload … failed or took longer than …; the session dispatches without a handover. If an instance is absent from both series while its adapter is plainly connected, look for that line. Restarting the adapter builds the session again.
Choosing a reader mode
Every replica that does not hold an adapter's session reads that adapter's stream. ReaderMode decides when:
| Mode | Reads | Idle cost | Delay of the first entry after a quiet spell |
|---|---|---|---|
Polling |
Every PollInterval (250 ms), whether or not anything was appended |
3.7 rounds a second; about 3 to 3.5 % of a core per reader process | Up to one PollInterval; 150 to 160 ms p50 in the bench |
Interrupt |
When the owner's hint arrives, plus a full round every IdlePollInterval (5 s) |
0.2 rounds a second; about 1.2 to 1.8 % of a core | A pub/sub round trip, about 30 ms p50 in the bench; up to IdlePollInterval if the hint is lost |
Adaptive (default) |
Like Interrupt while quiet, like Polling from the first entry until eight empty rounds pass |
As Interrupt while quiet |
As Interrupt after a quiet spell, as Polling under steady traffic |
The figures come from an isolated bench on a shared desktop CPU (tools/bench/workload-observation-replication/), not from a full backend or small hardware. Up to one entry a second per instance, Interrupt is the cheaper and faster of the two hinted modes, and Adaptive pays off only at hint rates well above that.
A plugin that calls CatchUpAsync when translating a command reads the owner's cursor at once, whatever the mode. Commands are unaffected by the mode.
- A lost hint costs latency, never data. The full round reads every instance, and a bus reconnect triggers one. The worst case is
IdlePollInterval, when a hint is lost, when an owner runs a host that publishes no hints, or when an owner usesPolling. - The idle interval delays noticing a Redis restart, an owner that stopped replicating, and a newly installed instance, each by up to
IdlePollInterval. The interval counts from the end of the last full round, so a run of hints can never postpone it. - A failed round backs off (one
PollInterval, doubling to a 5 s cap) before it is retried. While a retry is owed, no dirty round runs, so a storm of hints cannot postpone or skip the retry. - Under sustained traffic, each instance can cause a read per owner batch (up to 50 a second at the 20 ms batch interval).
Adaptiveswitches to one full round per interval instead. - Session open and close markers are not hinted. A reader waiting on hints sees a closed session on its next full round.
BehindOwner, shown in the Replication badge of the physical device page's header (Advanced mode) and returned byGetFreshnessAsync, adds how long ago the reader last read the cursor to the owner's own lag. On a quietInterruptorAdaptivereplica it grows to aboutIdlePollIntervalplus up to a 1 s heartbeat. That is expected, and thebehind_owner_secondsmetric still reports the owner's lag at the moment of a round.
Set the mode with Workloads__ObservationReplication__ReaderMode, or workloads.observationReplication.readerMode in the chart. Every replica should run the same mode. A mixed fleet is safe but slower: an Interrupt or Adaptive replica hears no hint from an owner on Polling, so it reads that owner's instances only on its full round. When replication is off on a single node, no reader loop runs.
What it keeps in Redis
Per workload instance, all under one hash tag: the stream (reeve:workload:obs:{<instance id, no dashes>}), a cursor hash that orders sessions, the latest checkpoint the owner's plugin produced, and the last measured size. Cluster-wide: the set of instances that hold observation bytes (reeve:workload:obs:instances), which divides the budget, and a liveness key.
Retention has no time limit. An entry stays until its instance's share pushes it out. A quiet instance's stream can hold frames that are weeks old. A stopped instance keeps its stream and checkpoint until its chain has been closed for DormantAfterHours (24 hours), when the sweep deletes them. That is the price of a session order that survives restarts. The stream holds only what plugins opted in to. Checkpoints hold whatever the plugin chose to put in them, and the plugin contract forbids secrets there.
Disabling the feature does not free its memory. The sweep that trims and removes streams runs only while the feature is enabled, so the keys stay as they were. Nothing reads them, and turning it back on continues the same chain. To get the memory back, delete reeve:workload:obs:* while the feature is off.
Cost model
share = min(PerStreamBudgetBytes, total / instances)
total = TotalBudgetBytes, or when unset
min(64 MiB, TotalBudgetPercentOfMaxmemory% × RedisMaxmemoryBytes − replicas × ReaderMaxReplyBytes)
history = share / (entries per second × bytes per entry)
The budget bounds memory whatever the traffic. At rest the streams hold at most total, and between an append and its trim at most 1.5 × total. Each replica adds, transiently, one poll reply (ReaderMaxReplyBytes) and one append batch per session it owns. What varies between installations is how much history the budget buys, and so how often a lagging replica recovers from a checkpoint instead of reading.
An entry costs its payload plus field names and an id, roughly two hundred bytes on top of the payload. Measure your own (below).
instances counts every instance holding observation bytes, including a stopped one whose chain has not been dormant for DormantAfterHours. An instance whose plugin opts into nothing, or whose session ran with replication off, is not counted. Adding one shrinks every share. Each stream converges to its new share on its next append, and quiet ones on the next sweep.
CheckpointIntervalSeconds has to fit inside that history. A restoring replica takes the checkpoint's state and resumes reading from the id the checkpoint named. When the checkpoint is older than the history the share buys, that id has been trimmed, so the replica reports a SequenceJump and reads on from wherever the stream starts. It recovers, but every such recovery costs a gap. The default is 60 s, which 8 MiB covers only below roughly sixty entries a second at 2 KB an entry, and far less at larger frames. In the bench, 64 KiB entries at 50/s left 2.5 s of history, and with checkpoints every 5 s two runs in four reported the jump. A 24 MiB share, or a 1 s interval, cleared it in every run. Set the interval from history, not from the default.
Without RedisMaxmemoryBytes (an external Redis the chart cannot see) the derived total is its 64 MiB ceiling.
The owner's cost is one guarded Redis transaction and one memory measurement per batch (a batch every 20 ms while frames arrive, sooner under load), plus a heartbeat each second when nothing was appended. An idle heartbeat is one guarded transaction with no memory measurement and no trim, and a session's first heartbeat trims once. A replica's cost is a couple of pipelined round trips per poll, whatever the number of instances it follows.
As arithmetic with the defaults: with the chart's 256 MiB maxmemory and two replicas, total is min(64, 51.2 − 2) = 49.2 MiB. Each instance gets the full 8 MiB up to six instances, and the share falls below the 1 MiB MinShareBytes from the fiftieth. How much history 8 MiB buys depends on the adapter's traffic, which ranges from a few frames a minute in a quiet home to hundreds a second while a large fabric re-primes after an adapter restart.
A share below MinShareBytes refuses nothing. Histories get shorter, larger checkpoints are rejected (a checkpoint may use at most half the share), and replicas report more trimmed-past gaps and gaps that stay open. The health check and reeve_workload_observation_share_below_min report it.
Sizing from your own measurements
Size from what your deployment does, with replication enabled, over a period that includes the busiest thing it does (an adapter restart, a rolling backend restart):
- Traffic per workload:
sum by (workload, kind) (rate(reeve_workload_observations_appended_total[5m])). - What a stream holds, and for how long.
reeve_workload_observation_bytesis reported by the replica that owns the session, so sum it across replicas.reeve_workload_observation_share_bytesis already the largest share across a replica's instances of the workload, so take the max across replicas. In Redis,MEMORY USAGE reeve:workload:obs:{<instance id, no dashes>} SAMPLES 0gives one stream's bytes, andXINFO STREAMon the same key gives its first and last entry ids. Entry ids are Redis time in milliseconds, so their difference is the history that stream holds. - Whether that history is enough. A replica falls behind by more than the history only when it stalls (a paused process, a slow plugin observer, a poll loop that could not reach Redis). Rising
reeve_workload_observation_gaps_total{reason="trimmed-past"}means it happens, and a longreeve_workload_observation_checkpoint_age_secondsmeans the recovery it forces replays a lot. - The instance count:
SCARD reeve:workload:obs:instances, or the count the health check prints. - Headroom for everything else: Redis's
used_memoryagainstmaxmemory, with replication on. Redis runs withnoeviction, so a full Redis refuses writes. The observation writer pauses on that refusal (reeve_workload_observation_writer_paused), but the cache, sessions and backplane feel it too.
reeve_workload_observation_budget_needed_bytes{knob} says which limit binds and what it has to become to restore MinShareBytes for the current count. While the share is under it, exactly one of knob="maxmemory", "total_budget" or "per_stream_budget" is above zero, the same knob and figure the health check names. Then:
- Raise Redis
maxmemory, andRedisMaxmemoryByteswith it. The chart does this for its built-in Redis. For any other, setworkloads.observationReplication.redisMaxmemoryBytes. This helps only while the derived total is under its 64 MiB ceiling, which is when the gauge namesmaxmemory. - Set
TotalBudgetBytesfor more than the ceiling, or a figure you choose. It is used as given, so make sure Redis has room for 1.5 × that value on top of everything else. The health check reports a total above half ofRedisMaxmemoryBytes. Once a total is set, orMinShareBytes × instancespasses the ceiling, the gauge and the health check nametotal_budget. - To give each instance more history without growing the total, raise
PerStreamBudgetBytes, but only if the total divided by the instance count is already above it. Otherwise the total binds.
Recovery times measured on a test setup of two replicas, two workload instances and one Redis, with the feature on. They are that setup's numbers, not a guarantee, but the right order of magnitude to alarm against:
| What happened | Back to a named owner |
|---|---|
| Both replicas restarted, one at a time | 1 min 57 s |
| The replica holding the sessions was killed | 31 s |
| Redis was restarted | 13 s unavailable; every stream, cursor and the presence key survived |
The handover does not wait on a supersede notification. The time is spent noticing a dead replica and waiting for the adapter to reconnect, and HandoverGrace (5 s) does not set it either.
A rolling restart, one replica at a time with each waiting for /health/ready, leaves every replica reporting the instance complete again (the owner from its own session, the others through replication). A replica that comes back finds the chain where it left it and reads forward. One whose position the share has passed recovers from the owner's checkpoint. Watch reeve_workload_observation_gaps_total through the rollout: a cold-start per instance on a replica that lost its position is expected, and anything else is worth reading. Read how far a follower runs behind from reeve_workload_observation_behind_owner_seconds, where it should sit near the poll interval.
Health, sweep and diagnostics
The observation-replication check in /health/details is degraded-tagged and never unhealthy: without replication, plugins do what they do on a single replica. It reads only in-process state, never Redis, and reports, naming up to three instances at a time:
- a share below
MinShareBytes, with themaxmemoryorTotalBudgetBytesthat would restore it TotalBudgetBytesabove half ofRedisMaxmemoryBytes- a writer on this replica paused by Redis's out-of-memory refusal for longer than
OomRetryMaxSeconds - this replica's view of an instance incomplete for more than five minutes. This leaves out an instance whose session this replica holds (the owner side reports that), and only notes, without degrading, one whose plugin cannot restore a checkpoint.
- a poll loop that has not finished a round in ten of its longest regular sleeps (
PollIntervalinPolling,IdlePollIntervalinInterruptandAdaptive, so 50 s at the default idle interval), or in 10 s (twice its longest backoff), whichever is longer
The reeve_workload_observation_reader_mode gauge and the start-up line Observation reader loop started (mode …) confirm which mode a replica runs.
The leader runs a sweep every InstanceRegistrationSeconds (60 s). It reconciles the instance set with the cursors in Redis, trims streams that have reached their share, and deletes dormant chains and keys left without a cursor. It also marks the chain of any instance whose session never opened one, so that every replica sees the gap (reeve_workload_observation_taints_total{source="not_replicating"}). Every step is idempotent, and a failure costs that instance, not the pass.
A gap in the feature itself is not trusted. Every replica running the feature extends the liveness key. It lapses after 120 s with no such replica, or when Redis loses it. The sweep then marks every chain as broken once (reeve_workload_observation_taints_total{source="alive_lost"}). Turning it off everywhere, or a full outage longer than two minutes, therefore costs one checkpoint round per instance when it comes back. Turning it off on one replica does not, because that replica's sessions are still recorded in the chain, without their frames, and the others report the time as a gap.
The device detail page shows, in Advanced mode, each workload instance's state on the replica that served the page: where its view comes from (the local session, replication, or neither), whether it is complete, how far behind the owner it is, and whether the owner is paused.
Read replicas
A second, read-only database context binds to the optional ReplicaDatabase connection. It is injected only into services classified replica-safe: analytics, device and location history, utility aggregation and high-volume collection listings. Everything else stays on the primary.
Read-only is not replica-safe. Token revocation, one-time-code replay protection and session role sync are read-only, and a stale answer to any of them is a security defect. Authentication, authorization, security and rate-limiting reads therefore never leave the primary. Neither does any read-after-create target (get-by-id, detail views, personal dashboards), which is why no read-your-writes stickiness is needed. The postgresql-replica health check asserts that the endpoint is a standby (pg_is_in_recovery()), so a connection string pointing at the primary is reported rather than accepted. Unset the connection and every read falls back to the primary.
Readiness and degradation
/health/live answers while the process runs. /health/ready reflects hard dependencies and the replica's own phase: the primary database, the cluster library's check (the replica has joined and is serving) and the safe-mode check. Redis, discovery and the read replica are degraded-tagged. They appear in /health/details for alerting and never pull a pod out of rotation. An outage of one of them degrades parts of the product while authentication, scenes, dashboards and automations keep working, and taking the pod out of the load balancer would turn a partial outage into a total one. Multi-replica correctness needs Redis, but that is enforced at start-up, not by the readiness probe. See observability.
A replica that is not serving, fenced or behind answers API requests with a problem document whose top-level errorCode is replica_not_serving, replica_fenced or replica_behind, plus Retry-After. A write whose commit is refused mid-request answers 503 write_refused, or 202 write_unconfirmed once entries were appended. The refusal is logged and carries Retry-After and the security headers.
Sign-in, health, metrics, /version, system status, replica logs, the recovery endpoints, /api/admin/cluster/skips and /api/admin/cluster/status (both need home.manage) still answer on a fenced replica, so an operator can reach it. GET /api/admin/cluster/status answers every member's row, sections and fence history as JSON, with Redis down and on a fenced replica.
What a fenced replica does
A fenced replica stops its unit kinds at fence step 0 and leaves the rest of the coordination at once. It claims no device-model job and no automation fire, and hands no running plugin instance to commands, notifications, alert deliveries, peer plugin calls or discovery scans. It takes its share back once the cluster library reports it Serving after that fence (the unit kinds at the library's next placement pass), whatever /health/ready says for other reasons. The log reads This replica is fenced: it aborted N open connections… at the fence and This replica serves again after fence N… at readmission.
Its plugin instances keep running and receiving device events, so an automation fired by an event that only the fenced
replica hears does not run during the fence. An event a peer also hears runs there. A plugin connection lease and the
MQTT availability mutex read lost from fence step 0: the leader publishes offline and releases, and a plugin that
observes IPluginConnectionLease.Lost or polls IsStillOwnedAsync closes its connection and disposes the lease,
after which a peer may take the device. The plugin operation locks read lost from step 0 too, so an install, update,
sync or retention pass stops at its next step. The demo seed's boot lock stays held, because it is taken only at boot.
A fire queued just before the fence is dropped. Two races remain at the instant of the fence: an alert delivery
already in flight spends an attempt, and the boot-time demo seeder can try to start an instance that is already
running.
A replica in safe mode
A replica in safe mode is fenced on the host side. /health/ready answers 503, so on Kubernetes the Service drops it, and a middleware refuses every request outside the fenced-member exemptions with 503 replica_not_serving. Compose's balancer ignores readiness, so there only the refusal applies. It stays Serving in the cluster library, so a peer's Cluster tab lists it and restarts it over the member ask. A lone replica is not reachable through the Service until it restarts. See troubleshooting.
- It does not take the workloads-engine mutex. It advertises the
safe-modecapability before it joins, and the placer gives it no kind that forbids it. The trigger host, alert delivery, the OAuth refresh, the secret rotation, the blueprint, widget and resource-index syncs, the artifact-store repair, the system-plugin bootstrap, the Matter bridge link, the config-flow reconciliation and the baby monitor run on a peer. A lone replica in safe mode leaves those unowned and keeps running the database-only kinds. - It runs no plugins, so a request that needs a plugin type loaded (starting a flow, creating an instance) is refused.
- OIDC answers 503 on the sign-in routes it still serves, so a federated sign-in whose challenge or callback lands there (Compose) fails and has to be retried. A login page loaded from it shows the password form and no provider button until a reload lands elsewhere. With local login disabled it accepts a password only from an account holding the Administrator role.
Skips
The host binary opens and closes a skip without starting the host or joining the cluster. Run it with the replica's usual configuration:
dotnet Reeve.Api.dll --cluster-skip open --type <type> --from <seq> --reason <text> --by <name>
dotnet Reeve.Api.dll --cluster-skip close --id <id> --by <name>
dotnet Reeve.Api.dll --cluster-skip list
--from comes from the Error log of the failing type, which names the type and the first unapplied seq. A successful open prints Opened <id>. Keep the id, or read it back with list. list prints each open skip (id, type, first seq, operator, time, reason) from the freshest member's skips status section, and exits 1 rather than print an empty list when no replica reports that section yet. A listing from a lagging member may still show a closed skip. Control characters are stripped from printed fields, because they arrive through the HTTP endpoint.
| Exit code | Meaning |
|---|---|
| 0 | Success. Closing prints the repair seq, and closing a skip again is not an error. |
| 2 | Open refused: replicas have already acknowledged --from or beyond (Refused(AckedSeq <n>)). |
| 1 | Malformed command (prints usage) or any error, including an unknown id. |
The command waits at most 30 s for the synchronous standby. On that timeout it prints Cluster skip command timed out while waiting for the standby… and exits 1, but the open may have committed under an id it never printed. Do not open again, which would open a second skip. Each running replica logs a Critical line A skip is open: … (skip <id>, opened by <name>: <reason>) at its next read of the open skips, and reeve_cluster_skip_open rises for the type. Take the id from that line. A timed-out close is simply run again.
Lowering a version or protocol floor
The host binary lowers a cluster floor without starting the host or joining the cluster:
dotnet Reeve.Api.dll --cluster-floor lower-version --version <X.Y.Z|none> --by <name>
dotnet Reeve.Api.dll --cluster-floor lower-protocol --protocol <N> --by <name>
Every flag is required. none clears the version floor, and a version is the plain X.Y.Z of the old build, without +<build> or -rc.N. The command reads the database like the skip command and needs the backend's environment and a REPLICA_ID no member uses. In a rollback it runs while every replica is stopped, so use a one-off container of the backend image (docker compose run --rm -e REPLICA_ID=floor-cli backend dotnet Reeve.Api.dll --cluster-floor …, or a pod from the image with the backend's secrets). The command is check-then-act: a starting or still-joining replica is not seen, so a full stop remains the rule around it.
| Exit code | Meaning |
|---|---|
| 0 | Lowered …, or Not lowered: … when the floor is already at or below the value, so a retry is a success. |
| 2 | Changed: …: the floor moved while the command ran. Run it again. |
| 3 | Refused: a member holds a valid lease in a state other than joining (named on stderr). Stop it first. A cleanly stopped or killed replica also blocks it until its lease ends (LeaseTtl, 30 s), so wait and run it again. |
| 1 | Malformed command (anything but X.Y.Z or none; prints usage) or any other error (prints the cause). A 30 s standby timeout also exits 1 and the floor may have been lowered. Run it again, and a lowering that landed answers Not lowered. |
The sequence around it, a full stop, is in upgrading.
Object-storage backend switch
An object-storage backend switch holds on any number of replicas. Every storage call reads the active backend and the migration state from the database, so a write on any replica is refused from the moment the switch is accepted, and every replica reads and writes the new backend from the moment the cutover commits. It is safe to purge the old backend as soon as the admin page shows the migration done. Do not switch backends during a rolling update, since a replica still on an older release does not take part. The provider list is a change-log aggregate (object-storage): adding, editing or removing a provider reaches every replica through the change log without polling.
- The claim takes write admission exclusively, then drains in-flight write leases. Cutover closes general admission and drains all leases. Each admission hold is capped at half
ObjectStorage:Gate:SharedWaitTimeout(5 s with the 10 s default), and new calls wait or retry while it is held. - If a drain is postponed, the owner of
object-storage-migrationreleases its locks and scans again after 3, 6, 12, 24, then 48 s, capped at 60 s. A completed attempt resets the delay to 3 s. A replica whose host is gone releases its share within about half a minute, unless a connection pooler sits between it and PostgreSQL. - While a migration runs, object-storage writes are blocked, so an install refuses with
artifact_store_migratingand a503until it finishes. A read is refused only while a claim or cutover step holds the barrier. Otherwise it reaches the source backend, so a cold replica can still boot from a stored artifact throughout the copy. - The pre-download size gate of an install reads the replica's own hint of the active backend's cap, which an idle replica refreshes on its next storage call or poll, up to a minute later. Between a cutover and that refresh, the same artifact can refuse with
artifact_too_largeon one replica and install on another. The write itself is always checked against the cap of the backend it lands on.
Connection pools
Budget PostgreSQL max_connections for every replica's pools, at their caps:
| Pool | Cap |
|---|---|
| Application | Database__Pool__MaxSize |
| Object-storage gate | Database__ObjectStoragePool__MaxSize (8) |
| Cluster library | four pools capped at Database__Pool__MaxSize, a renewal pool of 8, a read-index pool of 16, and unpooled applier connections |
Real use is a handful of connections, but a burst can reach the caps.
The MQTT broker is the operator's
Reeve ships no broker, and scaling the backend scales none. Every replica's MQTT integrations connect to the broker named in the plugin instance's settings, so a highly available MQTT setup is a clustered broker of your own.
The Docker workload provider
The Docker workload provider is bound to one backend replica's daemon, so it runs on a single backend only. A clustered host refuses to start while Docker is the stored provider or a live workload is managed on it (exit code 75, with a message naming the rule), and refuses a save that selects it. A workload row frozen by the operator's switch to Manual, or by the host's hold of one, counts as the operator's own runtime, which the engine never touches. A switch in progress still counts as Docker in use. Automatic provider selection never picks Docker in a cluster, because Docker's probe is per replica and would resolve differently on each. The provider stays registered for preview, orphan handling and an explicit test. Use Kubernetes or Manual for several replicas.