BreezRx · Architecture record · Read mode

Technical Design & Implementation Plan

A principal-architect view of the BreezRx platform: what the local investor proof of concept (POC) does today, what it deliberately does not do, and the proposed path to a US-first, regulated, direct-to-consumer prescription service, with GLP-1 as the flagship category.

0. Current implementation (v0.2 commerce platform)

Supersedes the POC sections

v0.2 replaces the v0.1 SQLite proof of concept with a PostgreSQL commerce platform. Sections 5, 6.1, 7, 9 and 10.1 below describe that historical v0.1 POC. Where they conflict with this section, this section is authoritative. Everything here is Implemented and verified by the API integration suite (PGlite) and Playwright end-to-end runs against the Docker stack, on desktop and iPhone 13.

0.1 Runtime

ServiceTechnologyNotes
dbPostgreSQL 16 (alpine)Named volume breezrx_pg-data. Bound to 127.0.0.1:5544 for inspection. Health-checked with pg_isready.
apiNode 22, Express 5, pgApplies SQL migrations (apps/api/migrations) at boot, guarded by an advisory lock. Seeds the product catalog only. Runs an in-process renewal scheduler (SCHEDULER_INTERVAL_MS). Not published to the host.
webNext.js 16 / React 19App Router storefront. Same-origin /api/* rewrite to the API. Published on 127.0.0.1:3100.

0.2 Data model

Money is integer cents and timestamps are timestamptz. Every externally originated record carries provider and livemode, so sandbox records remain identifiable after go-live. Nothing transactional is seeded: all rows come from API calls.

TablePurpose / key constraints
users, sessionsscrypt password hashes. Sliding 30-day sessions stored as SHA-256 token hashes in an HttpOnly brx_session cookie.
addressesSoft-archived, so historical orders keep their references. At most one default per user.
payment_customers, payment_methodsProvider customer and payment-method references plus display metadata (brand, last4, expiry, billing address). Never a card number or CVC.
products, cart_itemsCatalog with allowed autoship intervals and an autoship discount in basis points. One cart line per product (one-time or subscription).
evaluations, prescriptionsQuestionnaire answers and rule flags. Clinician decision. Prescriptions track fills authorized/remaining and expiry; status ∈ active/exhausted/expired/revoked.
orders, order_items, order_eventsSnapshotted prices, address and tax. A unique (user_id, idempotency_key) plus a request fingerprint. Source is checkout or subscription_renewal. Status ∈ awaiting_evaluation/confirmed/packed/shipped/delivered/cancelled.
payments, payment_eventsOne payment per order: authorized → captured / voided / refunded / failed. Append-only provider ledger.
shipmentsCarrier and tracking from the fulfillment provider.
subscriptions, subscription_eventsPrice locked at signup, interval, quantity, shipping method, address, card, linked prescription and next_order_at. Status ∈ pending_evaluation/active/paused/past_due/cancelled. A partial index on due rows.
audit_logActor (customer/staff/system), action and entity for every state change.
mock_gateway.*The sandbox processor's own state (customers, single-use tokens, payment methods, intents) in a separate schema that can be dropped at go-live.

0.3 Key flows

  • Card capture: the browser posts card fields to /api/mock-gateway/v1/tokens (standing in for processor hosted fields) and receives a single-use token. POST /payment-methods exchanges it for a customer-attached payment method.
  • Checkout: POST /checkout requires an idempotencyKey. The server re-prices the cart and creates a payment intent outside the database transaction, like a remote processor call. It captures immediately for non-Rx orders and authorizes only when any line awaits clinician review. A replay returns the original order with Idempotent-Replayed: true. A different payload under the same key returns 409.
  • Evaluation: Rx products need an evaluation before checkout. Approval issues a prescription, confirms the waiting order, captures the authorization and activates any pending subscription. Decline cancels the order and voids the authorization.
  • Autoship renewals: the scheduler claims due subscriptions with FOR UPDATE SKIP LOCKED. Each renewal re-checks prescription fills, charges the saved card with an idempotency key derived from the subscription and cycle, creates a renewal order and advances next_order_at. A declined card moves the subscription to past_due, and an exhausted prescription pauses it pending re-evaluation.
  • Security: non-GET requests need the x-breezrx-client header (CSRF defense alongside SameSite=Lax). Helmet, rate limiting, zod validation and structured errors {error:{code,message,param}} apply throughout. /ops/* is open to any signed-in user in the demo Open decision; production requires staff authentication with RBAC (see §15).

0.4 REST surface (/api)

auth/signup|login|logout|session · me · account/summary · addresses[/:id] · payment-methods[/:id[/default]] · mock-gateway/v1/tokens · catalog[/:slug] · cart, cart/items[/:productId], cart/merge · checkout/quote, checkout · orders[/:id[/cancel]] · evaluations · prescriptions · questionnaires/:category · subscriptions[/:id[/pause|resume|skip|cancel|ship-now]] · ops/overview, ops/evaluations/:id/decision, ops/orders/:id/advance, ops/subscriptions/:id/make-due, ops/scheduler/run · graphql (read-only).

0.5 Provider seams

PaymentProvider (src/payments/provider.ts) and ClinicalProvider, FulfillmentProvider and TaxProvider (src/integrations.ts) are the only integration points, wired in src/services.ts. The production integration register maps each one to candidate vendors.

1. Status labels & honesty statement

Each capability in this document has one status label. The POC is an investor demonstration. It is not a pharmacy, not a medical service and not a production system.

Implemented code exists in the repository (source-observed); tests by the parent confirm it POC contract agreed local behavior; the parent session confirms it against the code and tests Proposed production design, not built Target numeric goal, not measured or achieved Open decision needs a business, legal or vendor decision
Snapshot caveat

This document was written while the POC was being built in parallel. Sections 6.1, 7, 8.1 and 10.1 were checked against the API source in apps/api/src (db.ts, store.ts, app.ts, schemas.ts, graphql.ts) at writing time and are labeled Implemented. The backend build session confirmed them: build and typecheck pass, 11 API tests pass, and the API container is healthy on internal port 4000. Verified facts include the 400/413/422/409/429 error codes, the replay behavior (201 + Idempotent-Replayed: true), the response shapes, and introspection being off in production. Full Docker and browser verification is the parent session's next step. Front-end behavior reported by the build session (the synthetic session user is “Avery Demo”): editorial and compact modes switched from a discreet profile menu and saved in the browser; no real profile or PII fields; a fixed synthetic shipping address. Docker Compose project breezrx publishes 127.0.0.1:3100 → web:3000 and keeps the API internal. Anything labeled Proposed is not built. Do not present it to investors as a feature.

Capability honesty matrix
CapabilityLocal POCProduction
Catalog of products (GLP-1 flagship + wider Rx/wellness)Implemented seeded synthetic SQLite rows, invented pricesProposed drug compendium + formulary + pricing service
Customer identityImplemented one shared synthetic demo identity. No authenticationProposed OIDC (only once BAA and service eligibility are confirmed), MFA, WebAuthn
Medical intakeImplemented scenario selector (eligible/needs_review) and a consent flag. No real medical questions are storedProposed versioned clinical questionnaires reviewed by licensed clinicians
PrescriptionImplemented a simulated review record, created with the intake, that a demo operator approves or declinesProposed clinician-signed eRx through a vetted partner, plus pharmacist verification
PaymentsImplemented none. Totals are display-only and no card data is requestedProposed Stripe or another approved processor: authorize after eligibility, capture before lawful dispense
Fulfillment & trackingImplemented manual "advance" through simulated statusesProposed pharmacy management system, lots, FEFO, cold chain, carrier webhooks
Documents / OCR / EHR / telehealthNot in POC no uploads acceptedProposed PHI vault with AV quarantine; OCR is assistive only; FHIR and telehealth through partners
ComplianceNo claimOpen decision HIPAA program, SOC 2 audit, state licensure, GDPR applicability

2. Scope, principles & non-goals

In scope (POC)

  • Elegant storefront with editorial and compact modes
  • Guided care flow → simulated intake → order
  • Simulated pharmacist review queue and fulfillment advance
  • Persistent local SQLite with seed data and a reset path
  • Docker Compose project breezrx: host 127.0.0.1:3100 → web container :3000; API internal only on :4000

Explicit non-goals (POC)

  • Real authentication, identity proofing or government ID checks
  • Collecting real PHI, documents, insurance or payment data
  • EHR, OCR, eRx, telehealth, carrier or payment integrations
  • Any compliance, licensure or efficacy claim

Architectural principles

  • A purchase is never a prescription. Clinical decisions are explicit and attributable
  • Writes go through REST commands; reads can use GraphQL projections
  • Every money or clinical mutation is idempotent and audited
  • Minimize PHI and log no PHI
  • Build a modular monolith first, then extract services in stages

Stack decisions (ADR summary)

ADRDecisionRationaleStatus
ADR-001TypeScript throughout; Next.js 16 / React 19 web appOne language, server components, standalone output for containersPOC contract
ADR-002Separate Express 5 API on Node 22Deploys independently from the web app; mirrors the production service seam; the web app proxies /api/* internallyImplemented
ADR-003GraphQL for reads, REST for writesCommands get explicit idempotency, status codes and audit. Queries get flexible projectionsImplemented
ADR-004Node built-in node:sqlite on a Docker volumeNo native build step and zero ops. Persistent synthetic data. Not for productionImplemented
ADR-005AWS: EKS, Aurora PostgreSQL, ElastiCache Redis, S3 SSE-KMS, KMSManaged, widely BAA-covered services. Eligibility is confirmed per service before useProposed
ADR-006Transactional outbox → SQS workers; Temporal for long-running sagasReliable side effects; compensation for clinical and payment flowsProposed Open decision Temporal Cloud vs self-hosted vs Step Functions
ADR-007Vetted partners for eRx (Surescripts network), FHIR/EHR, telehealth, pharmacyCertification, network access and licensure are not built in-houseOpen decision

3. System context

3.1 Local POC (Docker)

POC local runtime topologyBrowser on host loopback port 3100 reaches the web container on port 3000, which proxies /api to the internal API on port 4000, which writes SQLite on a named volume.Host (loopback only)Docker Compose project “breezrx” · private networkBrowserlocalhost:3100web · Next.js 16container :3000React 19 · standaloneapi · Express 5Node 22 · :4000internal onlydemo-datavolume /databreezrx.sqlite127.0.0.1:3100→ :3000/api/* rewritenode:sqliteWALAPI_INTERNAL_URL=http://api:4000no host port · DEMO_MODE=true
Figure 1. POC runtime. The browser reaches only the web container: host loopback port 3100 is mapped to container port 3000. Host port 3000 was left alone because an unrelated service already uses it on the reference machine. The API listens on 4000 inside the Compose network and is not published to the host.

3.2 Proposed production (AWS)

Proposed production context on AWSClients reach CloudFront and WAF or zero-trust access, then an ALB in a private VPC routing to web and API pods, domain services, async workers, Aurora, Redis, S3 vaults and KMS, with undecided external partners.AWS VPC · 3 AZs · private subnets (proposed)Customerbrowser / appOps staffclinician · RPhCloudFront+ WAFZero-trustaccess + SSOALBLB controllerwebNext.js podsapi / BFFREST · GraphQL/apiIdentityCatalogOrdersClinicalPharmacyPaymentsoutbox → SQSTemporal (TBD)workerssagas · webhooksAuroraPostgreSQL · CMKElastiCacheRedis · sessionsS3 PHI vaultSSE-KMS · AV firstS3 audit WORMObject LockKMS · Secretsper data classOIDC IdP*BAA + eligibilityeRx · FHIR*telehealth partnersPharmacy*carriers · cold chainPayments PSP*no PHI metadata* undecided partners
Figure 2. Proposed production context. Dashed amber boxes are external partners still to be chosen, each under a BAA or other contract. Nothing in this figure is deployed.
Mermaid source: production context
flowchart LR
  subgraph Clients
    C[Customer browser / app]
    O[Operations console]
  end
  C --> CF[CloudFront + WAF] --> ALB
  O --> ZT[Zero-trust access] --> ALB
  subgraph AWS_VPC[AWS VPC - private subnets]
    ALB --> WEB[web: Next.js]
    WEB --> BFF[api gateway / BFF]
    BFF --> CAT[catalog] & ORD[orders] & CLIN[clinical] & PH[pharmacy] & PAY[payments] & ID[identity]
    ORD --> OUT[(outbox)] --> SQS[[SQS / Temporal]] --> WRK[workers]
    CAT & ORD & CLIN & PH & PAY --> PG[(Aurora PostgreSQL)]
    BFF --> R[(ElastiCache Redis)]
    CLIN --> S3[(S3 PHI vault SSE-KMS)]
    AUD[audit] --> WORM[(S3 Object Lock)]
  end
  ID --- IDP{{OIDC provider*}}
  CLIN --- ERX{{eRx / FHIR / telehealth partners*}}
  PH --- PMS{{pharmacy system / carriers*}}
  PAY --- PSP{{payment processor*}}

4. Domain boundaries & data ownership

Each bounded context owns its tables. Other contexts read through APIs, events or read models, and never through cross-schema joins. The POC keeps all tables in one SQLite file. Its modules should still follow these seams so they can be extracted later.

ContextOwns (authoritative)PublishesPHI?Production team owner
Identity & Consentaccounts, credentials refs, MFA/WebAuthn public keys, consents, legal acceptancesaccount.created, consent.granted/withdrawnIdentifiers (PII)Platform/Identity
Catalog & Pricingproducts, SKUs, NDC mapping, price books, state availabilityproduct.changedNoCommerce
Clinical Intakequestionnaire versions, intake responses, eligibility outcomesintake.submitted, intake.flaggedYesClinical Eng
Care & Prescribingencounters, clinician decisions, prescriptions, refill authorizationsrx.signed, rx.declined, rx.cancelledYesClinical Eng + Medical Director
Pharmacy Fulfillmentverification, inventory lots, reservations, dispense, shipments, quarantinedispense.completed, shipment.*, lot.recalledYesPharmacy Ops Eng + PIC
Ordersorders, order lines, subscriptions, status historyorder.*Limited (product implies condition)Commerce
Paymentspayment intents (token refs only), captures, refunds, ledgerpayment.authorized/captured/voided/refundedNo (by design; no PHI metadata)Payments
Documentsobject refs, scan state, retention classdocument.clean/quarantinedYesPlatform Security
Auditappend-only audit events, WORM exportnoneRefs only, no PHI payloadsSecurity
Notificationstemplates, delivery lognoneMinimal: "you have a message"Platform
Why "orders" carries limited PHI

Under HIPAA, a GLP-1 product name tied to an identifiable person can be PHI. Treat order data as PHI for access control and logging, even though payment records deliberately exclude product names (see §14).

5. POC architecture Historical v0.1

apps/web: Next.js 16

Storefront: editorial / compact modes, switched from the profile menu and saved in browser storage
Guided care flow (full page); fixed synthetic shipping address, no profile/PII fields
Orders and tracking timeline
Pharmacy workspace (simulated operator)
Rewrite /api/* → API_INTERNAL_URL

apps/api: Express 5

REST commands with zod validation
GraphQL read endpoint (graphql 16)
helmet, rate limiting, JSON size limit
Idempotency via orders.idempotency_key + audit_log
DEMO_MODE=true guard

SQLite: node:sqlite

File on Docker volume: /data/breezrx.sqlite
WAL mode, foreign keys ON
Idempotent seed on startup
Synthetic rows only

Request path

Browser127.0.0.1:3100 → :3000 web (Next.js)rewrite /api/* api:4000 (internal)sync, txn SQLite volume

POC safeguards

  • The UI shows a persistent "Demo, synthetic data" indicator. Checkout never renders card fields.
  • The API refuses to start unless DEMO_MODE=true is set explicitly (config.ts). Implemented (verified)
  • Free-text input stays minimal and bounded. Intake uses a scenario enum, not medical questions.
  • Rate limiting and body-size limits stop accidental abuse of a demo left running on a laptop.
  • Security headers: the web app sets X-Frame-Options: DENY, nosniff, Referrer-Policy and Permissions-Policy (camera, mic and geolocation off). This is in next.config.ts at writing time, plus helmet on the API.

6. Data model & ERD

6.1 POC logical schema (SQLite)

Implemented (verified) This is schema version 1 in apps/api/src/db.ts. It is applied idempotently on startup with PRAGMA foreign_keys=ON, journal_mode=WAL and busy_timeout=5000. The database file is DATABASE_PATH, which is /data/breezrx.sqlite in the container, on a named volume. Money is integer cents. Timestamps are ISO-8601 UTC text. IDs are prefixed opaque strings (ord_…, rx_…, intake_…).

POC SQLite entity relationship diagramTables users, products, intakes, prescriptions, orders, order_events and audit_log with keys and check constraints.usersidPKnameemailUQproductsidPKslugUQnamecategoryCKtaglinedescriptionprice_centsCK ≥0intervalCK 'month'prescription_requiredCK 0|1formaccentsort_orderintakesidPKuser_idFKproduct_idFKscenarioCKstatusCK pendingconsented_atcreated_atprescriptionsidPKintake_idFK · UQuser_idFKproduct_idFKscenarioCKstatusCKorder_idFK · UQcreated_atreviewed_atordersidPKuser_idFKproduct_idFKproduct_namesnapshottotal_centsCK ≥0statusCK 6 valuessubscriptionCK 0|1shippingCK demo_homeintake_idFK · UQidempotency_keyUQrequest_fingerprintcreated_atupdated_atorder_eventsidPKorder_idFKseqUQ(order_id,seq)statuslabelataudit_logidPKseqUQactionentity_idno FKcreated_atSolid and dashed lines are both FKs;dashing only separates crossing paths.Not drawn: prescriptions.user_id,prescriptions.product_id, orders.user_id.audit_log.entity_id is polymorphic.
Figure 3. POC ERD as implemented. PK = primary key, FK = foreign key, UQ = unique. Lines connect a child FK to its parent. The review record (prescriptions) is created at intake time, and order_id is filled in once an order is placed.
Mermaid source: POC ERD
erDiagram
  USERS ||--o{ INTAKES : submits
  USERS ||--o{ ORDERS : places
  USERS ||--o{ PRESCRIPTIONS : "subject of"
  PRODUCTS ||--o{ INTAKES : "for"
  PRODUCTS ||--o{ ORDERS : "snapshot of"
  PRODUCTS ||--o{ PRESCRIPTIONS : "for"
  INTAKES ||--|| PRESCRIPTIONS : "creates review (UQ intake_id)"
  INTAKES ||--o| ORDERS : "used once (UQ intake_id)"
  ORDERS ||--o| PRESCRIPTIONS : "linked (UQ order_id)"
  ORDERS ||--|{ ORDER_EVENTS : "tracking (UQ order_id,seq)"
  PRODUCTS {
    text id PK
    text slug UK
    text category "CHECK 4 values"
    int price_cents "CHECK >= 0"
    text interval "CHECK = month"
    int prescription_required "0|1"
    int sort_order
  }
  ORDERS {
    text id PK
    text user_id FK
    text product_id FK
    text product_name "snapshot"
    int total_cents "CHECK >= 0"
    text status "CHECK 6 values"
    int subscription "0|1"
    text shipping "CHECK = demo_home"
    text intake_id FK "UNIQUE, nullable"
    text idempotency_key UK
    text request_fingerprint
  }
  PRESCRIPTIONS {
    text id PK
    text intake_id FK "UNIQUE"
    text status "pending_review|approved|declined"
    text order_id FK "UNIQUE, nullable"
    text reviewed_at
  }
  AUDIT_LOG {
    text id PK
    int seq UK
    text action
    text entity_id
  }
POC tables (implemented), constraints and owner modules
TableKey constraintsOwner module
productsPK id; UNIQUE slug; CHECK category IN ('Weight care','Everyday health','Skin & hair','Wellness'); CHECK price_cents ≥ 0; CHECK interval = 'month'; CHECK prescription_required IN (0,1); sort_ordercatalog (seeded)
usersPK id; UNIQUE email. One seeded synthetic demo user. No credentialsidentity (demo)
intakesFK user_id, product_id; CHECK scenario IN ('eligible','needs_review'); CHECK status = 'pending_review'; consented_at NOT NULL (consent must be literal true at the API)intake
prescriptionsSimulated review record. UNIQUE intake_id; UNIQUE order_id (nullable); CHECK status IN ('pending_review','approved','declined'); reviewed_atclinical (simulated)
ordersFK user_id, product_id; UNIQUE intake_id (an intake is used at most once); UNIQUE idempotency_key; request_fingerprint; CHECK status IN (awaiting_review, approved, ready_to_ship, shipped, delivered, declined); CHECK shipping = 'demo_home'; CHECK total_cents ≥ 0; INDEX (user_id, created_at)orders
order_eventsFK order_id; UNIQUE (order_id, seq); status, label, at. Serves as trackingEventsorders
audit_logUNIQUE seq; action, entity_id, created_at. No free text and no PHI. Append-only in codeaudit

6.2 Proposed production schema (Aurora PostgreSQL)

Each context gets one PostgreSQL schema and its own database role. Cross-schema foreign keys are not allowed, so references across contexts are ID values checked by the owning service. The tables below are the high-value invariants.

Schema.tableNotable constraints / invariants
identity.accountsUUID PK; citext email UNIQUE where deleted_at IS NULL; state_of_residence CHECK in supported launch states
identity.webauthn_credentialscredential_id bytea UNIQUE; public_key bytea; sign_count bigint; no biometric data
identity.consents(account_id, purpose, version) UNIQUE; granted_at, withdrawn_at; purposes: telehealth, HIPAA notice acknowledgement, marketing (separate, opt-in), research (separate)
intake.responsesquestionnaire_version FK; answers jsonb; encrypted columns for sensitive answers (app-level envelope)
care.prescriptionsprescriber_npi NOT NULL; signed_at NOT NULL; signature_ref NOT NULL; refills_authorized ≥ 0; expires_at; status enum; one active Rx per (patient, drug, strength) via partial unique index
care.refill_authorizationsCHECK refills_remaining ≥ 0; earliest_fill_at; decremented only inside the dispense transaction
pharmacy.lots(ndc, lot_number) UNIQUE; expiry_date NOT NULL; qty_on_hand ≥ 0; state enum (available, quarantined, recalled, expired, destroyed)
pharmacy.reservationsFK lot; qty > 0; expires_at; EXCLUDE or SUM check enforced by SELECT … FOR UPDATE SKIP LOCKED allocation
pharmacy.dispensesrx_id, lot_id, verified_by_pharmacist NOT NULL, verified_at; immutable after insert
pharmacy.shipmentscold_chain boolean; temp_excursion boolean; carrier_tracking_ref
orders.ordersstatus enum with transition trigger; version int; idempotency_key UNIQUE per account
payments.payment_intentspsp_ref UNIQUE; amount_cents; state enum; no product name, no diagnosis, no Rx data
platform.outboxid, aggregate, type, payload (no PHI beyond IDs), created_at, published_at NULL; dispatched by worker
audit.eventsInsert-only grant; hash chain (prev_hash) for tamper evidence; streamed to S3 Object Lock

7. API contract (REST writes, GraphQL reads)

Base path: /api. The browser calls same-origin /api/* on the web container, which proxies to the API through a Next.js rewrite to API_INTERNAL_URL. Request bodies must be application/json, at most 16 KB, and pass strict zod schemas (unknown keys are rejected). Writes have a separate, stricter rate limit (default 60/min; reads 300/min). Every response carries an X-Request-Id header. Implemented (verified)

Endpoints (implemented)
Method & pathRequestSuccessNotes
GET /api/healthnone200 {status:"ok", demo:true}Used by the container HEALTHCHECK
GET /api/catalognone200 {products: Product[]}8 seeded synthetic products (GLP-1 flagship plus others such as omega-3 and calm-sleep), sorted by sort_order
GET /api/sessionnone200 {user:{id,name,email}, demo:true}. The seeded user is the synthetic “Avery Demo”Not authentication. Every visitor shares one synthetic identity
POST /api/intakes{productId, scenario:'eligible'|'needs_review', consent:true}201 {intake:{id, productId, status:'pending_review'}}Creates the intake and a pending review record in one transaction. A non-Rx product returns 422 intake_not_applicable
POST /api/orders{productId, intakeId?, shipping:'demo_home', subscription:boolean, idempotencyKey}201 {order}; a replay returns the same order with the header Idempotent-Replayed: trueRx: requires the intake for the same product, unused and not declined. Non-Rx: an intakeId is rejected
GET /api/ordersnone200 {orders: Order[]}The demo user's orders
GET /api/operationsnone200 {prescriptions, orders, audit}Simulated pharmacist workspace. Unauthenticated by design, demo only
POST /api/prescriptions/:id/review{decision:'approve'|'decline'}200 {prescription, order|null}Only from pending_review. Can happen before the order exists
POST /api/orders/:id/advancenone200 {order}approved→ready_to_ship→shipped→delivered; anything else returns 409
POST /api/graphql{query, variables?, operationName?}200 {data}Read-only. Other methods return 405 method_not_allowed

7.1 Resource shapes

type Product = {
  id: string; slug: string; name: string;
  category: "Weight care" | "Everyday health" | "Skin & hair" | "Wellness";
  tagline: string; description: string;
  priceCents: number;          // synthetic demo price, integer cents
  interval: "month";
  prescriptionRequired: boolean;
  form: string;                // e.g. "Weekly pen" (synthetic)
  accent: string;              // UI color token
};

type Order = {
  id: string; productId: string; productName: string;
  totalCents: number;
  status: "awaiting_review" | "approved" | "ready_to_ship" | "shipped" | "delivered" | "declined";
  createdAt: string;           // ISO-8601 UTC
  trackingEvents: { status: string; label: string; at: string }[];
};

7.2 Error envelope

Implemented (verified) {"error":{"code","message"}}, where codes are snake_case and messages are safe to show to people. The request ID is in the X-Request-Id header. Stack traces and SQL are never returned.

HTTP/1.1 409 Conflict
Content-Type: application/json
X-Request-Id: 3f0c…

{ "error": { "code": "invalid_transition",
             "message": "An order that is awaiting_review cannot be advanced." } }
HTTPcodeWhen
400validation_errorzod failure: unknown key, bad enum, consent not true, malformed idempotencyKey or ID
404not_foundUnknown order or prescription in a path
405method_not_allowedNon-POST to /api/graphql
409invalid_transitionAdvancing awaiting_review, declined or delivered; reviewing a decided prescription; a lost compare-and-set race
409idempotency_conflictSame idempotencyKey with a different request fingerprint
409intake_already_used / prescription_declinedReusing an intake; ordering after a decline
422unknown_product, intake_required, invalid_intake, intake_product_mismatch, intake_not_applicableBusiness-rule failures
413(payload too large)JSON body over 16 KB
429rate-limit code from the limiter handlerRead or write limit exceeded (draft-8 RateLimit headers)
500internal_errorUnexpected error. The log has the request ID, not the body

7.3 Idempotency

POC (source-observed)

  1. The client generates an idempotencyKey (8–128 characters from [A-Za-z0-9_.:-]) once per checkout attempt and reuses it on retry.
  2. Inside BEGIN IMMEDIATE, the server looks up orders.idempotency_key (globally UNIQUE).
  3. If a row exists and its request_fingerprint (JSON of productId, intakeId, shipping and subscription) matches, the server returns the stored order with 201 and Idempotent-Replayed: true. If the fingerprint differs, it returns 409 idempotency_conflict.
  4. The order, the first tracking event, the prescription link and the audit row are written in that same transaction. A crash rolls everything back.

Proposed for production: an Idempotency-Key header scoped per account and route; a separate idempotency_keys table (stored status code + body, SHA-256 fingerprint, 24 h orders and 7 day payments TTL); a Redis in-flight lock (SET NX) returning 409 request_in_progress; and the same pattern on every payment and clinical command.

7.4 Concurrency

POC Writes are serialized by SQLite BEGIN IMMEDIATE transactions. State changes use a compare-and-set on the current status (UPDATE … WHERE id=? AND status=?). If zero rows change, the API returns 409 invalid_transition. Proposed Production adds an explicit version column for optimistic concurrency, and pessimistic row locks only for inventory allocation (§13).

8. State machines

8.1 Order lifecycle Implemented (verified)

awaiting_reviewreview: approve approvedadvance ready_to_shipadvance shippedadvance delivered
awaiting_reviewreview: decline declined (terminal)
Transition table (anything not listed → 409 invalid_transition)
FromTriggerToGuard / side effects
(intake)POST /intakes (Rx product)review = pending_reviewThe review record is created with the intake; scenario is stored as a reviewer hint
(new)POST /orders, Rx, review pendingawaiting_reviewIntake for the same product and not yet used; links prescriptions.order_id
(new)POST /orders, Rx, review already approvedapprovedReview happened before checkout
(new)POST /orders, Rx, review declined—409 prescription_declined; no order created
(new)POST /orders, non-Rx productapprovedAn intakeId is rejected (422)
awaiting_reviewreview approveapprovedReview → approved; reviewed_at; order event; audit
awaiting_reviewreview declinedeclinedTerminal. Production would void the payment authorization (§14)
approvedadvanceready_to_shipProduction guard: pharmacist verification, dispense recorded, payment captured
ready_to_shipadvanceshippedProduction: carrier label and shipment event
shippedadvancedeliveredProduction: carrier delivery webhook only, not a manual action
awaiting_review / declined / deliveredadvance—Rejected 409. Clinical review cannot be skipped

8.2 Production prescription lifecycle Proposed

intake_submittedroute clinician_reviewsync/async visit signedeRx transmit received_by_pharmacyPV1 / DUR verifieddispense active (refills n)

Side branches: declined, needs_info (back to the patient), cancelled (CancelRx), expired, exhausted, on_hold (safety or recall).

9. Sequence diagrams

9.1 POC: Rx checkout (needs review)

POC Rx checkout sequenceCustomer submits intake then places an idempotent order which lands in awaiting_review.Avery DemosyntheticwebNext.jsapiExpressSQLitechoose GLP-1 · scenario · consentPOST /api/intakes {productId, scenario, consent:true}zod strict validationtxn: intake + review(pending) + audit201 {intake}POST /api/orders {…, idempotencyKey}lookup idempotency_key → noneorder(awaiting_review) + event · COMMIT201 {order}“Awaiting clinical review” (simulated)retry with same key → 201 same order · Idempotent-Replayed: true
Figure 4. Intake and order creation. Everything is synthetic, and no payment is collected.
Mermaid source
sequenceDiagram
  actor U as Demo customer
  participant W as web (Next.js)
  participant A as api (Express)
  participant D as SQLite
  U->>W: Choose GLP-1 product, scenario, consent
  W->>A: POST /api/intakes {productId, scenario, consent:true}
  A->>A: zod validate
  A->>D: BEGIN IMMEDIATE; INSERT intake + prescription(pending_review) + audit; COMMIT
  A-->>W: 201 {intake}
  W->>A: POST /api/orders {productId, intakeId, subscription, idempotencyKey}
  A->>D: BEGIN IMMEDIATE; lookup idempotency_key
  A->>D: INSERT order(awaiting_review), order_event; link prescription; audit; COMMIT
  A-->>W: 201 {order}
  Note over W,A: Retry with same key returns same order

9.2 POC: simulated review and fulfillment

POC review and fulfillment sequenceOperator cannot advance an order awaiting review; approval then advancing to delivered.Demo operatorwebworkspaceapiExpressSQLiteopen pharmacy workspaceGET /api/operations200 {prescriptions, orders, audit}POST /orders/:id/advance (too early)409 invalid_transitionPOST /prescriptions/:id/review {approve}CAS: review + order → approved200 {prescription, order}loop ×3 · approved → ready_to_ship → shipped → deliveredPOST /orders/:id/advanceCAS status → next · event · audit200 {order}
Figure 5. Operator approves, then advances the order. An attempt to advance from awaiting_review returns 409.
Mermaid source
sequenceDiagram
  actor P as Demo operator
  participant W as web workspace
  participant A as api
  participant D as SQLite
  P->>W: Open operations
  W->>A: GET /api/operations
  A-->>W: queue
  P->>W: Advance (too early)
  W->>A: POST /api/orders/:id/advance
  A-->>W: 409 INVALID_TRANSITION
  P->>W: Approve
  W->>A: POST /api/prescriptions/:id/review {approve}
  A->>D: UPDATE prescription, order=approved (CAS), order_event, audit
  A-->>W: 200
  loop until delivered
    W->>A: POST /api/orders/:id/advance
    A-->>W: 200 next status
  end

9.3 Production: order saga with payment and dispense Proposed

Proposed production order sagaAuthorize after eligibility, clinician signs, pharmacist verifies and reserves stock, then capture before dispense, with compensation.OrdersPaymentsClinicalPharmacyProcessor*pre-screen intakeeligible for reviewauthorize(amount, idemKey)confirm · manual captureauthorizedrequest clinician reviewrx.signed (e-signature)PV + FEFO reserveverified · reservedcapturecapturecaptured (signed webhook)dispense + shipalt · declined / out of stock / auth expired → compensatevoid auth or refundrelease reservation
Figure 6. Authorize after eligibility. Capture only once a lawful dispense is assured (pharmacist-verified and stock reserved). Compensation paths are shown in §14.
Mermaid source
sequenceDiagram
  participant O as Orders
  participant P as Payments
  participant C as Clinical
  participant R as Pharmacy
  participant S as PSP
  O->>C: intake eligible?
  C-->>O: eligible (pre-screen)
  O->>P: authorize(amount, idemKey)
  P->>S: create+confirm (manual capture)
  S-->>P: authorized
  O->>C: request clinician review
  C-->>O: rx.signed (clinician e-signature)
  O->>R: verify + reserve lot (FEFO)
  R-->>O: verified, reserved
  O->>P: capture
  P->>S: capture
  S-->>P: captured (webhook, signed)
  O->>R: dispense + ship
  alt declined / out of stock / auth expired
    O->>P: void or refund
    O->>R: release reservation
  end

10. GraphQL: POC read model & production proposal

10.1 POC schema Implemented (verified)

type Query {
  catalog: Catalog!
  products: [Product!]!
  product(id: ID!): Product
  orders: [Order!]!          # demo user's orders
  order(id: ID!): Order
}
type Catalog { products: [Product!]! }
type Product { id: ID! slug: String! name: String! category: String! tagline: String!
  description: String! priceCents: Int! interval: String! prescriptionRequired: Boolean!
  form: String! accent: String! }
type Order { id: ID! productId: String! productName: String! totalCents: Int! status: String!
  createdAt: String! trackingEvents: [TrackingEvent!]! }
type TrackingEvent { status: String! label: String! at: String! }
# No Mutation type: writes are REST-only.

GraphQL errors use the standard GraphQL format {"errors":[{"message","extensions":{"code"}}]}, not the REST error envelope. Guards: POST only; query ≤ 4,000 characters; one operation; depth ≤ 6; ≤ 200 fields; introspection disabled when NODE_ENV=production; sanitized error messages with codes QUERY_TOO_LONG, QUERY_TOO_DEEP and QUERY_TOO_COMPLEX.

10.2 Production proposal Proposed

  • Federated read graph through a gateway (Apollo Federation, GraphQL Mesh or a hand-rolled BFF). Each subgraph is owned by one context. There are no mutations; commands stay REST plus the outbox.
  • Persisted queries only in production: an allow-list of hashed operations, with introspection off outside non-prod.
  • Cost limits: max depth 8, cost budget per operation, pagination required (Relay connections, first ≤ 50).
  • Field-level authorization with @auth(policy:"…") directives. The resolver decides through the policy engine (§15). PHI fields resolve only for patient-self or an authorized clinician or pharmacist with a care relationship.
  • DataLoader batching per request, with no cross-request caching of PHI. Redis caches catalog data only.
  • Enums replace strings for status. Money becomes Money { amountCents: Int!, currency: Currency! }.
type Query {
  catalog(state: USState!, first: Int = 20, after: String): ProductConnection!
  me: Patient @auth(policy: "self")
  order(id: ID!): Order @auth(policy: "order.read")
  opsQueue(filter: QueueFilter!, first: Int!, after: String): WorkItemConnection!
    @auth(policy: "ops.queue.read")
}
type Patient { id: ID! orders(first: Int!, after: String): OrderConnection!
  prescriptions: [PrescriptionSummary!]! @auth(policy: "self|care-team") }

11. Identity, MFA, WebAuthn & biometrics

POC: no real authentication

Everyone shares one synthetic demo identity. The operations workspace is also unauthenticated. This is acceptable only because all data is synthetic and the app is bound to loopback. It must never be exposed to a network or used with real people.

Production proposal Proposed

  • Provider: Amazon Cognito or another OIDC provider. Choose one only after confirming it is covered by a signed BAA and listed as HIPAA-eligible for the intended use. Open decision (INT-ID-01 in the integrations report).
  • Flows: Authorization Code + PKCE. Sessions are server-side (HttpOnly, Secure, SameSite=Lax cookie; Redis session store), with 15-minute idle and 12-hour absolute timeouts for patients and shorter ones for operations.
  • MFA: required for all workforce users. Patients are offered MFA by default and must step up before viewing prescriptions, changing the address or payment method, or exporting data. Preferred factor order: WebAuthn passkey → TOTP → SMS (SMS only as a fallback because of SIM-swap risk).
  • WebAuthn and biometrics: the device's authenticator does the biometric check (Face ID, fingerprint) locally. The server receives only a signed assertion and stores the credential ID, public key, sign count and AAGUID. We never receive, store or process biometric templates. In the UI, say "Sign in with your device's passkey", not "We verify your face".
  • Identity proofing (government ID) goes through a vetted vendor if prescribing rules or fraud controls require it (INT-ID-03). We keep the result and a reference, not the document images, unless retention is legally required.
  • Workforce: SSO from the corporate IdP, with phishing-resistant MFA (FIDO2) mandatory for clinicians, pharmacists and admins. Access reviews run quarterly.

12. Prescription verification, telehealth & refills

12.1 Verification is not OCR approval

Design rule

OCR or ML may pre-fill or flag data from a user-uploaded prescription image. It must never approve, verify or dispense. Only a licensed pharmacist verifies a prescription, and only a licensed prescriber issues one. Electronic prescriptions arriving through a certified eRx network are preferred over images. An uploaded image can be treated as a transfer or lead that the pharmacy confirms with the prescriber, as state law allows.

  • Pharmacist verification (PV) checklist, recorded per item: patient identity match, prescriber license/NPI/DEA as applicable and in-state validity, drug/strength/directions, DUR (interactions, duplicate therapy, contraindications from intake), quantity and days' supply, refills, and signature validity.
  • Every PV action is attributed (who, when, what changed) and audited. Overriding a DUR alert requires a typed reason code.

12.2 Clinician-signed telehealth Proposed

  1. The patient completes a versioned intake. The system pre-screens against hard exclusions (for example contraindications defined by the medical director's protocol). The system cannot approve; it only routes the case.
  2. The case goes to a clinician licensed in the patient's state, using the telehealth partner's encounter (async or sync, as state rules require).
  3. The clinician documents the decision. Approval produces an eRx with the prescriber's credentials applied by the certified eRx system (electronic signature), sent to the dispensing pharmacy.
  4. Declines and requests for more information go back to the patient with a non-clinical-detail notification ("You have a new message").

12.3 Refill safeguards (GLP-1 focus)

  • A refill requires an active Rx with refills_remaining > 0, not expired, and now ≥ earliest_fill_at (days' supply × the policy fraction, e.g. 75%, which is a medical director setting).
  • Before each refill: a check-in questionnaire (side effects, new medications, pregnancy status where relevant, weight trend). Flagged answers send the case to a clinician before dispense.
  • Dose escalation is a new clinical decision by a clinician, never an automatic subscription step.
  • Subscription billing never triggers dispense on its own. The order saga (§14) still requires eligibility, PV and stock.
  • Duplicate-therapy guard: a partial unique index stops two active GLP-1 prescriptions for one patient unless a clinician explicitly overrides.
  • A pharmacy cooldown stops dispenses for the same patient and drug class that are less than N days apart.

13. Inventory, lots, FEFO, recalls & cold chain Proposed

13.1 Allocation (FEFO) and concurrency

-- Reserve qty for an order from the earliest-expiring sellable lot (first expired, first out)
BEGIN;
SELECT id, qty_on_hand - qty_reserved AS free
  FROM pharmacy.lots
 WHERE ndc = $ndc AND state = 'available'
   AND expiry_date > current_date + $min_remaining_shelf_days
 ORDER BY expiry_date, received_at
 FOR UPDATE SKIP LOCKED
 LIMIT 5;
-- choose the first lot with free >= qty; INSERT reservation (expires_at = now()+30m); UPDATE lots SET qty_reserved = qty_reserved + $qty
COMMIT;
  • SKIP LOCKED lets parallel pick workers avoid deadlocks. CHECK constraints (qty_reserved ≤ qty_on_hand) are the last line of defense.
  • Expired reservations are released by a sweeper. Dispense turns a reservation into a decrement in the same transaction as the dispense record and the refill decrement.
  • Minimum remaining shelf life at ship time is a configurable policy. A patient must not receive a pen that expires before the end of its supply period.

13.2 Recalls

  1. A recall notice (manufacturer or FDA) sets the matching lots to recalled. Allocation stops at once because the predicate excludes them.
  2. Open reservations on those lots are cancelled, and the affected orders are reallocated or put on_hold.
  3. A traceability query (lot → dispenses → patients) produces the outreach list for the pharmacist-in-charge. Messages stay PHI-minimal.
  4. The audit trail covers who triggered the recall, the counts affected and outreach completion.

13.3 Cold chain quarantine

  • Many GLP-1 pens need refrigeration before first use. Receiving records the temperature log. Any excursion sets the lot to quarantined until a pharmacist disposes of it (return to stock with a manufacturer stability justification, or destroy).
  • Outbound shipments use validated insulated packaging chosen by route and season. Carrier temperature indicators, or the patient reporting a compromised package, trigger a no-charge replacement workflow and quarantine of the returned item. Returned refrigerated medication is never restocked.
  • Shipments are restricted to service levels and days that avoid weekend dwell (for example no Friday ship for 2-day service).

14. Payments saga Proposed

Rule

Authorize once the intake pre-screen passes. Capture only once a lawful dispense is assured (Rx signed, pharmacist-verified, stock reserved). If capture fails, the order does not ship. Payment metadata sent to the processor must not include product names, conditions or Rx data. Use opaque order IDs and a generic descriptor such as "BreezRx order".

Saga steps and compensation
#StepOwnerCompensation on later failure
1Create order (pending_payment_auth)OrdersCancel order
2Authorize (manual capture, idempotency key)PaymentsVoid authorization
3Clinical review → rx.signedCare(decline) → void auth, notify
4PV + FEFO reservationPharmacyRelease reservation
5CapturePaymentsRefund (if a later step fails after capture)
6Dispense (decrement stock, decrement refills)PharmacyNot reversible. Handle with a pharmacist incident process, not automation
7Ship / deliver (carrier webhooks)PharmacyReplacement or refund policy
  • Authorizations expire (typically about 7 days for card networks; confirm with the processor). If clinical review may take longer, the saga re-authorizes or uses a setup-intent / saved-method pattern. Open decision
  • Run the saga in Temporal (durable timers, retries) or a state table plus SQS workers fed by the transactional outbox. Every step is idempotent and keyed by order_id + step.
  • Webhooks are verified with signatures and timestamp tolerance, de-duplicated by event ID, and processed asynchronously. See the webhook standard.
  • Card data never touches BreezRx servers. The processor's hosted fields or elements keep PCI scope at SAQ A, or A-EP if needed. HSA/FSA eligibility is a separate open item.

15. Operations console: RBAC + ABAC Proposed

Role (RBAC)CanABAC conditions
ClinicianReview intakes, approve/decline, signLicensed in the patient's state; assigned case or care-team; active credential; MFA ≤ 12 h
PharmacistPV, DUR override with reason, dispense release, quarantine dispositionLicensed for the pharmacy location; on shift; cannot verify their own entry (separation of duties)
Pharmacy technicianPick, pack, label, receive stockLocation-scoped. Cannot verify or override
Support agentOrder status, shipping, refunds up to $XNo clinical fields (masked). Break-glass needs a reason and creates an alert
Ops adminConfiguration, user provisioningNo PHI by default. Two-person rule for role grants
AuditorRead audit trailTime-boxed grant

Enforce policy centrally (OPA/Cedar or an equivalent library) with policies-as-code, unit tests and decision logging. Default deny. Every PHI read is audited with its purpose of use.

16. Encryption: why this is not end-to-end encryption

Do not claim E2EE

True end-to-end encryption means only the patient's endpoints hold the decryption keys, so the server cannot read the content. BreezRx clinicians, pharmacists, DUR checks, optional assistive OCR, fraud controls and lawful record-keeping all need server-side access to plaintext. E2EE therefore conflicts with how the service must work. TLS protects data in transit, and KMS envelope encryption protects data at rest. Neither is E2EE, and marketing must not describe them that way.

In transit

TLS 1.2+ (prefer 1.3) at CloudFront/ALB, TLS between services (mesh mTLS or ALB→pod TLS) and TLS to Aurora/Redis. HSTS with preload once the domain is stable.

At rest

Aurora, EBS, S3, Redis and backups encrypted with KMS customer-managed keys, one key per data class. S3 PHI vault uses SSE-KMS with bucket keys, and policies deny non-TLS access and unencrypted PUT.

Application-level envelope

The highest-sensitivity fields (intake answers, ID references) are encrypted with data keys from KMS (GenerateDataKey) and an encryption context of {tenant, table, purpose}. Only trusted clinical services have kms:Decrypt under that context.

Scoped decryption

Decryption happens only in clinical and pharmacy services, for an authorized principal with a recorded purpose. Analytics, support and logging pipelines get tokenized or de-identified data.

Document vault with AV quarantine (future)

client upload (pre-signed PUT)size/type limits s3://quarantineevent → scanner AV + content-type sniffclean s3://phi-vault (SSE-KMS)

Infected or invalid files move to an isolated bucket with no read access for applications, and security is alerted. Pre-signed URLs are short-lived (≤ 5 minutes), and downloads go only to authorized clinicians. The POC accepts no uploads.

17. Audit (WORM) & logging without PHI

  • Audit events record actor, actor role, action, resource type, resource ID, purpose of use, decision (allow/deny), request ID, IP hash and timestamp. They never contain field values from clinical records.
  • Tamper evidence: an insert-only DB grant plus a hash chain. Events stream to S3 with Object Lock in compliance mode (WORM). The retention period comes from a legal decision; plan for at least 6 years for HIPAA documentation and confirm state pharmacy record rules.
  • Application logs: structured JSON with allow-listed fields only. A redaction middleware drops request bodies by default, and CI has a lint rule against logging req.body. A PHI canary test fails the build if synthetic PHI markers appear in captured logs.
  • Traces and metrics: no PHI in span attributes or metric labels. Use opaque IDs only.
  • Third-party telemetry (analytics, session replay, error tracking): off on authenticated and clinical pages unless the vendor signs a BAA and the data is minimized. Session replay never runs on intake.
  • POC: the audit_log table records demo actions (action, entity ID, time). Structured JSON request logs carry the request ID, method, route, status and duration, without bodies. Implemented (verified)

18. Regulatory posture (no certification claims)

Not legal advice

This section frames engineering obligations. Counsel and qualified compliance staff must confirm every applicability decision.

TopicCorrect framingEngineering implication
HIPAAThere is no official HIPAA certification. Compliance is an ongoing program: risk analysis, safeguards, policies, training, BAAs and breach procedures. Third-party attestations exist but are not government certification.Security risk analysis before PHI; access controls; audit; encryption; contingency plan; minimum-necessary
BAAA BAA is necessary but not sufficient. It allocates responsibilities, and only some services or configurations are covered (for example AWS HIPAA-eligible services list).Use only BAA-covered and eligible services for PHI; configure them correctly; check each vendor (see integrations report)
SOC 2An independent CPA firm's audit against the Trust Services Criteria. Type I covers a point in time, and Type II an observation period. We cannot "be SOC 2" without that audit.Evidence automation, change management, access reviews and vendor management from MVP onward
State pharmacy & telehealthPharmacy licensure (resident and non-resident) and prescriber licensure per patient state. Telehealth prescribing and consent rules vary by state.Launch-state gating in catalog and intake; license data model; state rules engine
FDA / compoundingWhether compounded GLP-1 products can lawfully be offered depends on current FDA policy and state law, which change.Catalog flags and legal sign-off per SKU. No efficacy claims. Use FDA-approved labeling where applicable
Advertising / platformsPayment processors, ad networks and app stores may require pharmacy or telehealth certification, for example via LegitScript-type programs.Track as integration dependencies
GDPR (if ever in scope)The US-first launch may still trigger GDPR through EU-targeted offerings or monitoring. If it applies: Article 6 legal basis and an Article 9 condition for health data, a DPIA, records of processing, data subject rights, residency choices, and transfer mechanisms (SCCs or adequacy, plus a transfer impact assessment).Geo-scoped launch; region-aware data stores; DSR tooling; do not reuse US consent text
US state privacyConsumer health data laws (for example Washington MHMDA) can apply to non-HIPAA data such as browsing or marketing data.Separate consent for health-data collection outside HIPAA scope; no ad pixels on health pages

19. SLOs, RTO/RPO & performance budgets

All figures are Target. None has been measured. The POC has no SLOs; it is a single-host demo.

Availability (storefront + checkout)

99.9%

Monthly. Error budget ≈ 43 min/month.

Clinical + pharmacy console

99.9%

During staffed hours. Degraded mode: read-only queue.

RPO / RTO (Tier 1 data)

≤ 5 min / ≤ 1 h

Aurora PITR plus cross-region snapshot copy. Confirmed by a quarterly restore drill.

Audit store

RPO ≈ 0

Synchronous write to the DB plus a stream to S3 Object Lock within 5 minutes.

Performance budgets (targets)
SurfaceBudgetMeasured by
Storefront LCP (p75, mobile 4G)≤ 2.5 sRUM (no PHI) + Lighthouse CI
INP (p75)≤ 200 msRUM
CLS≤ 0.1Lighthouse CI
Initial JS (storefront route)≤ 170 KB gzipBundle analyzer gate
GET /catalog p95 (server)≤ 150 msk6 + APM
POST /orders p95 (excluding PSP)≤ 400 msk6
GraphQL operation p95≤ 300 msAPM
Ops queue load≤ 1 s for 500 itemsPlaywright trace
Throughput, launch50 orders/min sustained, 5× burstk6 soak 2 h

20. Test strategy

LayerPOCProduction addition
Unitnode --test (via tsx) in apps/api/test for state transitions, validation and idempotency. The parent confirms coveragePolicy-as-code tests; refill/FEFO property tests
API contractsupertest-style HTTP tests per endpoint, including 409 on awaiting_review advanceOpenAPI and GraphQL schema diff gates; consumer-driven contracts with partners' sandboxes
E2EBrowser flow: catalog → intake → order → approve → deliverPlaywright across the editorial and compact modes; accessibility (axe) gate
SecurityHeader checks; no upload route; dependency auditSAST, DAST, container scan, IaC scan, annual pentest, PHI-in-logs canary
ResilienceRestart the container; data persists on the volumeChaos (pod or AZ loss), PSP or partner outage simulation, restore drills
Performancenonek6 load and soak against §19 targets in a staging environment sized like production

21. Phased roadmap & acceptance gates

PhaseOutcomeAcceptance gate (all must pass)
0. Investor POC
POC contract
Local Docker demo with synthetic datadocker compose up --build works from a clean clone; web published only on 127.0.0.1:3100 (→ container 3000); API not host-published; data survives restart; API tests green; no real data inputs; demo disclaimers visible; both visual modes present
1. MVP: one state, one pharmacy partner
Proposed
Real patients for a narrow catalogSigned BAAs for every PHI vendor; HIPAA risk analysis done; pharmacy and prescriber licensure confirmed for the launch state; pentest with no open critical or high findings; restore drill meets RPO/RTO targets; PSP approval for the category; clinical protocols signed by the medical director; WebAuthn/MFA live; audit WORM verified; incident runbooks rehearsed
2. AutomationTemporal sagas, eRx/FHIR integration, refill automation, FEFO and lot tracking, cold-chain carriersSaga chaos tests show no double capture and no dispense without capture; recall drill traces 100% of affected dispenses within 4 h; SOC 2 Type I report issued; refill safeguards verified with clinical QA
3. ScaleMulti-state, multi-pharmacy, service extraction, multi-region DRSOC 2 Type II; load test at 10× MVP peak within budgets; regional failover game day meets RTO; per-state rules engine audited; cost per order within the business target

Service extraction order (staged, from a modular monolith): Payments → Pharmacy fulfillment → Clinical → Catalog. Extract a context only when team ownership, scaling or compliance isolation justifies the cost of running it separately.

22. Risks & open decisions

IDRisk / decisionMitigation / next stepStatus
R-01Investors read the POC as production-readyPersistent demo banner; this document's honesty matrix; scripted demo narrativePOC contract
R-02Licensed pharmacy operator and launch states undecidedChoose the partner versus building our own pharmacy; legal analysis by stateOpen decision
R-03Compounded GLP-1 regulatory volatilitySKU-level legal flags; fast catalog kill switchOpen decision
R-04Payment processor category restrictionsEarly underwriting conversation; backup processorOpen decision
R-05EKS operational complexity for a small teamManaged add-ons, GitOps and a minimal node footprint; ECS Fargate kept as a fallback ADRProposed
R-06Auth expiry during long clinical reviewRe-authorize or setup-intent pattern; SLA on review timeOpen decision
R-07node:sqlite is experimental in Node 22POC only; pin the Node version; production uses PostgreSQLPOC contract

Related: Production integrations report · Local & cloud deployment plan. The canonical source is docs/technical-design.html. Any copy under apps/web/public/reports/ is generated and should not be edited directly.

BreezRx is an investor proof of concept. All products, prices, identities, prescriptions and payments shown in the POC are synthetic. This document makes no claim of HIPAA compliance, SOC 2 attestation, GDPR compliance, pharmacy licensure or clinical efficacy.

Inline concierge and product packs — implemented runtime extension

The current PostgreSQL runtime adds product_packs and product_pack_items in migration 006_product_packs.sql. Curated packs are seeded after products; custom packs belong to the authenticated customer. Pack items are unique products with bounded quantities. Cart, order-item and subscription records retain pack IDs, with pack-name snapshots in orders and subscriptions.

Guest pack drafts remain in the browser bag until sign-in saves the pack and merges its items. Adding a pack is transactional, preserves unrelated bag items, and replaces existing lines for the same product. A shared customer lock serializes cart writes. Checkout uses the existing idempotency, pricing, payment and clinical rules; packs do not create another billing engine. Each recurring item keeps its own status, cadence, renewal lease, prescription checks and pause/skip/cancel controls.

POST /api/assistant/turn accepts bounded shopping preferences and an optional message. A private configurable OpenAI-compatible adapter extracts validated preferences and topics. Catalog facts, prices, budget/cadence filtering, question progression and clinical disclosures are server-controlled. Raw model prose and reasoning are never shown. Prescription selection requires an explicitly named product; clinician review remains mandatory.

Inference is bounded by total deadline, per-replica admission and response size, with explicit fallback reasons and a circuit breaker. Button answers and built-in FAQs need no inference. Chat transcripts are ephemeral and excluded from logs. API/network outages surface as errors rather than pretending guided inference succeeded. See the README for API/environment contracts and the deployment report for remaining VPC, privacy, licensing and global-capacity work.