Infrastructure (cdk/)
Two independent groups of stacks in us-east-1, plus a standalone
single-node pilot. Pick a group based on scale, not by mixing pieces from
both.
Dev-tier pipeline (current default) — npm run deploy
The full tcpserver → NATS → ws-gateway pipeline, sized for dev/early-pilot
traffic (the "hardly a handful of devices" stage), sharing one VPC with
zero NAT Gateways and no Load Balancer — the two things that cost money
regardless of traffic.
-
cse-tcp-be-dev-dev-network— the shared VPC, one AZ, two subnets:- public (
10.0.0.0/24): only the tcp-ingest host (which also runs ws-gateway), because devices and apps connect to it from the internet on its Elastic IP. - IPv6 egress (
10.0.128.0/24plus an IPv6/64): NATS and the telemetry DB. They only ever call out (package repos, Docker Hub, ECR, SSM, Secrets Manager, CloudWatch Logs), so instead of a paid public IPv4 address each (~$3.65/month) they get a free IPv6 address and an egress-only internet gateway (also free), which allows outbound connections and blocks inbound ones. There is no IPv4 route to the internet, so every tool on those hosts is set to use AWS's dual-stack endpoints:ECS_INSTANCE_IP_COMPATIBILITY=ipv6for the ECS agent, SSM Agent'sUseDualStackEndpoint,AWS_USE_DUALSTACK_ENDPOINTfor the AWS CLI in user-data, and ECR's dual-stack registry name (<account>.dkr-ecr.<region>.on.aws) for container images. Services still reach each other over private IPv4.
- public (
-
cse-tcp-be-dev-nats— NATS with JetStream, VPC-private only (no public IPv4 address, no public ingress — security group restricts port 4222/8222 to the VPC CIDR). Its address reaches the other services through the SSM parameter/cse-tcp-be/dev/nats/url, read at deploy time, not a CloudFormation export: CloudFormation refuses to change an export another stack imports, which would block replacing this instance. A deliberate single point of failure at this scale; migrate to a 3-node JetStream cluster once traffic justifies it. -
cse-tcp-be-dev-pilot-ecs-tcp-ingest—cmd/tcpserveras an ECS service on ECS-on-EC2 capacity: a min=max=1 Auto Scaling Group of onet4g.micro(ECS-optimized Amazon Linux 2023, ARM) in the public subnet, host network mode, no load balancer. (Unlike the standalone plain-docker pilot below, this is real ECS — task definitions,aws ecs update-service --force-new-deployment— and it lives in the shared VPC.) The ASG exists only because CDK'sEc2Servicerequires ASG-backed capacity. Its static Elastic IP is allocated on its own and the instance associates it to itself at boot (IMDSv2 instance ID +aws ec2 associate-address), so a replaced instance picks up the same address and the WiFi loggers never need re-pointing — the address is the stack'sPilotEcsPublicIpoutput. The instance security group opens the device port (8443as deployed — see Configuration) to0.0.0.0/0, and ws-gateway's8090only to CloudFront's managed origin-facing prefix list (com.amazonaws.global.cloudfront.origin-facing, looked up at synth time); ws-gateway's rule lives here because it shares this host. That prefix list counts as about 55 rules against the security group's default 60-rule quota. ReadsNATS_URLfrom the SSM parameter above, and getsPOSTGRES_HOST(the telemetry-db instance's private IP, looked up at deploy time) plusPOSTGRES_PASSWORD(injected by ECS from thecse-tcp-be-dev-telemetry-db-credentialssecret) so device registration and reconnect matching work. Without that database connection,tcpserverfalls back to unstableIP:portdevice keys and persistence-worker drops every reading as unregistered. Logs go to/cse-tcp-be/dev/pilot-ecs-tcp-ingest(2-week retention). -
cse-tcp-be-dev-telemetry-db—dev_telemetry_db(TimescaleDB), onet4g.microdoing double duty: a plaindocker run timescale/timescaledbcontainer (not ECS-managed — same pattern as NatsStack), plus an ECS-on-EC2 task runningcmd/persistence-workeron that same instance (host network mode, reaches Postgres over127.0.0.1, not a routed VPC hop). The worker durably consumes the sameTELEMETRYJetStream stream ws-gateway watches live, but only ever writes "default"-cadence samples — one per device per 5 minutes, whether or not that device is currently being watched. The extra 30-second "watched"-cadence readings exist purely to drive ws-gateway's live view and are deliberately never persisted (seeserver/internal/storage/postgres/postgres.go'sStoreTelemetrydoc comment), so storage per device is the same busy or idle. Postgres credentials are generated into Secrets Manager at deploy time, never committed; schema migrations (server/internal/storage/postgres/migrations/*.sql) are embedded in the worker binary and applied automatically on startup. The host has no public IPv4 address and no public inbound rules (see the IPv6 egress subnet above), and the TimescaleDB image is pinned by digest so an instance replacement can't silently upgrade the database. To reach Postgres from your machine (pgAdmin,psql), open an SSM port-forwarding session — it needs the AWS CLI's Session Manager plugin, no open port and no public IP:cd cdk && npm run db:tunnel # looks up the current instance ID, Ctrl+C to close(
scripts/db-tunnel.shwrapsaws ssm start-session ... --document-name AWS-StartPortForwardingSession; the instance ID is looked up by itsenv=dev-telemetry-dbtag on every run because the ASG replaces it.LOCAL_PORT=...changes the local port.) Then connect tolocalhost:15432with the credentials from thecse-tcp-be-dev-telemetry-db-credentialssecret. (Local port 15432 avoids clashing with a local Postgres on 5432.) The same tunnel is how the operator CLI reaches the deployed database — see Server behavior. The instance is a single point of failure at this scale, same as NatsStack — this is the pilot/dev tier, not the production path to 1M devices (RDS/Aurora with read replicas, sized separately, once device count justifies it). The data is not, though: it lives on a dedicated EBS volume (TelemetryDbDataVolume, separate from the instance's root volume) with aRETAINremoval policy, so it survives ASG instance replacement and evencdk destroy/npm run destroyof this stack untouched — destroying the stack only detaches CloudFormation's management of it, it does not delete the volume or its data. The credentials secret (cse-tcp-be-dev-telemetry-db-credentials) isRETAIN'd the same way, because the database on that volume was initialized with that password — Postgres only readsPOSTGRES_PASSWORDwhen it initializes an empty data directory, so a newly generated secret would lock every consumer out.npm run deploy(scripts/deploy.sh) rebinds both on every run, not only after a destroy: it looks up the newest volume taggedName=cse-tcp-be-dev-telemetry-db-data(statusavailableorin-use) and the secret namedcse-tcp-be-dev-telemetry-db-credentials, and passes whatever it finds as-c telemetryDbVolumeId=...and-c telemetryDbSecretArn=.... It has to pass them every time: CDK keeps no memory of earlier context, andtelemetry-db-stack.tscreates a new volume and secret whenever those keys are absent — which, against an existing stack, orphans an empty volume and fails on the duplicate secret name (both happened before the script was changed to always pass them). Importing the same IDs on every deploy is idempotent. Only a genuinely first-ever deploy finds nothing and creates a fresh, empty volume and a new secret. This is why a barecdk deployof the telemetry-db stack is unsafe — always go throughnpm run deploy.Push notifications. The same script also looks up an optional secret,
cse-tcp-be-dev-fcm-service-account, which holds the Firebase service-account key and is created by hand with the AWS CLI. When it exists,deploy.shpasses it as-c fcmSecretArn=.... The persistence-worker task then getsPUSH_ENABLED=true, and ECS injects the key asFCM_SERVICE_ACCOUNT_JSON; the execution role is granted read on that one secret. When it does not exist, the task getsPUSH_ENABLED=falseand no secret reference, so a deploy never fails because push is not set up.Push also has a kill switch: SSM
/cse-tcp-be/<env>/notify/push-enabled(true/false, a standard parameter, $0), which the stack writes and the HTTP server reads to show Push availability.deploy.shreads it back on every run and passes it as-c notifyPushEnabled=...(NOTIFY_PUSH_ENABLEDoverrides), so a value set by hand survives the next deploy. Push runs only when the secret exists and the switch istrue; otherwise the task getsPUSH_ENABLED=falseand no secret. The first deploy that finds no parameter creates it astrueif the secret exists,falseotherwise. See Push notifications.Web console work (see Web console). persistence-worker also refreshes the fleet rollups every 5 minutes (
plant_live_state,plant_curve_daily,plant_energy_daily,plant_energy_monthly; one replica at a time under an advisory lock), backfilling them fromenergy_dailyon its first start after migration 0102. It records every device-alert notification for the console's notification inbox (before the push is sent), and, whenhttpBusTopicArnis set, consumes the HTTP server's events, including the notification projection (notify.user.v1and friends) and the pushes it requests (see Messaging). ws-gateway's task gets a private, encrypted, TLS-only S3 bucket (cse-tcp-be-<env>-ws-gateway-device-files-<account>, retained on stack deletion) for technical files and large CSV exports. Browsers upload and download with URLs the gateway presigns; the task role may touch onlydevices/*andexports/*, and exports expire after a day.CDK only imports the secret by ARN and never creates it, so the key never passes through a CloudFormation template. Pushes go to
fcm.googleapis.comover the host's existing IPv6 egress (both Google endpoints have AAAA records); no NAT or endpoint is added. Setup, behaviour and limits are in Push notifications. To target a different volume than the one the script finds (e.g. one restored from an older snapshot), pass it explicitly; a later-cfor the same key overrides the script's:npm run deploy -- -c telemetryDbVolumeId=vol-xxxxxxxxxxxxxxxxx -
cse-tcp-be-dev-ws-gateway— a second ECS service (own task definition, own deploys) on the samet4g.microhost aspilot-ecs-tcp-ingest, host network mode, arm64 image (pinned explicitly — an unpinned build on an x86 machine or CI runner produces amd64 and crash-loops on this host). Reserves 128MiB with a 256MiB hard limit, so a leak gets ws-gateway OOM-killed before it can starve tcp-ingest; both services measured under 10MiB actual RSS. It previously ran on its own Fargate task, which cost ~$10.90/month (task + its public IPv4) for a ~7MB process. No ALB in front of it. WithwsGatewayWsson (see Configuration; set totrueincdk.jsonfor dev, but not yet deployed, so clients still use plainws://<Elastic IP>:8090/wsuntil the next deploy), clients connectwss://to a CloudFront distribution the stack owns (WsGatewayDistribution), which terminates TLS with AWS's*.cloudfront.netcertificate and forwards plain WS to port8090on the host. CloudFront can't use an IP as an origin, so the origin is the Elastic IP's EC2 public DNS name (ec2-a-b-c-d.compute-1.amazonaws.com), which is as stable as the EIP. Caching is disabled, all viewer headers are forwarded (the handshake,OriginforALLOWED_ORIGINS), edge compression is off (the gateway already usespermessage-deflate), and the origin read timeout is 60s; the gateway pings every ~54s, so live sockets never look idle. Because every connection arrives from a CloudFront edge, the task setsCLIENT_ADDR_HEADER=CloudFront-Viewer-Addressso logs show the real client address. This is safe only because the port admits CloudFront alone. Local dev doesn't set it and stays plainws://. Why CloudFront rather than an ALB: no domain or ACM certificate is needed, and it costs nothing at dev volume instead of ~$16+/month. The production shape (an ALB with our own domain and certificate) is unchanged. The URL is printed by the stack'sWsGatewayUrloutput. The CloudFront to host hop is plain WS, which is why this is a dev-tier setup rather than the production one. This setup was verified live on 2026-10-22, then lost from the CDK code and restored on 2026-10-28; the restored version has not been deployed yet.cdk.jsonnow sets"wsGatewayWss": true, so the next ordinarynpm run deployturns it on and every later deploy keeps it on. Removing that line (or setting itfalse) switcheswss://off and deletes the distribution;WS_GATEWAY_WSSapplies only whencdk.jsondoes not set it. Plainws://<Elastic IP>:8090closes the moment the stack updates, so every client, the mobile app included, must move to the newwss://URL in the same release. Turning the flag off and on again creates a new*.cloudfront.netname. After turning it on, check:/healthzreturns 200 over HTTPS, plain HTTP is refused (403), an allowlisted origin's handshake gets101and an unknown origin's gets403, the logs show the real client IP, and the oldws://<Elastic IP>:8090is closed. To check it again after a deploy:curl -s https://<ws-gateway-host>/healthz # oknc -z -w 5 <ingest-elastic-ip> 8090 || echo closed # closedThe URL itself:
aws cloudformation describe-stacks --stack-name cse-tcp-be-dev-ws-gateway \--query "Stacks[0].Outputs[?OutputKey=='WsGatewayUrl'].OutputValue" --output textTradeoffs accepted at this tier: replacing the host takes both services down together (~1-3 min boot), and a ws-gateway redeploy briefly drops WebSocket clients (one host, one port, so the old task stops before the new one starts). See WebSocket integration for what to actually send/receive on that connection.
Deploy/destroy/logs, via cdk/package.json:
cd cdk
npm run deploy # dev: all stacks, in dependency order, then prunes unused ECR images
STAGE=staging npm run deploy # the same tier for staging (see "Staging" below; not deployed yet)
npm run clean:ecr # preview the ECR prune on its own (add -- --apply to delete)
npm run destroy # destroys the five dev-tier stacks (dependency order);
# the RETAIN'd data volume and secret survive
npm run logs # tcpserver, --follow
npm run logs:ws-gateway # ws-gateway, --follow
npm run logs:persistence-worker # persistence-worker, --follow
npm run logs:nats # NATS has no CloudWatch log group (cost/complexity
# cut) — this streams `docker logs -f` over SSM instead
npm run logs:telemetry-db # TimescaleDB container logs on the telemetry-db instance,
# `docker logs -f` over SSM (no CloudWatch group either)
npm run logs:all # streams all four (NATS, tcp-ingest, ws-gateway,
# persistence-worker), each line prefixed; Ctrl+C stops all
npm run db:tunnel # SSM port-forward telemetry-db Postgres to localhost:15432
# (pgAdmin/psql), Ctrl+C to close
logs:nats, logs:telemetry-db and db:tunnel need the AWS CLI's Session Manager plugin
(brew install --cask session-manager-plugin). All of these default to
us-east-1; the shell scripts honour AWS_REGION.
ECR image cleanup. Every deploy that changes a service's code pushes a
new ~8MB image to the CDK bootstrap ECR repository, which nothing else ever
removes. After all stacks deploy successfully, npm run deploy runs
cdk/scripts/clean-ecr-images.mjs --apply, which deletes images no stack
uses any more. That repository is shared by every CDK app in the
account/region (cse-http-be included), so the script is deliberately
conservative:
- It skips the whole run if any stack in the region is mid-deploy, or if any
cse-tcp-be-*stack is failed or rolled back. - It keeps every image referenced by any stack's template, any active ECS task definition, or any container-image Lambda.
- It keeps anything pushed in the last 7 days (
ECR_CLEANUP_GRACE_DAYS). - If any AWS read fails, it aborts without deleting anything, and a failed cleanup never fails the deploy.
It isn't an ECR lifecycle rule on purpose: those only see age and count, so
they would expire the live image of any service whose code hasn't changed
recently, and the next host replacement would fail to pull it. Skip the
cleanup for a single deploy with SKIP_ECR_CLEANUP=1 npm run deploy.
Deploy order and instance replacement. Stacks deploy in this order:
dev-network → nats → telemetry-db → pilot-ecs-tcp-ingest →
ws-gateway (→ report-renderer, when the HTTP bus is configured). Neither address travels as a CloudFormation export, so the
order has to be set explicitly. NATS_URL is read from an SSM parameter,
so NATS must deploy first; that's a CDK stack dependency in
cdk/bin/app.ts. POSTGRES_HOST is looked up from the running
telemetry-db instance (the DbHostLookup custom resource in
pilot-ecs-tcp-ingest and ws-gateway), so telemetry-db must deploy
before both. That order is enforced by scripts/deploy.sh, which runs two
cdk deploy calls (telemetry-db first). It is deliberately not a stack
dependency: cdk deploy <stack> also deploys its dependencies, so a bare
cdk deploy of tcp-ingest would drag telemetry-db along without the
data-volume and secret context. Getting this order wrong is silent: during
the t3.micro → t4g.micro move, tcp-ingest looked up the old telemetry-db
instance's IP before that instance was replaced and kept pointing at a
terminated host. The remaining gap is a telemetry-db instance replaced
without the other two being deployed after it (a telemetry-db-only deploy,
or an ASG health-check replacement): re-run npm run deploy to refresh the
address.
Schema migrations follow the same order: tcpserver and
persistence-worker apply them on startup, ws-gateway never does. A
ws-gateway build that reads a new column needs that migration applied
first — currently migration 0148 (logger_sightings.model_code, read by
plant admission); see
Server behavior.
A change to an ASG host's AMI or instance type replaces the instance, and the two ASGs deliberately do it differently:
pilot-ecs-tcp-ingestkeeps CDK's default replacing update: the new instance launches first and takes over the Elastic IP on boot, and the old one is deleted when the deploy finishes. Devices reconnect as soon as the new host is up.telemetry-dbuses a terminate-first rolling update (minInstancesInService: 0). The data volume can only be attached to one instance at a time. Under the default, the old instance holds it until the end of the deploy, which is longer than the new instance's boot script retries attaching it (~2.5 min). After that, thenofailmount fails and Postgres silently initializes an empty database on the root volume. Terminating first frees the volume before the replacement boots.
Every ECS service carries an ecs.cpu-architecture == arm64 placement
constraint, and each service's rollout waits for its instance group (a
CDK dependency on the ASG), so a new arm64 image is never scheduled onto
an outgoing x86 host. A NATS instance replacement starts JetStream with
empty storage (its data lives on the root volume): unconsumed messages are
lost, and the TELEMETRY/ACTIVITY streams are recreated by the services
on startup.
cse-tcp-be-dev-telemetry-db's persistence-worker logs go to CloudWatch
(/cse-tcp-be/dev/persistence-worker — aws logs tail ... --follow); the
TimescaleDB container's own logs, like NATS's, are read via docker logs
over SSM (aws ssm start-session --target <instance-id>, then docker logs timescaledb).
Pass CDK context through npm run deploy --. The WebSocket gateway's
origin allowlist (required for any browser client — see the "Get your
origin whitelisted" section of
WebSocket integration) is committed
in cdk/cdk.json's context.allowedOrigins; add an origin there so every
deploy keeps it. A one-off -c override replaces that whole list
rather than adding to it:
npm run deploy -- -c allowedOrigins="https://your-frontend.example.com,http://localhost:3000"
Report renderer — cse-tcp-be-dev-report-renderer
Exists only while httpBusTopicArn is set (the HTTP server's bus is on);
deploy.sh then adds it to its second cdk deploy call, after
telemetry-db, because it looks up the telemetry-db host the same way
ws-gateway does.
Turning the HTTP bus on and off is explicit. Every deploy re-synthesizes
the templates from that run's context, so a deploy without
httpBusTopicArn would delete the from-http queue (and its unconsumed
events), TCP's events topic (and the HTTP server's subscription to it), and
leave the renderer subscribed to nothing. deploy.sh therefore:
-
stops if any of its AWS lookups fails for a reason other than "does not exist" (a throttle or a missing permission is never read as "no bus");
-
turns the bus on the first time only with
HTTP_BUS=on(HTTP_BUS=on npm run deploy), even once the HTTP server's topic exists; -
refuses to deploy without it once it is deployed, unless
HTTP_BUS=off. After an intentionalHTTP_BUS=offdeploy, destroy the renderer stack:npx cdk destroy cse-tcp-be-dev-report-renderer. It renders the HTTP server's reports — see Report renderer for the contract. -
Lambda
cse-tcp-be-dev-report-renderer: an arm64 container image (server/Dockerfile.report-renderer, Debian with headless Chromium), 2048 MB, 15-minute timeout, in the IPv6 egress subnet withIpv6AllowedForDualStack: it reaches Postgres over private IPv4 and S3, SNS and Secrets Manager on their dual-stack endpoints, with no NAT Gateway. Outbound-only security group. -
Queue
cse-tcp-be-dev-report-render.fifo(+…-report-render-dlq.fifo, 3 receives): subscribed tocse-http-be-dev-to-tcp.fifowith a body filter ontype = report.render.requested.v1; the from-http queue's subscription excludes that type. Visibility timeout 30 minutes (twice the function's), retention 1 day (a request's deadline is at most 3 hours). Batch size 1, maximum concurrencyreportRendererMaxConcurrency(2): the cap on database connections during a report burst. Maximum concurrency rather than reserved concurrency, which would take capacity from the account's shared pool. -
Role
cse-tcp-be-dev-report-renderer(fixed name, so its ARN is known in advance; outputReportRendererRoleArn, which the HTTP server's owner passes as-c tcpRendererRoleArn):s3:GetObjectoncse-http-be-dev-reports/reports/manifests/*,s3:PutObjecton…/reports/incoming/*,sns:Publishoncse-tcp-be-dev-events, read on the telemetry-db credentials secret, plus Lambda's logging and VPC network-interface policies. -
Logs:
/cse-tcp-be/dev/report-renderer, 2-week retention (aws logs tail /cse-tcp-be/dev/report-renderer --follow --region us-east-1).
Cost. Nothing between reports. A report takes a few seconds at 2 GB: about $0.00017 each (arm64, $0.0000133/GB-s), so ≈ $0.17 per 1,000 reports and ≈ $17/month at 100k reports/month, plus cents for requests, S3 PUTs and SQS. Estimated, not yet measured: the per-report time is confirmed once the real sections are built (load test of 200 queued reports, the HTTP server's rollout plan step 7). Dev volume is well under $1/month and is not in the total below.
Cost (us-east-1, on-demand, real pricing pulled from the AWS Price List API)
us-east-1 (N. Virginia) is one of AWS's cheapest regions — noticeably
cheaper per unit than both ap-south-1 (this project's original region) and
ap-east-1 (a brief intermediate migration target): about 5% cheaper than
ap-south-1 and about 27% cheaper than ap-east-1 for the same footprint.
| Item | Rate | Monthly (730 hrs) |
|---|---|---|
EC2 — NATS (t4g.micro) | $0.0084/hr | $6.13 |
EC2 — TCP ingest (t4g.micro) | $0.0084/hr | $6.13 |
EC2 — telemetry DB (t4g.micro, TimescaleDB + persistence-worker) | $0.0084/hr | $6.13 |
| EBS — NATS root volume (8GB gp3) | $0.0800/GB-mo | $0.64 |
| EBS — TCP ingest root volume (30GB gp3, ECS-optimized AMI default) | $0.0800/GB-mo | $2.40 |
| EBS — telemetry DB root volume (30GB gp3, ECS-optimized AMI default) | $0.0800/GB-mo | $2.40 |
EBS — telemetry DB data volume (20GB gp3, RETAIN, dedicated & persistent) | $0.0800/GB-mo | $1.60 |
| ws-gateway | — | $0 (shares the TCP ingest t4g.micro) |
| Secrets Manager — telemetry DB credentials | $0.40/secret-mo | $0.40 |
| Secrets Manager — Firebase service account (only once push is set up) | $0.40/secret-mo | $0.40 (not in the total below) |
| Public IPv4 — ingest Elastic IP only (NATS and telemetry DB use free IPv6) | $0.005/hr | $3.65 |
CloudFront — ws-gateway wss:// termination | free tier (1TB out, 10M requests/month) | $0 at dev volume |
| NAT Gateway / Load Balancer | — | $0 (neither exists) |
| IPv6 addresses, egress-only internet gateway | — | $0 |
| Total | ≈ $29.48/month |
Arithmetic: EC2 3 × $0.0084 × 730 = $18.40 (the rows above are rounded individually); EBS (8 + 30 + 30 + 20) GB × $0.08 = $7.04; public IPv4 $0.005 × 730 = $3.65; Secrets Manager $0.40 — $29.49 unrounded. Not included, because they're negligible at this traffic: CloudWatch Logs ingestion/storage (every log group has 2-week retention), ECR image storage (kept down by the cleanup below), the deploy-time lookup Lambdas, and data transfer. That includes push notifications: Firebase Cloud Messaging is free, and each send is about 1 KB of internet egress (an estimate), which stays inside the first free 100 GB/month at current volume. On the account's credit-based Free plan this is drawn from the credit balance rather than billed, but it is still the number that drains it.
Why Graviton t4g.micro: this account is on AWS's credit-based Free
plan (check with aws freetier get-account-plan-state), where every
instance-hour — t3.micro included — is paid from a fixed USD credit
balance rather than from free hours. On that plan the only lever is price,
and t4g.micro is the cheapest instance type the Free plan allows
launching: $0.0084/hr vs. t3.micro's $0.0104/hr (~19% less) for the same
2 vCPU / 1 GiB. (t4g.nano, cheaper still, cannot be launched on the Free
plan, and its 0.5 GiB is too small for these hosts anyway.) Every dev-tier
host therefore runs an ARM AMI and every image is built linux/arm64;
config.ts rejects x86 instance-type overrides at synth time rather than
letting them fail at boot, and every ECS service carries an
ecs.cpu-architecture == arm64 placement constraint so an arm64 image can
never be scheduled onto an x86 host. AWS bills every public IPv4
address, Elastic IPs included, whether or not it's attached.
Staging (built, not deployed)
The same single-host tier can be deployed as a separate staging stage:
STAGE=staging npm run deploy. Every name is derived from the stage
(cse-tcp-be-staging-* stacks, /cse-tcp-be/staging/* log groups, the
cse-tcp-be-staging-telemetry-db-data volume and
cse-tcp-be-staging-telemetry-db-credentials secret, the
staging_telemetry_db database, cse-http-be-staging-to-tcp.fifo as the
bus), so nothing is shared with dev except the CDK bootstrap repository,
whose image cleanup keeps every image any cse-tcp-be-* stack uses.
deploy.sh accepts only dev and staging: production is the
fleet-shaped stacks below, not this tier.
Before the first staging deploy, fill the stage's entries in cdk/cdk.json
from the HTTP server's staging stage. The synth refuses to run without them:
| Key | Value |
|---|---|
allowedOrigins.staging | The staging web console's origin(s); no localhost |
wsTicketJwksUrl.staging | The HTTP server's staging GET /v1/realtime/jwks URL |
deviceBindingEvents.staging | Stays false until the HTTP server's staging consumer is deployed (ADR 0018) |
Sizing is the dev shape (three t4g.micro hosts, a 20 GB data volume):
about $29.50 a month, the same line items as the dev cost table above,
plus well under $1 for the report renderer when the HTTP bus is on. On the
credit-based Free plan it draws on the same credit balance as dev, so it
roughly doubles the monthly burn. It costs nothing until it is deployed.
Both stages' deploy.sh stop when a lookup of the data volume or the
credentials secret fails for any reason other than "does not exist", so an
AWS error can never be read as "no volume" and create a fresh, empty
database.
Documentation site — cse-solar-docs-prod-docs
This site is not part of cse_tcp_be's CDK app — it lives in the
separate cse-solar-docs repo (its own
Docusaurus project and its own CDK app, cse-solar-docs/cdk/), deployed
independently of every backend stack: no VPC, no NATS, no shared
dependency, no shared deploy. S3 (private, Origin Access Control only —
never publicly reachable directly) behind CloudFront, served only at
https://docs.crownsolarenergy.com (requests on the distribution's own
*.cloudfront.net name are 301-redirected there), no GitHub Actions.
cd cse-solar-docs/cdk
npm run deploy # cdk deploy cse-solar-docs-prod-docs
The Docusaurus build (npm run build, run from cse-solar-docs's repo root)
runs as a synth-time side effect of constructing that stack — every
cdk synth/diff/deploy picks up whatever's currently committed under
cse-solar-docs/docs/, so cdk deploy alone keeps the live site in sync; there
is no separate build pipeline to also keep updated.
A CloudFront Function rewrites viewer requests (appending index.html to
any URI ending in / or lacking a file extension) — without it, every
Docusaurus "pretty URL" 404s, since CloudFront's defaultRootObject only
resolves index.html at the distribution root, not in subdirectories.
Confirmed live (on this stack's original deployment inside cse_tcp_be,
before this repo split out) before this was added: only the literal
.../page/index.html URL worked; .../page and .../page/ both 404'd.
Cost: effectively $0/month at this traffic (CloudFront's Free plan — 1M requests + 100GB transfer/month, permanent, not a 12-month tier — covers it with enormous headroom; S3 storage for a ~5MB site is a fraction of a cent/month regardless of Free Tier status).
Custom domain: docs.crownsolarenergy.com (docsDomainName in
cse-solar-docs/cdk/cdk.json), with a free us-east-1 ACM certificate. DNS is
in Cloudflare: the ACM validation CNAME and docs → CNAME → the stack's
CloudFrontDomain output, both DNS only. The same viewer-request
CloudFront Function 301-redirects any other Host (the *.cloudfront.net
name) to the custom domain, so DocsUrl stays
https://docs.crownsolarenergy.com even if the distribution is recreated —
only the Cloudflare CNAME target would change.
See cse-solar-docs's own README for full setup/deploy details.
Standalone plain-docker pilot — cse-tcp-be-dev-pilot-tcp-ingest
t4g.micro, public subnet, Elastic IP, plain docker run via user-data —
no NATS wiring, no ECS. A simpler single-node smoke test, independent of
the dev-tier pipeline above; not part of the tcpserver → NATS → ws-gateway
chain.
cd cdk && npx cdk deploy cse-tcp-be-dev-pilot-tcp-ingest
Logs: aws logs tail /cse-tcp-be/dev/pilot-tcp-ingest --follow. Shell
access without SSH: aws ssm start-session --target <instance-id>.
Fleet-shaped stacks (*-network, *-ecr, *-tcp-ingest)
The target production architecture — ~$100-140/mo even idle, not free-tier eligible regardless of device count. Not part of the current dev pipeline; deploy only once device count/traffic actually justifies NAT + NLB
- ASG cost.
*-network— VPC, 1 NAT Gateway, VPC Flow Logs.*-ecr— standalone image repo for future CI/CD.*-tcp-ingest— internet-facing NLB → ECS on EC2 (hostnetwork mode, not Fargate — avoids one-ENI-per-task at high connection density). Graviton (c7g.large) ASG with managed scaling, one instance of headroom for rolling deploys. Image pinned toPlatform.LINUX_ARM64explicitly. SSM shell access, no bastion/SSH key.
npx cdk diff cse-tcp-be-dev-tcp-ingest
npx cdk deploy cse-tcp-be-dev-tcp-ingest
# npx cdk deploy --all # every stack including fleet-shaped — real cost
This tier has no NATS/ws-gateway stack of its own yet — migrating the dev pipeline's NATS/ws-gateway pieces to sit alongside this fleet-shaped ingest tier (clustered JetStream, an ALB/NLB-fronted ws-gateway with stable DNS) is still open work, not yet built.
Configuration (config.ts)
Each key is read from CDK context first (-c key=value, or cdk/cdk.json's
context block), then its environment variable, then the default in
cdk/lib/config.ts. Because context wins, the two keys cdk/cdk.json
sets — devicePort (8443) and allowedOrigins — ignore their
environment variables; override them with -c or edit cdk.json.
| Key | Env var | config.ts default | Notes |
|---|---|---|---|
envName | ENV_NAME | dev | resource-name prefix; anything other than prod counts as a development environment |
devicePort | DEVICE_PORT | 9000 | cdk.json sets 8443, which is what is deployed |
desiredTaskCount | DESIRED_TASK_COUNT | 1 | fleet stack only |
instanceType | INSTANCE_TYPE | c7g.large | fleet stack only — must be Graviton/ARM |
pilotInstanceType | PILOT_INSTANCE_TYPE | t4g.micro | both pilot stacks (plain-docker and pilot-ecs-tcp-ingest, which ws-gateway shares) — must be Graviton/ARM |
natsInstanceType | NATS_INSTANCE_TYPE | t4g.micro | NatsStack — must be Graviton/ARM |
natsPort | NATS_PORT | 4222 | |
telemetryDbInstanceType | TELEMETRY_DB_INSTANCE_TYPE | t4g.micro | TelemetryDbStack — must be Graviton/ARM |
telemetryDbPort | TELEMETRY_DB_PORT | 5432 | |
telemetryDbName | TELEMETRY_DB_NAME | dev_telemetry_db | |
telemetryDbVolumeSizeGiB | TELEMETRY_DB_VOLUME_SIZE_GIB | 20 | size of a newly created data volume only |
telemetryDbVolumeId | TELEMETRY_DB_VOLUME_ID | (unset) | existing data volume to import; deploy.sh always sets it when one exists |
telemetryDbSecretArn | TELEMETRY_DB_SECRET_ARN | (unset) | existing credentials secret to import; deploy.sh always sets it when one exists |
fcmSecretArn | FCM_SECRET_ARN | (unset) | Firebase service-account secret for push notifications; unset = push off. deploy.sh sets it when cse-tcp-be-dev-fcm-service-account exists |
notifyPushEnabled | NOTIFY_PUSH_ENABLED | false | push kill switch; written to SSM /cse-tcp-be/<env>/notify/push-enabled. deploy.sh always sets it from that parameter (or NOTIFY_PUSH_ENABLED). Push needs this and fcmSecretArn |
webConsoleOrigin | WEB_CONSOLE_ORIGIN | (unset) | optional https://host of the web console; makes web push links absolute (WEB_CONSOLE_ORIGIN on persistence-worker). Unset: links are console paths such as /alerts?alert=<id>. Synth fails on anything but https://host[:port] |
wsGatewayPort | WS_GATEWAY_PORT | 8090 | |
tcpTlsSniffWindow | TCP_TLS_SNIFF_WINDOW | unset (tcpserver default 2s) | Per-stage TLS_SNIFF_WINDOW for tcpserver: how long a new device connection may stay silent before it is treated as plain. A TLS logger slower than this to send its ClientHello is misread as plain and hangs up. Dev: 15s |
tcpTlsDomain | TCP_TLS_DOMAIN | unset | Per-stage hostname for device TLS (see Device TLS). Sets tcpserver's TLS_DOMAIN, opens port 80 on the ingest host for Let's Encrypt, and adds host boot steps (a launch-template change, so the ingest instance is replaced on the deploy that turns it on). Set for dev in cdk.json. PilotEcsIngestStack only |
wsDomainName | WS_DOMAIN_NAME | unset | Per-stage custom hostname for the ws-gateway CloudFront distribution. Adds a free DNS-validated ACM certificate (us-east-1) and the name as a CloudFront alias; output WsGatewayCustomUrl. DNS is outside Route 53: during the deploy add the ACM validation CNAME (ACM console), then CNAME the name to WsGatewayDistributionDomain, both DNS only (not proxied). Set for dev in cdk.json; needs wsGatewayWss |
wsGatewayWss | WS_GATEWAY_WSS | false | true puts ws-gateway behind a CloudFront distribution as wss:// (output WsGatewayUrl) and opens 8090 only to CloudFront's origin-facing prefix list; false is plain ws://<Elastic IP>:8090. true in cdk.json (2026-10-29); takes effect at the next deploy. The cdk.json value wins over WS_GATEWAY_WSS. Turning it off deletes the distribution, so turning it on again creates a new *.cloudfront.net name. Needs AWS credentials at synth (the prefix-list lookup) |
allowedOrigins | ALLOWED_ORIGINS | (empty) | browser origins ws-gateway accepts. In cdk.json an object keyed by environment ({"dev": "...", "staging": "...", "prod": "..."}), or one comma-separated string for every environment. Each entry is scheme://host[:port]; one whole leftmost label may be * (https://*.console.example.com), never over a shared host such as *.vercel.app. Synth fails on a malformed entry, on an empty list outside dev, and on localhost outside dev. Dev includes the web console's http://localhost:5173 |
wsAuthMode | WS_AUTH_MODE | required on dev (cdk.json map keyed by envName); otherwise optional (required in prod). One deploy can override with -c wsAuthMode=optional | what a WebSocket connection without a realtime ticket may do: optional refuses web-console messages and the device messages (watch, read_registers, get_registers, write, custom_command) and keeps the mobile app's other messages working on a claimed userId, required refuses everything but auth, legacy trusts client userIds (rollback only). See Authentication |
wsTicketJwksUrl | WS_TICKET_JWKS_URL | (unset) | the HTTP server's GET /v1/realtime/jwks URL, whose public keys sign realtime tickets. Unset: no ticket can be verified (and required refuses to start). A public URL, not a secret. In cdk.json an object keyed by environment like allowedOrigins, or one URL for every environment; synth fails on anything but https://. Set for dev only (2026-11-03), from the next deploy; staging and prod are empty. If the HTTP server's key route is down, auth answers UNAVAILABLE and the gateway retries the fetch at most every 30 seconds, never crashing |
httpBusTopicArn | HTTP_BUS_TOPIC_ARN | (unset) | the HTTP server's SNS FIFO topic (cse-http-be-<stage>-to-tcp.fifo). Set: the telemetry-db stack creates the SQS FIFO queue cse-tcp-be-<stage>-from-http.fifo (+ DLQ, 5 receives), subscribes it with raw delivery, and persistence-worker consumes it (HTTP_BUS_QUEUE_URL). It also creates TCP's own outbound SNS topic cse-tcp-be-<stage>-events (output TcpEventsTopicArn, give it to the HTTP server's owner as their tcpEventsTopicArn), which persistence-worker publishes plant erasure completions to (TCP_EVENTS_TOPIC_ARN). The subscription excludes report.render.requested.v1 (body filter), and the report-renderer stack exists only while this is set. deploy.sh sets it when cse-http-be-dev-to-tcp.fifo exists and the bus is already deployed, or with HTTP_BUS=on; see Report renderer. Unset (today, the HTTP bus is off): none of it exists |
deviceBindingEvents | DEVICE_BINDING_EVENTS | false | Per stage in cdk.json ({"dev": true, "staging": false, "prod": false}, on for dev since 2026-11-04), or true for every stage. The cdk.json value wins over the environment variable. Publish device.binding.changed.v1 to the HTTP server (its ADR 0018; see Device binding). Needs httpBusTopicArn. Deploy order: set it only after the HTTP server's consumer is deployed with that type in its from-tcp filter. The first start with it on sends every device once, paced at 10/s (DEVICE_BINDING_BACKFILL_PER_SECOND on the persistence-worker task overrides that), and events the HTTP filter drops are lost. Unset: changes are recorded and wait |
co2KgPerKwh | CO2_KG_PER_KWH | 0.5 | kg CO₂ avoided per kWh: ws-gateway's ANALYTICS_CO2_KG_PER_KWH (Analytics screens) and the report renderer's (printed on every report as a provisional factor). One value for both; the product owner's provisional figure until an official one |
reportsBucketName | REPORTS_BUCKET_NAME | cse-http-be-<env>-reports | the HTTP server's reports bucket the renderer reads manifests from and writes report files to |
reportRendererMaxConcurrency | REPORT_RENDERER_MAX_CONCURRENCY | 2 (minimum 2) | most report renders at once; each holds one telemetry-db connection |
The four instance-type keys are checked at synth time: anything that isn't a
Graviton family (<letters><generation>g…, e.g. t4g, c7g, m6gd) fails
cdk synth with an error, because every stack uses an ARM AMI and arm64
images and an x86 type would only fail later, at boot.
Region is fixed to us-east-1 in bin/app.ts — override only via
-c region=..., never via CDK_DEFAULT_REGION (which reflects your local
AWS CLI default, not this project's chosen region). The shell scripts
(deploy.sh, db-tunnel.sh, the log scripts, clean-ecr-images.mjs)
don't read that context — they use AWS_REGION, defaulting to
us-east-1, so set both if you ever change region. The account always
comes from your current AWS credentials (CDK_DEFAULT_ACCOUNT).
Device TLS
The device port (8443 on dev) accepts TLS and plain TCP on the same
port. tcpserver reads the first byte of each new connection: 0x16 (a TLS
ClientHello) starts a TLS session; anything else, or nothing within
TLS_SNIFF_WINDOW (default 2s), is plain. Plain loggers wait for the
server to speak first, so they pay that window once per connection and are
otherwise unchanged. Loggers without TLS keep working.
- Address: devices dial
<tcpTlsDomain>:8443(stack outputPilotEcsDeviceTlsAddress). TLS 1.2 minimum. A client that sends no SNI gets the configured domain's certificate. - Certificate: a free Let's Encrypt certificate that tcpserver obtains
and renews itself (
golang.org/x/crypto/acme/autocert, HTTP-01). The ACME responder listens on:80(ACME_HTTP_ADDR) and answers only challenge paths. Certificates and the ACME account key are cached on the host in/var/lib/tcpserver/acme(TLS_CERT_CACHE_DIR), so task restarts reuse them; a replaced instance issues one new certificate (Let's Encrypt allows 5 duplicates per week). - DNS: an A record from the domain to the ingest Elastic IP, DNS only (a proxy such as Cloudflare's orange cloud breaks both raw TCP and HTTP-01). Until DNS resolves, TLS handshakes fail; plain TCP is unaffected.
- Host: port 80 open to all (Let's Encrypt does not publish its source
addresses); the boot script sets
net.ipv4.ip_unprivileged_port_start=80so the non-root container can bind it under host networking. - Slow TLS loggers: a logger that takes longer than the window to send
its ClientHello is read as plain, gets
AT+DTUPN?, and hangs up, which becomes a reconnect loop every few seconds (seen on the dev bench 2026-12-03 at 2s). Dev uses15s(tcpTlsSniffWindow); plain loggers then wait up to 15s per connection before identification. - Logs: with TLS on, each
connection acceptedline carriestransport_security(tls/plain),first_byte_wait_ms(how long the client took to speak), and TLS onestls_versionandtls_sni. A failed handshake logsconnection dropped before identification. - Cost: $0 (certificate free, no load balancer).
- Not covered:
TcpIngestStack(the NLB path) does not wire this yet; there, TLS would end at an NLB TLS listener with an ACM certificate. Certificates are server-only: devices are not authenticated by certificate.