Skip to content

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:


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.


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.

TableRowsPeriodEvents / day (mean)
dispensings2032026-03-29 → 2026-04-1810.2
shopping_list_items1692026-04-05 → 2026-04-1713.0
care_shifts1892026-03-29 → 2026-04-179.5
patient_sleep_entries892026-04-04 → 2026-04-176.4
patient_scripts122026-03-31 → 2026-04-14~0.8
audit_log472026-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 / handover
09:00 24 9 0 10 43 ███▊ ← morning med peak
10: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 megapeak
18:00 6 30 0 7 43 ███▊
19:00 12 6 0 11 29 ██▌
20:00 24 3 6 7 40 ███▌ ← evening med
21:00 10 7 0 0 17 █▌
22:00 5 0 10 30 45 ████ ← night handover
23: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.

DayMonTueWedThuFriSatSun
Dispensings (total)29233438312523
Index (Mon=100)100791171311078679

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.

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).


From the observed data, a single actively-managed patient generates:

MetricObservedNotes
Write events / day~40dispensings + shopping + sleep + shifts + appointments
Writes during peak hour~1017:00 local (megapeak)
Writes during typical waking hour~308:00–22:00 average
Distinct “active minutes” with writes5–10 / daymost of the day is idle
Burst maximum (5-min window)18 eventsmorning round / evening handover
Active users per tenant6carers + family
Concurrent SSE subscribers expected2–3those 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.


Two numbers matter:

  1. How many concurrent users are actually doing something at peak?
  2. 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)”
RegionShareTimezone range17:00-local falls at UTC
Australia / NZ / SE-Asia30%UTC+8 to +1304:00–09:00 UTC
Europe + UK + ME35%UTC-1 to +413:00–18:00 UTC
North America25%UTC-5 to -822:00–01:00 UTC
Africa + LatAm + rest10%UTC-5 to +3spread

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.

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.

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.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.

TierConfigRationale
Application4 nodes × 4 vCPU × 8 GB, each running uvicorn with --workers 416 app workers total, ~1 500 concurrent connections each headroom. Stateless.
Postgres primary8 vCPU, 32 GB RAM, gp3 SSD 500 GB, IOPS 6 000Handles ~5 000 qps at 50% headroom. Connection limit 500.
Postgres read replicas2 × 4 vCPU, 16 GBAnalytics queries, audit-log list, dashboards. Async streaming replication.
PgBouncer2 instances, session-pool mode per DB, transaction-pool for analyticsMultiplexes 2 000 app client conns → 200 backend Postgres conns. Essential.
Redis2 × cache.r7g.large (multi-AZ, replicated)SSE ticket store, PWA OAuth sessions, rate-limit counters, session cache.
LM Studio / scan workersSeparate GPU pool, 4–8 nodes auto-scaledOff-band. Never share Postgres pool with web tier.
Task queueRedis-backed (arq, rq, or Celery)For scans, emails, SSE fan-out, scheduled resets.
CDN + staticCloudFront / CloudflareFrontend bundle + authenticated-image byte-range cache.

