Skip to main content

Telemetry Pub/Sub WebSocket Service — Design & Implementation Brief

Status: Implemented — this is the original design brief, kept for its reasoning. It was written as the implementation spec before any of this existed, so its file/line references and "today" statements describe the repo at that time, not now.

:::note What changed since this brief (current as of the ARM/t4g.micro move) The core design shipped as written: NATS as the internal broker, a separate native-WebSocket gateway service, and a DB writer as an independent subscriber. The deployment details below differ from what was built:

  • Binary and library: the gateway is cmd/ws-gateway (not cmd/websocket-gateway), built with gorilla/websocket. The DB writer is cmd/persistence-worker.
  • Port: ws-gateway listens on 8090 (/ws, plus /healthz), not 8080. The device port is 8443 as deployed (cdk/cdk.json), not 9000 (9000 remains config.ts's fallback default).
  • NATS is not co-located and not on loopback: it runs with JetStream (nats:2.10-alpine -js) on its own t4g.micro (NatsStack), with no public IPv4, reached over its VPC-private IP on 4222 (security group limited to the VPC CIDR). Its URL is published in the SSM parameter /cse-tcp-be/dev/nats/url. The 127.0.0.1:4222 networking and "no SG rule for 4222" rows in §2 no longer apply.
  • JetStream is used (§3 deferred it): the TELEMETRY stream feeds persistence-worker durably, which runs on the separate telemetry-db host (TelemetryDbStack) next to TimescaleDB, not on the ingest host.
  • ws-gateway placement: it first shipped on its own Fargate task, then moved to exactly what §2 recommends — a second ECS service on the tcp-ingest host's cluster (cse-tcp-be-dev-pilot-ecs-tcp-ingest), host network mode. Clients reach it wss:// through a CloudFront distribution that terminates TLS (the WsGatewayUrl stack output); the 8090 ingress rule on that host's security group admits CloudFront's origin-facing range only. This replaces §6's two stopgap options below.
  • Instance type: every dev host is now Graviton t4g.micro (the brief originally targeted t3.micro); the account is on AWS's credit-based Free plan, so no instance-hour is free — "$0 marginal" below means no additional instance, not a free one.
  • Dependencies: the server is no longer stdlib-only (§10) — it uses nats.go, gorilla/websocket, pgx and golang-migrate.

For the current deployment, see Infrastructure and Messaging. :::

Grounding: this doc was written after inspecting the cse_tcp_be codebase (this design doc has since moved to this separate cse-solar-docs repo, but every file/line reference below is still against cse_tcp_be) — server/internal/server/session.go, server/internal/server/server.go, cdk/lib/pilot-ecs-ingest-stack.ts, cdk/lib/tcp-ingest-stack.ts, server/go.mod, .env.example. There is no NATS integration, no WebSocket code, and no frontend application anywhere in that repo today (website/ there is an empty stub, not a product frontend) — confirmed by direct search, not assumed.


1. Final recommendation (one paragraph)​

Solar Device → TCP Server (existing, Go) → decode Modbus → publish → NATS (core, new)
│
┌────────────────────┴────────────────────┐
▼ ▼
WebSocket Gateway (new ECS service) Telemetry Worker (future phase)
│ subscribes telemetry.> │ subscribes telemetry.>
▼ ▼
native WebSocket → Frontend Database

NATS is the internal broker (backend-to-backend). Native WebSocket is the frontend delivery protocol (backend-to-browser). They are not competing choices — they solve different halves of the pipe, and the WebSocket Gateway is simply a NATS subscriber that happens to also be a WebSocket server, translating between the two. No Socket.IO, no AppSync, no IoT Core, no Redis, no SQS/SNS. The Telemetry Worker (DB writer) and the WebSocket Gateway are both independent subscribers to the same NATS subject — the frontend never waits on a database write.


2. ECS deployment recommendation​

Run the new WebSocket Gateway as a separate ECS service + task definition, scheduled onto the same existing t4g.micro capacity provider (cse-tcp-be-dev-pilot-ecs-tcp-ingest's cluster) — not merged into the existing TcpIngest container, not on a new EC2 instance, not on Fargate, not behind an ALB yet.

Why not merge it into the existing container: the existing task (PilotEcsTaskDef in cdk/lib/pilot-ecs-ingest-stack.ts:156) runs one Go binary (cmd/tcpserver) doing device ingest. Bundling the WebSocket Gateway into the same container/process couples their deploy lifecycle, crash domain, and resource limits — a WebSocket Gateway bug would restart the device-facing TCP listener too, dropping every connected inverter. Separate task definitions/services fix this and cost nothing extra (same underlying EC2 instance, same monthly bill) — this is also exactly what makes "move to a separate EC2 instance later" a pure infra change instead of a code change: the service already only talks to the outside world over a network port (NATS), never via in-process coupling.

Why not a separate EC2 instance now: doubles compute cost for a service with "very little to no production load" per your own framing. Revisit once real frontend/dashboard concurrent-user counts justify it — this is one line's worth of change (new capacity provider target) once you do.

Why not Fargate for this specific service: introduces a second billing model with no free tier alongside the EC2 instance you're already paying nothing extra for. The reason the TCP ingest server uses EC2 host networking (NetworkMode.HOST, tcp-ingest-stack.ts:23-31) — high persistent-connection density per instance — doesn't apply to the WebSocket Gateway; its connection count is driven by concurrent frontend users, not by the device fleet, and is expected to be orders of magnitude smaller (see §6). Fargate becomes worth reconsidering only once you want the Gateway to scale independently of any EC2 capacity planning — not urgent.

Resource/networking specifics​

ConcernAnswer
EC2 resource usaget4g.micro = 1GB RAM, 2 vCPU burstable (Graviton). Existing TCP ingest container reserves memoryReservationMiB: 300. Budget NATS at ~30-50MiB (idle, no JetStream persistence) and the WebSocket Gateway at ~64-128MiB (a handful of long-lived connections, Go's per-goroutine overhead is small). Total reserved ≈ 450-500MiB, leaving real headroom under 1GB minus OS/Docker/ECS-agent overhead. Fine for dev-stage; first thing to watch if you outgrow it.
ECS networkingAll three (TCP ingest, NATS, WebSocket Gateway) run as separate services with NetworkMode.HOST on the same instance — they share the host's network namespace, so they reach each other over 127.0.0.1:<port>, zero network hop, zero Docker bridge overhead.
Container-to-container communicationTCP ingest → NATS: publish to 127.0.0.1:4222. WebSocket Gateway → NATS: subscribe on 127.0.0.1:4222. No service discovery needed at single-instance scale — plain env-var-configured NATS_URL=nats://127.0.0.1:4222.
Security groupsAdd exactly one new ingress rule to the existing instance SG (PilotEcsSg in pilot-ecs-ingest-stack.ts:71): TCP 8080 (WebSocket Gateway), source 0.0.0.0/0 for now — same directness as the existing 9000 rule. NATS's 4222 gets no SG rule at all — it's not reachable from outside the instance regardless (loopback), and omitting the rule is a second layer of "can't be opened by mistake" rather than relying on that alone.
Port exposure9000 (devices, existing), 8080 (frontend WebSocket, new). 4222 (NATS) stays off the SG and ideally bound to 127.0.0.1 explicitly in NATS's own config (not 0.0.0.0) as defense in depth.
ScalabilityEach piece scales on its own axis: TCP ingest scales with device count (already the fleet-stack's job), NATS scales with message throughput (very high headroom before it's the bottleneck — see §6), WebSocket Gateway scales with concurrent frontend viewers. Because they're separate ECS services, none of this requires re-architecting later — just changing desiredCount/capacity target per service.
Cost$0 marginal EC2 cost at dev stage (same instance, same t4g.micro). See §9 for full breakdown at both stages.
Future production deploymentSwap the WebSocket Gateway's capacity target to its own instance or Fargate service, put an ALB (which natively supports WebSocket Upgrade passthrough) in front for TLS termination + horizontal scaling, keep NATS either co-located with the TCP ingest fleet or promoted to its own small clustered deployment once throughput demands it. None of this touches application code — only CDK/infra.

3. Technology selection — WebSocket vs Socket.IO vs NATS, and why​

NATS (core, not JetStream — yet) is the internal broker.

  • Single static binary, official nats:2-alpine Docker image, effectively free to run (idle RAM in the tens of MiB).
  • Subject-based routing (telemetry.<device_key>, wildcard-subscribable as telemetry.>) gives you per-device topics for free — no manual room/channel bookkeeping needed on top.
  • Throughput headroom is enormous relative to this workload — a single modest NATS server routinely handles millions of messages/sec; even at 1M devices polling every 30s (≈33k msgs/sec sustained), NATS itself is nowhere near its ceiling. NATS will not be the bottleneck at any scale this project is realistically aiming for.
  • Fire-and-forget (at-most-once) by default — acceptable here because a dropped live telemetry update during a brief gateway restart is self-healing: the next 30s poll cycle refreshes it. JetStream (persistence, replay, at-least-once) is worth adding later specifically for the DB-writing Telemetry Worker path, where durability matters more than for the live-view path — that's a separate decision, not a prerequisite for this feature.
  • Already the direction your own architecture docs/prior conversations named as the intended broker — this doesn't introduce a new technology choice, it acts on one already decided.

Native WebSocket (not Socket.IO) is the frontend delivery protocol.

  • Socket.IO's real value-adds — rooms/namespaces and transport fallback (long-polling when WS isn't available) — are either redundant here (NATS subjects already give you topic-scoped delivery) or unnecessary (every modern browser and every serious frontend framework supports native WebSocket without a fallback need).
  • Socket.IO's server side has no first-party Go implementation — using it would mean adopting an unmaintained community port (googollee/go-socket.io) or a mismatched non-Go component, purely to get features NATS already provides. Not worth the dependency or the protocol-compatibility risk.
  • A Go WebSocket library (nhooyr.io/websocket or gorilla/websocket) is a small, well-understood, single-purpose dependency — RFC 6455 framing, ping/pong, close handshake — versus hand-rolling that against the project's current "stdlib only" policy, which is not worth the risk for a wire protocol with real edge cases (masking, fragmentation, control frames).
  • Recommendation: nhooyr.io/websocket — modern, context-aware, minimal transitive dependencies, actively maintained. gorilla/websocket is an equally reasonable, more battle-tested alternative if you'd rather optimize for "the one everyone's used before" over "the newer, leaner one" — either is fine, pick one and move on.

Why not the managed alternatives (AppSync, IoT Core, API Gateway WebSocket, Redis, SQS/SNS):

  • AWS AppSync — GraphQL subscriptions are powerful but bring a schema/ resolver layer and per-message + per-connection-minute billing that buys you nothing here; you already have a working ingest pipeline, not a GraphQL API surface to extend.
  • AWS IoT Core — built for device-facing MQTT ingest at huge scale. You already built and are hardening your own device ingest (this whole project); IoT Core would mean replacing that, not extending it — directly against "don't duplicate existing infra or introduce new tech if an existing component can do the job."
  • API Gateway WebSocket — viable in isolation, but per-connection-minute
    • per-message pricing gets real at "hundreds of thousands of devices" scale if ever conflated with device connections. It's not actually a bad fit for the frontend side specifically (frontend connection counts are modest — see §6) — but it adds a second, AWS-managed WebSocket stack running in parallel with infra you already operate yourself (ECS/EC2), for a workload (moderate frontend viewer count) your existing stack already handles fine. Revisit only if you want to get out of the connection-management business entirely for this one service.
  • Redis Pub/Sub / Streams — functionally comparable to NATS core/ JetStream for this use case, but means running (or paying for ElastiCache) a second broker technology when NATS already covers the need and was already the intended direction. No net benefit here.
  • SNS/SQS — queue/fan-out semantics fit intermittent event delivery, not sub-second live telemetry streaming to many transient WS gateway processes; per-message cost at millions of messages/day and the extra hop's latency make it a worse fit than a broker built for this pattern.

4. Architecture question — should the WebSocket Gateway consume directly from NATS?​

Yes — and this is already the correct shape, not a deviation from one. The Telemetry Worker (DB writer) and the WebSocket Gateway are both independent subscribers on the same telemetry.> subject tree. Neither depends on the other:

┌──────────────────────┐
│ NATS (telemetry.>) │
└───────────┬────────────┘
publish │ subscribe (both, independently)
│
┌──────────────┴──────────────┐
▼ ▼
Telemetry Worker (future) WebSocket Gateway (this feature)
│ │
▼ ▼
Database Frontend (live)

The frontend's live view is never gated on a database write completing — it receives the same NATS message the Telemetry Worker receives, at the same time, over an entirely separate subscription. This directly satisfies your stated goal: "Avoid unnecessarily sending telemetry through the database before broadcasting it to the frontend." Building the WebSocket Gateway to instead read from the DB (e.g. polling for new rows, or a DB change-stream) would add a real hop of latency and a dependency on the Telemetry Worker/DB path being healthy, for no benefit — don't do that.


5. Recommendation summary — why this beats the alternatives, at target scale​

Target scale per your framing: up to ~1M devices, "multiple" frontend users, high telemetry throughput, low latency, minimal ops complexity, reasonable cost.

The critical distinction this recommendation rests on: device-fleet scale and frontend-viewer scale are different numbers, and conflating them leads to over-provisioning the wrong layer.

  • Device-fleet scale (up to ~1M) drives the TCP ingest server's own scaling (already a separate, existing concern — the fleet-shaped NAT+NLB+ASG stack in tcp-ingest-stack.ts) and NATS's message throughput. NATS comfortably absorbs this (§3) without needing a managed, pay-per-message service.
  • Frontend-viewer scale ("multiple" users) drives the WebSocket Gateway's connection count — almost certainly tens to low thousands of concurrent dashboard viewers, not millions. Sizing the WebSocket layer for device-fleet-scale traffic would be provisioning for the wrong dimension entirely.

Given that split, self-hosted NATS + a self-hosted Go WebSocket service (horizontally scaled behind an ALB once needed) reaches every stated goal — high device throughput (NATS), low latency (no DB hop, no extra managed hops), horizontal scaling (stateless Gateway replicas, see §7), minimal ops complexity (two small, well-understood Go/NATS processes vs onboarding a GraphQL subscription layer or a device-ingest-shaped managed service for a browser-facing need) — at a fraction of what routing this through AppSync/IoT Core/API Gateway WebSocket would cost at real scale, without abandoning any infrastructure you've already built and hardened.


6. Frontend connectivity, security, CORS​

  • Update: the gateway can be served wss:// via CloudFront in front of the host (the wsGatewayWss flag, see Infrastructure), which removes the mixed-content problem below. As of 2026-10-29 the flag is set for dev but not yet deployed, so the problem applies there until the next deploy. Kept as the original reasoning.
  • Reachability (original plan): ws://<pilot-instance-public-ip>:8080 directly — same directness as the existing TCP ingest's public IP exposure, no ALB yet (matches "fine with running both on the same instance for now").
  • TLS / mixed-content — read this before testing against a real frontend: if the frontend is served over HTTPS (likely, e.g. Vercel/ Amplify/CloudFront), browsers block a plain ws:// connection to a different host as mixed content — it will silently fail, not just warn. Two options until an ALB+ACM cert exists:
    1. Test the frontend itself over plain HTTP during dev (same-origin mixed-content rules don't apply), or
    2. Terminate TLS directly on the Gateway with a self-signed cert (wss://, browser will show a certificate warning to click through). Neither is a real production answer — that's what §2's "future production deployment" ALB step solves properly (ACM-issued cert, wss:// through the load balancer). Don't skip straight to public frontend testing over HTTPS against the bare ws:// endpoint and be surprised when it silently doesn't connect.
  • Origin validation (the WebSocket equivalent of CORS): the WS handshake carries an Origin header; unlike REST, there's no preflight — the server must check it during the Upgrade and reject with 403 on mismatch. Both nhooyr.io/websocket and gorilla/websocket require you to supply this check explicitly (gorilla's default CheckOrigin is permissive if left unset — don't leave it unset). Config via ALLOWED_ORIGINS (comma-separated) env var.
  • Authentication/authorization — currently nothing exists to hook into. This codebase has no auth system today (phase 1, device-facing only). Recommend a short-lived signed token (minted by whatever the frontend's auth backend eventually is) passed as a query parameter at connect time (wss://.../ws?token=...) — browsers can't set custom headers on the WebSocket handshake, so query-param or subprotocol-embedded tokens are the two practical options; query-param is simpler to implement and reason about. Validate the token during Upgrade, before accepting the connection. This is a placeholder recommendation — if a real auth system exists elsewhere (frontend/other backend) that this should integrate with instead, that changes this section; don't build a parallel auth mechanism if one already exists outside this repo.
  • Behind an ALB later: ALB natively passes through WebSocket Upgrade requests to HTTP(S) target groups — no special ALB configuration beyond a normal target group pointing at the Gateway's port. No code changes needed on the Gateway side to move behind one later.

7. Horizontal scaling strategy​

The WebSocket Gateway is designed stateless with respect to telemetry data — every replica independently subscribes to the same NATS subject tree and forwards to only the frontend clients connected to that replica. This is the standard NATS-fan-out-to-WS-gateway pattern:

NATS (telemetry.>) ──┬──> Gateway replica A ──> its connected browsers
├──> Gateway replica B ──> its connected browsers
└──> Gateway replica C ──> its connected browsers

No sticky routing is required for data correctness — every replica gets the full stream regardless of which frontend clients happen to be attached to it. An ALB in front just needs normal round-robin/least-connections placement of new connections; existing long-lived connections naturally stay pinned to whichever replica accepted them (inherent to any persistent connection, not a special LB feature). Scale replica count on connection count / CPU, same as any stateless service behind an ALB.


8. Failure and reconnection handling​

  • NATS connection drop (Gateway side): use the NATS Go client's built-in auto-reconnect (nats.Connect with nats.ReconnectWait/ nats.MaxReconnects(-1) for infinite retry) — don't hand-roll this, the client library already does it well.
  • WebSocket client disconnect (browser side): the frontend should implement its own reconnect-with-backoff (standard practice for any WS client — exponential backoff, cap around 30s, resume on reconnect). No message replay/catch-up is needed given the "next poll cycle refreshes it" tolerance established in §3 — don't build a resume/backfill mechanism unless a real product requirement emerges for it.
  • Gateway process restart: stateless by design (§7) — in-flight connections drop, clients reconnect per the above, no data loss beyond "missed whatever arrived during the gap," which self-heals on the next telemetry cycle.
  • NATS server restart: at single-instance/single-NATS-node scale, this is a brief total outage for the live path (not the DB path if the Telemetry Worker is later resilient separately) — acceptable at dev scale; multi-node NATS clustering is a production-scale concern, not a day-one requirement.

9. Estimated AWS cost​

Development scale (current, this feature added to the existing t4g.micro):

ItemMonthly cost
EC2 (t4g.micro)$0 marginal — already paid for by the existing pilot stack
NATS container$0 marginal — same instance, no new billable resource
WebSocket Gateway container$0 marginal — same instance, no new billable resource
New SG rule (port 8080)$0 — SG rules are free
Total marginal cost of this feature~$0/mo

Future/production scale (hundreds of thousands of devices, real frontend user base):

ItemEstimated monthly cost
TCP ingest fleet (existing tcp-ingest-stack.ts — NAT+NLB+ASG)~$100-140/mo baseline + scales with device count (separate, pre-existing concern)
NATS, promoted to its own small instance(s) once throughput demands it~$15-30/mo per node (t4g.small/medium), 1-3 nodes depending on HA needs
WebSocket Gateway, own small ASG/Fargate service + ALBALB $16-20/mo fixed + per-task compute ($10-30/mo per replica depending on size), scaled to concurrent frontend viewer count — not device count (§6)
Total incremental for this feature at production scaleroughly $40-90/mo, dominated by NATS HA and the ALB, largely independent of device count since it scales with frontend viewers, not devices

The expensive part of "scaling to 1M devices" was always the TCP ingest fleet (already priced in your existing docs) — this feature adds a modest, frontend-viewer-scaled cost on top, not a device-scaled one.


10. Implementation notes (for the Claude Code session that builds this)​

Integration point in existing code: RequestTelemetry in server/internal/server/session.go (around line 393-444) is where decoded readings already exist as a map[string]Reading right before the existing "telemetry snapshot" log call (line ~431). The NATS publish call belongs immediately after readings is fully populated, alongside (not instead of) that log line — publish the same data you're already logging, don't build a second decode path.

Required small addition: Session (session.go:52-80) has no device identity field today — deviceKey is computed in server.go's handleConnection/resolveSession and used only for the profile mapping cache. Add a DeviceKey string field to Session, set it during resolveSession (server.go:271), and use it to tag published NATS subjects (e.g. telemetry.<deviceKey>) so the Gateway/Worker can distinguish devices.

Dependency footprint change — call this out explicitly, don't let it slide in quietly: adding NATS publishing to the existing TCP ingest server ends its current "stdlib only, zero deps" status (README.md's own description of server/). This is a deliberate, scoped tradeoff — flag it in the PR/commit description, don't present it as if nothing changed. go.mod currently has zero dependencies (verified) — this feature adds github.com/nats-io/nats.go to the TCP ingest server and both github.com/nats-io/nats.go + a WebSocket library (nhooyr.io/websocket recommended) to the new Gateway binary.

New env vars (extend .env.example, following its existing documented style):

# ---- NATS (shared by tcpserver and the new websocket-gateway) ----
NATS_URL=nats://127.0.0.1:4222
NATS_TELEMETRY_SUBJECT_PREFIX=telemetry

# ---- cmd/websocket-gateway ----
WS_GATEWAY_PORT=8080
ALLOWED_ORIGINS=http://localhost:3000
# WS_AUTH_TOKEN_SECRET= # only once a real auth mechanism is decided

Docker/CDK changes needed (do not implement yet — scope for the follow-up session):

  • New server/cmd/websocket-gateway/main.go (new Go binary, same module).
  • Either a second Dockerfile (or a multi-stage build producing both binaries from the existing server/Dockerfile, matching however cmd/tcpserver vs cmd/probe are currently differentiated — check server/Dockerfile before deciding).
  • cdk/lib/pilot-ecs-ingest-stack.ts: add a NatsTaskDef/NatsService (image nats:2-alpine, no port mappings exposed via SG) and a WsGatewayTaskDef/WsGatewayService (port 8080, host networking, targeting the same PilotEcsCapacity capacity provider), plus the one new SG ingress rule (§2).
  • server/internal/server/session.go + server.go: the DeviceKey field and the publish call described above.

Local development setup: run NATS locally via docker run -p 4222:4222 nats:2-alpine, then cmd/tcpserver and the new cmd/websocket-gateway both point NATS_URL at nats://127.0.0.1:4222 — no CDK/AWS needed to develop or test this feature end-to-end locally.


Open questions before implementation starts​

  1. Does a real frontend auth system exist outside this repo that the WebSocket Gateway's auth (§6) should integrate with, rather than the placeholder token scheme described here?
  2. Is nhooyr.io/websocket an acceptable new dependency, or is gorilla/websocket preferred for familiarity/precedent reasons?
  3. Confirm: implement now in this session, or treat this document as the finalized brief for a separate Claude Code implementation pass?