Skip to main content

Messaging (NATS)

The message bus between the services. cmd/tcpserver publishes device telemetry and presence; cmd/ws-gateway sends commands to devices and publishes Activity Trail records; cmd/persistence-worker writes telemetry and activity to TimescaleDB; cmd/deviceadmin sends session-control commands; cmd/live-viewer is a debugging tail. Subject names, stream and bucket names, and their setup live in one place — server/internal/natsclient — so every service agrees on them without re-typing strings.

Subjects​

SubjectTransportDeliveryPublisherConsumers
telemetry.<deviceKey>JetStream stream TELEMETRYdurable — retained so a restarted consumer catches uptcpserver, once per decoded snapshot at either cadence (default or watched), for registered devices only — an unregistered session is never polled (Session.ShouldPullTelemetry)ws-gateway (ephemeral, per watched device), persistence-worker (durable consumers persistence-worker, wildcard telemetry.>, and persistence-worker-param-history, the same subjects, for Historical Data parameter history; see Historical Data), live-viewer (ephemeral)
presence.<deviceKey>core NATSnot durable — a stale "device X was online 10 min ago" has no value to a late subscribertcpserver, on every liveness change/heartbeat reaffirmation, for registered devices only (an unregistered connection's key is an IP:port nobody can subscribe to, so publishing it has no reader)ws-gateway, live-viewer
plant.changedcore NATSnot durable — best-effort; every combined watch also re-reads its membership every 60 sws-gateway after register, an applied update_device plant move (old and new plant) and the start of a confirmed delete_device erasure; deviceadmin after revoke, restore, delete. Payload {"plantId": "…"} — one fixed subject, because a plant id may contain .ws-gateway (one subscription per process, routed in memory to the plant's combined watches — see Parallel inverters)
access.revokedcore NATSnot durable — best-effort; a gateway that misses it still loses the user's access when the ticket expires (≤ 10 min)persistence-worker's HTTP bus consumer, re-publishing the HTTP server's access.revoked.v1, and publishing a PLANT revocation itself when a plant is blocked. Payload {"scope": "USER"|"ORG"|"PLANT", "sub", "orgId", "plantIds", "reason", "effectiveAt"}ws-gateway: without plantIds, closes the user's (USER, any org) or the org's (ORG, by the ticket's org) authenticated connections with close code 4401. With plantIds, ends only those connections' live views of the plants (USER, ORG) or every connection's (PLANT). See revocations
command.<deviceKey>core NATSnot durable — only meaningful to whichever tcpserver node holds that device's live connection right nowws-gateway: watch_start/watch_stop (plain publish), device_write and read_registers (request-reply via nc.Request — see WebSocket integration), reresolve after a successful register, disconnect before a confirmed delete_device erasure. deviceadmin: disconnect (revoke, delete), reresolve (restore)tcpserver (the one session that holds that device's lease)
activity.<deviceKey>JetStream stream ACTIVITYdurable — retained so a restarted consumer catches upws-gateway, once per completed device_write and once per accepted sync_ble_activity entry (see Activity Trail)persistence-worker (durable consumer persistence-worker-activity, wildcard activity.>)
alertscan.<deviceKey>JetStream stream ALERT_SCANSdurable — retained so a restarted consumer catches uptcpserver's AlarmScan poll step, but only on a snapshot (new session), a change (the device's active alert set changed since the last scan), or session_end — a steady-state device with nothing changed publishes nothing. Deduplicated with the Nats-Msg-Id header (loggerId:sessionEpoch:seq) — the first use of JetStream dedup in this codebasepersistence-worker's alert-processor (durable pull consumer, wildcard alertscan.>)
alertevt.<deviceKey>JetStream stream ALERT_EVENTSdurablepersistence-worker's alert-processor, once per alertscan message that changed something, after the database commitws-gateway (one wildcard subscription on alertevt.> per process, fanning out in-memory to subscribed clients — not per-device, see Why ws-gateway subscribes per-device, not fleet-wide for why this stream is the deliberate exception), persistence-worker's push sender (durable pull consumer persistence-worker-push, wildcard alertevt.>, only when push is enabled — see Push notifications)

Streams and KV buckets​

Everything JetStream-backed, as natsclient creates it. Each Ensure* helper creates the stream or bucket if it is missing, so whichever service starts first creates it. For an existing stream, the helper reconciles MaxAge to the value in code on every service start (natsclient.ensureStream); every other setting, and every KV bucket setting, is left as it is on the server — changing one of those in code does not alter a stream or bucket that already exists.

NameKindSubjects / keysRetentionCreated by
TELEMETRYstream, file storagetelemetry.>MaxAge 72 htcpserver, ws-gateway, persistence-worker, live-viewer
ACTIVITYstream, file storageactivity.>MaxAge 72 hws-gateway, persistence-worker
ALERT_SCANSstream, file storagealertscan.>MaxAge 72 htcpserver, persistence-worker
ALERT_EVENTSstream, file storagealertevt.>MaxAge 24 hpersistence-worker, ws-gateway
WATCHED_DEVICESKV, history 1encoded deviceKey → watched marker30-minute TTL per keytcpserver, ws-gateway
DEVICE_SESSIONSKV, history 1encoded deviceKey → owning tcpserver instance id6-hour TTL per keytcpserver
PENDING_DEVICE_DELETIONSKV, history 1plant.<confirmation token> → {deviceKey, userId, plantId} (plantId re-checked against the device at confirmation)5-minute TTL per keyws-gateway
TCP_INSTANCESKV, history 1<tcpserver instance id> → last-heartbeat timestamp90-second TTL per keytcpserver (refreshed every poll cycle, ~30 s)

What each bucket is for:

  • WATCHED_DEVICES — whether anyone is watching a device, so a session that reconnects after missing a watch_start still learns it is watched. ws-gateway writes it alongside every watch_start/watch_stop; tcpserver reads it once per new connection. See Delivery semantics.
  • DEVICE_SESSIONS — the session lease. One device can briefly hold more than one TCP connection (a DTU whose WiFi dropped opens a new one before the server notices the old one is dead), and two sessions on command.<deviceKey> would execute a single write twice on real hardware. The newest connection wins: its session takes the key with a compare-and-swap on the entry's revision (the revision is the lease epoch), refreshes it every heartbeat cycle, and a session whose refresh finds a newer owner closes itself. It is shared state rather than an in-process map because the two connections are often on different tcpserver tasks. The 6-hour TTL only clears entries for devices that stopped connecting; a live session refreshes every ~30 s (natsclient/sessionlease.go).
  • PENDING_DEVICE_DELETIONS — see Device deletion confirmation.
  • TCP_INSTANCES — one key per tcpserver process (not per device), refreshed on the same cadence as the poll loop. persistence-worker's offline sweeper reads this bucket's live key set to tell "this instance crashed or was redeployed" from "this specific device disconnected cleanly" — see Device Alerts.