This is specific to LynCareOS and not a copy-paste cloud pattern.

  • APScheduler → per-timezone fan-out. The existing _run_recurring_reset at 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 with FOR EACH tenant SCHEDULE reset AT 06:00 IN tenant.timezone. APScheduler’s CronTrigger(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.
  • Cache-warming sweep can follow the peak: at 17:00 - 10 min local, 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:
    # pseudo-code
    async 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 ...
    The current get_db dependency cannot do this. Create a secondary dependency get_db_short that is only used for the quick pre-flight query, and explicit async with pool.connection() as db for the post-work write.
  • Set DB_POOL_MAX = 30 per worker, not the current 10. At 16 workers × 30 = 480 client-side, funnelled through PgBouncer to ~150 backend conns.
  • Add statement_timeout = 5s at the lyncare_app role level. A runaway query then cannot tie up a connection for minutes. Admin queries use a separate role with a longer timeout.

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/scripts and GET /api/dispensings list endpoints — acceptable to be 1–5 seconds behind primary.

Keep these on the primary (writes + read-your-writes):

  • GET /api/auth/me
  • GET /api/patients/current (nav bar freshness matters)
  • GET immediately following any same-session POST/PATCH/DELETE on 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/NOTIFY or Redis Streams / Pub-Sub. LISTEN/NOTIFY is zero new infrastructure, payload ≤ 8 KB, delivery is exactly-once within the cluster. Each app worker runs one background task that LISTEN shopping_events; every mutation NOTIFY shopping_events, json inside the same txn that commits the mutation. All workers’ SSE subscribers fan out locally from the NOTIFY they received.
    • Critical nuance: NOTIFY is per-transaction and only fires on COMMIT. This is exactly what you want: no phantom broadcasts for rolled-back operations.
  • SSE tickets → Redis with SET key <userId> EX 60 NX. The _consume semantics become GETDEL. 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 → slowapi with 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 id PK 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_login or 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.

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.

Tier every request by how much latency the user perceives. The app today implicitly treats everything the same. At scale, bucket them:

TierLatency SLOExamplesPath
Interactivep99 < 300 msCalendar load, dispensing log, shopping tickPrimary DB, synchronous
Near-interactivep99 < 2 sAnalytics chart, audit listRead replica, synchronous, cacheable
Deferredp99 < 30 sPrescription scan completion, email send, exportQueue, user polls or SSE
BatchHoursDaily reset, monthly report, backup verificationScheduler

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.


Putting it all together, here is the capacity the proposed design has, vs. the target:

MetricTargetProposed capacityHeadroom
Registered users100 000500 0005×
Concurrent users2 000–5 00015 0003–7×
Sustained req/sec (app tier)~4006 00015×
Peak req/sec (Europe 17:00 + US 08:00 overlap)~1 5008 0005×
Writes/sec sustained~351 000 (Postgres primary, indexed)30×
SSE concurrent subscribers3 00020 000 (across 4 app nodes)6×
Scans in flight200400 (8 × 50 per scan worker, off-band)2×
p99 interactive latency< 300 ms150 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.

  1. 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_login pattern), so the first tap of the day feels instant.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.

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.

  1. PgBouncer in transaction-pool mode.
  2. Move SSE / PWA / rate-limiter state to Redis or LISTEN/NOTIFY.
  3. Release DB connection before LM Studio call.
  4. Split scan endpoint into queue + poll (tier-3 SLA).
  5. Set statement_timeout on lyncare_app role.
  1. Read replicas + get_ro_db dependency for analytics / audit.
  2. Redis cache for the four hot endpoints (§5.7).
  3. Signed-URL CDN in front of authenticated-image endpoint.
  4. Per-tenant timezone-aware APScheduler job store.
  1. Request-level metrics: method, route, tenant_id, status, latency_ms into Prometheus.
  2. Slow-query log + pg_stat_statements dashboard.
  3. SSE connection-count gauge per worker.
  4. 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)”
  1. Region-sticky routing by tenant.region.
  2. Cross-region replication of Postgres primary.
  3. Per-region Redis cluster.
  4. Global audit-log aggregation to a central warehouse.

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_id on every row + RLS is the correct, horizontally-scalable choice. No ORM hiding join bugs.
  • Module gating. require_module dependency 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.

All derived from the live DB at the time of writing. Reproducible with:

Terminal window
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 total
FROM 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 n
FROM 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 events
FROM 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”
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.

ServicePurposeScaling
appFastAPI API + built SPAHorizontal, uvicorn --workers N per replica
scan_workerLM Studio image-scan worker consuming Redis queueHorizontal — one or many
postgresPrimary data store (PostgreSQL 16)Vertical + optional read replica
pgbouncerTransaction pool in front of Postgres1 per DB host; N per region
redisSSE tickets, PWA sessions, pub/sub, rate-limit buckets, cachesHA 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.

VariableRequiredNotes
REDIS_URLYes in prode.g. redis://redis:6379/0
DATABASE_URLYes in prodPoints at PgBouncer, not directly at Postgres
DATABASE_READ_URLOptionalPoints at the read replica; falls back to DATABASE_URL when unset
MFA_ENCRYPTION_KEYRecommendedRotatable base64 Fernet key. When unset, derived from SECRET_KEY via HKDF
AUTH_COOKIE_DOMAINOptionalSet when API and SPA are on sibling subdomains
AUTH_COOKIE_SECUREAuto-on in prodSet 1 to force Secure cookies in staging
STRIPE_SECRET_KEYYes for billingEmpty in dev → Stripe endpoints return 503
STRIPE_WEBHOOK_SECRETYes for billingVerifies POST /api/stripe/webhook
STRIPE_BILLING_PORTAL_RETURN_URLYes for billingWhere Stripe redirects after portal session
APP_PUBLIC_URLYesUsed to build Checkout / portal URLs
DB_POOL_MIN, DB_POOL_MAXOptionalPer-worker psycopg pool sizes. With PgBouncer in front, keep MAX ≤ 30

