17 — Scale design, capacity model & hardening runbook
Part I (below) is the usage, workload, and 100k-user capacity model (empirical data and design implications). Part II is the day-2 operational runbook for the hardened stack (Redis, PgBouncer, read replica,
scan_worker, Stripe, etc.) in Docker Compose or a small orchestrator. The opening paragraphs that follow the table of contents primarily describe Part II; use the Part headings to navigate.
Audience: Operators, SREs, on-call engineers. Developers should start with 05-DEVELOPER-GUIDE.md and 01-ARCHITECTURE.md.
Companion docs:
- ../04 - OPERATIONS/07-PLATFORM-RUNBOOK.md — day-2 tunnel / backup / restore procedures.
- ../04 - OPERATIONS/11-DATABASE-SAFETY-AND-MIGRATIONS.md — schema and PHI migration safety.
Part I — Usage patterns, workload & capacity
Section titled “Part I — Usage patterns, workload & capacity”Merged 2026-04-28 from the former 16-SCALING-AND-USAGE-PATTERNS (filename retired).
Version: 1.1 Last Updated: 2026-04-26 Goal: 100 000+ users, 2 000–5 000 concurrent, globally distributed. Method: empirical — derive per-user behavioural model from 3 weeks (20 days) of real production activity in one live tenant (Australia/Sydney), then project to 100k-user scale with a global timezone mix.
How to read this document. The 100 000-user target is the architectural ceiling — it proves the design can scale without a re-architect. It is not a near-term provisioning target. For the phased build plan (workstation → VPS → managed DB → horizontal replicas) and researched provider costs, read ../archive/25-PRODUCTION-SERVER-BUILD-AND-PROVIDER-ANALYSIS.md (archived May 2026). Live hosting: 20-PRODUCTION-DEPLOYMENT-GUIDE.md §1.
1. The data we have
Section titled “1. The data we have”The local UAT database (Docker on a workstation at 127.0.0.1:5433) used for this analysis contains 20 consecutive days of real activity from one tenant (“Peter”, Australia/Sydney) with one patient and six users (Peter, Craig, Michelle, Tony, Sue, Ellie). This is small in absolute volume but behaviourally authentic: real humans dispensing real medications, logging real sleep, doing real shopping handovers.
| Table | Rows | Period | Events / day (mean) |
|---|---|---|---|
dispensings | 203 | 2026-03-29 → 2026-04-18 | 10.2 |
shopping_list_items | 169 | 2026-04-05 → 2026-04-17 | 13.0 |
care_shifts | 189 | 2026-03-29 → 2026-04-17 | 9.5 |
patient_sleep_entries | 89 | 2026-04-04 → 2026-04-17 | 6.4 |
patient_scripts | 12 | 2026-03-31 → 2026-04-14 | ~0.8 |
audit_log | 47 | 2026-03-30 → 2026-04-17 | ~2.4 |
Baseline per active patient = ~40 write-events/day across core modules.
2. Time-of-day pattern (the important finding)
Section titled “2. Time-of-day pattern (the important finding)”Activity is highly concentrated into a ~14-hour waking window with three distinct peaks. Below is the combined write count by local hour, summed across dispensing, shopping, sleep, and care-shift mutations.
Hour (Australia/Sydney) Dispensing Shopping Sleep Shifts TOTAL Visualisation─────────────────────────────────────────────────────────────────────00:00 0 4 0 0 4 ▍01:00 – 04:59 0 0 0 0 0 (quiet)05:00 10 0 0 0 10 █06:00 6 0 0 0 6 ▌07:00 3 0 35 8 46 ████08:00 6 1 0 36 43 ███▊ ← morning med / handover09:00 24 9 0 10 43 ███▊ ← morning med peak10:00 24 7 3 12 46 ████11:00 17 22 9 2 50 ████▌12:00 19 3 0 1 23 ██13:00 8 3 5 12 28 ██▌14:00 1 7 0 2 10 █15:00 11 5 0 24 40 ███▌16:00 1 15 0 0 16 █▍17:00 11 43 21 27 102 ████████▌ ← evening megapeak18:00 6 30 0 7 43 ███▊19:00 12 6 0 11 29 ██▌20:00 24 3 6 7 40 ███▌ ← evening med21:00 10 7 0 0 17 █▌22:00 5 0 10 30 45 ████ ← night handover23:00 5 4 0 0 9 ▊Three structural peaks emerge:
- 08:00–10:00 (morning medication round + day-shift handover) — carers arrive, previous-shift notes are read, morning meds dispensed, shopping list checked. ~43 writes/hour × ~4× read amplification = ~170 requests/hour for this single patient.
- 17:00 (the megapeak) — 102 writes in one hour. Shopping planning before dinner, afternoon meds, sleep-nap logging, evening-shift handover arrival all converge. This is 2.2× the average peak hour.
- 22:00 (night handover) — day/night carer changeover, evening meds bookkeeping, last sleep entry.
Dead hours 01:00–04:59 are absolute: no events whatsoever, consistently across the 20 days. This is the patient sleeping, and the app is genuinely inactive.
Weekly pattern
Section titled “Weekly pattern”| Day | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
|---|---|---|---|---|---|---|---|
| Dispensings (total) | 29 | 23 | 34 | 38 | 31 | 25 | 23 |
| Index (Mon=100) | 100 | 79 | 117 | 131 | 107 | 86 | 79 |
Care is 7-day — weekends are only ~20% below midweek, not the 60% drop typical of enterprise SaaS. There is no weekend relief window for scaling or maintenance.
Burst intensity
Section titled “Burst intensity”At 5-minute granularity the hottest single bucket for one patient held 18 events. That’s 3.6 events/sec sustained for 5 minutes — a morning-round burst where a carer dispenses six medicines and updates the schedule in quick succession. One patient / one carer. For a tenant with six carers working simultaneously in a shared care group, multiply by ~3 (overlap not total — most carers aren’t on shift at once).
3. Per-user / per-patient model
Section titled “3. Per-user / per-patient model”From the observed data, a single actively-managed patient generates:
| Metric | Observed | Notes |
|---|---|---|
| Write events / day | ~40 | dispensings + shopping + sleep + shifts + appointments |
| Writes during peak hour | ~10 | 17:00 local (megapeak) |
| Writes during typical waking hour | ~3 | 08:00–22:00 average |
| Distinct “active minutes” with writes | 5–10 / day | most of the day is idle |
| Burst maximum (5-min window) | 18 events | morning round / evening handover |
| Active users per tenant | 6 | carers + family |
| Concurrent SSE subscribers expected | 2–3 | those looking at shopping/calendar right now |
Read-to-write ratio (estimated, not measured — no request logs in DB):
Every dispensing implies ≥ 2 reads (view schedule, view script). Every shift open implies ≥ 3 reads (shift detail, previous handover, task list). Shopping SSE broadcast to 3 subscribers on each write = 3 extra reads per write. Calendar / schedule polling on page open = ~8 queries. Safe estimate: 8–12 reads per write.
4. Projecting to 100 000 users
Section titled “4. Projecting to 100 000 users”Two numbers matter:
- How many concurrent users are actually doing something at peak?
- What’s the peak write/read throughput in requests per second?
4.1 The “all users in one timezone” myth
Section titled “4.1 The “all users in one timezone” myth”This is the most important insight in the document. You never face a global peak. The 17:00 megapeak in Sydney is:
- 09:00 in Berlin
- 08:00 in London
- 00:00 in New York
- 21:00 the previous day in Los Angeles
The peak rolls around the globe at the speed of the Earth’s rotation. For a user base distributed across timezones, the aggregate global load curve flattens substantially.
Assumed 100k-user distribution (care-product common case)
Section titled “Assumed 100k-user distribution (care-product common case)”| Region | Share | Timezone range | 17:00-local falls at UTC |
|---|---|---|---|
| Australia / NZ / SE-Asia | 30% | UTC+8 to +13 | 04:00–09:00 UTC |
| Europe + UK + ME | 35% | UTC-1 to +4 | 13:00–18:00 UTC |
| North America | 25% | UTC-5 to -8 | 22:00–01:00 UTC |
| Africa + LatAm + rest | 10% | UTC-5 to +3 | spread |
The peak UTC hour is the hour where the most users simultaneously sit in their personal 17:00 window. With this mix, no single UTC hour sees more than ~18% of total users in peak-hour. That caps the simultaneously-peaking population to ~18 000 users for a 100 000-user base.
4.2 Concurrent users
Section titled “4.2 Concurrent users”A user is “concurrent” if they have the app open (SSE connection live, calendar polling, or a mutation within the last 60 s).
From the observed data, an active carer during a peak hour averages one mutation every 6 minutes (10 per hour), plus reads. That means they are not actually online the whole hour — they are online in ~3 bursts of ~5 minutes each.
Concurrent load at peak-UTC-hour estimate:
- 18 000 users in their local peak hour
- × 40% probability of being engaged in any given 5-minute window (derived from distinct-active-minutes / hour-minutes ratio)
- = ~7 200 concurrent engaged users globally
Your stated target of 2 000–5 000 concurrent is comfortably below this; 7 200 is the worst-case headroom the architecture needs to survive, not the expected load.
4.3 Peak request rate
Section titled “4.3 Peak request rate”Peak-hour writes per patient (from §3): ~10. Assume ~0.7 patients per user (most users are carers for one patient; family hierarchies dilute this). Per user the share of write events per hour in peak is ~7.
- 18 000 peak-hour users × 7 writes/hour = 126 000 writes/hour ≈ 35 writes/sec sustained, ~100 writes/sec burst during the 17:00-local 5-minute rush.
- At a 10:1 read:write ratio → ~350 reads/sec sustained, ~1 000 reads/sec burst.
These are small numbers for Postgres. A single modest Postgres 16 instance (4 vCPU, 16 GB RAM, SSD) handles 3 000–5 000 simple queries/sec. The challenge is not raw DB throughput — it’s connection count, pool behaviour, and the long-tail of slow queries (notably LM Studio vision scans).
4.4 Scan workload (the real asymmetric cost)
Section titled “4.4 Scan workload (the real asymmetric cost)”The prescription-scan feature (POST /api/scripts/scan) makes a synchronous 15–120 s call to LM Studio. If 1% of peak-hour users trigger one scan (reasonable — pharmacy visits are infrequent), that’s 180 concurrent scans. Every scan currently holds a DB connection (see Code-Review §4.3). That alone would consume 180 of the 20-max pool size, 9× over. This is the single biggest architectural bottleneck the app faces at scale.
5. Design implications
Section titled “5. Design implications”5.1 Capacity sizing (endgame configuration for 100k users)
Section titled “5.1 Capacity sizing (endgame configuration for 100k users)”These values are not for Day 1. They describe the steady-state infrastructure at full 100 000-user scale. For the phased build from first subscriber through 5 000 subscribers, see archive/25-PRODUCTION-SERVER-BUILD-AND-PROVIDER-ANALYSIS.md §4.
Values are targets for production at full scale, with headroom to auto-scale 2× during Europe/17:00 or US/17:00 megapeaks.
| Tier | Config | Rationale |
|---|---|---|
| Application | 4 nodes × 4 vCPU × 8 GB, each running uvicorn with --workers 4 | 16 app workers total, ~1 500 concurrent connections each headroom. Stateless. |
| Postgres primary | 8 vCPU, 32 GB RAM, gp3 SSD 500 GB, IOPS 6 000 | Handles ~5 000 qps at 50% headroom. Connection limit 500. |
| Postgres read replicas | 2 × 4 vCPU, 16 GB | Analytics queries, audit-log list, dashboards. Async streaming replication. |
| PgBouncer | 2 instances, session-pool mode per DB, transaction-pool for analytics | Multiplexes 2 000 app client conns → 200 backend Postgres conns. Essential. |
| Redis | 2 × cache.r7g.large (multi-AZ, replicated) | SSE ticket store, PWA OAuth sessions, rate-limit counters, session cache. |
| LM Studio / scan workers | Separate GPU pool, 4–8 nodes auto-scaled | Off-band. Never share Postgres pool with web tier. |
| Task queue | Redis-backed (arq, rq, or Celery) | For scans, emails, SSE fan-out, scheduled resets. |
| CDN + static | CloudFront / Cloudflare | Frontend bundle + authenticated-image byte-range cache. |
5.2 Timezone-aware scheduling
Section titled “5.2 Timezone-aware scheduling”This is specific to LynCareOS and not a copy-paste cloud pattern.
- APScheduler → per-timezone fan-out. The existing
_run_recurring_resetat 06:00 runs once in server UTC. That’s midnight in Sydney — wrong from a UX perspective, but OK so long as tenants understand it. At 100k scale, enrich the scheduler withFOR EACH tenant SCHEDULE reset AT 06:00 IN tenant.timezone. APScheduler’sCronTrigger(timezone=...)supports this per-job. Concretely:- On tenant creation, register one cron job keyed by
tenant_id+tenant.timezone. - On tenant deletion or timezone change, unregister / reregister.
- Persist the job store in Postgres (
APSJobStore) so jobs survive restarts and so the same job can’t fire twice across app instances.
- On tenant creation, register one cron job keyed by
- Cache-warming sweep can follow the peak: at
17:00 - 10 minlocal, pre-warm medication-schedule and today’s-shopping caches for that tenant. Trivial to schedule per-timezone. - Analytics aggregation roll-up jobs should run in the tenant’s local deep-night window (02:00–04:00 local), not UTC deep-night.
5.3 Connection strategy (the single most important scaling fix)
Section titled “5.3 Connection strategy (the single most important scaling fix)”- Introduce PgBouncer in transaction-pool mode between FastAPI and Postgres. Without this, 16 app workers × 100 connections each = 1 600 idle connections, and Postgres dies long before the product is under real load. With PgBouncer you can run 2 000 app-facing clients and only hold 200 real Postgres backends.
- Release the connection before any external call. Rewrite the scan path (and any future webhook/email path) as:
The current# pseudo-codeasync with pool.connection() as db: ... fetch script metadata ...# release. Long-running external work happens here.result = await lmstudio.extract(image_bytes)async with pool.connection() as db: ... write result, commit ...
get_dbdependency cannot do this. Create a secondary dependencyget_db_shortthat is only used for the quick pre-flight query, and explicitasync with pool.connection() as dbfor the post-work write. - Set
DB_POOL_MAX = 30per worker, not the current 10. At 16 workers × 30 = 480 client-side, funnelled through PgBouncer to ~150 backend conns. - Add
statement_timeout = 5sat thelyncare_approle level. A runaway query then cannot tie up a connection for minutes. Admin queries use a separate role with a longer timeout.
5.4 Read / write split
Section titled “5.4 Read / write split”The workload is 90% reads. Move the following to read replicas:
GET /api/analytics/*— all aggregation endpoints.GET /api/audit/*— admin audit-log listing.GET /api/scriptsandGET /api/dispensingslist endpoints — acceptable to be 1–5 seconds behind primary.
Keep these on the primary (writes + read-your-writes):
GET /api/auth/meGET /api/patients/current(nav bar freshness matters)GETimmediately following any same-sessionPOST/PATCH/DELETEon the same resource.
psycopg v3 supports explicit AsyncConnectionPool instances — give the app two pools (pool_rw, pool_ro) and let routers pick via a dependency Depends(get_ro_db). Opt-in, not magic.
5.5 Eliminate in-process state (already in the code-review document, but scale-critical)
Section titled “5.5 Eliminate in-process state (already in the code-review document, but scale-critical)”Re-stated here because the scale target makes it non-negotiable:
- SSE fan-out → Postgres
LISTEN/NOTIFYor Redis Streams / Pub-Sub.LISTEN/NOTIFYis zero new infrastructure, payload ≤ 8 KB, delivery is exactly-once within the cluster. Each app worker runs one background task thatLISTEN shopping_events; every mutationNOTIFY shopping_events, jsoninside the same txn that commits the mutation. All workers’ SSE subscribers fan out locally from the NOTIFY they received.- Critical nuance:
NOTIFYis per-transaction and only fires on COMMIT. This is exactly what you want: no phantom broadcasts for rolled-back operations.
- Critical nuance:
- SSE tickets → Redis with
SET key <userId> EX 60 NX. The_consumesemantics becomeGETDEL. Atomic, cross-worker safe. - PWA OAuth session handoff → Redis with the same 10-minute TTL. Key is the session id, value is the JSON blob. Small, sub-KB per entry.
- Rate limiter →
slowapiwith Redis backend. The current in-memory limiter’s buckets reset per worker; under 16 workers the effective limit is 16× what’s configured.
5.6 Sharding plan (not yet, but designed for)
Section titled “5.6 Sharding plan (not yet, but designed for)”100k users in a multi-tenant DB does not require sharding. Well-indexed Postgres 16 handles 100k users × hundreds of MB of data comfortably. But the path must be preserved.
Sharding-safe choices already present in the schema:
- Every row carries
tenant_id. - RLS policies make cross-tenant queries impossible at the DB level.
- No cross-tenant joins anywhere in the app (verified by grep — no
JOIN … ON x.tenant_id != y.tenant_id).
Sharding-hostile choices to avoid adding later:
- Tenant-spanning aggregation queries (e.g. “how many dispensings across all tenants today?”). Keep these out of user-facing code paths; compute them off a daily ETL to a warehouse.
- Global sequences. The current integer
idPK per table is fine for now — at shard time these become composite(tenant_id, id)or UUID. Write the product assuming opaque string IDs could be substituted. last_loginor any cross-tenant index that has to scan every tenant’s partition at query time.
When to shard: the rule of thumb for a workload like this is “when 80% DB CPU at peak cannot be driven below 60% by vertical scale + read replicas”. At 100k users you are 2–3 orders of magnitude away from that on modern hardware.
5.7 Caching layer
Section titled “5.7 Caching layer”With 10:1 read:write and hard peaks, a small in-process LRU fronting the two hottest endpoints is worth more than 50% of the read QPS reduction.
GET /api/subscriptions/modules— tenant-level, changes rarely. Cache for 60 s in Redis. Invalidate on subscription mutation.GET /api/patients(per user) — user-level, changes on membership add/remove. 30 s Redis cache with user-id key.GET /api/medicines(per tenant) — tenant-level catalog. 5 min Redis cache.- Catalog tables (
catalog_categories,catalog_items) — global, rarely change. Cache in-process per worker with 10-minute TTL.
Authenticated-image byte streams already have browser-Cache-API client-side caching (useAuthenticatedImage). At scale, put a CDN in front of the authenticated-image endpoint using signed URLs (short-lived 5-minute signed URL returned by the API; the CDN serves the blob itself). This turns 3 000 image requests/sec into 30 backend signature-generation requests/sec.
5.8 Background work and SLA tiers
Section titled “5.8 Background work and SLA tiers”Tier every request by how much latency the user perceives. The app today implicitly treats everything the same. At scale, bucket them:
| Tier | Latency SLO | Examples | Path |
|---|---|---|---|
| Interactive | p99 < 300 ms | Calendar load, dispensing log, shopping tick | Primary DB, synchronous |
| Near-interactive | p99 < 2 s | Analytics chart, audit list | Read replica, synchronous, cacheable |
| Deferred | p99 < 30 s | Prescription scan completion, email send, export | Queue, user polls or SSE |
| Batch | Hours | Daily reset, monthly report, backup verification | Scheduler |
The current POST /api/scripts/scan is a tier-3 operation dressed as tier-1. Fix: the endpoint enqueues the scan to a worker queue and returns { job_id } immediately; the frontend opens an SSE to /api/scripts/scan/{job_id}/events and receives the result when ready. This single change removes the scan tier from the web-tier connection budget.
6. What this means in numbers
Section titled “6. What this means in numbers”Putting it all together, here is the capacity the proposed design has, vs. the target:
| Metric | Target | Proposed capacity | Headroom |
|---|---|---|---|
| Registered users | 100 000 | 500 000 | 5× |
| Concurrent users | 2 000–5 000 | 15 000 | 3–7× |
| Sustained req/sec (app tier) | ~400 | 6 000 | 15× |
| Peak req/sec (Europe 17:00 + US 08:00 overlap) | ~1 500 | 8 000 | 5× |
| Writes/sec sustained | ~35 | 1 000 (Postgres primary, indexed) | 30× |
| SSE concurrent subscribers | 3 000 | 20 000 (across 4 app nodes) | 6× |
| Scans in flight | 200 | 400 (8 × 50 per scan worker, off-band) | 2× |
| p99 interactive latency | < 300 ms | 150 ms at target load | ✓ |
The bottleneck at target load shifts from “app tier” (today) to “LM Studio scan GPU budget” (after fixes), which is the right place for it to be — it’s the only feature with real COGS attached.
7. Behavioural insights you can productise
Section titled “7. Behavioural insights you can productise”These are not scaling notes but UX opportunities that the data uncovered. I include them because they may influence the design brief as much as the load model.
- Users are not “always-on” — they are “thrice-on”. Morning, evening, night. Consider an aggressive service worker pre-fetch ~15 minutes before each local peak (learned from
last_loginpattern), so the first tap of the day feels instant. - The 17:00 peak is shopping-led, not medication-led. Shopping (43 events that hour) outnumbers dispensing (11) by 4×. The shopping module is your highest-leverage UX investment.
- Night-time audit trail is sparse but compliance-critical. The 22:00–23:00 window is night-shift handover (30 + 0 shift updates) — precisely the moment where audit log omissions matter legally. See Code-Review §1.5.
- Sleep entries cluster at 07:00 (35 events — waking log of the night’s sleep) and 17:00 (21 events — afternoon nap recording). The data model can safely pre-aggregate “last-night” and “today-so-far” views and serve them from a materialised view refreshed every 15 minutes.
- Day-of-week variance is tiny (79–131 range). There is no safe “maintenance Sunday” window. Maintenance has to happen in a rolling tenant-local deep-night slot.
- The quiet window (01:00–04:59 local) is absolute across 20 days. This is the only reliable per-tenant free space for heavy operations: re-index, audit-log archival, analytics ETL.
8. Recommended sequencing
Section titled “8. Recommended sequencing”See archive/25-PRODUCTION-SERVER-BUILD-AND-PROVIDER-ANALYSIS.md for the full phased infrastructure plan correlated to subscriber counts. The sprint plan below describes code and configuration changes; the provider document describes where those changes are deployed.
Sprint 1 (make it horizontally safe)
Section titled “Sprint 1 (make it horizontally safe)”- PgBouncer in transaction-pool mode.
- Move SSE / PWA / rate-limiter state to Redis or LISTEN/NOTIFY.
- Release DB connection before LM Studio call.
- Split scan endpoint into queue + poll (tier-3 SLA).
- Set
statement_timeoutonlyncare_approle.
Sprint 2 (make it cost-efficient at 100k)
Section titled “Sprint 2 (make it cost-efficient at 100k)”- Read replicas +
get_ro_dbdependency for analytics / audit. - Redis cache for the four hot endpoints (§5.7).
- Signed-URL CDN in front of authenticated-image endpoint.
- Per-tenant timezone-aware APScheduler job store.
Sprint 3 (make it observable)
Section titled “Sprint 3 (make it observable)”- Request-level metrics:
method, route, tenant_id, status, latency_msinto Prometheus. - Slow-query log +
pg_stat_statementsdashboard. - SSE connection-count gauge per worker.
- Scan-queue depth + p95 completion time.
Sprint 4+ (make it multi-region ready — only when required)
Section titled “Sprint 4+ (make it multi-region ready — only when required)”- Region-sticky routing by
tenant.region. - Cross-region replication of Postgres primary.
- Per-region Redis cluster.
- Global audit-log aggregation to a central warehouse.
9. Things that do not need to change
Section titled “9. Things that do not need to change”It’s as important to say what’s fine. The following parts of the current design already scale straightforwardly to 100k users without modification beyond the operational changes above:
- Multi-tenant isolation model.
tenant_idon every row + RLS is the correct, horizontally-scalable choice. No ORM hiding join bugs. - Module gating.
require_moduledependency is cheap, per-request, per-tenant. - JWT auth with rotating tokens. Stateless; ideal for horizontally-scaled app tier.
- Pydantic-based API contracts. Zero marshalling overhead worth worrying about.
- Migration runner. Numbered migrations + schema_migrations ledger is correct. Only add the advisory lock (Code-Review §6.2).
- The patient → carer → family access graph. Already flexible enough for real-world care arrangements without per-tenant schema.
Appendix — the queries used
Section titled “Appendix — the queries used”All derived from the live DB at the time of writing. Reproducible with:
docker compose exec -T postgres psql -U lyncare -d lyncareos -c "<query>"Activity by local hour (the core table in §2):
WITH writes AS ( SELECT created_at, 'dispensing' AS k FROM dispensings UNION ALL SELECT created_at, 'shopping' FROM shopping_list_items UNION ALL SELECT created_at, 'sleep' FROM patient_sleep_entries UNION ALL SELECT created_at, 'care_shift' FROM care_shifts)SELECT EXTRACT(HOUR FROM created_at AT TIME ZONE 'Australia/Sydney')::int AS hr, COUNT(*) FILTER (WHERE k='dispensing') AS disp, COUNT(*) FILTER (WHERE k='shopping') AS shop, COUNT(*) FILTER (WHERE k='sleep') AS slp, COUNT(*) FILTER (WHERE k='care_shift') AS shift, COUNT(*) AS totalFROM writes GROUP BY 1 ORDER BY 1;Day-of-week variance:
SELECT EXTRACT(DOW FROM created_at AT TIME ZONE 'Australia/Sydney')::int AS dow, to_char(MIN(created_at AT TIME ZONE 'Australia/Sydney'),'Dy') AS day, COUNT(*) AS nFROM dispensings GROUP BY 1 ORDER BY 1;Burst measurement:
WITH buckets AS ( SELECT date_trunc('hour', created_at) + INTERVAL '5 min' * (EXTRACT(MINUTE FROM created_at)::int / 5) AS bucket FROM dispensings UNION ALL SELECT date_trunc('hour', created_at) + INTERVAL '5 min' * (EXTRACT(MINUTE FROM created_at)::int / 5) FROM shopping_list_items UNION ALL SELECT date_trunc('hour', created_at) + INTERVAL '5 min' * (EXTRACT(MINUTE FROM created_at)::int / 5) FROM patient_sleep_entries)SELECT bucket, COUNT(*) AS eventsFROM buckets GROUP BY bucket ORDER BY 2 DESC LIMIT 20;End of scaling brief. 2026-04-18.
Part II — Day-2 operations and procedures
Section titled “Part II — Day-2 operations and procedures”1. Service topology
Section titled “1. Service topology” Internet │ ▼ ┌───────────┐ │ Cloudflare / │ reverse proxy │ └─────┬─────┘ │ HTTPS ▼ ┌───────────────┐ ┌──────────────┐ │ app (N) │◄──────►│ scan_worker │ │ FastAPI+SPA │ │ (Redis Q) │ └──┬────────┬───┘ └──────┬───────┘ │ │ │ Redis │ │ PgBouncer │ Redis pub/sub state │ │ :6432 │ ▼ ▼ │ ┌───────┐ ┌───────────────┐ │ │ redis │ │ postgres │◄────┘ └───────┘ │ (primary) │ └───────┬───────┘ │ streaming replication (optional) ▼ ┌───────────────┐ │ postgres_ro │ └───────────────┘All services are defined in docker-compose.yml.
| Service | Purpose | Scaling |
|---|---|---|
app | FastAPI API + built SPA | Horizontal, uvicorn --workers N per replica |
scan_worker | LM Studio image-scan worker consuming Redis queue | Horizontal — one or many |
postgres | Primary data store (PostgreSQL 16) | Vertical + optional read replica |
pgbouncer | Transaction pool in front of Postgres | 1 per DB host; N per region |
redis | SSE tickets, PWA sessions, pub/sub, rate-limit buckets, caches | HA via Redis sentinel when required |
2. Environment variables (Phase 1 onwards)
Section titled “2. Environment variables (Phase 1 onwards)”Only the variables added or materially changed by the hardening
plan are listed here. See backend/.env.example for the full list.
| Variable | Required | Notes |
|---|---|---|
REDIS_URL | Yes in prod | e.g. redis://redis:6379/0 |
DATABASE_URL | Yes in prod | Points at PgBouncer, not directly at Postgres |
DATABASE_READ_URL | Optional | Points at the read replica; falls back to DATABASE_URL when unset |
MFA_ENCRYPTION_KEY | Recommended | Rotatable base64 Fernet key. When unset, derived from SECRET_KEY via HKDF |
AUTH_COOKIE_DOMAIN | Optional | Set when API and SPA are on sibling subdomains |
AUTH_COOKIE_SECURE | Auto-on in prod | Set 1 to force Secure cookies in staging |
STRIPE_SECRET_KEY | Yes for billing | Empty in dev → Stripe endpoints return 503 |
STRIPE_WEBHOOK_SECRET | Yes for billing | Verifies POST /api/stripe/webhook |
STRIPE_BILLING_PORTAL_RETURN_URL | Yes for billing | Where Stripe redirects after portal session |
APP_PUBLIC_URL | Yes | Used to build Checkout / portal URLs |
DB_POOL_MIN, DB_POOL_MAX | Optional | Per-worker psycopg pool sizes. With PgBouncer in front, keep MAX ≤ 30 |
3. Start / stop / health
Section titled “3. Start / stop / health”# Full stack (prod profile includes app + scan_worker)docker compose --profile production up -ddocker compose psdocker compose logs -f app scan_worker
# Local dev (hot-reload backend + vite)./dev-start.ps1./dev-stop.ps1Health checks
Section titled “Health checks”| Endpoint | Expected |
|---|---|
GET /api/health/live | 200 {"status":"ok"} |
GET /api/health/ready | 200 only when DB + Redis reachable |
docker compose ps | All services healthy |
4. Redis operations
Section titled “4. Redis operations”4.1 Keyspace layout
Section titled “4.1 Keyspace layout”| Prefix | TTL | Producer |
|---|---|---|
sse:ticket:<uuid> | 30 s | services/sse_tickets.issue_ticket |
pwa:session:<hex> | 10 min | services/pwa_auth |
ratelimit:* | SlowAPI-managed | middleware/rate_limit |
cache:modules:<tenant> | 5 min | services/cache |
cache:patients:<tenant> | 2 min | services/cache |
cache:medicines:<tenant> | 5 min | services/cache |
scan:queue | (list) | API /api/scan/enqueue |
scan:result:<job_id> | 10 min | scan_worker |
scan:pub:<tenant> | (pub/sub) | scan_worker |
shopping:pub:<tenant> | (pub/sub) | services/shopping_pubsub |
4.2 Emergency cache flush
Section titled “4.2 Emergency cache flush”Fired when a schema change invalidates a specific cache group:
docker compose exec redis redis-cli --scan --pattern 'cache:modules:*' | \ xargs -r docker compose exec -T redis redis-cli DELFlush all caches (safe — caches repopulate on demand):
docker compose exec redis redis-cli --scan --pattern 'cache:*' | \ xargs -r docker compose exec -T redis redis-cli DELNever FLUSHDB — that would drop SSE tickets and PWA sessions.
4.3 Rate-limit incidents
Section titled “4.3 Rate-limit incidents”Temporarily clear one IP’s bucket (e.g. customer report):
docker compose exec redis redis-cli --scan --pattern 'ratelimit:*<IP>*' | \ xargs -r docker compose exec -T redis redis-cli DEL5. Database operations
Section titled “5. Database operations”5.1 Pool sizing
Section titled “5.1 Pool sizing”With PgBouncer in transaction-pool mode:
backends_used = min(DB_POOL_MAX * replicas * workers, pgbouncer default_pool_size)Keep default_pool_size * number_of_app_replicas * workers_per_replica
well under Postgres’s max_connections. A typical Scale-to-100k
profile:
| Parameter | Value |
|---|---|
Postgres max_connections | 200 |
PgBouncer default_pool_size | 50 |
PgBouncer max_client_conn | 10 000 |
DB_POOL_MAX (per worker) | 30 |
| App replicas × workers | 4 × 2 |
5.2 Read replica
Section titled “5.2 Read replica”- Streaming replication configured out-of-band (managed service recommended).
- Set
DATABASE_READ_URLon the app + scan_worker services. get_ro_dbtransparently falls back to the primary when the replica is unreachable (autocommit read-only connections, so no transaction leakage).- Verify routing:
-- On the replica (should return 't')SELECT pg_is_in_recovery();5.3 Migrations under rolling deploys
Section titled “5.3 Migrations under rolling deploys”migrations/runner.py::run now acquires a pg advisory lock before
applying pending migrations. Multiple app replicas can start in
parallel; only one will run the migration, the others will wait then
no-op.
Rollback path: migrations are additive/idempotent where practical. For
hard schema changes (e.g. V039 dispensings.patient_id NOT NULL) the
deploy order is:
- Ship app version with backfill tolerant of nullable column.
- Run backfill job (included in the migration’s
UPDATE ... FROM). - Ship migration applying the constraint.
If step 3 fails, the previous app version continues to serve — no data loss.
5.4 statement_timeout
Section titled “5.4 statement_timeout”Each worker installs SET statement_timeout on every connection from
config.DB_STATEMENT_TIMEOUT_MS (migration V037 covers the
server-level default). A query exceeding the limit raises
psycopg.errors.QueryCanceled, which FastAPI surfaces as HTTP 503.
Adjust only for analytics endpoints that legitimately need longer
budgets — they run against the read replica via get_ro_db.
6. Scan worker
Section titled “6. Scan worker”- Image: same base as
app, entry pointbackend/scan_worker.py. - Consumes
scan:queue(Redis blocking list pop). - Calls LM Studio at
LMSTUDIO_BASE_URL. - Writes results under
scan:result:<job_id>and publishes toscan:pub:<tenant>. - Scale horizontally by adding replicas: each worker takes one job at a time.
6.1 Stuck jobs
Section titled “6.1 Stuck jobs”# Queue depthdocker compose exec redis redis-cli LLEN scan:queue
# Inspect a jobdocker compose exec redis redis-cli GET scan:result:<job_id>
# Drain queue (last resort — notifies users)docker compose exec redis redis-cli DEL scan:queue6.2 LM Studio outage
Section titled “6.2 LM Studio outage”- API endpoint that enqueues still returns 200 — jobs pile up in Redis.
- Users see SSE “processing” state indefinitely.
- Remediation: restart LM Studio; the worker’s inner
httpxretry kicks in within 10 s of the endpoint coming back.
7. Stripe billing
Section titled “7. Stripe billing”7.1 Webhook endpoint
Section titled “7.1 Webhook endpoint”POST /api/stripe/webhook is idempotent via the stripe_events
table: every incoming event.id is inserted with ON CONFLICT DO NOTHING before processing.
7.2 Reconciliation
Section titled “7.2 Reconciliation”If a subscription state disagrees between Stripe and Postgres:
# Manual sync — pulls the current subscription state from Stripedocker compose exec app python -m scripts.stripe_reconcile --tenant <tenant_id>The reconcile helper calls the same sync_subscription_items function
that the webhook uses.
7.3 Failed payment handling
Section titled “7.3 Failed payment handling”- Stripe moves the subscription into
past_due→ webhook marks the matchingsubscriptionsrows aspast_due. require_modulecontinues to allow access during the Stripe-defined grace period.- After
canceled, access flips to HTTP 402 on the next request.
8. Auth incidents
Section titled “8. Auth incidents”8.1 Rotate SECRET_KEY
Section titled “8.1 Rotate SECRET_KEY”Affects JWTs + (if derived) MFA encryption:
- Generate:
python -c "import secrets; print(secrets.token_hex(32))" - If MFA_ENCRYPTION_KEY is derived from SECRET_KEY you must first
set
MFA_ENCRYPTION_KEYto the current derived value, then rotate SECRET_KEY. Otherwise existing MFA secrets become unreadable. - Update env, restart app replicas. All access/refresh JWTs are invalidated; users re-login once.
8.2 Rotate MFA_ENCRYPTION_KEY
Section titled “8.2 Rotate MFA_ENCRYPTION_KEY”Run the backfill helper (keeps legacy secrets decryptable during rollout):
docker compose exec app python -m scripts.encrypt_mfa_secrets --rotate8.3 Suspicious account
Section titled “8.3 Suspicious account”# Force-logout all sessions for a userdocker compose exec postgres psql -U lyncare -d lyncareos -c \ "UPDATE users SET token_version = token_version + 1 WHERE id = <user_id>;"All outstanding access and refresh tokens for that user become invalid on next request.
9. Observability (current — deliberately minimal)
Section titled “9. Observability (current — deliberately minimal)”The plan excluded Sprint 3 observability. Until that lands the operator signals are:
| Signal | Source |
|---|---|
| App health | GET /api/health/ready + Compose healthcheck |
| Postgres health | Compose pg_isready |
| Redis health | docker compose exec redis redis-cli PING |
| Application logs | docker compose logs -f app scan_worker |
| Slow queries | log_min_duration_statement = 500 in postgresql.conf |
| Audit trail | GET /api/audit (tenant admin) |
When observability lands, Prometheus endpoint will be exposed at
/metrics on the app container.
10. Backup and restore (delta from doc 07)
Section titled “10. Backup and restore (delta from doc 07)”Doc 07 remains authoritative for Postgres backup. Additional checks:
| Item | Procedure |
|---|---|
| Redis | Not backed up — treated as ephemeral cache. SSE tickets and PWA sessions auto-expire; rate-limit buckets are best-effort. |
| Stripe state | Backed up in Stripe. Our DB is a cache; if you lose stripe_events, the webhook replays everything cleanly on the next delivery. |
| MFA secrets | Backed up with Postgres. They are encrypted at rest — restoring them to a server without the matching MFA_ENCRYPTION_KEY makes them unreadable. |
11. Load test targets
Section titled “11. Load test targets”Part I of this document (usage patterns and 100k-user model) defines SLOs. The expected headroom after the hardening plan:
| Workload | p95 budget | Notes |
|---|---|---|
GET /api/patients | 80 ms | Served from Redis cache after first hit |
GET /api/subscriptions/active | 40 ms | Redis cache |
POST /api/dispensings | 150 ms | Writes through primary, invalidates patient cache |
POST /api/auth/login | 250 ms | Dominated by bcrypt + constant-time branch |
POST /api/scan/enqueue → first SSE event | 15 s | LM Studio dependent |
GET /api/analytics/daily | 1 s | Read replica |
Re-run k6 scripts (not committed) after every infrastructure change.
12. Rolling-deploy checklist
Section titled “12. Rolling-deploy checklist”docker compose build app scan_worker- Apply DB migration on one replica:
docker compose run --rm app python -m migrations.runner— advisory lock ensures safety if this is skipped and concurrent replicas race. docker compose up -d --no-deps --scale app=2 app- Smoke test:
/api/health/ready, login, scan, Stripe webhook. - Roll scan_worker replicas:
docker compose up -d --no-deps scan_worker - If anything regresses,
docker compose up -d app:<previous-tag>— Postgres and Redis stay untouched, rollback is safe.
12.5 When you outgrow one host
Section titled “12.5 When you outgrow one host”Production today is one operations machine (Docker + Compose). The tuning in this runbook (pool sizes, Redis, PgBouncer) applies regardless of which machine — but the infrastructure levers change when you move to a stronger box, a VPS, or a managed database.
For the full phased infrastructure plan — including researched provider costs and a step-by-step migration checklist — see archive/25-PRODUCTION-SERVER-BUILD-AND-PROVIDER-ANALYSIS.md.
12.5.0 Move to a stable VPS (Phase 1 — before first payment)
Section titled “12.5.0 Move to a stable VPS (Phase 1 — before first payment)”The workstation is suitable only for private beta. The moment a first live Stripe payment is accepted, the production host must be a stable, managed server. The Windows workstation carries Windows Update reboot risk, hardware failure risk, and ISP uptime risk that are not acceptable with paying subscribers.
Trigger: Accepting the first live payment — not subscriber count.
Recommended provider: DigitalOcean Sydney (Basic, 2 vCPU / 4 GB, ~$24/mo). Vultr Sydney is an equivalent alternative. Both run Linux (Debian/Ubuntu), support Docker Compose identically to the workstation, and allow the Cloudflare Tunnel to be re-pointed within minutes. DigitalOcean is preferred because the entire Phase 1 → 3 growth path (managed Postgres, Redis, Spaces object storage, load balancer) is available on the same provider and in Sydney.
Key pre-migration action: automated nightly pg_dump to Backblaze B2
(or equivalent off-host object storage) must be running and tested before
the VPS migration — do not assume the workstation’s data is safe without it.
Env changes on the VPS:
DB_POOL_MAX= 20 (up from 10)- Uvicorn workers: 2 (matching 2 vCPU)
- Postgres data on a block-storage volume separate from the OS disk
See archive/25-PRODUCTION-SERVER-BUILD-AND-PROVIDER-ANALYSIS.md §9 for the full migration checklist.
12.5.1 Vertical / hardware
Section titled “12.5.1 Vertical / hardware”Add RAM and CPU, or move to a larger host. After the move, re-tune
DB_POOL_MAX, PgBouncer, and Uvicorn workers; verify disk I/O for
Postgres.
Trigger: sustained high CPU, memory pressure, or disk latency on the current host.
12.5.2 More disk
Section titled “12.5.2 More disk”Expand the volume that stores Docker data (or the folder hosting
lyncare_pg_data / backups\). For Docker Desktop on Windows, data
usually lives in a WSL2 virtual disk (ext4.vhdx); deleting layers
inside Linux does not always shrink that file on the NTFS drive until
you compact the VHDX (below).
Trigger: docker system df and host free space warnings.
Reclaim space — LynCareOS only (this repository’s Compose project)
Section titled “Reclaim space — LynCareOS only (this repository’s Compose project)”Use a shell in the repository root (e.g. D:\Projects\LynCareOS — adjust
the path if you cloned elsewhere). Running docker compose from that
directory only affects the default project for this folder (the
LynCareOS docker-compose.yml), not other projects’ containers unless
you also run global prune commands (listed at the end — avoid if other
repos must keep running).
Data volumes in this project (see
docker-compose.yml volumes:; Docker often shows
them with a lyncareos_ prefix, e.g. lyncareos_lyncare_pg_data — check with
docker volume ls):
| Volume (logical name) | Role |
|---|---|
lyncare_pg_data | PostgreSQL |
lyncare_redis_data | Redis AOF |
lyncare_uploads | File uploads (app / scan workers) |
-
Inspect LynCareOS only
Terminal window Set-Location D:\Projects\LynCareOSdocker compose psdocker compose imagesdocker system df -
Remove LynCareOS containers, keep all named volumes (default DB / Redis / uploads preserved):
Terminal window Set-Location D:\Projects\LynCareOS# Add --env-file and --profile if you use production (see doc 07).docker compose down -
Remove LynCareOS containers and drop locally built images for this compose file (optional; next
up+ build recreates theappimage):Terminal window Set-Location D:\Projects\LynCareOSdocker compose down --rmi localDo not add
-vtodocker compose downunless you intend to delete LynCareOS named volumes (wipes this stack’s DB/uploads in Docker). Read [../04 - OPERATIONS/07-PLATFORM-RUNBOOK.md](../04 - OPERATIONS/07-PLATFORM-RUNBOOK.md) before any-v. -
Dangling image layers (optional — can affect any repo’s unreferenced layers; use only if you are OK with global
<none>cleanup)Terminal window docker image prune -f -
Build cache (optional — shared by all projects on the machine, but is often where repeated
docker compose build appin LynCareOS consumed space). Next builds may be slower until cache refills.Terminal window docker builder prune -f -
Avoid if other Docker projects on the same PC must stay as-is, unless you know what you are doing:
docker system prune;docker container prune(affects every stopped container); and especiallydocker volume prune(removes all unused named volumes on the engine — not limited to LynCareOS).
After prunes, Windows may still show little change on C: until you
compact the WSL2 VHDX (next subsection).
Return freed space to the Windows drive (compact the Docker WSL2 VHDX)
Section titled “Return freed space to the Windows drive (compact the Docker WSL2 VHDX)”Do this when you have quit Docker Desktop and nothing is using the distro (so the file is not locked).
-
Quit Docker Desktop fully (tray → Quit).
-
Shut down WSL (elevated PowerShell or normal —
wsl --shutdownis often enough):Terminal window wsl --shutdown -
Confirm which VHDX to compact — Docker Desktop’s layout has changed across versions. The file that actually holds almost all Docker data on current installs is usually:
%LOCALAPPDATA%\Docker\wsl\disk\docker_data.vhdxA second, small file may exist at
%LOCALAPPDATA%\Docker\wsl\main\ext4.vhdx(OS layer only — compacting it barely helps). The older doc pathwsl\data\ext4.vhdxis often missing on up-to-date Docker Desktop; if DiskPart says the file cannot be opened orselect vdiskfails, you selected the wrong path.List VHDXs (PowerShell, any window):
Terminal window Get-ChildItem "$env:LOCALAPPDATA\Docker\wsl" -Recurse -Filter *.vhdx |Select-Object FullName, @{N='SizeGB';E={[math]::Round($_.Length/1GB,2)}}Compact the large one (typically
docker_data.vhdx). -
Verify WSL is not holding the disk — in an Administrator prompt,
wsl -l -vshould show docker-desktop / docker-desktop-data (if listed) as Stopped, not Running. If anything is still Running, runwsl --shutdownagain and wait a few seconds. Ifdiskpartreports the file is in use, reboot once with Docker not set to start at logon, then try compact before starting Docker. -
Compact the virtual disk so the
.vhdxfile shrinks on disk and NTFS free space goes up. Pick one method:-
DiskPart (built in; run Command Prompt or PowerShell as Administrator). Use the full path to
docker_data.vhdx(adjust username if needed):diskpartselect vdisk file="C:\Users\<You>\AppData\Local\Docker\wsl\disk\docker_data.vhdx"attach vdisk readonlycompact vdiskdetach vdiskexit -
Hyper-V (if installed): from an Administrator PowerShell, after the same quit +
wsl --shutdownsequence:Terminal window Optimize-VHD -Path "$env:LOCALAPPDATA\Docker\wsl\disk\docker_data.vhdx" -Mode Full
If
select vdiskfails, re-run theGet-ChildItemsearch above and paste the exactFullNameintoselect vdisk file="...". -
-
Start Docker Desktop again. LynCareOS (and your other stacks) come back after you
docker compose upas usual; you have only reclaimed file-system space inside the WSL2 disk, not deleted active volume data (assuming you did not rundown -vordocker volume pruneon data you still need).
Note: The maximum disk image size slider in Docker Desktop →
Settings → Resources sets an upper bound; it does not by itself run
compact on the VHDX. Prune + compact is what moves bytes back to
the host.
12.5.3 Managed PostgreSQL (future)
Section titled “12.5.3 Managed PostgreSQL (future)”If uptime / backup / HA requirements exceed what a single host
comfortably provides, plan a move to a managed Postgres (any
cloud provider) or a dedicated DB server. PgBouncer in front of the
new endpoint remains a valid pattern. Full cutover is a project:
pg_dump / pg_restore, connection string change, and tunnel/DNS
review — track in a dedicated migration plan; 03%20-%20DEPLOYMENT%20AND%20PRODUCTION/20-PRODUCTION-DEPLOYMENT-GUIDE.md is the anchor doc.
Trigger: data size, RPO/RTO targets, multi-region, or team size that makes single-host risk unacceptable.
12.5.4 Horizontal app replicas (future)
Section titled “12.5.4 Horizontal app replicas (future)”With shared Redis and stateless app containers, you can run multiple
app replicas against one Postgres (through PgBouncer) once networking
and load distribution are in place. That usually implies a
load-balancing layer in front of the app tier and careful tunnel/DNS
design. Do not start here until vertical scaling and DB tuning are
exhausted.
13. Glossary of new files
Section titled “13. Glossary of new files”| Path | Role |
|---|---|
backend/services/cache.py | Redis TTL cache primitives |
backend/services/crypto.py | Fernet + HKDF for MFA encryption |
backend/services/scheduler.py | TZ-aware APScheduler with SQLAlchemyJobStore |
backend/services/sse_tickets.py | Redis-backed SSE ticket issuance |
backend/services/pwa_auth.py | Redis-backed PWA ↔ Safari OAuth handoff |
backend/services/shopping_pubsub.py | Redis pub/sub fan-out |
backend/services/stripe_service.py | Thin Stripe SDK wrapper |
backend/services/stripe_provisioning.py | Tenant/user creation from Checkout |
backend/scan_worker.py | Redis queue consumer for LM Studio calls |
backend/migrations/V037..V041 | Statement timeout, MFA encryption, dispensings NOT NULL, BOOLEAN must_change_password, Stripe schema |
backend/scripts/encrypt_mfa_secrets.py | One-shot backfill + rotation helper |
frontend/src/hooks/useShoppingSync.ts | SSE consumer for shopping pub/sub |
frontend/src/components/scripts/* | Modals extracted from ScriptDetail/Scripts |
frontend/src/components/settings/* | Modals extracted from Settings |
Last updated: 2026-04-22 — §12.5 generalised for workstation production; removed vendor-specific cloud VM commands.