Skip to content

Search Architecture

This document describes the internal architecture of OctoFHIR’s search parameter system, including how search parameters are loaded, registered, and used during search operations.

For a user-facing overview of query/index behavior, see Search Indexing.

┌─────────────────────────────────────────────────────────────────┐
│ FHIR REST API Layer │
│ POST /SearchParameter → Create & Auto-Register │
│ GET /Patient?name=... → Query using Registry │
└──────────────────┬──────────────────────────────────────────────┘
│
┌──────────┴──────────┐
▼ ▼
┌───────────────────┐ ┌────────────────────┐
│ Postprocess Hook │ │ Search Handler │
│ - Validate FHIRPath│ │ - Parse Query │
│ - Apply Registry │ │ - Get Config │
│ - Clear Cache │ │ - Execute Search │
└─────────┬─────────┘ └──────────┬─────────┘
│ │
▼ ▼
┌─────────────────────────────────────────────┐
│ ReloadableSearchConfig (Arc-Swap) │
│ ┌───────────────────────────────────────┐ │
│ │ SearchConfig (Lock-Free Reads) │ │
│ │ ┌─────────────────────────────────┐ │ │
│ │ │ SearchParameterRegistry │ │ │
│ │ │ ArcSwap<RegistryData> │ │ │
│ │ │ - by_url (HashMap) │ │ │
│ │ │ - by_resource (HashMap) │ │ │
│ │ │ - by_type (HashMap) │ │ │
│ │ │ - common (HashMap) │ │ │
│ │ └─────────────────────────────────┘ │ │
│ │ ┌─────────────────────────────────┐ │ │
│ │ │ QueryCache (Optional) │ │ │
│ │ └─────────────────────────────────┘ │ │
│ └───────────────────────────────────────┘ │
└─────────────────────────────────────────────┘
│
▼
┌──────────────────┐
│ Canonical Manager│
│ (PostgreSQL) │
└──────────────────┘

The registry keeps all its indices in one immutable snapshot behind an ArcSwap. Readers load the snapshot without a lock. A writer takes a mutex, clones the data, rebuilds every index and publishes the new snapshot in one store.

Location: crates/octofhir-search/src/registry.rs

Data Structures:

pub struct SearchParameterRegistry {
data: ArcSwap<RegistryData>,
writer: Mutex<()>,
}
struct RegistryData {
/// Definitions from packages, by canonical URL
declarations: HashMap<String, Arc<SearchParameter>>,
/// Committed runtime resources: id -> (version, definition or deletion)
resources: HashMap<String, (i64, Option<Arc<SearchParameter>>)>,
/// Effective definitions by canonical URL
by_url: HashMap<String, Arc<SearchParameter>>,
/// Runnable parameters by (resource_type, code)
by_resource: HashMap<(String, String), Arc<SearchParameter>>,
/// Runnable parameters by resource type
by_type: HashMap<String, Vec<Arc<SearchParameter>>>,
/// Common parameters (base = "Resource" or "DomainResource")
common: HashMap<String, Arc<SearchParameter>>,
/// Every declared (resource_type, code) pair
declared: HashSet<(String, String)>,
}

Key Methods:

  • register(&self, param: SearchParameter) - Add a package definition
  • register_all(&self, params) - Add a batch and publish one snapshot
  • upsert(&self, param: SearchParameter) - Alias for register
  • apply_resource(&self, id: &str, version: i64, param: Option<SearchParameter>) -> bool - Apply a committed runtime revision. None marks a deletion. A version that is not newer than the known one is ignored, so a delayed event cannot bring back an old definition.
  • remove_by_url(&self, url: &str) -> bool - Remove a package definition by canonical URL
  • get(&self, resource_type: &str, code: &str) -> Option<Arc<SearchParameter>> - Look up a parameter

Runtime resources override package definitions. When a runtime resource is deleted, the package definition of the same URL comes back.

Why ArcSwap over HashMap?

  • Readers never wait for a writer
  • All indices change together, so a reader never sees a half-updated registry
  • Writes are rare and pay for the rebuild

Wrapper providing lock-free configuration access using atomic pointer swapping.

Location: crates/octofhir-search/src/reloadable.rs

Implementation:

pub struct ReloadableSearchConfig {
/// Inner config with atomic pointer swap (lock-free reads!)
inner: Arc<ArcSwap<SearchConfig>>,
options: Arc<RwLock<SearchOptions>>,
cache: Option<Arc<QueryCache>>,
}

Key Operations:

Get Config (Lock-Free Read):

pub fn config(&self) -> Arc<SearchConfig> {
self.inner.load_full() // Single atomic load, ~1-5 nanoseconds
}

Reload Registry (Atomic Swap):