Terminal window
# Full stack (prod profile includes app + scan_worker)
docker compose --profile production up -d
docker compose ps
docker compose logs -f app scan_worker
# Local dev (hot-reload backend + vite)
./dev-start.ps1
./dev-stop.ps1
EndpointExpected
GET /api/health/live200 {"status":"ok"}
GET /api/health/ready200 only when DB + Redis reachable
docker compose psAll services healthy

PrefixTTLProducer
sse:ticket:<uuid>30 sservices/sse_tickets.issue_ticket
pwa:session:<hex>10 minservices/pwa_auth
ratelimit:*SlowAPI-managedmiddleware/rate_limit
cache:modules:<tenant>5 minservices/cache
cache:patients:<tenant>2 minservices/cache
cache:medicines:<tenant>5 minservices/cache
scan:queue(list)API /api/scan/enqueue
scan:result:<job_id>10 minscan_worker
scan:pub:<tenant>(pub/sub)scan_worker
shopping:pub:<tenant>(pub/sub)services/shopping_pubsub

Fired when a schema change invalidates a specific cache group:

Terminal window
docker compose exec redis redis-cli --scan --pattern 'cache:modules:*' | \
xargs -r docker compose exec -T redis redis-cli DEL

Flush all caches (safe — caches repopulate on demand):

Terminal window
docker compose exec redis redis-cli --scan --pattern 'cache:*' | \
xargs -r docker compose exec -T redis redis-cli DEL

Never FLUSHDB — that would drop SSE tickets and PWA sessions.

Temporarily clear one IP’s bucket (e.g. customer report):

Terminal window
docker compose exec redis redis-cli --scan --pattern 'ratelimit:*<IP>*' | \
xargs -r docker compose exec -T redis redis-cli DEL

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:

ParameterValue
Postgres max_connections200
PgBouncer default_pool_size50
PgBouncer max_client_conn10 000
DB_POOL_MAX (per worker)30
App replicas × workers4 × 2
  • Streaming replication configured out-of-band (managed service recommended).
  • Set DATABASE_READ_URL on the app + scan_worker services.
  • get_ro_db transparently 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();

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:

  1. Ship app version with backfill tolerant of nullable column.
  2. Run backfill job (included in the migration’s UPDATE ... FROM).
  3. Ship migration applying the constraint.

If step 3 fails, the previous app version continues to serve — no data loss.

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.


  • Image: same base as app, entry point backend/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 to scan:pub:<tenant>.
  • Scale horizontally by adding replicas: each worker takes one job at a time.
Terminal window
# Queue depth
docker compose exec redis redis-cli LLEN scan:queue
# Inspect a job
docker compose exec redis redis-cli GET scan:result:<job_id>
# Drain queue (last resort — notifies users)
docker compose exec redis redis-cli DEL scan:queue
  • 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 httpx retry kicks in within 10 s of the endpoint coming back.

POST /api/stripe/webhook is idempotent via the stripe_events table: every incoming event.id is inserted with ON CONFLICT DO NOTHING before processing.

If a subscription state disagrees between Stripe and Postgres:

Terminal window
# Manual sync — pulls the current subscription state from Stripe
docker 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.

  • Stripe moves the subscription into past_due → webhook marks the matching subscriptions rows as past_due.
  • require_module continues to allow access during the Stripe-defined grace period.
  • After canceled, access flips to HTTP 402 on the next request.

Affects JWTs + (if derived) MFA encryption:

  1. Generate: python -c "import secrets; print(secrets.token_hex(32))"
  2. If MFA_ENCRYPTION_KEY is derived from SECRET_KEY you must first set MFA_ENCRYPTION_KEY to the current derived value, then rotate SECRET_KEY. Otherwise existing MFA secrets become unreadable.
  3. Update env, restart app replicas. All access/refresh JWTs are invalidated; users re-login once.

Run the backfill helper (keeps legacy secrets decryptable during rollout):

Terminal window
docker compose exec app python -m scripts.encrypt_mfa_secrets --rotate
Terminal window
# Force-logout all sessions for a user
docker 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:

SignalSource
App healthGET /api/health/ready + Compose healthcheck
Postgres healthCompose pg_isready
Redis healthdocker compose exec redis redis-cli PING
Application logsdocker compose logs -f app scan_worker
Slow querieslog_min_duration_statement = 500 in postgresql.conf
Audit trailGET /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:

ItemProcedure
RedisNot backed up — treated as ephemeral cache. SSE tickets and PWA sessions auto-expire; rate-limit buckets are best-effort.
Stripe stateBacked up in Stripe. Our DB is a cache; if you lose stripe_events, the webhook replays everything cleanly on the next delivery.
MFA secretsBacked up with Postgres. They are encrypted at rest — restoring them to a server without the matching MFA_ENCRYPTION_KEY makes them unreadable.

