Adrian Bernhard
← Technical docs

01 · Hospital

Erebor: technical documentation

The hospital: HAPI FHIR R4 behind a gateway that keeps reads open, gates writes and runs the front desk.

Synced from source on 26 October 2026

Erebor is the "hospital" in a three-part interoperability sandbox: a public HAPI FHIR R4 server holding synthetic patients, fronted by a small Node gateway that keeps reads open, gates writes behind an API key, serves a custom browsing UI and runs a front desk for linking patients to a separate patient portal. This page describes Erebor's code, configuration and data as deployed in October 2026.

Live: https://fhir.adrianbernhard.ch (explorer) and https://fhir.adrianbernhard.ch/fhir (FHIR base).

1. Overview#

The sandbox has three systems with deliberately separate identities:

  • Erebor: the hospital. Clinical records as FHIR R4 resources.
  • Orthanc: a radiology institute with a PACS and its own FHIR server.
  • Imladris (portal.adrianbernhard.ch): a patient-driven portal that stores accounts and link state but no clinical data. It links a patient's account to their record at each institution and reads the records over each institution's public API.

Erebor and Orthanc never share patient IDs. Matching a person across them is Imladris's job, and Erebor's part in it is the front desk (/desk), where hospital "staff" confirm that a portal user is a given Erebor patient.

All data is synthetic or fictional. Public read access is a feature: anyone can query the API with a browser or curl. Writes need a key that only trusted backends and the seeding scripts hold, and the database is restored to a clean snapshot every night at 03:00 UTC, so whatever was written during the day disappears.

The live server holds 359 patients: 8 curated Swiss showcase patients with full hospital records, and 351 Synthea-generated patients.

2. Architecture#

flowchart LR
    subgraph Internet
        B[Browser: explorer, desk]
        C[curl / any FHIR client]
        P[Imladris backend]
    end
    subgraph VPS["VPS (Coolify, Docker Compose)"]
        RP[reverse proxy<br/>TLS]
        subgraph GW["Gateway (Node 22, Express)"]
            HDR[CSP + HSTS on every response]
            DESK["/desk router<br/>same-origin API, rate limits"]
            CORS[CORS *]
            READY{"HAPI ready?<br/>readiness.js"}
            GUARD{"/fhir guard<br/>operation allowlist,<br/>per-IP rate limits"}
            GATE{write method?<br/>X-API-Key check}
            PROXY["/fhir proxy<br/>http-proxy-middleware"]
            READER["/explorer-api/read<br/>Markdown to safe HTML"]
            STATIC[static explorer<br/>public/]
        end
        HAPI[HAPI FHIR 8.12 JPA<br/>R4, no public port]
        PG[(PostgreSQL 16<br/>live DB)]
        SEEDVOL[(seed snapshot volume)]
        CRON[[host cron 03:00 UTC<br/>reset-cron.sh]]
    end
    IML[Imladris API<br/>portal.adrianbernhard.ch]

    B --> RP
    C --> RP
    P -->|reads| RP
    RP --> HDR --> DESK
    DESK -->|not /desk| CORS --> READY
    READY -->|starting| S[503 + Retry-After]
    READY --> GUARD
    GUARD -->|other operation| F[403]
    GUARD -->|over limit| T[429]
    GUARD --> GATE
    GATE -->|bad/missing key| X[401]
    GATE -->|GET/HEAD, or key OK| PROXY --> HAPI
    GATE --> READER --> HAPI
    GATE --> STATIC
    DESK -->|reads Patient| HAPI
    DESK -->|lookup/redeem,<br/>institution key| IML
    HAPI --> PG
    READY -.->|poll /metadata, warm-up| HAPI
    CRON -->|pg_restore into temp DB, swap| PG
    SEEDVOL --> PG

Walkthrough. The host's reverse proxy terminates TLS and forwards every request for the domain to the gateway, the only service with an exposed port. HAPI and Postgres are reachable only on the internal Docker network.

Inside the gateway (gateway/app.js) the middleware order matters:

  1. CSP, HSTS and nosniff headers on every response.
  2. The desk router (gateway/desk.js): /desk and its API. It comes before CORS and the write gate because its POSTs never reach HAPI and browsers may only call it same-origin.
  3. CORS with Access-Control-Allow-Origin: * for everything else.
  4. The readiness gate (gateway/readiness.js): until HAPI has started and been warmed up, /fhir and the reader answer 503 (see Startup and readiness in section 8). GET /health sits just before the desk and always answers.
  5. The /fhir guard (gateway/fhir-guard.js): read-only operations allowlist (403 otherwise, any method, key or not) and per-IP rate limits.
  6. The write gate: POST, PUT, PATCH and DELETE need an X-API-Key header matching WRITE_API_KEY, otherwise 401.
  7. The FHIR proxy: /fhir and below, forwarded verbatim with no body parser in front. A request that cannot connect to HAPI marks it down (readiness) and answers 503 "starting"; other proxy errors answer 502 without naming the internal host.
  8. The reader endpoint GET /explorer-api/read/:type/:id.
  9. Static files for every other path (the explorer).

