Hexser - Zero-Boilerplate Hexagonal Architecture
Zero-boilerplate hexagonal architecture with graph-based introspection for Rust.
The hexser crate provides reusable generic types and traits for implementing Hexagonal Architecture (Ports and Adapters pattern) with automatic graph construction, intent inference, and architectural validation. Write business logic, let hexser handle the architecture.
Table of Contents
- Why hexser?
- Quick Start
- Feature Flags
- Complete Tutorial
- CQRS Pattern with hex
- Application Lifecycle and Entry Points
- Testing Your Hexagonal Application
- Error Handling
- Real-World Example - TODO Application
- Advanced Patterns
- Knowledge Graph
- Static (non-dyn) DI β WASM-friendly
- Repository: Filter-based queries (vNext)
- AI Context Export (CLI)
- MCP Server (Model Context Protocol)
- Examples & Tutorials
- Potions (copy-friendly examples)
- Contributing
- License
- Acknowledgments
- Additional Resources
Tip: Press Cmd/Ctrl+F and search for βPartβ to jump to tutorials.
Why hexser?
Traditional hexagonal architecture requires significant boilerplate:
- Manual registration of components
- Explicit dependency wiring
- Repetitive trait implementations
- Complex validation logic
hexser eliminates all of this. Through intelligent trait design, compile-time graph construction, and rich error handling, you get:
- Zero Boilerplate - Define your types, derive traits, done
- Type-Safe Architecture - Compiler enforces layer boundaries
- Self-Documenting - Graph visualization shows your architecture
- Intent Inference - System understands itself through structure
- Rich Errors - Helpful, actionable error messages
- Zero Runtime Overhead - Everything happens at compile time
- AI Completion - Expose your Rust architecture to AI agents
Quick Start
Add to your Cargo.toml:
[]
= "0.4.7"
Your First Hexagonal Application
use *;
// 1. Define your domain entity
// 2. Define a port (interface)
// 3. Implement an adapter
// 4. Use it!
That's it! You've just built a hexagonal architecture application with:
- Clear layer separation
- Type-safe interfaces
- Testable components
- Swappable implementations
Feature Flags
Hexser provides granular feature flags to enable only the functionality you need. This keeps compile times fast and binary sizes small, especially for WASM targets.
Available Features
default = ["macros", "static-di"]
Enabled by default. Includes procedural macros and zero-cost static dependency injection.
[]
= "0.4.7" # Uses default features
macros
Enables procedural macros for deriving hexagonal architecture traits.
Provides:
#[derive(HexEntity)]- Implement HexEntity trait for domain entities#[derive(HexValueItem)]- Implement HexValueItem trait with default validation (override validate() for custom logic)#[derive(HexAggregate)]- Mark aggregate roots#[derive(HexPort)]- Mark port traits#[derive(HexAdapter)]- Mark adapter implementations#[derive(HexRepository)]- Mark repository ports#[derive(HexDirective)]- Mark command/directive types#[derive(HexQuery)]- Mark query types
Dependencies: hexser_macros
[]
= { = "0.4.7", = false, = ["macros"] }
static-di
Zero-cost, WASM-friendly static dependency injection. No runtime overhead, no dynamic dispatch.
Provides:
StaticContainerfor compile-time dependency resolution- Type-safe service registration without
dyn - Full WASM compatibility
Dependencies: None (zero-cost abstraction)
[]
= { = "0.4.7", = ["static-di"] }
Example:
use *;
let container = new
.with_service
.with_service;
let service = container.;
ai
Enables AI context export functionality for exposing architecture metadata to AI agents.
Provides:
AIContexttype with architecture metadataAgentPackfor packaging context- JSON serialization of graph data
- CLI tools:
hex-ai-export,hex-ai-pack - Method-level documentation: ComponentInfo now includes a
methodsfield capturing method signatures, parameters, return types, and documentation (currently empty, ready for future extraction via rustdoc JSON)
Dependencies: chrono, serde, serde_json
[]
= { = "0.4.7", = ["ai"] }
Usage:
# Export architecture context to JSON
# Create agent pack
mcp
Model Context Protocol server implementation for serving architecture data via JSON-RPC.
Provides:
- MCP server over stdio transport
- Resources:
hexser://context,hexser://pack - JSON-RPC 2.0 interface
- CLI tool:
hex-mcp-server
Dependencies: Requires ai feature, plus serde, serde_json
[]
= { = "0.4.7", = ["mcp"] }
Usage:
# Start MCP server (communicates via stdin/stdout)
async
Enables async/await support for ports and adapters.
Provides:
AsyncRepositorytraitAsyncDirectivetraitAsyncQuerytrait- Tokio runtime integration
Dependencies: tokio, async-trait
[]
= { = "0.4.7", = ["async"] }
Example:
visualization
Enables graph visualization and export capabilities.
Provides:
- Graph serialization to JSON
- DOT format export for Graphviz
- Architecture diagram generation
Dependencies: serde, serde_json
[]
= { = "0.4.7", = ["visualization"] }
container
Dynamic dependency injection container with async support. Not enabled by default to maintain WASM compatibility.
Provides:
DynContainerwith runtime service resolution- Async service factories
- Dynamic dispatch with
dyntraits
Dependencies: tokio, async-trait
Note: Use static-di instead if you need WASM compatibility or want zero runtime overhead.
[]
= { = "0.4.7", = ["container"] }
full
Enables all features: ai, mcp, async, macros, visualization, container, and static-di.
Use for: Development, full-featured applications, or when you need all capabilities.
[]
= { = "0.4.7", = ["full"] }
Binary Targets
Hexser includes three command-line tools that require specific features:
hex-ai-export
Exports architecture context as JSON for AI consumption.
Required feature: ai
hex-ai-pack
Creates a complete agent pack with architecture metadata.
Required feature: ai
hex-mcp-server
Runs an MCP (Model Context Protocol) server over stdio.
Required feature: mcp
Feature Combinations
Minimal (no default features)
[]
= { = "0.4.7", = false }
WASM-optimized
[]
= { = "0.4.7", = false, = ["macros", "static-di"] }
AI-enabled with async
[]
= { = "0.4.7", = ["ai", "async", "visualization"] }
Full development setup
[]
= { = "0.4.7", = ["full"] }
Complete Tutorial
Part 1: Understanding Hexagonal Architecture
Hexagonal Architecture (also known as Ports and Adapters) structures applications into concentric layers:
βββββββββββββββββββββββββββββββββββββββββββββββ
β Infrastructure Layer β
β (Databases, APIs, External Services) β
β β
β βββββββββββββββββββββββββββββββββββββββββ β
β β Adapters Layer β β
β β (Concrete Implementations) β β
β β β β
β β βββββββββββββββββββββββββββββββββββ β β
β β β Ports Layer β β β
β β β (Interfaces/Contracts) β β β
β β β β β β
β β β βββββββββββββββββββββββββββββ β β β
β β β β Domain Layer β β β β
β β β β (Business Logic) β β β β
β β β βββββββββββββββββββββββββββββ β β β
β β βββββββββββββββββββββββββββββββββββ β β
β βββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββ
Key Principles:
- Dependency Rule: Dependencies point inward (Domain has no dependencies)
- Port Interfaces: Define what the domain needs (don't dictate how)
- Adapter Implementations: Provide concrete implementations using specific tech
- Testability: Mock adapters for testing without infrastructure
Part 2: The Five Layers
- Domain Layer - Your Business Logic The domain layer contains your core business logic, completely independent of frameworks or infrastructure. Entities - Things with identity:
use *;
Value Objects - Things defined by values:
;
Domain Events - Things that happened:
Domain Services - Operations spanning multiple entities:
;
- Ports Layer - Your Interfaces Ports define the contracts between your domain and the outside world. Repositories - Persistence abstraction:
Use Cases - Business operations:
Queries - Read operations (CQRS):
- Adapters Layer - Your Implementations Adapters implement ports using specific technologies.
Database Adapter:
API Adapter:
Mapper - Data transformation:
;
- Application Layer - Your Orchestration The application layer coordinates domain logic and ports. Directive (Write Operation):
Directive Handler:
Query Handler:
- Infrastructure Layer - Your Technology Infrastructure provides the concrete technology implementations.
Part 3: CQRS Pattern with hex
hexser supports Command Query Responsibility Segregation (CQRS) out of the box.
Write Side (Directives):
// Directive represents intent to change state
// Handler executes the directive
Read Side (Queries):
// Query represents read operation
// Handler executes the query
Part 3.5: Application Lifecycle and Entry Points
The Application trait marks top-level entry points and coordinates the system lifecycle in hexagonal architecture. It orchestrates initialization of adapters, ports, and domain services, and manages the application from startup to shutdown.
The Application Trait
use *;
Minimal Application
The Application trait follows hexser's zero-boilerplate philosophy. All lifecycle methods have default implementations, so you only override what you need:
use *;
;
Application with CQRS Integration
Here's a complete example showing how the Application trait coordinates Directives and Queries:
use *;
// Application that processes user directives and queries
Error Handling in Applications
The Application trait integrates seamlessly with hexser's error handling:
Architecture Benefits
The Application trait provides several architectural benefits:
- Clear Entry Points: Marks the top level of your application, making architecture explicit
- Lifecycle Management: Standardizes initialization, execution, and cleanup patterns
- Error Propagation: Ensures errors during any lifecycle phase are properly handled
- Testability: Easy to test each lifecycle phase independently
- Composability: Applications can compose other applications for microservices or modular systems
// Example: Compose multiple applications
Part 4: Testing Your Hexagonal Application
Hexagonal architecture makes testing trivial - just mock the ports!
Unit Testing Domain Logic:
Testing with Mock Adapters:
Part 5: Error Handling
hexser provides rich, actionable, code-first errors with automatic source location and layering support. Prefer the new macro-based constructors and error codes over manual struct construction.
Preferred: macro + code + guidance
Display output (example):
E_HEX_001: Order must contain at least one item
at src/domain/order.rs:42:13
Next steps:
- Add at least one item to the order
Suggestions:
- order.add_item(item)
- order.items.push(item)
Cookbook
// Validation errors (field-aware)
return Err;
// Not Found errors (resource + id)
return Err;
// Port errors (communication issues)
let port_err = hex_port_error!.with_suggestion;
// Adapter errors (infra failures) with source error
π₯ Amazing Example: Layered mapping (Adapter β Port β Domain)
// Adapter layer
// Port layer wraps adapter failure with port context
// Domain layer consumes rich errors
Notes
- All hexser errors implement std::error::Error and the RichError trait (code, message, next_steps, suggestions, location, more_info, source).
- Prefer hex_domain_error!, hex_port_error!, hex_adapter_error! and constants from hexser::error::codes::*.
- Use with_source(err) to preserve underlying causes; Display shows a helpful, compact summary.
Security: Controlling Source Location in Serialized Errors
When using the serde feature to serialize errors (e.g., for API responses), source location information (file paths, line numbers, column numbers) can expose internal code structure to clients. hexser is secure by default and excludes this sensitive information from serialization unless explicitly enabled.
Environment Variable: HEXSER_INCLUDE_SOURCE_LOCATION
Control whether source location is included in serialized errors:
# Production (default, secure) - source location excluded
# No environment variable needed
# Development/Debug - include source location
# or
Example:
use *;
Production Best Practice:
- Never set
HEXSER_INCLUDE_SOURCE_LOCATIONin production environments - Source location is still captured and available via
Displayformatting for logs - Only serialization (JSON/API responses) is affected by this setting
Affected Error Types:
DomainError,PortError,AdapterError(LayerError-based types)ValidationErrorNotFoundErrorConflictError- All errors with
locationfields
Part 6: Real-World Example - TODO Application Let's build a complete TODO application using hexagonal architecture. Domain Layer:
use *;
;
Ports Layer:
Adapters Layer:
Application Layer:
π Advanced Patterns
Event Sourcing
Dependency Injection
π Knowledge Graph
hexser/
βββ domain/ [Core Business Logic - No Dependencies]
β βββ HexEntity - Identity-based objects
β βββ HexValueItem - Value-based objects
β βββ Aggregate - Consistency boundaries
β βββ DomainEvent - Significant occurrences
β βββ DomainService - Cross-entity operations
β
βββ ports/ [Interface Definitions]
β βββ Repository - Persistence abstraction
β βββ UseCase - Business operations
β βββ Query - Read-only operations (CQRS)
β βββ InputPort - Entry points
β βββ OutputPort - External system interfaces
β
βββ adapters/ [Concrete Implementations]
β βββ Adapter - Port implementations
β βββ Mapper - Data transformation
β
βββ application/ [Orchestration Layer]
β βββ Directive - Write operations (CQRS)
β βββ DirectiveHandler - Directive execution
β βββ QueryHandler - Query execution
β
βββ infrastructure/ [Technology Layer]
β βββ Config - Infrastructure setup
β
βββ error/ [Rich Error Types]
β βββ Hexserror - Actionable errors
β
βββ graph/ [Introspection - Phase 2+]
βββ Layer - Architectural layers
βββ Role - Component roles
βββ Relationship - Component connections
βββ NodeId - Unique identification
π‘ Design Philosophy
- "Language of the Language": Use Rust's type system to express architecture
- Zero Boilerplate: Derive everything, configure nothing
- Compile-Time Guarantees: Catch errors before runtime
- Rich Errors: Every error is helpful and actionable
- Self-Documenting: Graph reveals architecture automatically
- Testability First: Mock anything, test everything
π€ Contributing
We welcome contributions! This crate follows strict coding standards:
- One item per file: Each file contains one logical item
- No imports: Fully qualified paths (except std prelude)
- Documentation: Every item has //! and /// docs
- In-file tests: Tests live with the code they test
- No unsafe: Safe Rust only
- Rust 2024: Latest edition
See CONTRIBUTING.md for details.
π License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT license (LICENSE-MIT)
at your option.
π Acknowledgments
Inspired by:
- CEQRS by Scott Wyatt
- N Lang by Scott Wyatt
- Domain-Driven Design by Eric Evans
- Hexagonal Architecture by Alistair Cockburn
- Clean Architecture by Robert C. Martin
- Rust's type system and error handling
- The Rust community's commitment to excellence
π Additional Resources
- Hexagonal Architecture Explained
- Domain-Driven Design
- CQRS Pattern
- Ports and Adapters
π― Examples & Tutorials
The hex crate includes comprehensive examples and tutorials to help you learn hexagonal architecture.
Running Examples
π§ͺ Potions (copy-friendly examples)
Looking for concrete, minimal examples you can paste into your app? Check out the Potions crate in this workspace:
- Path: ./hexser_potions
- Crate: hexser_potions
- Focus: small, mixable examples (auth signup, CRUD, etc.)
Add to your project via workspace path:
[]
= { = "../hexser_potions", = "0.4.7" }
Then in code:
use ;
βοΈ Static (non-dyn) DI β WASM-friendly
When you want zero dynamic dispatch and the smallest possible runtime footprint (including on wasm32-unknown-unknown), use the new static DI utilities.
Feature flags:
- Enabled by default:
static-di - Opt-in for dyn container (tokio-based):
container
Static DI provides two simple building blocks:
StaticContainer<T>: owns your fully built object graphhex_static! { ... }macro: builds the graph from a block without anydyn
Example:
use *;
;
let app = hex_static!;
let = app.into_inner;
WASM guidance:
- Default features are WASM-friendly (no tokio). Keep
containerdisabled for wasm. - Use
static-di(default) and avoid the dyn container for maximum compatibility.
Repository: Filter-based queries (vNext)
We are migrating the repository port away from id-centric methods (find_by_id/find_all) toward a generic, filter-oriented API that better models your domain while staying storage-agnostic. The new QueryRepository trait introduces domain-owned Filter and SortKey types plus FindOptions for sorting and pagination.
Highlights:
- Define small Filter and SortKey enums/structs in your domain
- Use find_one for unique lookups and find for lists with sorting/pagination
- Legacy methods are still available but deprecated; prefer the new API
Example:
use *;
use ;
// Domain-owned query types
Migration tips:
- find_by_id(id) -> find_one(&Filter::ById(id))
- find_all() -> find(&Filter::All, FindOptions::default())
- Add sorting/pagination via FindOptions { sort, limit, offset }
For more details, see MIGRATION_GUIDE.md and docs/core-concepts.md.
v0.4 QueryRepository Examples (5+)
The following focused examples demonstrate the new query-first API using domain-owned Filter and SortKey types. These snippets avoid deprecated methods and illustrate common tasks.
- Unique lookup with find_one
// Given: domain types User, UserFilter::ByEmail(String)
let repo = default;
let maybe_user =
find_one?;
- Listing with multi-key sorting (Email asc, CreatedAt desc)
let opts = FindOptions ;
let users = find?;
- Pagination (page size 10, second page)
let opts = FindOptions ;
let page = find?;
- Existence check
let exists = exists?;
- Count matching entities
let total = count?;
- Delete by filter (returns removed count)
let removed = delete_where?;
π€ AI Context Export (CLI)
Export a machine-readable JSON describing your project's architecture for AI assistants and tooling.
Requirements:
- Enable the
aifeature (serde/serde_json are included automatically).
Commands:
# Build and run the exporter (prints JSON to stdout)
# Save to a file
What it does:
- Builds the current
HexGraphfrom the component registry - Generates an
AIContextviahexser::ai::ContextBuilder - Serializes to JSON with a stable field order
Notes:
- The binary
hex-ai-exportis only built when theaifeature is enabled. - For reproducible diffs, commit
target/ai-context.jsonor generate it in CI as an artifact.
π AIContext Structure
The exported AIContext JSON includes detailed component information:
ComponentInfo fields:
type_name: Fully qualified type namelayer: Architectural layer (Domain, Port, Adapter, Application)role: Component role (Entity, Repository, Directive, Query, etc.)module_path: Module path where component is definedpurpose: Optional description of component purposedependencies: List of component dependenciesmethods: List of public methods with detailed information (NEW)
MethodInfo structure (available in methods array):
name: Method namesignature: Full method signaturedocumentation: Doc comment for the methodparameters: Array of parameter details (name, type, description)return_type: Method return typeis_public: Visibility flagis_async: Async flag
Current Status: The methods field is included in the JSON schema and ready for use. Currently populated as an empty array; future enhancement will extract method information via rustdoc JSON output or source code parsing to provide complete API documentation to AI models.
Example ComponentInfo with methods:
π§ AI Agent Pack (All-in-One)
Export a comprehensive, single-file JSON that bundles:
- AIContext (machine-readable architecture)
- Guidelines snapshot (rules enforced for agents)
- Embedded key docs (README, ERROR_GUIDE, and local AI/guideline prompts when present)
Commands:
# Print Agent Pack JSON to stdout
# Save to a file
Notes:
- Missing optional docs are skipped gracefully. The pack remains valid JSON.
- Use this artifact as the single source of truth for external AIs and tools when proposing changes.
π MCP Server (Model Context Protocol)
Hexser includes a built-in MCP (Model Context Protocol) server that exposes your project's architecture to AI assistants via a standardized JSON-RPC interface. This enables AI tools like Claude Desktop, Cline, and other MCP-compatible clients to query your architecture in real-time.
π New to MCP? Check out the Beginner's Walkthrough for IntelliJ + Junie for step-by-step setup instructions.
Requirements:
- Enable the
mcpfeature (automatically includesai,serde, andserde_json).
Running the MCP Server
# Run the MCP server (stdio transport)
# The server reads JSON-RPC requests from stdin and writes responses to stdout
Available MCP Resources
The MCP server supports multi-project mode, exposing resources for multiple projects simultaneously:
Resource URI Format:
- New (multi-project):
hexser://{project}/contextandhexser://{project}/pack - Legacy (backward compatible):
hexser://contextandhexser://pack(assumes project name "hexser")
Resource Types:
-
hexser://{project}/context- Machine-readable architecture context (AIContext JSON)- Current component graph for the specified project
- Layer relationships
- Architectural constraints
- Validation rules
-
hexser://{project}/pack- Comprehensive Agent Pack (all-in-one JSON)- AIContext (architecture)
- Guidelines snapshot (coding rules)
- Embedded documentation (README, ERROR_GUIDE, etc.)
Example Resources:
hexser://hexser/context- Architecture context for the hexser projecthexser://myapp/pack- Full agent pack for myapp projecthexser://context- Legacy format, maps tohexser://hexser/context
Integration with AI Assistants
Configure your AI assistant to use the MCP server:
Claude Desktop (config.json):
Cline / Other MCP Clients: Follow the client-specific configuration to add the above command as an MCP server endpoint.
What the MCP Server Does
- Accepts JSON-RPC 2.0 requests via stdin
- Implements the Model Context Protocol specification
- Provides
initialize,resources/list,resources/read, andhexser/refreshmethods - Serves architecture data from multiple projects via
ProjectRegistry - Enables AI assistants to understand your project structure in real-time
Refreshing Architecture After Code Changes
When AI agents modify project code (adding new components, changing architecture), the MCP server needs to be updated to reflect these changes. Hexser uses Rust's inventory crate which populates a static registry at compile time, so changes require recompilation.
The hexser/refresh Method:
Workflow:
- AI agent makes code changes (adds
#[derive(HexEntity)]to new struct, etc.) - AI agent calls
hexser/refreshwith project name - MCP server triggers
cargo build -p {project} --features macros - Server returns compilation result:
- Success: Returns
{"status": "restart_required", "compiled": true, ...}with message that MCP server must be restarted - Error: Returns
{"status": "error", "compiled": false, "error": "..."}with compilation errors
- Success: Returns
Important: After successful compilation, you must manually restart the MCP server to load the updated architecture graph. The inventory static cache is cleared and repopulated during the restart.
Example Response (Success):
Example Response (Compilation Error):
Best Practices:
- Call
hexser/refreshafter making architectural changes - Check the
compiledfield to verify build success - Restart your MCP client or server process after successful refresh
- Handle compilation errors gracefully in your AI workflow
Multi-Project Configuration
The MCP server supports serving multiple projects simultaneously using ProjectRegistry:
Default Behavior (Single Project):
By default, McpStdioServer::new() creates a registry with the current HexGraph as a single project named "hexser". This provides backward compatibility with existing configurations.
Custom Multi-Project Setup: Create a custom binary to register multiple projects:
use ;
use McpStdioServer;
use HexGraph;
Environment-Based Configuration (Future): Future versions may support configuration via environment variables or config files for dynamic project discovery.
Available APIs:
McpStdioServer::new()- Single project mode (backward compatible)McpStdioServer::with_registry(registry)- Multi-project modeMcpStdioServer::with_graph(graph)- Deprecated, usewith_registryinstead
Notes:
- The
hex-mcp-serverbinary is only built when themcpfeature is enabled. - The server uses stdio transport (line-delimited JSON-RPC messages).
- Each project in the registry gets its own
hexser://{project}/contextandhexser://{project}/packresources. - For production use, consider wrapping in a process manager or systemd service.
π¦ REST Adapter Example: WeatherPort
Hexser includes a complete example of a REST-based adapter using reqwest::blocking and serde_json. This adapter connects to an external weather API and maps JSON responses to domain models with robust error handling.
Domain Model
// Domain: Forecast value object (in hexser::domain::forecast)
Port Definition
// Port: WeatherPort trait (in hexser::ports::weather_port)
Adapter Implementation
// Adapter: RestWeatherAdapter (self-contained in examples/weather_adapter.rs)
This complete example is available at examples/weather_adapter.rs. Run with:
π Integrating User Authentication Potions
When integrating pre-built authentication patterns from hexser_potions, you must connect the Potion's defined Ports to your own concrete adapters for databases and session management.
Step 1: Define Your Ports
// Port for user persistence
// Port for session management (new for question 4)
Step 2: Implement Database Adapter
// Concrete PostgreSQL adapter
Step 3: Implement Session Adapter (Redis or In-Memory)
// Redis-based session adapter
Step 4: Wire Adapters to Application
// Application context with wired adapters
π Transactional Directives: ProcessOrder Example
When a directive involves multiple repository operations that must succeed or fail atomically (e.g., decrementing stock and creating an order), use a database transaction and pass it explicitly to each repository call.
Port Definitions
// Ports accepting a transaction context
Directive Handler with Transaction
Adapter Implementation (PostgreSQL)
;
Key Points:
- Pass
&mut PgTransaction(or equivalent) to all repository methods within the transaction. - Rollback is automatic via Rust's
Droptrait if any error occurs beforecommit(). - Publish events only after successful commit to ensure consistency.
π Composite Adapters: ProfileRepository Example
When data must be fetched from multiple sources (e.g., SQL for core profile, NoSQL for preferences), implement a composite adapter that queries both, handles failures gracefully, and optionally caches results.
Port Definition
Composite Adapter Implementation
Handling Data Inconsistencies
- Primary Source Failure: Return
Hexserror::AdapterorHexserror::NotFoundwith actionable guidance. - Secondary Source Failure: Degrade gracefully by logging a warning and using defaults (e.g.,
Preferences::default()). - Caching Strategy: Use an LRU cache with TTL to reduce load; invalidate on writes.
- Stale Data: Implement cache invalidation hooks or TTL-based expiry for eventually-consistent NoSQL data.
Caching Strategies
- Read-Through Cache: Check cache before querying databases (shown above).
- Write-Through Cache: Invalidate or update cache on writes.
- TTL-Based Expiry: Use a cache with time-to-live for each entry.
// Example: TTL-based cache wrapper