Part I of this document (usage patterns and 100k-user model) defines SLOs. The expected headroom after the hardening plan:

Workloadp95 budgetNotes
GET /api/patients80 msServed from Redis cache after first hit
GET /api/subscriptions/active40 msRedis cache
POST /api/dispensings150 msWrites through primary, invalidates patient cache
POST /api/auth/login250 msDominated by bcrypt + constant-time branch
POST /api/scan/enqueue → first SSE event15 sLM Studio dependent
GET /api/analytics/daily1 sRead replica

Re-run k6 scripts (not committed) after every infrastructure change.


  1. docker compose build app scan_worker
  2. 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.
  3. docker compose up -d --no-deps --scale app=2 app
  4. Smoke test: /api/health/ready, login, scan, Stripe webhook.
  5. Roll scan_worker replicas: docker compose up -d --no-deps scan_worker
  6. If anything regresses, docker compose up -d app:<previous-tag> — Postgres and Redis stay untouched, rollback is safe.

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.

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.

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_dataPostgreSQL
lyncare_redis_dataRedis AOF
lyncare_uploadsFile uploads (app / scan workers)
  1. Inspect LynCareOS only

    Terminal window
    Set-Location D:\Projects\LynCareOS
    docker compose ps
    docker compose images
    docker system df
  2. 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
  3. Remove LynCareOS containers and drop locally built images for this compose file (optional; next up + build recreates the app image):

    Terminal window
    Set-Location D:\Projects\LynCareOS
    docker compose down --rmi local

    Do not add -v to docker compose down unless 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.

  4. 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
  5. Build cache (optional — shared by all projects on the machine, but is often where repeated docker compose build app in LynCareOS consumed space). Next builds may be slower until cache refills.

    Terminal window
    docker builder prune -f
  6. 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 especially docker 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).

  1. Quit Docker Desktop fully (tray → Quit).

  2. Shut down WSL (elevated PowerShell or normal — wsl --shutdown is often enough):

    Terminal window
    wsl --shutdown
  3. 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.vhdx

    A second, small file may exist at %LOCALAPPDATA%\Docker\wsl\main\ext4.vhdx (OS layer only — compacting it barely helps). The older doc path wsl\data\ext4.vhdx is often missing on up-to-date Docker Desktop; if DiskPart says the file cannot be opened or select vdisk fails, 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).

  4. Verify WSL is not holding the disk — in an Administrator prompt, wsl -l -v should show docker-desktop / docker-desktop-data (if listed) as Stopped, not Running. If anything is still Running, run wsl --shutdown again and wait a few seconds. If diskpart reports the file is in use, reboot once with Docker not set to start at logon, then try compact before starting Docker.

  5. Compact the virtual disk so the .vhdx file 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):

      diskpart
      select vdisk file="C:\Users\<You>\AppData\Local\Docker\wsl\disk\docker_data.vhdx"
      attach vdisk readonly
      compact vdisk
      detach vdisk
      exit
    • Hyper-V (if installed): from an Administrator PowerShell, after the same quit + wsl --shutdown sequence:

      Terminal window
      Optimize-VHD -Path "$env:LOCALAPPDATA\Docker\wsl\disk\docker_data.vhdx" -Mode Full

    If select vdisk fails, re-run the Get-ChildItem search above and paste the exact FullName into select vdisk file="...".

  6. Start Docker Desktop again. LynCareOS (and your other stacks) come back after you docker compose up as usual; you have only reclaimed file-system space inside the WSL2 disk, not deleted active volume data (assuming you did not run down -v or docker volume prune on 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.

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.

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.


PathRole
backend/services/cache.pyRedis TTL cache primitives
backend/services/crypto.pyFernet + HKDF for MFA encryption
backend/services/scheduler.pyTZ-aware APScheduler with SQLAlchemyJobStore
backend/services/sse_tickets.pyRedis-backed SSE ticket issuance
backend/services/pwa_auth.pyRedis-backed PWA ↔ Safari OAuth handoff
backend/services/shopping_pubsub.pyRedis pub/sub fan-out
backend/services/stripe_service.pyThin Stripe SDK wrapper
backend/services/stripe_provisioning.pyTenant/user creation from Checkout
backend/scan_worker.pyRedis queue consumer for LM Studio calls
backend/migrations/V037..V041Statement timeout, MFA encryption, dispensings NOT NULL, BOOLEAN must_change_password, Stripe schema
backend/scripts/encrypt_mfa_secrets.pyOne-shot backfill + rotation helper
frontend/src/hooks/useShoppingSync.tsSSE 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.