Skip to main content

Architecture overview

Hard invariant — backend isolation​

This service never connects to the TCP telemetry server, and never joins a VPC. The product has two fully independent backends sharing only the Flutter client:

Flutter ──HTTPS──▶ CloudFront → HTTP API → Lambda → DynamoDB (HTTP Server, this doc set)
──WSS ───▶ ws-gateway → NATS → PostgreSQL (TCP Server, see /docs)

The HTTP Server owns users, plants, devices (registration/claiming metadata), memberships, roles, settings. It does not own telemetry, readings, live power, or alarm detection — that is the TCP Server's cmd/ws-gateway and dev_telemetry_db (see the TCP Server's infrastructure doc).

This is enforced as a hard rule (see cse-http-be's CLAUDE.md), not just a convention: the failure mode it prevents is someone adding "just one" Lambda that reads the telemetry Postgres for a report, which reintroduces a VPC, a NAT gateway, and a shared blast radius with the live TCP ingest path in a single PR. If a feature seems to need telemetry, it belongs in the TCP Server repo or in a projection that side writes — never a direct read from here.

Planned changes (not implemented): see Roadmap → Target architecture.

Overall architecture​

┌─────────────┐
Flutter app ───▶ │ CloudFront │ (authored, not deployed — see note below)
│ + WAF │
└──────┬──────┘
│ HTTPS
┌──────▼──────────────┐
│ API Gateway HTTP API │ $default stage, no stage prefix
│ + HttpUserPoolAuthorizer
└──────┬──────────────┘
│ per-family Lambda integration
┌────────────┼────────────────────┐
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────────┐
│ Lambda │ │ Lambda │ │ Lambda │
│ (packages/api)│ │ (packages/api)│ │ (Cognito triggers)│
└──────┬───────┘ └──────┬───────┘ └────────┬─────────┘
│ │ │
└────────┬───────┘ │
▼ ▼
┌───────────────┐ ┌───────────────┐
│ DynamoDB │ │ Cognito User │
│ single table │ │ Pool (LITE) │
└───────────────┘ └───────────────┘
│
▼ stream
┌───────────────┐ publish ┌─────────────┐
│ stream-router │ ────────────────▶ │ SNS FIFO │
│ (IntegrationStack, │ to-tcp.fifo │
│ authored, not deployed) └─────────────┘
└───────────────┘

Note on CloudFront/WAF: lib/edge-stack.ts (T002-060, FR-036) now exists and is a real CDK stack — CloudFront (CACHING_DISABLED policy, a security-headers response policy, HTTP/2+3) with a CfnWebACL per-IP rate-limit rule in front of the HTTP API. It is authored but not deployed: bin/app.ts only instantiates EdgeStack with CDK context -c edgeEnabled=true (renamed from withEdge, T002-148, CR-26 — same gate), so a plain cdk deploy --all/npm run deploy:dev never creates it, and even once a human opts in, deploying it is its own separate, targeted, human-run step (never bundled into --all) — see Infrastructure → EdgeStack for the full resource list. Today, in every stage, the API Gateway $default stage's own apiEndpoint is the actual entry point; treat CloudFront/WAF as authored-but-not-yet-deployed infrastructure, not something currently fronting the API.

Layers​

  • packages/api — thin Lambda handlers: parse the request, validate, call core, map the result to HTTP. No business logic, no direct DynamoDB SDK calls.
  • packages/core — framework-free domain logic: Zod schemas, repositories (DynamoDB access), the IdentityProvider abstraction. No AWS Lambda types, unit-testable without mocking AWS.
  • lib/ — AWS CDK v2 stacks. lib/constructs/ApiFunction is the only way any Lambda is declared (see Infrastructure).

Request flow​

A typical authenticated request, e.g. GET /v1/me:

  1. Flutter app calls the API Gateway HTTP API endpoint with an Authorization: Bearer <Cognito ID/access token> header.
  2. API Gateway's HttpUserPoolAuthorizer (a JWT authorizer) verifies the token before Lambda runs: signature against the pool's JWKS, issuer, expiry, and audience. The audience is aud on an ID token or client_id on an access token, and it must be one of the two mobile app clients — plus, in dev only, server-admin (KI-18 fixed, T002-048): a server-admin token fails this check in prod and every other stage. An invalid, missing or expired token never reaches application code. The gateway itself answers 401 with body {"message":"Unauthorized"}, not this API's error envelope.
  3. On success, API Gateway invokes the route's Lambda (via HttpLambdaIntegration), passing the verified claims in event.requestContext.authorizer.jwt.claims — under HTTP API payload format 2.0, every claim value arrives as a string, including what were booleans in the token.
  4. The handler calls requireClaims(event) (packages/api/src/http/claims.ts) to read sub/email out of that context. If the authorizer somehow isn't attached to the route (a new route defaults to open in HTTP API v2 — see Security considerations), this throws a 401 UNAUTHENTICATED rather than silently treating the caller as anonymous.
  5. The handler validates any request body/query against a Zod schema from packages/core/src/schemas.ts, then calls into a packages/core repository function, which issues one or more DynamoDB commands.
  6. The handler returns its result via packages/api/src/http/respond.ts's ok()/created()/fail() helpers — never a bare object. Payload format 2.0 turns a return value with no statusCode key into an HTTP 200 containing whatever the return value was, so returning { error: ... } directly would reach the client as a successful 200 carrying an error body. The handler() wrapper also catches any unexpected throw and maps it to a 500 INTERNAL instead of letting API Gateway produce a bare, unlogged 502.

Data flow​

Single-table DynamoDB, one table per stage (cse-http-be-<stage>-main), one generic inverted GSI (GSI1). See Types & schemas and Infrastructure for the full entity/key catalogue. Every read is a targeted GetItem/Query on a known key shape — Scan is banned (a full-table read that bills for the whole table on every call).

Two data-flow patterns recur throughout the API:

  • Denormalisation over joins. A plant-membership item carries a copy of the plant's name, status, timezone, pvCapacityKwp — so listing "my plants" is one Query, not one query plus N GetItems. The tradeoff: any write that changes a plant's name/status must update the denormalised copy in the same TransactWriteCommand, or the two can drift. No plant-update endpoint exists yet, so nothing can drift today. The first one to be added must respect this rule. The plant-type, country, address, solar-mode, grid, tariff and battery fields are deliberately not denormalised, so the list endpoint doesn't return them.
  • Server-side re-validation, never trusting a stored or client-supplied reference. The clearest example: the account's selectedPlantId (the "last active plant" state — see GET /v1/me) is re-checked against the caller's current plant memberships on every read, not only when it is written. If access to that plant was revoked since the last call, the server silently heals it to another accessible plant (or clears it) before the response is built, rather than returning a now-invalid reference the client would have to detect and retry around.

Authentication and authorization​

Authentication is Amazon Cognito (User Pool, FeaturePlan.LITE), behind a single interface — IdentityProvider (packages/core/src/auth/identity-provider.ts). Only cognito-identity-provider.ts may import the Cognito SDK; every other file in the codebase is forbidden from doing so. This exists because Cognito cannot export password hashes: migrating off it later means lazy re-hashing on each user's next successful login, which is only tractable if every auth call already goes through one seam.

Two public (no-secret) app clients exist for the Flutter app, split only by session length:

ClientrefreshTokenValidityWhen used
flutter-app-default1 dayNormal sign-in ("keep me signed in" off)
flutter-app-remembered90 days"Keep me signed in" on (the app pre-ticks it)

Both accept USER_SRP_AUTH (standard email+password sign-in, performed client-to-Cognito directly — this API never sees a password) and CUSTOM_AUTH (email + one-time code sign-in, implemented by this repo's own Cognito Lambda triggers rather than Cognito's native passwordless feature — see Important architectural decisions below for why). A third, server-only client (ADMIN_USER_PASSWORD_AUTH) exists purely so CI/curl/support tooling can mint a test JWT without SRP, which cannot be performed outside a real client SDK.

Authorization is read from DynamoDB at request time, never carried in the JWT. A plant-membership item (role: OWNER/ADMIN/VIEWER) is looked up per request that needs it (e.g. claiming a device checks the caller isn't a VIEWER). This is deliberate: Cognito's LITE plan explicitly forgoes custom access-token claims for this reason — a cached token would keep carrying a role that changed hours ago, and every screen's authorization would silently be stale until the token expired.

In practice, today, the only membership writer is POST /v1/plants, which always writes OWNER. There's no invite/add-member endpoint, so ADMIN and VIEWER memberships can't exist yet, and the one role rule in code (a VIEWER can't claim a device) can't be reached (KI-12).

A plant that doesn't exist and a plant the caller can't access both return 403 FORBIDDEN. The membership check runs first, so a caller probing IDs learns nothing.

Authorization model (packages/core/src/access/)​

The organisations/team/access feature's core authorization engine. Every feature-003 route (Team & Access, Invitations, Shares, Access requests, Access-change log, Realtime tickets) gates through requireOrgLevel/resolveRequestContext on the model summarised below. The seven original mobile endpoints above are not yet migrated: they still authorize through the legacy single-plant OWNER/ADMIN/VIEWER membership, unaware of this model (see Compatibility below for how the evaluator bridges the two).

For the full reference — the complete role × category matrix, scope kind caps, revocation mechanics, MFA enforcement rollout (including OQ-09) and session semantics — see Authorization. This section stays a summary; it won't be repeated there.

This organisation-scoped model replaces the single plant OWNER/ADMIN/VIEWER model above for organisation-scoped (web console) access; the existing mobile OWNER membership keeps working unchanged underneath it (see Compatibility below).

Levels (cumulative, weakest to strongest): NONE < VIEW < EDIT < MANAGE < FULL. VIEW = see; EDIT = create/change, no delete/approve; MANAGE = + delete/approve; FULL = + category-level settings.

Categories (10, fixed): plants, devices, alerts, commands, firmware, service, reports, customers, team, settings. A caller's access to an organisation or a plant is a level per category, not one blanket role.

System roles (identical in every organisation, not editable): Super Admin (FULL everywhere), Administrator (FULL on most categories, MANAGE commands, VIEW firmware — FULL in the Crown org since RBAC v2 — MANAGE team, EDIT settings), Viewer (VIEW on plants/devices/alerts/service/reports, NONE elsewhere). Four further seeded roles start as editable copies per organisation: Operations Manager, Technician, Sales, Compliance Auditor — each with its own fixed starting matrix. A role whose scope rule is "all" (Super Admin, Administrator, Compliance Auditor) always has scope ALL; the other four are scoped per member.

MFA requirement. A membership's effective MFA requirement is on when any of these is true: it's set explicitly on the membership; the organisation is PLATFORM; or the role holds FULL on any single category — personal organisations are exempt from all three. Administrator meets that third condition (it's FULL on plants/devices/alerts/service/reports/customers, not just Super Admin's all-FULL row), so Administrators require MFA too, not only Super Admins — this is the confirmed reading of "any FULL level" (07-security.md §1), not a narrower "every category FULL" one. Once the floor applies, it can be raised freely but never lowered below it by an administrator action (422). Superseded 2026-11-11: two-factor is the user's own choice — the effective requirement is always false and the floor is never applied.

Scope controls which plants a role's levels apply to, independent of the levels themselves. Exactly one kind per membership: ALL (every plant the org operates, or every plant on the platform membership), REGION / TAG (plants carrying one of up to 10 target tags), CUSTOMER (plants belonging to one of up to 10 related customer organisations), PLANTS (up to 500 explicit plant ids), or NONE. Which kinds an organisation may use depends on its kind: an operator organisation may use all six; a partner or customer organisation may only use ALL, PLANTS or NONE (relative to the plants already shared with or owned by it); the platform organisation (Crown HQ) may only use ALL or NONE.

External access (shares) grant a plant selector to an organisation, individual user or (via a portal relationship) a whole customer organisation, at one of 5 external levels — VIEW < MONITOR < EDIT < SERVICE < FULL — each mapping to a fixed per-category ceiling (e.g. FULL caps firmware at NONE forever; a share can never grant firmware access). An individual grantee's effective level is exactly that ceiling; an organisation grantee's is min(their own role's level, the ceiling) — sharing access with a partner never gives that partner's staff more than their own role already allows.

The evaluator (effectiveAccess(facts, plant)) decides, per request, per plant, per category: the max over every path that reaches the plant — a platform membership, the caller's own operator-org membership, an external share, or a customer-portal relationship — of min(role level, that path's ceiling), treating a path whose scope doesn't cover the plant, or whose membership/share is suspended, removed, revoked or expired, as contributing nothing. It's a pure function: the same inputs always produce the same decision, and nothing is cached across requests — a suspension or a narrowed scope takes effect on the caller's very next call. It also derives: a command risk ceiling (a share at SERVICE caps command execution at risk LOW, FULL at MEDIUM; a role-based path is never capped), and redaction flags (an external VIEW/MONITOR-level path hides device serials and engineering data unless a role path independently grants that category at the same or a higher level).

Compatibility with the existing mobile OWNER/ADMIN/VIEWER model​

The legacy per-plant membership described earlier in this section (OWNER/ADMIN/VIEWER) is read by the evaluator as a legacy path alongside the organisation paths above, not replaced by them: OWNER reads as the external FULL ceiling (a fallback for a plant not yet attributed to its owner's personal organisation), ADMIN reads as external EDIT, and VIEWER reads as external VIEW — matching the mapping promised in Known issues. Existing mobile routes and response shapes are unaffected until a future change explicitly wires them through this evaluator.

Database interactions​

All application-side database access is DynamoDB, through the single table described above, via @aws-sdk/lib-dynamodb's DynamoDBDocumentClient (module-scoped, reused across warm Lambda invocations — packages/core/src/ddb.ts). Every repository function issues one of: GetCommand, QueryCommand (never ScanCommand), PutCommand (usually with a ConditionExpression to prevent silently overwriting an existing item), UpdateCommand, or TransactWriteCommand (when two items must both succeed or both fail — e.g. creating a plant and its owner's membership atomically).

In the application code path, this API has no access to anything outside its own table. It doesn't read the TCP Server's PostgreSQL database, by design (see the hard invariant above).

The table's DynamoDB stream (NEW_AND_OLD_IMAGES) is enabled, and a real consumer Lambda (stream-router) is now authored in lib/integration-stack.ts (T002-085) — but that whole stack is authored, not deployed: bin/app.ts only creates it with CDK context -c busEnabled=true (renamed from withIntegration, T002-148, CR-26 — the same single flag now also enables every event-source mapping in it, enabled: busEnabled, CR-21, so there's no longer a separate deploy step to flip mappings on) (B-01, the concurrency quota, closed 2026-10-26 at 1000; deploying with the flag is a human decision). So in every stage that exists today, nothing actually runs against the stream. See Infrastructure → IntegrationStack for the full resource list and context keys. Separately, the TCP Server's ws-gateway will eventually need to check plant membership before allowing a WebSocket subscription. The intended design for that is a read-only grant on this table to the TCP side (dependency direction TCP → DynamoDB, never Lambda → TCP). That's not implemented yet, and it's planned as ADR 0003 in cse-http-be.

Outbound: stream → outbox → SNS (HTTP → TCP; authored, not deployed)​

A transactional outbox (blueprint 03 §6.7, 05 §3.1; research R15; FR-023, FR-024) is this side's mechanism for telling the TCP Server about a state change — a plant created, a device claimed, etc. Nothing publishes through it in this feature yet: no handler calls buildEnvelope/outboxPut (packages/core/src/outbox.ts) today — 002 ships the pipeline, not a publishing feature. The pipeline itself, though, is real code exercised by unit and (authored) integration tests, not just a sketch:

  1. A future handler's write would build an envelope with buildEnvelope(...) and include outboxPut(item)'s TransactWriteItems entry in the same transaction as the entity write — so the event can never exist without the state change it describes, or vice versa. The item lands on the table (OUTBOX#<hour>#<shard> prefix) with a 7-day TTL.
  2. The table's DynamoDB stream delivers that INSERT to stream-router (packages/api/src/handlers/stream-router.ts). It unmarshals the record and calls the pure planner planRecord (packages/core/src/stream/plan.ts): an OUTBOX# INSERT plans one publish action (no action for MODIFY/REMOVE on an outbox item — they're write-once); the SAME planner also derives facet-counter (COUNT#…) and search-token (SRCH#…) actions from the diff of a registered collection's old/new images (FR-025) — 002 registers no collections, so this path is currently a no-op for every real item.
  3. executeActions (packages/core/src/stream/execute.ts) runs the non-publish actions in one TransactWriteItems guarded by a DEDUP#stream#<eventID> marker (attribute_not_exists(PK)) — a redelivered record (Lambda's at-least-once stream processing) trips the guard and is silently treated as already-applied. publish actions run separately via publishOutbox, batched PublishBatchCommand calls (SNS's 10-per-call limit) to SNS FIFO topic cse-http-be-<stage>-to-tcp.fifo, with MessageDeduplicationId = the envelope's id and MessageGroupId = <aggregateType>/<aggregateId> (same-aggregate events stay ordered; different aggregates process independently). Per-item publish failures are reported back rather than thrown, and stream-router turns the first failing record in a batch into the one batchItemFailures entry — the event-source mapping then retries from that record's sequence number onward, preserving order.
  4. EMF metrics per record: StreamRecords (Result: ok), OutboxPublished, OutboxPublishFailed (Result: error), CounterUpdates — see Operations → Custom metrics.

Envelope shape (CloudEvents-influenced). outbox.ts has its own plain TypeScript Envelope interface for building outbound envelopes; packages/core/src/schemas.ts's IntegrationEnvelope Zod schema validates them (both outbound, were anything to parse one back, and inbound — see below). The two now agree on every field's optionality except correlationId, which IntegrationEnvelope treats as optional (.optional()) while outbox.ts's Envelope/buildEnvelope always sets it (the originating request's correlation id) — see Types & schemas for the exact diff:

{
specversion: '1.0';
id: string; // ULID; consumers dedupe on it (= MessageDeduplicationId)
type: string; // e.g. "plant.created.v1"
source: string; // "cse-http-be/<stage>"
time: string; // ISO-8601 datetime
subject?: string;
correlationId: string; // the originating API request's correlation id
causationId?: string; // the event that caused this one, if any
seq: number; // per-aggregate monotonic version
data: unknown;
}

Inbound: TCP → SQS → consume (authored, not deployed)​

The reverse direction (blueprint 05 §3.1; research R16; FR-028): TCP publishes to its own topic, whose messages land in this service's from-tcp and alert-events SQS queues (IntegrationStack, subscribed only when context tcpEventsTopicArn is set). One Lambda, tcp-events (packages/api/src/handlers/tcp-events.ts), consumes both queues (CR-21) — it parses each SQS record's JSON body and calls consume (packages/core/src/integration/consume.ts), which is itself source-agnostic: it never knows or cares which queue a message came from.

consume(raw) validates the parsed body against IntegrationEnvelope.safeParse and returns one of five outcomes:

ResultMeaningSQS outcome
invalidNot an object, or missing/malformed required fieldsBatch item failure — retried, then the DLQ after 5 attempts
ignoredValid envelope, but no handler is registered for its type (registerTcpEventHandler, packages/core/src/registry/tcp-handlers.ts — 002 registers none)Ack (no DB write)
appliedA registered handler ran and its write succeededAck
duplicateThe handler's own DEDUP#tcp#<id> guard (7-day TTL) already existed — a redelivery of an already-applied eventAck
staleThe dedup guard passed, but the handler's projection write's own seq condition failed (a superseded/out-of-order event)Ack

A registered handler is responsible for its own DynamoDB write, typically via the building block applyIfNewer: one TransactWriteItems call combining the DEDUP#tcp#<id> put (attribute_not_exists(PK)) and the projection update (attribute_not_exists(lastSeq) OR lastSeq < :seq) — so dedup and the seq check land in the SAME transaction, and consume distinguishes the two failure modes from the resulting TransactionCanceledException's CancellationReasons (index 0 = dedup, any later index = the handler's own condition).

Unlike the DynamoDB-stream case, SQS failures are not "from the first failure" — each message in a batch is independent, so tcp-events reports back exactly the messages that were invalid or threw, by their own messageId, regardless of position. EMF metric TcpEvents is emitted per message with dimensions Result and EventType (best-effort type from the body, unknown if the body didn't even parse) — see Operations → Custom metrics.

This whole path shares IntegrationStack's authored-but-not-deployed status and busEnabled gate above — in every stage that exists today, no message is ever actually delivered to tcp-events.

TCP-facing device event contract (feature 005)​

Removed (ADR 0012). device.upserted.v1 and device.removed.v1 are gone from the SNS allowlist; device.observed.v1, device.binding.result.v1 and device.erasure.completed.v1 are gone from the from-tcp filter and the tcp-events dispatch, together with the DeviceInboundAnomaly metric. None was ever deployed. Devices belong to the TCP server; the only device data here is the plant ↔ serial binding (Plant devices), and plant deletion lists the plant's serials in plant.deletion.requested.v1 (serials).

Plant events and the delete saga (feature 004)​

Plant changes reach the TCP side only as outbox events (ADR 0005), never by a direct call. Each is written in the same DynamoDB transaction as the change it describes (packages/core/src/plants/lifecycle.ts, packages/core/src/plants/events.ts):

EventDirectionWritten when
plant.upserted.v1HTTP → TCPcreate, edit, settings change, legacy migration
plant.archived.v1 / plant.restored.v1HTTP → TCParchive / restore (C10, C10b)
plant.deletion.requested.v1HTTP → TCPplatform delete request (C11)
plant.erasure.completed.v1TCP → HTTPTCP has erased its telemetry for the plant

Payload fields are listed under Types → Event payload builders.

Delete saga. DELETE /v1/plants/{plantId} with X-Org-Id (C11):

  1. Provider onPlantDeleting hooks are asked for blockers; none is registered today (ADR 0012 removed the feature 007 command blocker), so this step never blocks. A blocker would answer 409 INVALID_STATE.
  2. One transaction sets the plant to DELETING, removes its list keys so every list hides it, writes a pending-deletion marker and the plant.deletion.requested.v1 outbox row. Reads of the plant now return 410 GONE.
  3. TCP erases its data and replies with plant.erasure.completed.v1 on the HTTP-owned inbound queue. The handler cleans up idempotently, keeping a tombstone and the plant-code guard so the code is never reused.
  4. An hourly sweep (plant-deletion-sweep) emits PlantDeletionOverdue for any marker older than 24 hours (see Operations → Alarms runbook).

Until TCP ships the erasure side (TCP-REQ-12), deleted plants stay DELETING (hidden, 410) and the overdue alarm is expected to fire.

TCP requirements from feature 004. Telemetry is never stored or served here; these screens wait on the TCP side:

IDWhat it unblocksBlocks an HTTP route?
TCP-REQ-04TCP projection of plant eventsNo
TCP-REQ-07status and telemetry columns, status tabs, telemetry counts in saved viewsNo (the client shows "—")
TCP-REQ-08energy and analytics tabs, dashboard KPIsNo
TCP-REQ-09applying alert rules, alerts tabNo
TCP-REQ-10live data behind share linksNo (live.available: false)
TCP-REQ-12delete saga completionYes, for completion only (plants stay DELETING)
TCP-REQ-14verifying web realtime joins (TCP WebSocket is ws:// today)No

External integrations​

  • Amazon Cognito — identity, described above.
  • Amazon SES: CreateAuthChallengeFn emails the sign-in code (SendEmail, only when deployed with -c otpSenderEmail). SES is still in sandbox with DKIM pending (KI-6).
  • Amazon SNS: the alert topic in ObservabilityStack. No SMS is sent anywhere.
  • AWS Systems Manager Parameter Store: AuthStack/DataStack publish the pool ID, client IDs and table name as parameters for tooling. Application code doesn't read them at runtime; Lambdas get TABLE_NAME as an environment variable.
  • CloudWatch / AWS Budgets / X-Ray: alarms, budgets and tracing (X-Ray outside prod only). See Observability.
  • Amazon SES — planned for password-reset email delivery once the account's SES sandbox restriction is lifted (see Important architectural decisions). Cognito is not yet pointed at SES; it currently uses Cognito's own built-in email sender (~50 emails/day, account-wide), which is a dev/test-only capacity.
  • The Flutter mobile app — the only client. No other service or third party consumes this API today.
  • Explicitly not integrated: the TCP Server, its NATS bus, or its PostgreSQL database (the hard invariant above).

Important architectural decisions​

A few decisions shape this codebase disproportionately; each has a fuller writeup as a repo ADR (docs/adr/ in cse-http-be) — summarised here:

  • Cognito LITE, not the ESSENTIALS default. New Cognito user pools default to the ESSENTIALS feature plan. LITE vs ESSENTIALS is a ~$6,055/month difference at 600k MAU for features this product doesn't need (Managed Login, native passwordless, custom token claims, password reuse prevention). See Scalability considerations for the full cost curve.
  • Email OTP sign-in via custom Cognito Lambda triggers, not native passwordless. Cognito's native passwordless sign-in requires the Essentials or Plus feature plan — verified against AWS's own plan-comparison documentation. Flipping the whole user pool to Essentials to get one sign-in method would reproduce exactly the cost cliff LITE was chosen to avoid. Instead, three Lambda triggers (DefineAuthChallenge/CreateAuthChallenge/VerifyAuthChallengeResponse) implement the same capability directly on LITE, using SES for email delivery — the standard technique used industry-wide before Cognito shipped a native version of this feature.
  • DynamoDB single-table, not one table per entity. One table with a generic PK/SK plus one inverted GSI covers every current access pattern (docs/data-model.md in cse-http-be is the authoritative contract). Adding a second table would mean cross-table transactions DynamoDB doesn't support atomically the way TransactWriteCommand does within one table.
  • Selected-plant state lives server-side, self-healing on every read, not as client-only cached state the client has to detect staleness in. See Data flow above.
  • Endpoints designed per screen, not per entity. At roughly 250ms round-trip time to the primary user base (Pakistan), six sequential per-entity calls costs about 1.5 seconds of pure network latency and roughly doubles the request bill versus one screen-shaped call. GET /v1/me is the clearest example: it returns the profile, the currently-selected (and re-validated) plant, and account-wide plant/device counts in a single call, rather than requiring three.

Scalability considerations​

Modelled against 60 requests/MAU/month (see docs/cost-model.md in cse-http-be for the full derivation):

MAUInfrastructure (Lambda+API GW+DynamoDB+SES etc.)Cognito (LITE)Total
100 (dev)~$1/mo$0~$1/mo
10,000~$4/mo$0~$4/mo
50,000~$15/mo~$220/mo~$235/mo
100,000~$29/mo~$495/mo~$524/mo
300,000~$81/mo~$1,415/mo~$1,496/mo
600,000~$168/mo~$2,795/mo~$2,963/mo

Cognito is 94–98% of the total bill above 50k MAU. Everything else — Lambda, API Gateway, DynamoDB, SNS/SES — is a rounding error by comparison, which is why cost-review effort in this codebase concentrates on the IdentityProvider boundary and the LITE-tier decision rather than on Lambda memory tuning.

Other scalability-relevant choices already in place:

  • DynamoDB on-demand (no manually-provisioned throughput) until 3-4 weeks of real production traffic data justify switching to provisioned capacity.
  • Lambda arm64, 256MB — not the smallest available memory: a function that finishes in a quarter of the time at 4x the memory costs the same and feels faster over the ~250ms RTT to the primary user base.
  • No reservedConcurrentExecutions anywhere. The AWS account's Lambda concurrency quota is 1000 (raised from 10), shared with the live TCP Server's ingest Lambdas. Consumers cap themselves with maxConcurrency; reservations need the owner's approval.
  • Every list endpoint is server-capped (max 50 items) with an opaque cursor, never an unbounded scan or a client-supplied page number.

Error handling​

Every handler is wrapped by packages/api/src/http/respond.ts's handler() function, which:

  • Maps a thrown AppError (from packages/core/src/errors.ts) to its declared HTTP status and stable code.
  • Maps a thrown ZodError (schema validation failure) to 422 VALIDATION_FAILED with the flattened Zod error details attached.
  • Catches any other thrown error, logs it as a structured JSON line ({"level":"ERROR","msg":"unhandled_error", ...} — request/response bodies are never included, per the no-body-logging rule), and returns a generic 500 INTERNAL — so an unexpected bug never surfaces as an unlogged, opaque 502 from API Gateway.

A body that isn't valid JSON currently falls into that last bucket and returns 500, not 422 (KI-7).

Every error response from application code uses the same stable envelope. Responses API Gateway generates itself (an authorizer 401, an unmatched-route 404, a timeout or throttle 5xx) have the body {"message": "..."} instead. See API overview → Gateway responses.

{ "error": { "code": "NOT_FOUND", "message": "Plant not found" } }

code is a shipped contract: once an APK ships checking for a specific code value, that value is never changed. See Types & schemas → Error codes for the full, current list.

Observability​

  • Logs: every Lambda logs JSON to its own 14-day log group. API Gateway writes one JSON access-log line per request to a separate log group. The structured events (unhandled_error, email_signin_*, …) are catalogued in Operations → Logs.
  • Alarms: Lambda throttles and Lambda errors (both account-wide, including the TCP Server's functions), API 5xx, and DynamoDB throttles. All go to one SNS alert topic. See Infrastructure → ObservabilityStack.
  • Budgets: $50 actual and $200 forecast monthly tripwires, account-wide.
  • Tracing: X-Ray active in dev, off in prod.
  • Metrics: AWS-provided metrics only. There are no custom metrics, and API Gateway detailed (per-route) metrics are deliberately off.

Security considerations​

  • A new HTTP API route defaults to open (API Gateway HTTP API v2 behavior) — the authorizer is attached per-route, not globally. Every route in lib/api-stack.ts's route table is therefore required to pass the shared authorizer; a route added without it is a silent authentication bypass, not a visible error. requireClaims() is the application-level backstop: if the authorizer context is missing, it throws 401 UNAUTHENTICATED rather than treating the request as anonymous.
  • No request or response bodies are logged in production. CloudWatch logging is structured JSON with explicit fields only; a raw body could contain a password (signup form data during an unrelated debugging pass) or other sensitive input.
  • Non-disclosure of account existence. Every app client sets preventUserExistenceErrors: true, so a sign-in or password-reset attempt against a non-existent account returns the same response shape as one against a real account with a wrong password/code. This had to be kept by hand in the custom email OTP triggers, since Cognito's own protection doesn't automatically extend to fully custom auth flows. Response timing still differs for the email OTP flow (KI-5).
  • OTP generation and throttling. The 6-digit sign-in code comes from crypto.randomInt (KI-4 fixed). It's valid for 5 minutes, with 3 attempts per session; a retry within that session reuses round 1's code and sends no second email (KI-3 fixed); one email per address per 60 s — see Authentication. Neither the email address nor the code is ever logged.
  • IAM scope. Each route Lambda gets read-only or read/write access to the one table (and its index) and nothing else. CreateAuthChallengeFn has ses:SendEmail only on the configured sender identity (and its domain and configuration set), with an ses:FromAddress condition. The only Cognito admin permission any function has is meFn's cognito-idp:AdminGetUser, scoped to this pool's ARN only, used to resolve/repair email when a bearer token has no email claim (see GET /v1/me).
  • Refresh tokens aren't rotated on the LITE plan. The mitigations are secure device storage (Keychain/Keystore), a bounded refresh validity (1 or 90 days), token revocation, and GlobalSignOut for lost devices.
  • CloudWatch metric dimensions stay low-cardinality. Never userId or deviceSerial as a metric dimension — each distinct dimension value creates a new CloudWatch custom metric, billed per metric per month; a per-user dimension would silently create thousands of billed metrics. High-cardinality detail belongs in logs (queryable via CloudWatch Logs Insights), not metrics.
  • Cognito is never pointed at SES while SES is sandboxed. Doing so would make every signup to an unverified email address fail silently, leaving the account permanently stuck UNCONFIRMED — see Operations → Common failure scenarios.
  • The account's Lambda concurrency quota (1000) is shared with the live TCP Server's ingest functions. Never load-test this API from this AWS account — doing so risks throttling production inverter data ingestion on the TCP Server side, an entirely unrelated system that happens to share the account.
  • No real secrets ever appear in this repo's code or in this doc set — not an AWS access/secret key, a Cognito app client secret, a bearer token, a password, or a database credential, whether in application code, infrastructure code, or documentation (cse-http-be's CLAUDE.md makes this a hard, no-exception rule). What does appear — a Cognito User Pool ID, a public, no-secret app client ID, an API Gateway endpoint, a table/stack name — is configuration, not a credential: none of it grants access, decrypts anything, or authenticates as anything by itself, which is why it's safe for the FE team to have in Authentication and Infrastructure. This repo has no application secrets to manage today (Cognito holds credentials itself and never exposes them); if one is ever introduced, it belongs in Secrets Manager or an SSM SecureString, referenced by ARN/parameter name, never as a literal value anywhere.

:::warning Registered in code, not deployed The 006 work-order routes are now registered in code in the route-area stack cse-http-be-<stage>-api-service (Q27) and become callable after the owner's next deploy. No order — and no event below — has been produced in any stage yet. :::

  • HTTP never verifies alerts. Alerts are detected and owned by the TCP Server. A work order created from an alert carries the client-supplied alert {alertId, code?, title?, severity?, deviceKey?}; this API checks its format only, stamps linkedAt and clientSupplied: true, and never reads TCP data to confirm it exists (the hard invariant above). One open order per alertId (409 ALREADY_EXISTS otherwise).
  • Outbox events (written in the same DynamoDB transaction, published via the integration bus — see Integration bus; the bus is itself gated behind busEnabled):
EventTriggerGroupPayload
workorder.linked.v1create / bulk-create with an alert; :reopen of an alert orderalert/<alertId>{workOrderId, code, orgId, plantId, deviceId?, alertIds, status, priority, createdAt, version}
workorder.completed.v1:close (outcome COMPLETED) and :cancel (single or bulk) of an alert order. Lifecycle v2 (ADR 0023, built, not deployed) moved this from :complete to :close; dev emits it at :complete until the next deployalert/<alertId>{workOrderId, code, orgId, plantId, alertIds, outcome, result?, completedAt?, cancelledAt?, resolutionSummary?, version}

seq = the order version. Completing an order does not close the alert here; TCP decides what to do with the event. 006 consumes no events (plant deletion reaches it as an in-process hook from 004's saga, which makes the plant's orders read-only).

Device operations: command flow (feature 007)​

Removed (ADR 0012). No 007 route is registered; the api-devices-ops stack, command sweep, bulk-task-driver, firmware and engineering-files buckets, command.* events and the commandsDispatchEnabled flag no longer exist in code. Commands, bulk tasks, firmware and device files are served by the TCP server over the WebSocket. The realtime ticket still carries the per-plant commands level, which TCP enforces (Realtime tickets).

Notifications (planned)​

Feature 008 adds push tokens, notification rules and settings here, and publishes them as projections to the TCP Server, which sends push. The routes are registered in code (stack cse-http-be-<stage>-api-notify) and live after the owner's next deploy; the NotifyStack workers (cse-http-be-<stage>-notify) are built but opt-in (-c busEnabled=true) and not deployed; large audience changes are queued to notify-recompute when it exists, otherwise synchronous (Q36) — see Notifications architecture.

Sign out everywhere (feature 010)​

POST /v1/me/sessions:end-all (see Account settings API):

  1. One DynamoDB transaction sets profile.tokensValidAfter = now (forward only) and writes an outbox item access.revoked.v1 { scope: USER, sub, reason: END_ALL_SESSIONS }.
  2. Only after the commit, the IdentityProvider calls Cognito AdminUserGlobalSignOut (revokes refresh tokens). A Cognito failure → 503; a retry with the same Idempotency-Key repeats both steps safely.
  3. Any access/ID token issued before tokensValidAfter gets 401 SESSION_REVOKED on its next call, in every org. Sign-in records are not rewritten; their status is derived from tokensValidAfter when listed.
  4. (2026-11-12, not deployed) Best-effort: every sign-in's pointer (SESSIONJTI#<origin_jti>) is marked ended, so the per-route sign-in guard refuses its tokens on every route, including routes that never read the profile watermark.

The outbox event reaches the TCP side only when the integration bus is deployed (busEnabled, off by default). Until then, open WebSocket streams are not cut by this call; they end when their token expires.