One function (isFhirPath: exactly /fhir or /fhir/..., case-sensitive) decides both what the guard inspects and what the proxy forwards, so no path can reach HAPI without passing the guard. The write gate applies to every path that reaches it, not only /fhir: a POST to / also gets 401.

3. Stack#

Component Version Source
HAPI FHIR JPA server image hapiproject/hapi:v8.12.0-1 (reports HAPI FHIR 8.12.0, FHIR 4.0.1) docker-compose.yml, live X-Powered-By
PostgreSQL postgres:16.15 docker-compose.yml
Gateway runtime node:22.23-alpine (Node 22 LTS), dependencies installed with npm ci gateway/Dockerfile
express 4.22.3 (range ^4.19.2) package.json, lockfile
http-proxy-middleware 2.0.10 (range ^2.0.6) same
cors 2.8.6 same
markdown-it 14.3.2 same
sanitize-html 2.18.0 same
Synthea v4.0.0 jar, run in eclipse-temurin:21-jre seed/generate.sh
Explorer UI vanilla HTML/CSS/JS, no build step, no framework gateway/public/
Tests Node's built-in node:test, 61 tests gateway/test/
Hosting Coolify, Docker Compose build pack, auto-deploy on push to main

HAPI is configured entirely through environment variables in docker-compose.yml: the Postgres dialect (without it HAPI crash-looped on Postgres during initial setup), R4, JSON, the public server address, a maximum page size of 200, and expunge and mass deletes switched off (section 7).

4. Data model#

Two populations#

Synthea patients (351 observed on the live server). seed/generate.sh runs Synthea v4.0.0 with seed 12345 for both the population and clinician seeds, -p 300, state Massachusetts, exporting one FHIR R4 transaction Bundle per patient plus shared hospital and practitioner Bundles. seed/load.sh POSTs those Bundles through the gateway's normal write path (with the key), hospitals and practitioners first. The output is US-flavoured: US addresses, SNOMED CT, LOINC, RxNorm and CVX codes, and no Swiss identifiers.

Curated patients (8). Built by a separate generator from YAML specs: fictional Swiss patients with hospital stays, surgery, anaesthesia, oncology, labs in SI units, ICD-10-GM diagnoses, letters and reports. Each is one transaction Bundle in which every entry is a PUT with a deterministic ID, so loading twice changes nothing. Imaging for the same people lives at Orthanc under different IDs. The curated data's dates are pinned to an anchor of 2026-10-03. History stays on those dates; only the booked appointments after the anchor are moved forward every night, so they stay upcoming (section 8, "Demo dates"). A shared weekly rebuild that shifts the whole timeline across Erebor, Orthanc and Imladris is planned, not running.

Resource types#

Erebor's HAPI supports all R4 resource types (146 in the CapabilityStatement). What the data and the code actually use:

Resource Used by
Patient everything; curated IDs are the Erebor MRN
Encounter, Condition, Procedure, Observation both populations; explorer patient file
DocumentReference Synthea notes (folded into encounters), curated letters (rows)
DiagnosticReport curated pathology/radiology/lab reports; Synthea note twins (excluded)
Appointment curated future bookings ("Upcoming" in the explorer and Imladris), moved forward nightly
Practitioner, PractitionerRole, Organization, Location authors, participants, places
MedicationRequest, MedicationStatement, MedicationAdministration, AllergyIntolerance, CarePlan, ServiceRequest, Specimen curated records (not shown by the explorer)
erDiagram
    Patient ||--o{ Encounter : "subject"
    Patient ||--o{ Condition : "subject"
    Patient ||--o{ Appointment : "participant"
    Encounter ||--o{ DocumentReference : "context.encounter"
    Encounter }o--o{ Practitioner : "participant"
    Patient ||--o{ DocumentReference : "subject"
    Patient ||--o{ DiagnosticReport : "subject"
    DocumentReference }o--|| Practitioner : "author"
    DiagnosticReport }o--|| Practitioner : "performer"
    Appointment }o--o{ Location : "participant.actor"

Identifiers and tags#

What System Format / example
Erebor MRN https://fhir.adrianbernhard.ch/sid/erebor-mrn EB + 8 digits, e.g. EB40271853; also the curated Patient.id
Demo AHV number https://fhir.adrianbernhard.ch/sid/ahv-demo 999.4001.0000.19
Case (encounter) number https://fhir.adrianbernhard.ch/sid/erebor-case C-YYYY-NNNNNN
Order number https://fhir.adrianbernhard.ch/sid/erebor-order EO-NNNNNNN
Staff roster ID https://fhir.adrianbernhard.ch/sid/erebor-staff e.g. erebor-brunner
Curated tag meta.tag https://fhir.adrianbernhard.ch/CodeSystem/erebor-tags code curated plus rules-v1 (generator rules version)

The AHV system is a demo system on Erebor's own domain. The real Swiss AHVN13 has an OID (urn:oid:2.16.756.5.32) and numbers starting with 756; the curated data uses neither on purpose and prefixes every number with 999, so a demo number can never be mistaken for a real one. Synthea patients carry no AHV and no Erebor MRN; their IDs are server-assigned.

The explorer separates the two populations with _tag=...|curated and _tag:not=...|curated.

5. Interfaces#

5.1 FHIR REST API: /fhir (public reads)#

Standard HAPI FHIR R4 REST: read, vread, search, _history, _include/_revinclude, _elements, _summary and paging, with no authentication. Limits that apply to everyone:

  • Operations: only $everything, $meta and $validate are allowed. Any other operation ($expunge, $reindex, $lastn, $expand, ...) answers 403 with an OperationOutcome.
  • Page size: _count is capped at 200 by HAPI; larger values are clamped.
  • Rate limits: 120 requests per minute per IP on /fhir, of which at most 10 may be $everything. Over the limit: 429 with Retry-After. Requests carrying the write key or a trusted read-client key (X-Client-Key) are not counted.
  • Links: Bundle.link, fullUrl and Content-Location use the public base URL, so next links can be followed directly.
  • While starting: after a deploy, restart or the nightly reset, every /fhir request answers 503 with Retry-After: 30 and an OperationOutcome (code: transient, "Erebor is starting up, try again in a minute") until HAPI is up and warm. GET /health says which: {"status":"ready"|"starting","warmupMs":…,"readySince":…}.
sh
curl -s "https://fhir.adrianbernhard.ch/fhir/Patient?identifier=https://fhir.adrianbernhard.ch/sid/ahv-demo|999.4001.0000.19&_elements=name,birthDate"

5.2 Explorer pages: /#

The explorer is a single static page plus app.js, served by the gateway. It calls the same public /fhir endpoints any client could.

  • Search: name (with autocomplete), ID (direct GET Patient/{id}), condition (resolved through a paged Condition?code:text= search, because this HAPI version rejects modifiers inside a _has chain), age range (turned into birthdate=le/ge), sex.
  • Patient file: four parallel searches (Condition; Encounter with _include=Encounter:participant; DocumentReference and DiagnosticReport with _elements so no text is transferred) at _count=200, following next links (path and query only, so it also works locally) up to 1000 resources each. Rows are grouped by year, 50 per year before "show all".
  • Synthea note folding: Synthea writes one undescribed "History and physical" DocumentReference per encounter. Such a note becomes its encounter's "read" action instead of its own row, and its DiagnosticReport twin (category LOINC 34117-2) is excluded in the search with category:not=http://loinc.org|34117-2.
  • Upcoming: booked Appointments from today on, with practitioner and location included.
  • Live counts: total, curated and Synthea patient counts, and server status from /fhir/metadata.
sh
curl -s https://fhir.adrianbernhard.ch/ | grep -o '<title>.*</title>'

5.3 Reader: GET /explorer-api/read/:type/:id#

Returns one DocumentReference or DiagnosticReport as JSON: title, typeLabel, date, author, and html, the document's Markdown text rendered to sanitized HTML. Only those two types are accepted, and the ID must match ^[A-Za-z0-9.-]{1,64}$; anything else is 404. Responses are Cache-Control: no-store and the text is never logged.

sh
curl -s https://fhir.adrianbernhard.ch/explorer-api/read/DocumentReference/doc-e3fbda5142022c6f

5.4 Front desk: /desk#

GET /desk is a staff page in which a portal link code is looked up, matched to an Erebor patient, and redeemed. Imladris opens it as a popup (/desk?code=XXXX-XXXX); it also works when opened directly. Its JSON API serves that page:

Route Purpose Limit (per IP)
POST /desk/api/lookup {code} Imladris lookup; returns the claimed identity and suggested Erebor patients 10/min
GET /desk/api/search?q= manual search: name words, birth date (YYYY-MM-DD or D.M.YYYY), AHV, EB... MRN, any mix; max 20 30/min
POST /desk/api/redeem {code, patient_id, confirmed} redeems the code at Imladris with Erebor's patient ID and a match summary 10/min

Browsers can only call the API from the desk page itself. Non-browser clients such as curl can call it too, by design: the desk is public, and what protects a link is the code, which is single-use, expires, allows a limited number of attempts at Imladris, and is looked up through rate-limited routes.

sh
curl -s -D - -o /dev/null https://fhir.adrianbernhard.ch/desk   # shows COOP, Referrer-Policy, no-store
sequenceDiagram
    actor U as Patient (Imladris)
    participant I as Imladris
    participant D as Desk page
    participant G as Gateway /desk/api
    participant H as HAPI
    U->>I: "Link my Erebor record"
    I->>I: issue single-use code, remember claimed identity
    I->>D: open popup /desk?code=XXXX-XXXX
    D->>D: read code, strip it from the URL
    D->>G: POST lookup {code}
    G->>I: lookup (institution key)
    I-->>G: claimed name, birth date, AHV
    G->>H: Patient?identifier=ahv-demo|AHV, else birthdate + name filter
    G-->>D: claim + suggestions
    D->>D: staff pick a patient, page shows match level
    D->>G: POST redeem {code, patient_id, confirmed}
    G->>I: lookup again
    G->>H: GET Patient/{id}
    G->>G: compareIdentity() server-side
    G->>I: redeem {external_patient_id, match:{level, fields}}
    G-->>D: redeemed
    D->>I: postMessage to IMLADRIS_ORIGIN, close popup

5.5 Writes (protected)#

POST, PUT, PATCH and DELETE on /fhir need X-API-Key. Without it the gateway answers 401 {"error":"Missing or invalid X-API-Key header"} before HAPI sees the request. The key lives only in trusted backends and the seeding scripts' environment. There is no way to write to the live server without it, even a keyed request cannot run admin operations or expunge, and anything written is gone after the next reset.

6. Standards#

FHIR R4 fidelity. The server is unmodified HAPI FHIR, so the REST semantics, search parameters and CapabilityStatement are HAPI's. The gateway does not rewrite FHIR traffic; it only refuses requests (non-allowlisted operations, rate limits, unkeyed writes). The CapabilityStatement still advertises every operation HAPI registers, including those the gateway refuses. The curated data uses standard terminologies (LOINC, SNOMED CT, ICD-10-GM, UCUM, HL7 v2-0203 identifier types, v3 ActCode encounter classes) but does not declare or validate against any profile, including the Swiss CH Core profiles. Synthea data follows Synthea's own US-oriented conventions.

The mappings below are analogies, not conformance claims.

IHE PDQm (Patient Demographics Query for mobile). PDQm defines a Patient search by demographics (name, birth date, identifier) over FHIR. Erebor's Patient search supports those parameters because HAPI does, and the desk uses exactly that shape internally, but there is no PDQm profile and no $match.

IHE PIXm (Patient Identifier Cross-referencing). PIXm answers "what is this patient's ID in other domains?" from a cross-reference manager. Erebor has no PIXm endpoint. The closest analogue is Imladris, which ends up holding (institution, external_patient_id) pairs per account; the front desk is the human-confirmed step that creates such a pair.

SMART on FHIR. Not implemented. Reads are anonymous; writes use a single shared API key. There is no OAuth2, no scopes, no launch context. Listed as out of scope for v1.

Swiss EPD. In the Swiss electronic patient record the cross-community patient identifier is the EPR-SPID, not the AHV number. Matching here on a (demo) AHV number is a simplification chosen because it is easy to explain and to fake safely. A realistic setup would resolve a local MRN to an EPR-SPID through the community's MPI (PIX/PDQ), and the front desk's AHV checks would become EPR-SPID checks plus demographic checks.

7. Security and privacy#

  • No real data. Synthea output and fictional curated patients only; demo AHV numbers use a non-real prefix and a non-real identifier system.
  • Open reads, keyed writes. Only the gateway is exposed. The key is compared in constant time (SHA-256 of both sides, then crypto.timingSafeEqual), so neither its content nor its length leaks through timing.
  • Operations allowlist, defended twice. HAPI's admin operations ($expunge, $reindex, $mark-all-resources-for-reindexing, $hapi.fhir.merge, terminology uploads) are all affectsState: true in their OperationDefinitions, and HAPI accepts those only over POST, so they never pass the write gate without the key. On top of that, the gateway forwards only $everything, $meta and $validate, for any method and key or not, decoding the path first so %24expunge is caught too. Inside HAPI, expunge and mass deletes are switched off as well.
  • Load protection. The rate limits and page-size cap from section 5.1.
  • Trusted read clients. A backend that reads for many users from one IP (Imladris) would exhaust a per-IP budget, so it gets its own key from CLIENT_KEYS, sent as X-Client-Key. The key is hash-compared in constant time like the write key and only lifts the rate limits: writes still need X-API-Key, and the operations allowlist and page cap still apply. A leaked client key therefore allows unthrottled reads of public data and nothing else, and each client has its own key so one can be revoked alone.
  • Nightly reset bounds the damage of any write, malicious or buggy, to one day.
  • Rendering untrusted text. Anyone with the key (or any consumer app bug) can write document text, so the reader treats it as hostile. gateway/markdown.js renders Markdown with html: false and links/images disabled, then runs sanitize-html with a tag allowlist (headings, paragraphs, lists, emphasis, code, rules, breaks) and no attributes at all. A test feeds a deliberately hostile document through both the renderer and the endpoint.
  • Headers. CSP on every response: script-src 'self' (no inline script), styles from self and Google Fonts, object-src 'none', base-uri 'none', frame-ancestors 'none', form-action 'self'. HSTS max-age=31536000, this host only, no preload. X-Content-Type-Options: nosniff; no X-Powered-By. The explorer builds the DOM with textContent; the one innerHTML of server data is the reader's sanitized HTML.
  • No internal addresses in responses: HAPI writes the public base URL into links.
  • Front desk.
    • The match result sent to Imladris is computed on the server from a fresh lookup of the code and a fresh read of the Patient; the browser cannot choose it. A mismatch without confirmed: true is refused with 409.
    • Only field names travel in the match (given_name, birth_date, ...), never values.
    • For browsers, the API is same-origin only: it rejects OPTIONS and any Sec-Fetch-Site other than same-origin, and sends no CORS headers. Clients that send no Sec-Fetch-Site at all (curl) are allowed by design (section 5.4).
    • JSON bodies are capped at 2 kB, every route is rate-limited per IP, and every invalid code gives the same answer.
    • Codes, identities, searches and the institution key are never logged; upstream failures log the route plus an HTTP status or the error's class name only.
    • /desk sends Referrer-Policy: no-referrer (the URL holds the code) and Cross-Origin-Opener-Policy: unsafe-none, so the Imladris opener keeps its window reference.
  • Shared identity module. gateway/identity.js and gateway/test/identity.test.js are byte-identical in the Erebor and Orthanc gateways, so both institutions report match levels by the same rules. The module normalizes names (case, spacing, hyphens, ß to ss, other diacritics dropped) and folds umlauts two ways (ä to ae and ä to a); two names are equal if either folding agrees. mismatch means the birth date differs or both AHVs exist and differ; differences means a name differs or an AHV is missing; otherwise match.

8. Operations#

Deploy. Coolify watches main and redeploys the Compose stack on every push. The gateway image is built from gateway/Dockerfile; HAPI and Postgres are pinned images. The public domain points at the gateway, never at HAPI.

Environment variables (secrets set in Coolify, never committed; .env.example lists the gateway's):

Name Purpose
POSTGRES_PASSWORD database password, shared by Postgres and HAPI
WRITE_API_KEY the write key; the gateway refuses to start without it
FHIR_RATE_LIMIT, FHIR_EVERYTHING_RATE_LIMIT optional overrides of the /fhir limits (120, 10)
CLIENT_KEYS trusted read-client keys, comma-separated (sent as X-Client-Key)
INSTITUTION_KEY_EREBOR Erebor's key at Imladris (32+ chars)
IMLADRIS_URL Imladris API base, server-to-server
IMLADRIS_ORIGIN the only postMessage target; must be a bare origin
FHIR_UPSTREAM_URL the gateway's internal address for HAPI (set in the Compose file)
JAVA_TOOL_OPTIONS HAPI heap flags (Compose file)
HAPI_FHIR_SERVER_ADDRESS, HAPI_FHIR_MAX_PAGE_SIZE, HAPI_FHIR_EXPUNGE_ENABLED, HAPI_FHIR_DELETE_EXPUNGE_ENABLED, HAPI_FHIR_ALLOW_MULTIPLE_DELETE, HAPI_FHIR_ALLOW_CASCADING_DELETES HAPI settings (Compose file)

If any of the three desk variables is missing or invalid, /desk says it is not configured, its API answers 503, and the rest of the gateway is unaffected.

Startup and readiness. HAPI takes 1-2 minutes to start, and the first /metadata afterwards takes ~18 s while its caches fill. The gateway does not wait for it (plain depends_on, no service_healthy): it starts at once and keeps a ready flag (gateway/readiness.js), false at startup.

stateDiagram-v2
    [*] --> starting
    starting --> warming: GET /fhir/metadata 200 (every 5 s, timeout 30 s)
    warming --> ready: warm-up done, duration logged
    warming --> starting: network error during warm-up
    ready --> starting: 3 failed checks in a row, or a proxied request can't connect
  • Warm-up (straight to the HAPI container, not through the public pipeline, so not rate-limited), read-only, one request at a time:

    • /metadata; _summary=count for Patient, Encounter, and DocumentReference and DiagnosticReport with the curated tag (the showcase stats queries); Patient?_count=10.
    • One request per query shape Imladris's dashboard sends, for one curated demo patient (Léa Morand, resolved by her demo AHV, Patient?identifier=…/sid/ahv-demo|999.4001.0000.33, since server ids can change after a reset): Patient/<id>; Condition, Encounter (_include=Encounter:participant), DocumentReference and DiagnosticReport (_elements + _include of author/performer) and booked future Appointments (_include=Appointment:actor), each ?patient=<id>&_count=200 (one page for typical patients, no _total); and the two document reads that opening a letter or report sends (DocumentReference?_id=…&_include=DocumentReference:author, likewise for DiagnosticReport). Imladris reads no Binary.

    A step that depends on an earlier answer (no patient, no document) is skipped. Each request has a 60 s timeout and the whole warm-up a 180 s budget; once that is spent, the remaining steps are skipped and Erebor opens anyway. A connection that is refused or a host that doesn't resolve (HAPI gone) sends it back to polling; anything else (HTTP error, timeout) is logged and skipped, so one bad query can't keep Erebor closed. Each step's time is logged by name (no ids). Locally it takes 1-3 s.

    Imladris fetches pages of 200 without _total. With smaller pages, the second page of any new search cost about 600 ms on HAPI whether it was warm or not (only a repeat within 60 s was fast, from HAPI's search cache), so one page per patient is both the faster dashboard and the shape the warm-up primes.

  • While not ready: /fhir and /explorer-api answer 503 + Retry-After: 30 with an OperationOutcome; the desk API answers 503 {"error":"starting"} and the desk page shows "Erebor is starting up, try again in a minute." (it checks /health on load and every 10 s); the explorer's status shows "starting up" instead of "offline".

  • While ready: /metadata is still checked every 5 s. Three failures in a row, or one proxied request that gets ECONNREFUSED/ENOTFOUND/EAI_AGAIN/EHOSTUNREACH (a stopped container drops out of Docker's DNS), set ready back to false and the cycle repeats. A single timeout or reset doesn't.

  • GET /health: status, warmupMs (the last completed warm-up, kept while starting again) and readySince (ISO time, null unless ready). No hostnames, no error details. Cache-Control: no-store.

  • Docker healthcheck on the HAPI container: the image is distroless (no shell, curl or wget) and its JRE has no jdk.compiler, so neither a shell probe nor java Probe.java works. It ships /app/HealthCheck.class, which GETs HAPI's own /actuator/health from inside the container and exits 0 on 200. The Compose file runs it with its own small heap flags (overriding JAVA_TOOL_OPTIONS for that JVM), every 30 s, start_period: 180s. It is informational (docker ps, Coolify); /fhir/metadata and the warm-up are the gateway's job. The gateway has no healthcheck: Traefik drops containers that aren't healthy from routing, which would replace the "starting" answer with a bare 404/502.

Seeding. generate.sh, load.sh (through the gateway), then snapshot.sh, which writes a compressed pg_dump onto a named volume that survives redeploys. The curated patients are loaded on top of the Synthea base and the combined database is snapshotted.

Nightly reset (swap-restore). A host cron entry runs reset/reset-cron.sh at 03:00 UTC and restores the combined curated + Synthea snapshot:

flowchart TD
    A[check snapshot exists and pg_restore --list reads it] -->|fail| Z[exit 1, live DB untouched]
    A --> B[drop + create temp database]
    B --> C[pg_restore into temp DB, --exit-on-error]
    C -->|fail| Y[drop temp DB, exit 1, live DB untouched]
    C --> D[stop HAPI]
    D --> E[drop live DB, rename temp DB to live name]
    E --> F[start HAPI, exit trap restarts it on any failure]
    F --> G[poll /fhir/metadata up to 600 s, log Patient count]
    G --> W[wait for gateway /health ready, log warm-up ms]
    W --> S[demo dates: move booked appointments forward, failure is a warning]
    S --> H[Reset complete.]

The restore targets an empty temporary database instead of using pg_restore --clean, so a failed restore never leaves the live database empty or half-restored. A --clean restore drops objects before recreating them, and HAPI's schema is managed by Hibernate update, which only adds tables: a dump from an older HAPI can fail partway, after the drops. Snapshots are named after the HAPI version they were taken with and must be retaken after an upgrade. The swap briefly needs disk space for two database copies; HAPI is offline only for the swap and its startup. HAPI is restarted by the swap, so its caches are cold afterwards: the gateway notices the outage itself (connection errors on proxied requests, failed checks), answers "starting" meanwhile and warms HAPI up again. The script waits for /health to say ready and logs the warm-up time; a gateway that isn't ready in time is a warning, not a failed reset.

Demo dates. The curated data is pinned to an anchor of 2026-10-03, so its booked appointments would drift into the past. As its last step, the reset runs node demo-dates.js in the gateway container (gateway/demo-dates.js). It writes straight to HAPI over the internal network, not through the public gateway:

  • What moves: curated-tagged Appointments with status booked whose original start is after the anchor day: 8 in the seed, one per curated patient except one patient with two. Only start and end change. Past events, letters, reports, birth dates and identifiers stay as they are, and so do appointments visitors create (no curated tag). The seed has no Slot, Schedule, planned Encounter or open ServiceRequest.
  • By how much: the whole weeks since the anchor, floor((today - anchor) / 7) * 7 days, with "today" in Europe/Zurich, so the shift steps up every Saturday. Whole weeks keep the weekday. The wall-clock time in Zurich is kept too, and the UTC offset is recomputed for the new date (09:00+02:00 in October becomes 09:00+01:00 in November). The earliest appointment is 9 days after the anchor, so every appointment stays in the future on every day of the week.
  • Idempotent: the first shift stores the original period in the extension https://fhir.adrianbernhard.ch/StructureDefinition/demo-original-period, and every run computes from that. A second run, or a run without a restore, writes nothing. An appointment already at its target isn't written. Each write is a normal versioned update with If-Match.
  • Log: Demo dates: anchor 2026-10-03, today <date>, shift N days; 8 future-dated appointments, 8 shifted, 0 already in place. A failure logs WARNING demo date shift failed and the reset still counts as done. The appointments then keep the seed's dates until the next night.
  • Not run on deploy: a redeploy doesn't touch the database, so the data is at most one night behind. Running it at gateway startup would make the read-only proxy write to HAPI. To apply it at once (after the first rollout, say), run docker compose exec -T fhir-gateway node demo-dates.js by hand.

JVM memory. The VPS has 4 GB of RAM. Without flags the JVM took 25% of host RAM as max heap and HAPI ran into swap. The Compose file sets JAVA_TOOL_OPTIONS="-Xms256m -Xmx768m" (not JAVA_OPTS: the image is distroless and starts java without a shell, so only the variable the JVM reads itself works) and mem_limit: 1280m, leaving about 500 MB above the heap for metaspace, code cache and threads. If the container is ever OOM-killed, the documented response is to raise mem_limit before touching -Xmx.

Logging. Container output, viewed through Coolify. The gateway logs its start line, desk configuration warnings, proxy errors, readiness transitions ([readiness] …: waiting for HAPI, each warm-up step's time, warm-up took N ms; ready, failed checks), and failures as route plus status; no request logging, metrics or alerting. The reset logs timestamped steps (including the Demo dates: line) ending in Reset complete. or RESET FAILED.

Tests. npm test in gateway/ (69 passing): the request pipeline against a fake HAPI (allowlist, write gate, rate limits, client keys, headers), the readiness state machine against a fake HAPI that is down, slow, up and goes down again (plus the 503s, /health and a proxied request that can't connect), the warm-up's Imladris query shapes against a fake HAPI with the demo patient (order, document reads, no next page, GET only, no ids in the log) and its per-request timeout and total budget, the desk API against fake Imladris and HAPI, the identity rules, the renderer and reader against hostile input, and the demo date shift (the week arithmetic on the anchor day, mid-week and years later, Zurich time across daylight-saving changes, which appointments move, idempotence, and a week later computed from the original).

9. Design decisions and trade-offs#

Gateway instead of HAPI interceptors. Decision: enforce access in a small Express proxy. Why: "open reads, keyed writes" in HAPI means custom Java; the proxy's own logic is a few dozen lines. Trade-off: the gateway sees HTTP, not FHIR semantics: it can check methods, paths and operation names, but not, say, which resources a transaction Bundle touches.

Allowlist operations instead of blocklisting dangerous ones. Decision: forward only three named read-only operations, refuse the rest, and also switch off expunge in HAPI. Why: HAPI's operation list grows with versions and modules; an allowlist stays closed by default. Trade-off: harmless operations such as $lastn or $expand are refused too, and each new one a consumer needs must be added.

One shared API key instead of SMART/OAuth. Decision: a single X-API-Key held by trusted backends. Why: visitors never see auth, and the nightly reset caps the impact of misuse. Trade-off: no per-app identity, no scopes, no audit of who wrote what; rotating the key means updating every holder.

Swap-restore instead of in-place restore or API replay. Decision: restore into a temporary database, then rename it into place. Why: a bad dump never touches live data, schema drift cannot block the restore, and downtime is limited to a HAPI restart. Trade-off: double disk space during the swap, and snapshots must be retaken after every HAPI upgrade.

Own explorer instead of HAPI's tester UI. Decision: a static, dependency-free UI that uses only the public API. Why: it shows a clinician-style patient file and proves the API is enough to build one. Trade-off: client-side logic (note folding, paging, caps) that must track the data's quirks; very large histories are capped at 1000 resources per search.

Server-side Markdown rendering with two independent layers. Decision: render and sanitize in the gateway, keep CSP as a further layer. Why: the data is writable by design, so document text is untrusted. Trade-off: documents lose links, images and any formatting outside the allowlist.

Identity module duplicated, not packaged. Decision: identical copies of identity.js and its test in two repos. Why: no shared package registry or build step for two small services. Trade-off: drift is prevented by discipline, not tooling.

Demo AHV as the matching key. Decision: match on an AHV-like identifier plus name and birth date. Why: easy to explain, and the 999 prefix and private system make it safe. Trade-off: unlike the Swiss EPD, which uses the EPR-SPID; see section 6.

10. Known limits#

Erebor is a public demo sandbox. These limits are accepted for that scope:

  • Rate limits are per IP and held in memory. Users behind one NAT share a budget, the counters reset when the gateway restarts, and they would not be shared across several gateway instances. Servers that read for many users use a client key instead. Reason: one gateway instance is enough for a demo.
  • The front desk is public. Its API is meant for the desk page but does not require a browser, and Imladris limits each institution key per route, so heavy desk traffic can slow linking for everyone. Reason: link codes are single-use, short-lived and rate-limited, and the data is synthetic.
  • The CapabilityStatement lists more than the gateway allows. It is HAPI's unmodified statement and still advertises operations the gateway refuses. Reason: the gateway does not rewrite FHIR responses.
  • http-proxy-middleware v2 carries an npm audit finding in a transitive dependency (braces). Reason: the fix is a breaking upgrade to v3 that needs its own change.
  • No profiles and no validation on write. Anything HAPI accepts is stored until the nightly reset. Reason: writes come only from trusted backends and are wiped daily.
  • Synthea data is American and carries no Swiss identifiers, so only the 8 curated patients can be found by the desk's AHV path. Reason: the Synthea setup used generates a US population.
  • Only appointments move. The nightly demo date shift keeps booked appointments upcoming, but the rest of the curated history stays at its 2026-10-03 anchor. Over time the gap between the last visit and today grows, and patients don't age along with it. Reason: past documents stay as written, and the shared weekly rebuild of the whole timeline across Erebor, Orthanc and Imladris is planned, not running.
  • Letter texts can name the original appointment dates. Two curated letters mention a booked date, e.g. "Anaesthesia pre-assessment on 12.10.2026". The appointment itself has moved on, so the letter and the "Upcoming" entry disagree. Reason: letters are part of the record and aren't rewritten.
  • No SMART on FHIR, no audit log, no metrics. Reason: out of scope for v1.

Next steps: the shared weekly rebuild of the whole timeline, the proxy library upgrade, SMART on FHIR as a second auth demonstration, CH Core profiles for the curated patients, and EPR-SPID-style matching in the desk.

11. Try it#

  1. Open https://fhir.adrianbernhard.ch, type Aebischer in the name field, open the patient and pull the patient file. Open a letter with "read".
  2. Search a Synthea patient by condition (for example diabetes) and an age range, and compare how a thin Synthea history looks next to a curated one.
  3. Query the API directly and follow a next link: curl -s "https://fhir.adrianbernhard.ch/fhir/Encounter?patient=EB40271853&_count=5&_elements=type,period,serviceType" | grep -A1 '"next"'
  4. See the gateway refuse what it should: curl -s -X POST https://fhir.adrianbernhard.ch/fhir/Patient -H "Content-Type: application/fhir+json" -d '{"resourceType":"Patient"}' (401, no key) and curl -s 'https://fhir.adrianbernhard.ch/fhir/$expunge' (403).
  5. Open https://fhir.adrianbernhard.ch/desk to see the front desk. Without a link code from an Imladris account there is nothing to redeem; the full flow starts at https://portal.adrianbernhard.ch.