#[cfg(feature = "canonical")]
pub async fn reload_registry(
&self,
canonical_manager: &CanonicalManager,
resolver: Option<&dyn ElementTypeResolver>,
) -> Result<(), LoaderError> {
// 1. Load new registry (doesn't block readers)
let new_registry = Arc::new(load_search_parameters(canonical_manager, resolver).await?);
// 2. Create new config
let current = self.inner.load_full();
let new_config = SearchConfig {
default_count: current.default_count,
max_count: current.max_count,
registry: new_registry,
cache: self.cache.clone(),
};
// 3. Atomic swap (old readers keep old config, new readers get new config)
self.inner.store(Arc::new(new_config));
// 4. Clear query cache
if let Some(cache) = &self.cache {
cache.clear();
}
Ok(())
}

The resolver fills in element types from the FHIR schema.

Why Arc-Swap?

  • Zero lock contention - Readers never wait for writers
  • Atomic updates - Pointer swap is atomic (single CPU instruction)
  • Graceful transition - Old readers finish with old config
  • Automatic cleanup - Old config freed when last reader releases it

Location: crates/octofhir-search/src/loader.rs

Loading Process:

  1. Register Common Parameters (built-in)

    • _id, _lastUpdated, _tag, _profile, _security, _source
    • Apply to all resource types
  2. Query Canonical Manager

    • Load all SearchParameter resources from PostgreSQL
    • Read them in pages of 1,000 until the last page
  3. Parse

    • Extract required fields (code, url, type, base)
    • Build internal SearchParameter struct
    • Resolve the element type from the schema, when a resolver is given
    • Skip a resource that fails to parse
  4. Register in Registry

    • All parsed parameters go in with one register_all call, which publishes one snapshot
    • Index by URL
    • Index by (resource_type, code) for each base
    • Mark as common if base includes “Resource” or “DomainResource”

A SearchParameter written through the REST API reaches the registry in two ways. Both call apply_resource with the committed version, so applying the same revision twice does nothing.

Request path. postprocess_resource in crates/octofhir-server/src/handlers.rs runs after a successful create or update. The delete handler does the same with None.

async fn postprocess_resource(
resource_type: &str,
resource_id: &str,
payload: &Value,
state: &crate::server::AppState,
) -> Result<(), ApiError> {
if let Some(cache) = &state.resource_cache {
cache.invalidate(resource_type, resource_id).await;
}
if resource_type == "SearchParameter" {
if let Some(expression) = payload.get("expression").and_then(|v| v.as_str()) {
validate_fhirpath_expression(expression)?;
}
match octofhir_search::parse_search_parameter(payload) {
Ok(param) => {
let config = state.search_config.config();
let version = payload["meta"]["versionId"]
.as_str()
.and_then(|version| version.parse().ok())
.ok_or_else(|| {
ApiError::internal("Committed SearchParameter has no revision")
})?;
config
.registry
.apply_resource(resource_id, version, Some(param));
if let Some(cache) = &config.cache {
cache.clear();
}
}
Err(e) => {
// The resource is already saved, so the request does not fail.
tracing::error!(error = %e, "Failed to parse SearchParameter for incremental update");
}
}
}
Ok(())
}

Event path. SearchParamHook in crates/octofhir-server/src/hooks/search.rs handles the resource events for SearchParameter. It also receives events from other instances, see Multi-Instance Behavior.

async fn handle(&self, event: &ResourceEvent) -> Result<(), HookError> {
let config = self.search_config.config();
let version = event.version_id.ok_or_else(|| {
HookError::execution("SearchParameter event has no committed revision")
})?;
let parameter = match event.event_type {
ResourceEventType::Created | ResourceEventType::Updated => {
let resource = event
.resource
.as_ref()
.ok_or_else(|| HookError::execution("SearchParameter event has no snapshot"))?;
Some(
octofhir_search::parse_search_parameter(resource)
.map_err(|error| HookError::execution(error.to_string()))?,
)
}
ResourceEventType::Deleted => None,
};
if config
.registry
.apply_resource(&event.resource_id, version, parameter)
{
if let Some(cache) = &config.cache {
cache.clear();
}
}
Ok(())
}

FHIRPath Validation:

fn validate_fhirpath_expression(expression: &str) -> Result<(), ApiError> {
use octofhir_fhirpath::parse;
let result = parse(expression);
if !result.success {
let error_msg = result.error_message
.unwrap_or_else(|| "Unknown parse error".to_string());
return Err(ApiError::bad_request(format!(
"Invalid FHIRPath expression: {}",
error_msg
)));
}
Ok(())
}

Validation Scope:

  • Checked: syntax (parentheses, operators, function names)
  • Checked: basic structure (paths, predicates, function calls)
  • Not checked: semantics against the resource schema
  • Not checked: return types
// Multiple threads can read simultaneously
let config = state.search_config.config(); // Arc<SearchConfig>
let param = config.registry.get("Patient", "name"); // Option<Arc<SearchParameter>>
// 1. config() - single atomic load
// 2. registry.get() - load the current snapshot, then a HashMap lookup
// Incremental update (after POST/PUT/DELETE SearchParameter)
let config = state.search_config.config();
config.registry.apply_resource(id, version, Some(param)); // rebuild and publish one snapshot
// Full reload
state.search_config.reload_registry(&canonical_manager, resolver).await?;
// 1. Loads a new registry
// 2. Swaps the pointer atomically
// 3. The old config stays alive until readers release it
  1. No locks in the read path - Readers use two ArcSwap loads
  2. Single writer - Registry writers take a mutex; readers do not
  3. Consistent snapshots - A reader sees all indices from one generation