Bucket keys are encoded, not raw deviceKeys (natsclient.WatchedDeviceKey, used by both device-keyed buckets). NATS restricts KV keys to [-/_=.a-zA-Z0-9], and an unregistered device's fallback identity is its connection's IP:port — the : made every Put/Get/Delete for such a device fail with nats: invalid key, silently disabling durable watch recovery for exactly the devices most likely to be reconnecting (confirmed live in ws-gateway's logs). Disallowed bytes are escaped as =<hex>, so a registered device's id (a UUID) is unchanged and two different device keys can never collide on one bucket key.

:::note Why the retention values are what they are The database, not the stream, is the system of record. A stream only has to hold messages long enough for persistence-worker's durable consumer to catch up after an outage, so the 72-hour limit on TELEMETRY, ACTIVITY and ALERT_SCANS covers a worker that is down over a weekend. ALERT_EVENTS is only read live, and a notification about a day-old state change is not worth sending, so it keeps 24 hours. The streams use the default limits-based retention, not work-queue retention: acked messages stay until MaxAge removes them. A worker outage longer than the limit loses the messages that aged out and needs a manual backfill.

These limits were added on 2026-10-06. Until then every stream had none and grew until the NATS root volume filled. The first service start with the change trims each existing stream to its new limit straight away. :::

What deviceKey is​

deviceKey is the device's id (devices.id), a UUID the database generates when the device is registered (migration 0072). Every subject and KV key above that names a device uses it. It is deliberately not the logger: a device's logger can be replaced (update_device), and keying on the logger would move the device's subjects, session lease and watchers to a new key at every swap. Keyed by id, the new logger's session publishes on the same telemetry.<deviceKey>, takes over the same DEVICE_SESSIONS lease (which closes the old logger's session if it is still connected), and every client already watching keeps receiving readings. Telemetry records, alert scans and write results also carry the reporting logger as loggerId.

tcpserver resolves it when a connection is established. It asks the DTU for its own part number (AT+DTUPN?), looks up the device that logger is fitted to (devices.logger_id), then reads the inverter's serial over Modbus to check that this logger is still plugged into the inverter it was registered with. See Server behavior for the full resolution order and the refusal outcomes.

Messages published before migration 0072 carry a logger ID in these fields: the logger the device was registered with, which stayed its key after a logger swap — so for a swapped device it is not the logger fitted now, and that logger may since be on another device. persistence-worker resolves such a key to the live device whose first logger it was (its earliest loggers row; postgres.deviceIDForKey), so a backlog that straddles the deploy is still stored, on the right device, rather than discarded. Telemetry, parameter history, alert scans and alert events' push notifications all resolve this way.

Logger IDs have one spelling: lowercase. The DTU reports I3000…; the app's QR scan stores i3000…. Every entry point — each WebSocket message, the AT+DTUPN? reply, the registrar — converts to lowercase (internal/deviceid; inverter serials go to uppercase the same way), and migration 0031 adds CHECK constraints on devices to enforce it. That matters here because NATS subjects are case-sensitive: before this, a client that watched I3000… subscribed to telemetry.I3000… while the device published to telemetry.i3000…, and received nothing.

Source IP is not part of identity: behind carrier NAT it could resolve a connection to a different tenant's device, and migrations 0015-0018 removed it. A connection that is not tied to a registered device falls back to its source IP:port as its key. That key changes on every reconnect — see WebSocket integration.

Session-control commands​

Two command.<deviceKey> kinds end a session instead of instructing it: disconnect and reresolve. A registered session listens on its device id; an unregistered one on its logger id (below). Each sender addresses the kind of session it means: ws-gateway's delete_device the device id, its register nudge the logger id, and deviceadmin both, since a revoked device that stayed connected is an unregistered session.

They exist because identity is resolved once, when a connection is established, and nothing re-checks it mid-session. A change to what the database says about a device has no effect on a connected session until the device reconnects — which, for a stable connection, can take hours.

A third kind, power_intent, does not end the session: it asks it to re-read its plant's block state and apply a pending shutdown or start (Plant block). persistence-worker sends it.

KindSent byWhenWhat happened without it
disconnectdeviceadminrevoke, deleteThe removed device kept polling and publishing
disconnectws-gatewaya confirmed delete_device, before erasure startsThe device kept reporting while its rows were being erased
reresolvews-gatewaya successful registerRegistering a connected device appeared to do nothing
reresolvedeviceadminrestoreThe restored device stayed unregistered and unpolled

Both are handled by closing the connection, not by re-running resolution on the live one. A DTU reconnects within seconds, and the reconnect goes through the one resolution path that is already correct. The alternative would mean swapping the session's device key, session lease and Modbus batch limit underneath a running poll loop.

Only an unregistered session acts on a reresolve; a session that already resolved ignores it. register is deliberately idempotent (a client may retry a request whose response it never saw), and it publishes a reresolve every time it succeeds. If a healthy session acted on it, every retry would drop a working device's connection.

How a reresolve reaches an unregistered session. Such a session's own key is a throwaway IP:port that no sender knows. So when its logger is unclaimed (nobody has registered it), or the connection was refused as logger_moved / inverter_taken (which its owner registering the logger again can resolve — see Reusing a logger), the session also subscribes to command.<loggerId> (Session.subscribeUnclaimed). That second subscription honours only disconnect and reresolve, never watches, reads or writes. No session lease fences it, so two sessions for the same logger can both be listening. Closing twice is harmless; writing to a device twice is not. It is safe for a refused connection for the same reason: a registered device's commands go to its device id (command.<deviceKey>, a UUID), never to its logger id, so nothing meant for the device the logger is bound to can reach this session.

:::note Why senders publish to two spellings natsclient.PublishSessionControl publishes to command.<id> exactly as the sender holds it and to its lowercased form, and the unclaimed subscription always uses the lowercased form (natsclient.UnclaimedCommandSubject). This dates from before identifiers were canonicalized: the DTU reported I3000…, senders used the stored i3000…, and a command sent to one spelling reached no subscriber on the other. Core NATS gives no feedback when nobody is subscribed, so the failure was silent.

Now that every logger id is lowercased where it enters the system (see What deviceKey is), both spellings are normally the same subject, and the helper publishes once. The lowercasing stays until no binary older than that change is running; migration 0031's header lists it among the case-folding to retire after its constraints are validated. Only session-control commands are dual-published. Watch, read and write commands go to command.<deviceKey> as given. :::

Delivery is best-effort, and neither sender treats a failure as fatal: the database change is already committed, and that is what matters. A device that is not connected has no subscriber, which is normal at commissioning time. Senders do flush before returning (PublishSessionControl waits for the broker to acknowledge the publish). deviceadmin exits right after publishing, and without the flush a buffered command could be lost just after an operator was told the device was revoked. A successful flush means the broker accepted the message, not that a session acted on it.

Delivery semantics — do not assume exactly-once​

Per this project's own engineering guidelines: never assume exactly-once delivery, and design every consumer to tolerate duplicates and gaps. Concretely here:

  • telemetry.<deviceKey> has two consumer shapes on the same durable stream. ws-gateway's per-device subscription is ephemeral (DeliverNew

    • AckNone): a client that (re)subscribes sees telemetry from that point on, never backlog. That is fine, because a missed live update only leaves the client's chart one sample behind. persistence-worker subscribes to telemetry.> with a durable consumer (persistence-worker, DeliverAll, AckExplicit — server/cmd/persistence-worker/main.go), so a restart resumes from its last acked message instead of losing backlog. See Durable consumers are created explicitly for why the worker creates this consumer itself instead of letting js.Subscribe do it. It stores only default-cadence records from registered devices (watched-cadence snapshots exist only to drive the live view) and acks a record only after StoreTelemetry succeeds. A crash mid-write therefore causes redelivery, not data loss, and ON CONFLICT (device_id, time) DO NOTHING makes the redelivery a no-op.
  • Failures in persistence-worker are split three ways, on both its consumers (telemetry and activity). A message that does not parse as JSON is acked and dropped; redelivering it would fail identically forever. A write error classified as permanent (postgres.ErrPermanent — for example, telemetry for a device whose row was deleted) is logged at ERROR and terminated (msg.Term()), so JetStream stops redelivering it. Anything else is treated as transient and left unacked, so it is redelivered once the database recovers. As a backstop, every durable consumer has MaxDeliver 250 — over two hours of retries at the 30 s ack wait. natsclient.EnsureDurableConsumer sets it on creation and reconciles it on an existing consumer at startup.

  • alertscan.<deviceKey> is applied in order, and replays are no-ops. Each message carries (sessionEpoch, seq): the epoch is the DEVICE_SESSIONS lease revision, which only grows, and seq counts within a session. The alert-processor stores the last applied position per device in device_alert_state and drops any message at or below it — snapshots included. A new session's snapshot always has a higher epoch, so it never needs an exception. Two remain, and both are ordered by server clock instead: a snapshot with epoch 0 (the session never got a lease), or with an epoch lower than the stored one, is applied only if it was scanned after the last applied scan. Epochs only go backwards when the session-lease bucket itself was recreated, for example when the NATS host and its volume are replaced; without that exception every device would stop getting alert updates until its epoch climbed past the old value (postgres.scanIsStale).

    Until 2026-10-06 snapshots skipped this check. A redelivered old snapshot then reset a device's position, every later change of that session was applied again, and each incident was written to alert_history once more under a new id. Combined with the consumer bug below, that was one duplicate per incident per persistence-worker restart.

    Two database-side guards back this up, so a replay that somehow gets past the ordering check still writes nothing. An incident is identified by (device_id, code, raised_at), where raised_at is the opening scan's server timestamp. The alert-processor will not re-open an incident that is already in alert_history (so no second "raised" push either). The history insert is ON CONFLICT DO NOTHING: a conflict counts as "already recorded", and the open row is cleared without a second "resolved" push. The unique index alert_history_incident_idx on (device_id, code, raised_at, event_time) makes that conflict a database guarantee. It is a pending migration (pending_migrations/), activated by hand once the precondition queries in its file pass.

  • presence.<deviceKey> and command.<deviceKey> are plain core NATS: there is no delivery guarantee if no one is subscribed at publish time. That is deliberate, and fine for presence (see the table above). device_write and read_registers use NATS request-reply instead of a plain publish, so the caller gets a definite result or a timeout back instead of silence. See WebSocket integration.

  • watch_start/watch_stop were originally documented the same way ("arrives late or not at all just means one extra cadence cycle — not correctness-critical"). That turned out to be wrong in practice: a device's TCP connection to tcpserver can be down for the entire window a watch_start is published in — confirmed live against real hardware, where the device's session was cycling every 5-160 seconds on a flaky link — and a core-NATS publish with no subscriber at that instant is simply dropped, with nothing to retry it. ws-gateway used to republish watch_start only on a 0→1 watcher-count transition, so a client could be stuck at the default (5-minute) cadence indefinitely, well past "one cycle longer." The WATCHED_DEVICES JetStream KV bucket (above) fixes this: ws-gateway writes a device's watched/unwatched status there on every watch_start/watch_stop (in addition to, not instead of, the existing publish), and tcpserver reads it once per new connection (internal/server's resolveSession/handleConnection). A reconnecting session finds out it's watched even if it missed every watch_start publish while it was down, and immediately pulls telemetry rather than waiting for the next tick. device_write is unaffected — it already had its own request-reply guarantee.

  • watch_start is published on every watch, not only on a 0→1 watcher transition — throttled per device (a couple of seconds) so a crowd opening one device doesn't multiply into a crowd of Modbus round trips. Gating it on the refcount made "this client gets a prompt reading" conditional on that client happening to be the device's only watcher, which a browser refresh routinely breaks: the new WebSocket watches before the old socket's close has been processed, so the device still has a (dead) watcher. Subscriptions and watch_stop remain refcounted per device; only the snapshot request is per client. The throttle is watchStartMinInterval (2 seconds) in cmd/ws-gateway.

  • tcpserver gates the pull that watch_start requests, rather than obeying it unconditionally (internal/server's handleConnection). Two guards, both learned the hard way against real hardware: a full telemetry cycle measures 19-26 seconds on a live link (353 registers over 6 batches, each round trip paying full RTT), and the DTU's firmware drops the connection if AT+HTBT doesn't arrive roughly every 30 seconds. So an out-of-band cycle started with a stale heartbeat can outlast the watchdog and kill the connection it was serving — confirmed live as mid-session heartbeat failed drops and cycles that decoded 0 of 353 registers because the DTU had already stopped relaying. heartbeatDue therefore yields to a heartbeat first, and ShouldPullTelemetry skips the device entirely when its last reading is still current for the active cadence (the gateway replays its own cached record to that client instead). A device at the slow default cadence still pulls immediately, which is the case the mechanism exists for.

  • Modbus responses are read frame-at-a-time, not read-at-a-time (internal/modbus/framing.go). TCP has no message boundaries, and the DTU is a transparent serial-to-Ethernet bridge: it forwards RS-485 bytes as they trickle off the wire rather than buffering a whole Modbus frame, so a 223-byte response is spread across many small TCP segments over hundreds of milliseconds. A reader that took whatever one Read returned therefore truncated the response and left its tail in the socket buffer, where the next request collected it as its own answer — desynchronising the connection for good. Confirmed live once the device started reaching AWS over the internet instead of a LAN: telemetry cycles reporting decoded 0 of 353 registers, and the plain-text AT+HTBT heartbeat receiving \x01\x03\xda... — a stray function-3 response carrying 218 data bytes. Responses are now sized from their own header (RTU byte count / MBAP length) and read with io.ReadFull, so nothing beyond the frame is ever consumed, and any failed read arms the drain.

Why ws-gateway subscribes per-device, not fleet-wide​

ws-gateway opens telemetry.<deviceKey>/presence.<deviceKey> subscriptions only for devices someone is actively watching, refcounted across all connected clients (see WebSocket integration for the client-side watch/unwatch protocol) — never a wildcard telemetry.>. At 1M total devices with 10k concurrent watchers, this gateway holds ~10k subscriptions of each kind, not ~1M — its NATS-side load tracks watched devices, not fleet size. A wildcard subscription here would mean every gateway replica processes every device's traffic regardless of who's watching, which is exactly the cost blowup this design avoids at scale.

Activity Trail​

Every register write issued from the app that reaches the device is recorded as an Activity Trail entry — an audit record of who changed what, on which device, to what value, and whether it took. Entries are stored in the activity_events TimescaleDB hypertable (migrations 0024-0028) and kept for 730 days (migration 0026's retention policy, a placeholder that product and compliance have not yet confirmed).

BLE writes made by the app without the server are uploaded later with sync_ble_activity (cmd/ws-gateway/ble_activity.go). For each batch (at most 100 entries, one batch in flight per connection) ws-gateway reads every named device in one id = ANY(...) query, keeps an entry only when the caller owns the device and it is in the named plant, fills in the title, category, unit and address from the register catalog, and publishes it to the same activity.<deviceKey> subject with channel: "ble" and the app's own UUID as the record id (and Nats-Msg-Id). It replies only after JetStream has acked every publish, so "accepted" means durable; a retried batch is stored once by the same ON CONFLICT. Discarded entries are logged as ble activity discarded: no registered device found. activity_events.channel (migration 0086, default tcp) records the path.

Writes only. Nothing records read_registers: publishActivity is called only from the write path, and storage.ActivityKindWrite is the only kind ever published. The read API accepts a reads filter (kind = 'read') so clients can already build the tab, but it always returns an empty list.

Reading it back is built: ws-gateway answers get_activity (a paginated list, newest first) and get_activity_detail (one full record, including the protocol trace) straight from activity_events in Postgres — no NATS is involved on the read path. See WebSocket integration for the message shapes. The parts that matter for capacity (cmd/ws-gateway/activity.go):

  • Bounded by construction. The page size is fixed at 10, and the client cannot choose a limit. Pagination is keyset on (time, id), not OFFSET, and each connection can have only one get_activity and one get_activity_detail in flight at a time.
  • Scoped to the caller. With a deviceKey, the same ownership check as write applies. Without one, the list covers every device the userId owns. get_activity_detail returns the same "not found" whether a record doesn't exist or belongs to someone else, so ids cannot be probed. This relies on the same unverified userId as the rest of ws-gateway; see that page's known gaps.
  • By device id, served by activity_events_device_time_idx (migration 0072), so a device's trail spans every logger it has had. Each row also keeps logger_id, the logger the write went through, as a snapshot that is returned but never matched on.
  • The Failed tab's count is computed on the first page only (no cursor), using the partial index activity_events_status_failed_idx.

Why ws-gateway publishes it, not tcpserver. The record needs two kinds of information that live on opposite sides of the command.<deviceKey> request/reply:

  • tcpserver's Session.WriteRegister is the only place that knows the protocol-level facts: how many attempts it took, how long the round trip took, the register's value immediately before the write, the read-back value after, and the raw request/response frame bytes. These now ride back on the existing natsclient.CommandResult reply (PreviousValue, Attempts, DurationMs, Address, FunctionCode, RequestHex, ResponseHex) rather than a separate message.
  • ws-gateway's hub.write is the only place that already knows the caller's claimed identity (userID, from checkOwnership) and can resolve the register's UI category and display label — via the same registerGroupsByModel overlay and internal/displaylabel package get_registers itself uses. That per-model UI metadata deliberately does not exist on tcpserver's side of the wire.

So hub.write's respondConfirmed builds one storage.ActivityRecord from the CommandResult it already has plus that local enrichment, and publishes it — fire-and-forget, after the client's own write_result has already been sent, so a slow or failed activity publish never delays or fails the write itself.

Only a completed device attempt is recorded — success or failure, either counts, but a request rejected before it ever reached the device does not. server.Session.handleDeviceWrite has two shapes of reply, and both are valid CommandResults that reach respondConfirmed the same way:

  • An early rejection — unknown/non-writable register, unsupported function code, a value that fails to encode, or "a write is already in progress for this device" — replied to directly by handleDeviceWrite's fail helper, before the job ever reaches Session.writeRequests. Nothing was ever sent to the device.
  • A completed attempt — the job went through the poll loop and Session.WriteRegister actually sent a Modbus frame, succeeding or failing at the device.

cmd/ws-gateway tells these apart using CommandResult.Attempts: it is set to a positive number only inside WriteRegister, immediately before it sends the first (or a retried) frame, and stays 0 on every early-rejection path. hub.publishActivity calls isCompletedWriteAttempt (Attempts > 0) and skips publishing entirely when it's false — so "a write is already in progress, try again" never shows up as a phantom Activity Trail entry, while a write the device genuinely rejected (a Modbus exception response, say) still does, correctly, as status: failed.

Idempotency. storage.ActivityRecord.ID is a UUID generated by ws-gateway at publish time (storage.NewActivityID, hand-rolled over crypto/rand rather than a new dependency). persistence-worker inserts with ON CONFLICT (id, time) DO NOTHING, so JetStream redelivery of the same record is a no-op. (id, time) rather than id alone, because a unique index on a hypertable must include its time column. StoreTelemetry uses the same pattern with (device_id, time).

Status is success or failed only, and a write that never reached a device is not recorded at all. hub.write calls publishActivity only when a tcpserver session actually replied. A write to an offline device (the request times out or has no responders), one that fails ws-gateway's own ownership check, and one rejected before the device (Attempts == 0, above) leave no entry. The client still gets its write_result. There is no command queue for offline devices, so nothing produces the pending ("queued for next logger poll") status the schema leaves room for.

Device Alerts​

:::note Status: implemented, not yet verified live Every layer below exists in code and passes go build/go vet/unit tests: detection in tcpserver, reconciliation in persistence-worker, and the WebSocket API in ws-gateway (see Device Alerts for that API). None of it has been exercised against a live app or real device hardware yet. Known, named gaps as of this writing: on the IP20 2KW/6.5KW/12KW, the bench unit's firmware answers only the 70–73 fault/warning set (not the 1094–1097 copy), which is the set the catalog reads. displayCodes are the screen's exact text, from the inverter user manuals' code tables, because the screen number is not readable over Modbus. tcpserver records each alert's device-specific form in the alert's context.displayCodes, and ws-gateway serves it on every alert. Bits no manual lists have none. The NEXUS (Aotai) manual's tables also confirm the Aotai warning registers (135/136). See MANUAL_REGISTER_AUDIT_REPORT.md at the cse_tcp_be repo root. The IP20 3K6/5K (ASCII protocol, polled since 2026-11-23) has its own y3k6.* catalog of 53 codes, scanned from its GWS, GMOD and FAN??? replies (see IP20 3K6/5K); plant membership is still unverified against cse-http-be (§5 below); and there is no "pending" (unconfirmed, still counting toward its raise threshold) status anywhere — a condition is invisible until it's already a confirmed alert. ALERTS_DESIGN_REPORT.md at the cse_tcp_be repo root is the full design this was built from. :::

Device alerts (inverter faults/warnings, and later connectivity and system events) are a separate pipeline from telemetry, not a field inside it — telemetry's own active_faults/active_warnings strings (still populated, unchanged) have no stable identity, no history and no per-user read state, which is what this pipeline adds.

The catalog is per model, frozen, and lives with the register spec it describes. server/internal/modbus/specs/<model>.json carries two new top-level fields alongside registers/fault_codes:

  • alarm_scan_registers — the register addresses tcpserver's alarm-scan poll step reads, declared explicitly rather than inferred from a register's category (relying on category is exactly how one model's alarm registers went unpolled before this existed — see MODBUS_ALERTS_AUDIT_REPORT.md in cse_tcp_be).
  • alerts — the catalog itself: one entry per detectable condition, each with a permanent code (e.g. "aotai.F13") that is never renamed or renumbered once shipped, since the database stores the code, not a spec array position. An entry is either "modbus_bit" (one bit of a status word is set) or "state" (a register's value, optionally masked down to one packed field, equals — or differs from — a constant: e.g. IP20's state_machine_status == 7 for fault mode, or energy_terminal_status bits 0–1 == 00 for grid not connected). Both go through the same raise/clear hysteresis. modbus.LoadProfiles() rejects a spec at startup if a catalog entry's register/bit isn't declared, isn't in alarm_scan_registers, or its severity isn't one of critical/warning/info — a bad catalog entry fails the service that loads it rather than failing silently the first time a device trips it.

The database schema exists (server/internal/storage/postgres/migrations/0033-0037): device_alert_state (one row per device — reconciliation state and connectivity), alerts_active (currently-open conditions, one row per (device, code)), alert_history (a TimescaleDB hypertable — resolved incidents, 400-day retention since migration 0112 (365 before), compressed after 14 days), plus alert_read_watermarks/alert_reads for per-user read state. Split into three tables rather than one with in-place updates because a hypertable cannot enforce "one active alert per device and code" (a unique index must include the partition column) and updating a resolved-at timestamp in place would mean writing into an already-compressed chunk for a long-running fault.

The NATS contracts exist (server/internal/natsclient/alerts.go) — see Subjects and Streams and KV buckets above for alertscan.<deviceKey>/ALERT_SCANS, alertevt.<deviceKey>/ALERT_EVENTS, and the TCP_INSTANCES heartbeat bucket the offline sweeper depends on.

Plant scoping is a local join, not a cross-service call. devices.plant_id (migration 0032) already holds the plant a device was registered under, so resolving "which plant does this alert belong to" is a same-database read, not a DynamoDB lookup into cse-http-be — see ALERTS_DESIGN_REPORT.md §5 for the history of that decision (an earlier draft of the design assumed the DynamoDB call would be necessary).

Push notifications​

persistence-worker runs an optional push sender (internal/pushsender, cmd/persistence-worker/push.go). It is enabled when PUSH_ENABLED=true and a Firebase service account is configured. App-side integration and setup are in Push notifications. This section covers the messaging side.

  • Input. The ALERT_EVENTS stream, through its own durable pull consumer persistence-worker-push. It is a consumer rather than a call inside the alert-processor, so a slow or failing Firebase never delays saving alerts. A failed push can be retried without re-running an already-committed reconciliation. The alert-processor publishes only after commit and only on a real change, so the push sender inherits its duplicate protection.
  • Consumer settings.
    • DeliverNew: the first creation does not turn the stream's last 24 hours into pushes.
    • AckWait 90 s, MaxDeliver 5.
    • Fetches 16 messages at a time and pushes them concurrently.
  • Per message.
    1. Only raised events are pushed. Several in one message become one notification.
    2. Events older than 15 minutes are skipped.
    3. Recipients are the tokens in push_tokens (migration 0054) of the device's owner_user_id; revoked devices notify nobody.
    4. Each send is retried up to 3 times on a transient Firebase error, and never on a permanent one.
    5. Tokens Firebase reports as unregistered are deleted.
  • Ack, nak or terminate.
    • Ack once every token has succeeded or failed permanently.
    • NakWithDelay(30s) only when nothing was delivered and every failure was transient (or the token lookup failed), so a redelivery never pushes a phone twice.
    • Terminate malformed messages.
  • Platform incidents. When one offline-sweep tick opens 200 or more Logger Offline alerts, the sweeper publishes them with platformIncident: true (a new optional field on AlertEventMessage; the gateway ignores it). The push sender does not notify customers about those. Many loggers going quiet in the same minute is almost always this platform failing, not each customer's connection. The alerts are still recorded and shown in the app.

Device deletion confirmation​

cmd/ws-gateway's delete_device/confirm_delete_device flow (see WebSocket integration) puts cmd/deviceadmin's permanent erasure sequence behind WebSocket. Both binaries call the same internal/erasure package; deviceadmin's CLI is a thin wrapper around it. A two-step confirmation stands in for an operator typing --yes with a database credential.

The token lives in a KV bucket (PENDING_DEVICE_DELETIONS), not in an in-memory map on the hub. The reason is the same as for WATCHED_DEVICES: ws-gateway can run as more than one replica, and the confirming client may land on a different replica from the one that issued the token. The token is 256 random bits. It maps to the {deviceKey, userId} pair that requested it, and the bucket's 5-minute TTL expires an unconfirmed one (the reply's expiresInSeconds is 300).

A token is single-use. On confirm_delete_device, ws-gateway reads the entry, then deletes it with a revision-conditioned delete (NATS KV's LastRevision). If two confirmations race on the same token, one wins, and the loser gets a revision mismatch and is treated as already consumed. The token is consumed before the device/user match is checked, so a confirmation that names the wrong device or user also burns the token, and the client has to request deletion again.

Tokens don't carry across releases. Each token is stored under a plant. key prefix (confirmTokenKeyPrefix in cmd/ws-gateway/delete_device.go); the client never sees the prefix. The release before plant checks stored bare tokens and never re-checked a plant, and during a rolling deploy both releases serve traffic. Because neither can find the other's keys, a confirmation that lands on the other release is refused as unknown and the user requests deletion again. Without the prefix, an old replica could confirm a new token and erase a device that had moved plant. Change the prefix whenever the checks a pending deletion relies on change.

The database is the real concurrency guard. Two tokens issued separately for the same device (two delete_device requests before either is confirmed) each pass their own KV check, because the bucket has no notion of "one token per device". What enforces one erasure at a time is a partial unique index on device_deletions (logger_id_hash) over open rows, WHERE completed_at IS NULL AND dispose_stopped_at IS NULL. Migration 0029 added it with completed_at IS NULL alone. That also matched rows BeginErasure had just superseded, so migration 0030 narrowed it. A second BeginErasure for the same logger then fails with erasure.ErrAlreadyInProgress, and the client is told a deletion is already in progress. Only the database can make that check atomic against concurrent transactions.

The erasure runs detached from the WebSocket. Once confirmed, it runs on its own goroutine with a 30-minute timeout (deviceErasureTimeout, the same budget deviceadmin gives the CLI), whether or not the client stays connected to see delete_device_progress. After BeginErasure opens the audit row, it publishes a disconnect, so the device stops reporting before its rows are removed. Every step commits incrementally, so a failure or timeout leaves the resumable "interrupted erasure" state that deviceadmin resume completes.

Durable consumers are created explicitly​

persistence-worker creates its durable consumers (persistence-worker and persistence-worker-param-history on TELEMETRY, persistence-worker-activity on ACTIVITY, persistence-worker-alerts on ALERT_SCANS, and — when push is enabled — persistence-worker-push on ALERT_EVENTS) with natsclient.EnsureDurableConsumer. It then attaches to them with nats.Bind(stream, name); it never lets js.Subscribe/js.PullSubscribe create them.

The reason is a nats.go behaviour: when the library creates a consumer during Subscribe, it treats the subscription as the consumer's owner and deletes the consumer on Unsubscribe() or Drain(), durable name or not. The worker unsubscribes on every graceful shutdown. Until 2026-10-06 every deploy therefore deleted all three consumers, and the next start recreated them with DeliverAll and replayed all three streams from the beginning. The worker's own startup log showed it: the consumer was new (MaxDeliver previously -1) on every start. Telemetry and activity inserts are idempotent, so for those the replay only cost load. For alerts it duplicated history, because of the snapshot ordering gap described above. Measured in dev: one logger had 1,844 alert_history rows for 407 real incidents.

A bound subscription does not own its consumer, so shutdown leaves the consumer, and its delivery position, in place. The worker logs durable consumer ready with action created, updated or unchanged on every start. created is expected only on the very first deploy, or after the NATS store was lost; anywhere else it means the consumer disappeared and the stream is being replayed.

Current deployment​

A single NATS node (t4g.micro, plain EC2, the nats:2.10-alpine container with JetStream file storage under /data on the root EBS volume). It is a deliberate single point of failure at dev-tier scale: while it is down, no telemetry, presence or command traffic flows, and nothing that was published to JetStream survives loss of that volume. See Infrastructure for how it is deployed. Move to a clustered JetStream setup (3+ nodes) before that stops being acceptable. The stream retention limits (see Streams and KV buckets) also bound how much a single node's disk has to hold.

Events from the HTTP server​

The HTTP server publishes integration events on its SNS FIFO topic cse-http-be-<stage>-to-tcp.fifo. When httpBusTopicArn is configured, the TCP server subscribes its own SQS FIFO queue cse-tcp-be-<stage>-from-http.fifo (raw delivery, dead-letter queue after 5 receives), and persistence-worker consumes it:

EventEffect
plant.upserted.v1plant_projection row (operator, customer, installer, tags + region, capacity, expected yield, tariff, lifecycle, and since RBAC v2 customerSub and status) and plants.timezone (source http_projection). Applied only when its seq is newer than the stored version. When operatorOrgId changes (an End User joined or left a Business, or an Admin / Super Admin transferred the plant to a user in another org; same plant id), the plant's devices get the new org as owner_org_id; that alone does not change their user owner. Plant owner (owner decision 2026-11-20): ownerUserSub is the plant's creator (any role) until an end user is assigned, the end user once the plant is shared, and whoever unshared it after an unshare. Plant transfer (owner decisions 2026-11-19): a plant is transferred to a registered user by email. A Business or Installer transfer keeps the plant in its Business (operatorOrgId unchanged) and makes the receiving End User its end user. An Admin / Super Admin transfer moves the plant to the receiving user's org (their personal org when they are in none, else their Business or Installer org) and sends that user as ownerUserSub, even when they are a Business or Installer user; one event then changes both the devices' org and their owner. The plant's end user is ownerUserSub when it is set to a user, else customerSub when that is a user id. When a newer version changes that end user, every device in the plant gets that user as owner_user_id, and each device's batteries follow it (trigger devices_sync_batteries, migration 0143). ownerUserSub may name a user on a Business plant too (the user it was transferred to, End User or staff), and every later event of that plant carries it. A newer event with ownerUserSub null and no user customerSub, for a plant that had an end user (the End User was detached, or the staff member left the Business), clears owner_user_id on its devices (and so their batteries): access is then through the org's grants. An event without the ownerUserSub field (an older HTTP build) never changes or clears an owner. createdByUserSub is the user who created the plant (end user, business owner or installer); cse-http-be sends it on every event of a plant that stores a creator, absent (never null) when unknown. A batteries array on an older create event (2026-11-19 builds) is ignored: since 2026-11-20 a battery is added only to a registered device (add_device_battery), never with a plant. See Device batteries. Events for one plant arrive in order (one FIFO group per plant), never coalesced. blocked, when present, is mirrored into plant_blocks (no shutdown or start: those follow the block events)
plant.archived.v1, plant.restored.v1plant_projection.lifecycle
org.upserted.v1org_projection row (name, kind, status, personal), from which the console's Device Inventory shows Business and installer names. personal decides whether a device owner keeps implicit full access (Authentication). Applied only when its version is newer, except that an event at the stored version or older still fills a personal flag TCP never received (and changes nothing else), which is how the HTTP server's org republish backfills it. The status (ACTIVE, SUSPENDED, CLOSED) is stored, not enforced: the HTTP server withholds tickets and sends revocations instead, because End Users keep working on a suspended Business
customer.status.v1Since 2026-12-02. customer_status_projection row (customerOrgId key, operatorOrgId, status ACTIVE or CHURNED, endUserSuspended), a full snapshot; subject customer/<customerOrgId>. Newest seq (epoch ms of the snapshot) wins; an older or equal seq changes nothing. Read by get_plant_health's counts.attention, which leaves out CHURNED customers and suspended End Users; a customer with no row counts as ACTIVE, not suspended. Needs migration 0161 and the HTTP server's republish for existing customers
user.profile.v1Since 2026-12-02. user_projection row (sub key, lower-cased; displayName; deleted), a full snapshot; subject user/<sub>. Newest seq wins; deleted: true clears the name. Read by get_device_details owner and the get_activity / get_activity_detail actor. A user with no row has no name (the sub is still sent). Needs migration 0165 and the HTTP server's one-off replay of existing users
tag.upserted.v1, tag.deleted.v1Since 2026-11-27 (TCP side ready; HTTP publishing pending). tag_projection row (tagId, orgId, label, group), from which list_plants shows tag labels. Newest version wins; a delete leaves a tombstone so an older upsert delivered late cannot revive the tag
access.revoked.v1Re-published on NATS access.revoked (revocations)
plant.blocked.v1, plant.unblocked.v1plant_blocks and one power intent per device. See Plant block
plant.deletion.requested.v1A plant erasure job (plant_erasures), worked outside the consumer. See Plant deletion
notify.user.v1notify_users (push/email preferences, quiet hours, push_eligible: false = not an End User, no push at all, WebSocket-registered tokens included) and notify_endpoints (FCM tokens: ANDROID, IOS, WEB). Applied only when its version is newer; the endpoint list is replaced, so an endpoint missing from a newer version is deleted. This is how a staff member's web push stops (cse-http-be ADR 0022)
notify.user.deleted.v1The person becomes a tombstone row; their endpoints and queued push requests are dropped
notify.audience.v1notify_audience (per operator org: level, access selectors, alert rules). Stored for rule-based delivery; not read yet. level: NONE is kept as a tombstone
notify.push.requested.v1A row in notify_push_requests (idempotent on requestId), sent by a separate loop. eligibilityExempt: true (cse-http-be ADR 0031, the membership notices) is stored in eligibility_exempt and skips only the push_eligible check. See Push notifications
anything elseRecorded and acknowledged (notify.org-settings.v1 and notify.reconciliation.completed.v1 included, for now)

report.render.requested.v1 never reaches this queue: the subscription filters it out (on the event body's type), and the report renderer's own FIFO queue cse-tcp-be-<stage>-report-render.fifo receives it instead, so a monthly report burst never delays plant and access events. See Report renderer.

Each event id is recorded in http_bus_inbox in the same transaction as its effect, so a redelivery changes nothing. A message that fails stays on the queue for SQS to redeliver; an unparseable one ends in the dead-letter queue. On dev the HTTP server's bus is enabled. TCP consumes it once deployed with HTTP_BUS=on (see cdk/scripts/deploy.sh). TCP publishes back on cse-tcp-be-<stage>-events with the event's type both in the body and as the SNS message attribute type: plant.erasure.completed.v1, device.binding.changed.v1, device.block-state.v1 (see Plant block), customer.alerts.v1 (see Customer open alerts) and notify.endpoint.invalid.v1 ({userSub, tokenId, reason}, when Firebase reports a projected push token dead).

Customer open alerts (customer.alerts.v1)​

Since 2026-12-02 (dev, not yet deployed). TCP → cse-http-be on the same outbound topic as device.block-state.v1; persistence-worker needs TCP_EVENTS_TOPIC_ARN. Subject customer/<customerOrgId>, seq = the snapshot's epoch ms (monotonic per customer), data:

{"customerOrgId": "…", "operatorOrgId": "…",
"openAlerts": {"critical": 1, "warning": 2, "info": 0, "total": 3},
"occurredAt": "2026-12-02T10:00:00Z"}
  • Full snapshot, newest seq wins. Counts are open alerts (alerts_active) on the customer's active plants, leaving out plants whose customer is their own Business operator (list_plants' rule).
  • Only changed customers are sent, from a 30-second diff against customer_alert_counts_published (migration 0164). A customer whose last open alert closed gets an all-zero snapshot. Every known customer is re-sent once per persistence-worker start. A failed publish is retried on the next run.
  • cse-http-be must allowlist the type on its from-TCP subscription.

Access revocations​

What ws-gateway does with each access.revoked (HTTP server's RBAC v2 contract, 2026-11-13). Unknown scopes and reasons are logged and ignored.

ScopeplantIdsEffectHTTP reasons that use it
USERnoneClose every connection of sub, whatever org its ticket is forBUSINESS_SUSPENDED, BUSINESS_CLOSED (one event per member or installer), USER_BLOCKED, END_USER_DETACHED, REMOTE_CONTROL_OFF, END_ALL_SESSIONS
USERsomeEnd that user's live views of those plantsINSTALLER_REASSIGNED
USER + originJtis (1–100)noneClose only the connections of sub whose ticket oj is listed, and those whose ticket has no oj; the user's other sign-ins stay connected. Tickets with a listed oj are refused until they expire; no user-wide revocation is recorded. A list with another reason, over 100 ids or an empty id is ignored and the event acts as plain USER (since 2026-11-30)SESSIONS_ENDED (end one sign-in, end others, sign out, password-change report)
ORGnoneClose every connection whose ticket org is orgIda share to the org narrowed
ORGsomeEnd the live views of those plants on connections whose ticket org is orgIdPLANT_MOVED, END_USER_DETACHED
PLANTsomeEnd every connection's live views of those plants, ticketless ones includedsent by TCP itself: PLANT_BLOCKED

A live view is a device watch (ended with a refused watch_ack), a combined watch (group_watch_ended) or the live alert feed (rebuilt and re-sent). If the gateway cannot look up a plant's devices, a USER or ORG revocation with plantIds closes the matching connections instead.

Plant block (Block B)​

A Super Admin or Admin can block a user together with their plants. The HTTP server sends plant.blocked.v1 (and later plant.unblocked.v1) once per plant, {plantId, blockedSub, mode, reason, by, at}.

  1. Access. plant_blocks records the plant blocked, ordered by seq against plant.upserted.v1's blocked. Every operation on its devices is refused, for every caller; a platform Super Admin or Admin keeps view access. Open live views end (a PLANT revocation). See Blocked plants.

  2. Device gate. tcpserver refuses every write, raw command and logger restart for a device of a blocked plant, whoever sends it, and pulls no telemetry from it.

  3. No telemetry. Readings in flight are dropped on storage. Alert scans still record the device online or offline (device_alert_state), but no alert is opened or closed while the plant is blocked.

  4. Shutdown. Each device of the plant gets a power intent (device_power_intents, one row per device, the latest wins): shutdown on a block, start on an unblock. tcpserver applies it when the device connects, and persistence-worker wakes an online device at once (power_intent) and every minute while it stays pending.

    ModelRegisterShutdownStart
    Nexusswitch_on_and_off_enable (0x420, 1056)01
    Yorker (IP20 2–12 kW)remote_on_off_enable (0x4123, 16675)21
    IP20 3K6/5K (ASCII)power_switch (SOFF / SON)01
    any othernoneUNSUPPORTEDUNSUPPORTED

    A failed write is retried on the next wake or connection, up to 5 attempts, then recorded as failed. The write is sent only when tcpserver runs with POWER_CONTROL_ENABLED=true. It is off in every stage: the intent stays pending (reported SHUTDOWN_QUEUED) and nothing reaches the inverter. Blocks still refuse operations and stop telemetry.

  5. Outcome. persistence-worker reports each device's state to the HTTP server as device.block-state.v1 {plantId, deviceId, state, at}, seq = the intent's version, every 10 seconds while something changed. state is SHUTDOWN_QUEUED, SHUTDOWN_SENT, START_QUEUED, STARTED, UNSUPPORTED or FAILED, exactly the values the HTTP server accepts (it dead-letters any other). Best effort: a failed publish is retried on the next run.

Unblocking queues a start for each device, resumes telemetry and allows operations again. A device out of service (revoked or deactivated) gets no intent.

Plant deletion​

When the HTTP server deletes a plant it sends plant.deletion.requested.v1. The consumer records a job in plant_erasures and acknowledges at once, because erasing years of readings takes longer than a queue message may stay invisible. persistence-worker's plant eraser then:

  1. Frees the plant's devices: no plant, no owner org and no owner user, so any user or any Business can attach them again. This applies whoever deleted the plant (Crown staff or a Business). The plant's projection row stays as a deleting tombstone, so a stale plant.upserted.v1 cannot bring the plant back.
  2. Erases each of those devices' history: readings, parameter history, aggregates, energy and financial days, the Activity Trail, alerts and their console workflow. The devices themselves, their logger history and their command audit stay; they keep reporting as stock.
  3. Deletes the plant's own rows: rollups, targets, irradiance, alert read watermarks, registration drafts and its timezone row. Recent energy_daily rows still tagged with the plant (devices that left it earlier) are untagged, so the fleet rollup does not re-create it.
  4. Publishes plant.erasure.completed.v1 ({"plantId": "..."}, seq echoing the request) on TCP's own SNS topic cse-tcp-be-<stage>-events, which the HTTP server's from-tcp queue subscribes to.

Every step is safe to repeat. A failed job retries with backoff (1 minute, doubling to an hour). The HTTP server republishes the request until it hears back; a repeat runs the job again and reports again, which the HTTP side treats as a no-op. A device bound to another plant before step 2 reaches it is kept, with a warning in the log. Without TCP_EVENTS_TOPIC_ARN the eraser still erases but cannot report, and retries the report hourly.

Device binding (device.binding.changed.v1)​

Which serials belong to which plant is recorded in both servers. The HTTP server keeps a plant ↔ serial binding; TCP owns the device. Under the HTTP server's ADR 0018 (accepted 2026-11-04), TCP is the source of truth. TCP publishes device.binding.changed.v1 on cse-tcp-be-<stage>-events whenever a device's plant, logger, inverter serial, label or model changes, it is taken out of service or put back, or it gains its first battery or loses its last, and the HTTP server keeps its binding (and each plant's derived "has a battery") from those events.

  • Every writer is covered. A database trigger (migration 0123) records the change in device_binding_outbox in the same transaction as the change itself, whatever made it: the console, the mobile app's register or update_device, deviceadmin, the plant eraser, or device erasure. A reading never touches the trigger.
  • The outbox holds state, not a log. It keeps one row per device: the device's latest state, plus the values from before the first change not yet sent. Several changes while the bus is down go out as one event, and the table never grows past the number of devices.
  • The relay. persistence-worker publishes due rows every 5 seconds, in SNS batches of 10, a few batches at a time.
    • It holds no row lock while publishing, so a device change is never held up by the bus.
    • A failed publish backs off from 10 s up to 15 minutes and is retried until it goes.
    • One replica works at a time (advisory lock).
  • Off until switched on. The relay runs only with DEVICE_BINDING_EVENTS=true, set by the CDK context deviceBindingEvents (see Infrastructure). Until then the trigger keeps recording, one row per device, so waiting loses nothing. Switch it on only after the HTTP server's consumer is deployed with device.binding.changed.v1 in its from-tcp filter. Events sent earlier are dropped by that filter, and the backfill with them.
  • Backfill. The first start with the relay on queues every device's current state once (reason SYNC), so the HTTP side's bindings converge on TCP's from the start. The backfill is paced and always comes second:
    • It is sent at 10 events/s by default (DEVICE_BINDING_BACKFILL_PER_SECOND), because the HTTP server's from-tcp consumer drains about 10–20 events/s. At 1M devices it takes about 28 hours.
    • Every run sends all due live changes first, so live bindings, plant.erasure.completed.v1 and report events never wait behind it.
    • It runs once per backfill generation, a number in the code (BindingBackfillGeneration). Raising it queues every device again on the next start with the relay on, including devices already sent: that is how to re-send everything after a lost emit. Generation 2 (2026-11-04) re-sends dev's first backfill, which went out before the HTTP server's subscription existed. Generation 3 (2026-11-25) re-sends every device with its lifecycle, so devices revoked or deactivated before that field existed are known.
  • Ordering. The topic is standard SNS, not FIFO. seq is the device's inventory version, which only increases, so the HTTP server applies an event only when its seq is newer than the one it holds. A repeat or a reordering changes nothing.
{
"specversion": "1.0", "id": "01JC0000000000000000000003", "type": "device.binding.changed.v1",
"source": "cse-tcp-be/dev", "time": "2026-11-04T09:32:00.000Z",
"subject": "device/3f2c8a9e-5b1d-4c7a-9e2f-1a2b3c4d5e6f", "seq": 5,
"data": {
"deviceId": "3f2c8a9e-5b1d-4c7a-9e2f-1a2b3c4d5e6f",
"loggerId": "y25319070195", "inverterSn": "CR60H2291884",
"previousLoggerId": null, "previousInverterSn": null,
"plantId": "01JPLANT00000000000000000B", "previousPlantId": null,
"reason": "TRANSFER", "label": "Roof east", "model": "Nexus",
"hasBattery": false, "lifecycle": "in_service", "version": 5, "changedAt": "2026-11-04T09:32:00.000Z"
}
}
FieldMeaning
sourcecse-tcp-be/<stage>, the stage taken from the topic's name
subject, deviceIdTCP's device id. It stays the same when the logger is swapped
loggerId, inverterSnThe serials now, as TCP stores them: logger ids lowercase, inverter serials uppercase
previousLoggerId, previousInverterSnSet when that serial changed, so a binding keyed on the old one can move. Otherwise null
plantId, previousPlantIdThe plant now, and before the change. plantId: null means the device is in no plant
reasonInformational: REGISTER, BIND, UNBIND, TRANSFER, LOGGER_SWAP, LIFECYCLE, ERASE or SYNC. LIFECYCLE is a device taken out of service or put back. A deleted device is sent once with reason ERASE and plantId: null, so the binding and its serial guard go
hasBatteryThe device has at least one battery. Always present, false for ERASE. A change in it alone sends an event with reason SYNC (migration 0138). The HTTP server marks a plant as having a battery when any of its devices does
lifecyclein_service, revoked (taken out of service, remove_device) or deactivated (its logger was taken off or moved to another inverter). Always present. Added 2026-11-25 (migration 0154); a change in it alone sends an event with reason LIFECYCLE
versionEquals seq. It only increases, but can skip numbers: other inventory changes TCP does not send also raise it

A device taken out of service (remove_device) or restored keeps its plant, so the binding does not change. Since migration 0154 each still sends an event, with lifecycle and reason LIFECYCLE. A change to the device's display name (label) or model alone sends one with reason SYNC.

The full set of example envelopes is in the TCP repository at server/internal/httpbus/testdata/device_binding_changed_v1.json. A test keeps that file equal to what the code builds.