Storage Architecture
The system employs polyglot persistence across PostgreSQL (with the pgvector extension), Redis and MinIO, each optimised for a distinct access pattern. No single database technology excels at every workload the system must support: low-latency vector similarity search, transactional relational joins over entities, ephemeral session and rate-limit state, and large-object storage for raw document content.
Storage-level trade-offs
| Decision | Chosen | Alternatives considered | Rejected because |
|---|---|---|---|
| Vector store | PostgreSQL + pgvector (@pgvector_docs): one transactional database for embeddings, taxonomy and tenant metadata | Managed vector databases (Pinecone, Weaviate, Qdrant); in-process FAISS (@johnson2017faiss) | Managed vector databases add a second operational system, a separate access-control plane and a synchronisation surface against tenant and taxonomy data; FAISS is non-persistent and lacks transactional guarantees. pgvector keeps everything in one transactional database with one backup story. |
| ANN index type | HNSW (Hierarchical Navigable Small World) | IVFFlat (pgvector's other index type); exact nearest-neighbour search | IVFFlat needs periodic reindexing as the corpus grows, which is costly with continuous ingestion. Exact search scales linearly per query. HNSW handles insertions incrementally; the trade-off is higher memory at index build time, accepted at this corpus size (about ten thousand chunks). The approximate-versus-exact trade-off is the one Faiss @johnson2017faiss characterises at billion scale; pgvector's HNSW inherits that curve at PostgreSQL scale. |
| Knowledge graph | PostgreSQL taxonomy tables | A Neo4j graph database with graph algorithms (@neo4j_gds_manual) | Neo4j was removed on 2026-05-02 (see the Neo4j removal decision in the ADR register). Its graph algorithms (PageRank, community detection) were never load-bearing; the queries actually used were joins over typed entity tables. Removing it eliminated an operational service without losing retrieval capability. |
| Cache backend | PostgreSQL | Redis with the Redis Stack search module; in-process LRU cache | The second cache tier requires HNSW similarity search over 1,536-dimension embeddings, which plain Redis does not provide, and Redis Stack is not in the current deployment. An in-process cache loses its entries on every redeploy. PostgreSQL already has pgvector, so an extra table is the simplest change. |
| Object store | MinIO (self-hosted, S3-compatible) | AWS S3, Azure Blob Storage, Cloudflare R2 | Keeping raw document content on infrastructure controlled by the project was preferred as a data-residency precaution. MinIO presents an S3-compatible interface, so the application code is portable to a cloud store later. |
Storage overview
Vector store: PostgreSQL + pgvector
Why pgvector?
The vector store is the backbone of semantic search: it holds the dense embeddings that enable similarity-based retrieval (Reimers & Gurevych, 2019). Embedding pgvector in PostgreSQL rather than using a standalone vector database gives:
- A single database for relational metadata and vector embeddings
- Transactions protecting data integrity during ingestion
- A mature ecosystem: backup, monitoring and tooling from decades of PostgreSQL investment
- No vendor lock-in: pgvector is an open-source extension
Data model
Two record types carry the searchable content.
| Record | Holds |
|---|---|
| Document | Title, content type, category, processing status (pending, completed, failed), flexible metadata (source URL, entity types, campus), chunk and token counts, an authority score, a content-freshness label, creation and update times, and a soft-delete marker |
| Chunk | The text, its 1,536-dimension embedding, flexible metadata (page summary, canonical questions, section header), its position and token count, and a full-text search vector for keyword search; each chunk belongs to one document |
One document is split into many chunks. The flexible metadata uses a JSON column, so new attributes can be added without a schema migration.
Page summaries (contextual retrieval)
The chunk metadata stores page summaries generated during ingestion by the LLM entity validator (ADR-0014): two-to-three-sentence Dutch descriptions of the source document, used for contextual retrieval. Anthropic reports that the technique reduces retrieval failures by 49% when combined with hybrid search (the vendor's own published result, not measured by this project).
At query time, context assembly prepends the page summary to the first chunk of each document, giving the language model document-level context that individual chunks lose during chunking.
HNSW index
The system uses a Hierarchical Navigable Small World (HNSW) index for approximate nearest-neighbour search. HNSW was selected over IVFFlat for an architectural reason:
| Criterion | HNSW | IVFFlat |
|---|---|---|
| Insert performance | No reindex needed | Requires periodic reindexing |
| Query speed | Slightly faster | Fast after reindex |
| Memory usage | Higher | Lower |
| Dynamic data | Excellent | Poor without reindex |
Because the hospital's content is continuously ingested (new brochures published, website updated), HNSW's ability to absorb insertions without reindexing is decisive. IVFFlat would need scheduled reindexing jobs to maintain search quality.
The index uses 16 connections per layer and a construction-quality setting of 200, balancing search accuracy against build time. The pilot corpus is about 10,400 chunks (as counted when this page was last verified). The academic basis for HNSW's trade-off is summarised in @johnson2017faiss.
Vector dimensions
Each embedding is a 1,536-dimensional vector produced by OpenAI text-embedding-3-large, truncated from the model's native 3,072 dimensions to fit pgvector's 2,000-dimension HNSW limit. See ADR-0048, @openai2024embeddings and @pgvector_docs.
Migration history:
- nomic-embed-text (768 dimensions, self-hosted): initial deployment
- BGE-M3 (1,024 dimensions, self-hosted): February 2026
text-embedding-3-large(1,536 dimensions, truncated, OpenAI): current since April 2026 (ADR-0048)
The current model provides:
- Stronger Dutch retrieval (MTEB-NL about 64.6 versus 60.0 for BGE-M3)
- No self-hosted embedding service to operate
- Predictable latency under load
- A cost of about $0.13 per million tokens (roughly $0.20 per month at the 25,000 monthly queries stated in the January 2026 project brief), accepted in ADR-0048 for the quality and operational gains
Entity taxonomy: PostgreSQL
Relational model
Entity relationships are stored in PostgreSQL taxonomy tables, replacing the earlier Neo4j knowledge graph. This keeps all structured data in one database, simplifying operations and allowing transactional consistency with the vector store.
Entity types
The taxonomy is modelled across several tables, each scoped by hospital:
| Entity | Description | Example |
|---|---|---|
| Hospital | Top-level organisation | The pilot hospital |
| Campus | Physical location | A hospital campus |
| Department | Hospital department, with aliases | Cardiology (alias: "heart department") |
| Condition | Medical condition, with SNOMED codes | Heart failure |
| Treatment | Medical procedure | Knee replacement, chemotherapy |
| Examination | Diagnostic procedure | MRI, blood test |
| Doctor | Medical professional | A cardiologist |
Relationships
Relationships are stored in link tables with foreign keys: department to campus, doctor to department (with role, schedule, status and contact details), department to condition, treatment and examination, and treatment or examination to the condition it addresses. Every link table carries the hospital reference for isolation and uses composite uniqueness rules to prevent duplicate relationships.
Tiered query strategy
The taxonomy uses a two-tier strategy to balance precision and recall:
- Tier 1, typed entities: SQL queries against typed entity tables, routed by entities extracted by the language model. Used for precise lookups ("Who is this doctor?") and for questions resolved through aliases (a lay term for heart problems resolves to heart failure, then to Cardiology). Highest confidence, fastest.
- Tier 2, vector fallback: falls back to pgvector semantic search when the taxonomy has no relevant entity, so the system always returns results.
Neo4j was fully removed on 2026-05-02 (see the Neo4j removal decision in the ADR register). All entity relationships now live in PostgreSQL taxonomy tables. This removed a separate infrastructure dependency while preserving the same entity model and query semantics; SQL queries replaced the graph query language behind an unchanged interface.
Operational and analytics tables
The taxonomy and document tables above are the primary semantic surface. A second group of tables, added between April and May 2026, captures the operational state of the running system and feeds the operations dashboard. All are scoped per hospital (see Multi-Tenancy).
| Data set | Purpose | Main content |
|---|---|---|
| Ingest audit log | One record per nightly ingestion invocation | Mode, start and end time, URL counts (discovered, indexed, failed), failure class, notes |
| Business hours | Per-hospital opening hours, so the voice channel can answer "is the hospital open right now?" | Weekday, opening and closing time, closed flag |
| Cost models | Per-hospital language-model cost model used by the cost tracker | Per-token rates by model tier, effective date |
| Daily metrics | Daily aggregation feeding the value dashboard | Queries served, cache hit rate, deflection count, estimated savings |
| Category mismatch telemetry | Per-turn telemetry for the intent re-ranking: what fraction of top-ranked chunks were outside the intent's preferred categories. Drives the category mismatch chart | Intent class, primary category, mismatch rate, chunk counts, a short query preview |
| Diagnostic feedback | Operator verdicts (agree, partial, disagree) on diagnostic-investigation outputs; one rating per operator per investigation. Drives the diagnostic accuracy chart | Investigation, operator, verdict, notes |
These data sets are read by the administrative statistics functions; see Feedback Dashboard Metrics for the rendering layer.
Semantic query cache: PostgreSQL + pgvector (ADR-0031)
The query cache is a two-tier system that stores previous query results in PostgreSQL, using the same pgvector infrastructure as the vector store. It operates on language-model-reformulated queries, not raw user input, which raises the hit rate because the intent classifier normalises language, spelling and word order before caching.
Two-tier lookup
| Tier | Mechanism | Latency | What it catches |
|---|---|---|---|
| Tier 1 | SHA-256 hash of the reformulated query text | about 1 ms | Identical reformulations, including queries in other languages that normalise to the same Dutch form |
| Tier 2 | Cosine similarity through the HNSW index over 1,536-dimension embeddings | about 30 ms | Semantically equivalent queries worded differently (for example two different Dutch phrasings of "which doctors work in orthopedics?") |
Why reformulated queries?
The intent classifier already normalises each user query to well-formed Dutch clinical language, which collapses many distinct inputs into identical strings. For example, "rugpijn" (Dutch), "back pain" (English) and the same phrase in Turkish all become the same Dutch question about which departments treat back pain. All three produce the same reformulated query and therefore a Tier 1 hit after the first request, whatever the language.
Stored data and indexes
Each cache entry stores the hospital, the hash and text of the reformulated query, the original query, its embedding, the cached response text, the citations, the classified intent, a hit counter and creation and expiry times. Three indexes support it: a uniqueness rule on hospital plus hash (for exact-match lookup and as the target of updates), an HNSW index for similarity search, and an index on expiry time for clean-up sweeps.
Configuration
| Setting | Default | Description |
|---|---|---|
| Cache enabled | on | Switches the whole cache on or off |
| Time to live | 1 hour | How long an entry lives |
| Similarity threshold | 0.97 | Minimum cosine similarity for a Tier 2 hit (allowed range 0.80 to 1.00) |
All settings can be changed at runtime through the administration settings page and persist per hospital.
Why PostgreSQL instead of Redis?
| Criterion | PostgreSQL + pgvector | Redis |
|---|---|---|
| Vector similarity search | Native HNSW support | Requires Redis Stack (not deployed) |
| Persistence | Survives restarts | Volatile without extra persistence settings |
| Multi-tenant queries | SQL filters | Manual key namespacing |
| Already deployed | Yes (vector store) | Yes (sessions only) |
| Transactional guarantees | Full transactions | Eventual consistency |
The decisive factor is Tier 2: approximate nearest-neighbour search on embeddings needs pgvector's HNSW index. Since PostgreSQL is already the primary data store, adding a table is simpler than deploying Redis Stack.
A cache hit avoids all language-model calls (intent classification, query rewriting, generation, quality evaluation), which together cost roughly $0.003 per query. At the 25,000 monthly queries stated in the January 2026 project brief and an assumed 40-60% hit rate, caching would save an estimated $30-45 per month and reduce latency from about 5.5 s to under 50 ms. These are planning estimates, not measured results.
Sessions and rate limiting: Redis
Redis serves three ephemeral roles:
| Role | TTL | Purpose |
|---|---|---|
| Session storage | 30 minutes | Maintain conversation context across requests |
| Rate-limit counters | 1 minute | Sliding-window rate limiting |
| Token blacklist | 24 hours | Invalidate tokens on logout |
Object storage: MinIO
MinIO stores the canonical source content: the Markdown extracted from documents and the raw HTML crawled from the website. This serves two purposes:
- Re-processing: when the chunking strategy or embedding model changes, content can be re-processed from MinIO without re-crawling the website or re-extracting PDFs.
- Audit trail: the raw content is a verifiable reference for what the system ingested, supporting content governance.
MinIO was chosen over cloud object storage to keep the raw content on infrastructure controlled by the project, as a data-residency precaution.