Location: crates/octofhir-search/src/query_cache.rs

QueryCache stores SQL templates keyed by query structure: resource type, parameter names, modifiers and types, pagination and sort fields. Values are not part of the key.

The search path does not use it. execute_search_raw_with_terminology_options receives the cache but always builds SQL from scratch. Renderers can embed values in the SQL, so a structural key does not prove that a template fits. The argument stays until templates can be identified safely.

Implementation:

pub struct QueryCache {
cache: DashMap<u64, CacheEntry>,
capacity: usize,
max_age_secs: u64,
enabled: bool,
stats: Arc<CacheStatistics>,
}

Eviction:

  • Entries go stale after one hour
  • When the cache is at capacity, an insert removes stale entries with a 1% chance
  • Above 1.5 times the capacity, every insert removes stale entries

Cache Invalidation:

  • Cleared when a SearchParameter is created, updated or deleted
  • Cleared when the registry is reloaded

Multiple OctoFHIR instances sharing the same PostgreSQL database:

┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Instance A │ │ Instance B │ │ Instance C │
│ │ │ │ │ │
│ Registry A │ │ Registry B │ │ Registry C │
└──────┬───────┘ └──────┬───────┘ └──────┬───────┘
│ │ │
└───────────────────┴───────────────────┘
│
┌─────────▼──────────┐
│ PostgreSQL │
│ (Canonical Mgr) │
└────────────────────┘

With Redis enabled ([redis] enabled = true), every instance publishes its resource events to the octofhir:resource_events channel and subscribes to the same channel. A received event goes to the local hooks, including SearchParamHook.

┌──────────────┐ ┌──────────────┐
│ Instance A │ ◄─────► │ Redis │
│ POST /SP │ Pub/Sub │ │
└──────────────┘ └──────┬───────┘
│
┌───────────┴───────────┐
│ │
┌───────▼──────┐ ┌───────▼──────┐
│ Instance B │ │ Instance C │
│ apply_resource│ │ apply_resource│
└──────────────┘ └──────────────┘
  1. SearchParameter Created on Instance A:

    • Stored in PostgreSQL (shared)
    • Applied to Instance A’s registry
  2. Instance B and C:

    • Receive the event with the resource and its version
    • Apply it to their registries with apply_resource
    • Ignore it if they already know that version or a newer one

Without Redis there is no such sync. The other instances pick up the change at their next start.

The setup lives in crates/octofhir-server/src/events/mod.rs (RedisPublishHook), events/redis.rs (RedisEventSync) and server.rs.

Config File: octofhir.toml

[search]
default_count = 10 # Default result count
max_count = 100 # Maximum allowed count
cache_capacity = 1000 # Query cache size

Environment Variables:

Terminal window
OCTOFHIR__SEARCH__DEFAULT_COUNT=20
OCTOFHIR__SEARCH__MAX_COUNT=500
OCTOFHIR__SEARCH__CACHE_CAPACITY=5000

Rust Configuration:

use octofhir_search::SearchOptions;
let options = SearchOptions {
default_count: 10,
max_count: 100,
cache_capacity: 1000,
};
let config = ReloadableSearchConfig::new(&canonical_manager, options, resolver).await?;

Enable debug logging to see search parameter operations:

Terminal window
RUST_LOG=octofhir_search=debug cargo run

Log Examples:

DEBUG octofhir_search::loader: Loaded search parameter code=name bases=["Patient"]
INFO octofhir_search::loader: Loaded search parameters from canonical manager loaded=1247 skipped=3 total=1247
INFO octofhir_server::handlers: Search parameter registered incrementally code="custom-field"
DEBUG octofhir_search::reloadable: Cleared query cache after registry reload

The server exports Prometheus metrics on /metrics. See Metrics & dashboards.

In code:

// Registry size
let param_count = state.search_config.config().registry.len();
// Cache statistics (if caching is enabled)
if let Some(stats) = state.search_config.cache_stats() {
println!("Cache hits: {}", stats.hits);
println!("Cache misses: {}", stats.misses);
println!("Hit ratio: {:.2}%", stats.hit_ratio * 100.0);
}

Slow search queries:

  • Use the index advisor
  • Check for complex FHIRPath expressions
  • Review database indices

Inconsistent results across instances:

  • Verify all instances use the same FHIR packages
  • Enable Redis so that SearchParameter changes reach every instance
  1. Take a snapshot - Call config() once per operation and use the returned Arc
  2. Incremental updates - Use apply_resource for runtime changes
  3. Clear caches - Clear the query cache after registry changes
  1. Use test helpers - ReloadableSearchConfig::with_registry() for unit tests
  2. Avoid the database - Build the registry in the test