-
Notifications
You must be signed in to change notification settings - Fork 1
Module replication Architecture
Navigation: Home > Modules
The replication module composes replication orchestration, consensus/failover behavior, conflict resolution, logical replication/CDC streaming, and replication observability into a bounded high-availability subsystem.
- Core orchestration plane
- replication manager lifecycle and mode control
- leader promotion/failover and topology management
- Data propagation and conflict plane
- WAL/logical propagation and slot/event stream behavior
- HLC/LWW/CRDT conflict detection and merge behavior
- Observability and policy plane
- lag/health/topology diagnostics and export behavior
- replication policy validation and assignment behavior
| Contract | Behavior |
|---|---|
| replication contract | deterministic init/replicate/promote semantics |
| consensus contract | explicit election/promotion transitions |
| conflict contract | deterministic conflict resolver outcomes per strategy |
| observability contract | explicit lag/health/topology visibility |
- initialization and promotion failures are explicit.
- slot/stream/CDC path faults surface deterministic outcomes.
- conflict-resolution edge cases remain explicit and non-silent.
- degraded replica lag/health is observable via module surfaces.
To prevent circular deadlocks and ensure bounded lock contention, the replication module implements a strict multi-level lock hierarchy across all components:
-
Files:
replication_slot.cpp,multi_tier_replication.cpp,logical_replication.cpp -
Locks:
slots_mutex_,collection_tiers_mutex_,slots_mutex_(shared_mutex) - Scope: Slot/tier collection access (create/lookup/list)
- Hold Time: MINIMAL (~microseconds for map operations only)
- Pattern: Acquire shared/unique β map access β release β I/O outside
-
Mutex Type:
std::mutexorstd::shared_mutexdepending on read/write ratio
-
Files:
replication_slot.cpp,raft_v2.cpp,event_stream.cpp,logical_replication.cpp -
Locks:
state_mutex_,config_mutex_,subs_mutex_,SlotRuntime::mutex - Scope: Individual slot/config state (pause/resume/query)
- Hold Time: MINIMAL (~microseconds for state copy)
- Pattern: Copy state under lock β release β I/O on copy
-
Mutex Type:
std::mutexorstd::lock_guard
-
Files:
async_wal_shipper.cpp -
Locks:
queue_mutex_,callback_mutex_,stats_mutex_ - Scope: Queues, callbacks, metrics (external I/O operations)
- Hold Time: VARIABLE (depends on network, 10ms-1000ms typical)
- Pattern: Acquire β quick operation β release β invoke handler outside
-
Mutex Type:
std::unique_lockwith optional timeout support
Level 1 (Manager Collection)
βββ slots_mutex_ (ReplicationSlotManager)
βββ collection_tiers_mutex_ (MultiTierReplicationManager)
βββ slots_mutex_ (LogicalReplicationManager, shared_mutex)
β
Level 2 (Per-Resource State)
βββ state_mutex_ (ReplicationSlot)
βββ config_mutex_ (RaftV2ClusterConfig)
βββ subs_mutex_ (ReplicationEventStream)
βββ SlotRuntime::mutex (LogicalReplicationManager)
β
Level 3 (Background I/O)
βββ queue_mutex_ (AsyncWalShipper)
βββ callback_mutex_ (AsyncWalShipper)
βββ stats_mutex_ (AsyncWalShipper)
β
[Blocking Operations - NO LOCKS HELD]
βββ File I/O (persist slots, state)
βββ WAL append (wal_->append())
βββ Network I/O (ship handler)
βββ Callbacks (event listeners)
- Acquire-Only Forward Pattern: Always acquire locks in increasing level order (1β2β3βI/O)
- No Backward Locks: Never acquire Level N lock while holding Level N-1 lock
- Lock-Free I/O: All blocking operations execute OUTSIDE all acquired locks
- State Copy Pattern: Copy mutable state while holding lock, release, then use copy for I/O
- Timeout Guards: Long-running operations (condition variable waits) use timeouts
bool ReplicationSlot::pause() {
SlotState state_copy;
{
std::lock_guard<std::mutex> lock(state_mutex_); // Level 2
state_.status = SlotStatus::PAUSED;
state_copy = state_;
} // β Lock RELEASED
persistStateImpl(state_copy); // β I/O happens OUTSIDE lock
return true;
}// BEFORE (UNSAFE - Lock ordering violation):
MembershipChangeEntry MembershipChangeManager::writeEntry(...) {
entry = ...;
wal_->append(wal_entry); // β I/O UNDER lock_guard
return entry;
}
// AFTER (SAFE - I/O outside lock):
auto entry = writeEntry(...); // β Create entry under lock
{
std::lock_guard<std::mutex> lock(mutex_); // β Release before I/O
// ...
}
wal_->append(wal_entry); // β I/O outside lockAll long-running blocking operations use timeouts to ensure bounded wait times:
-
Condition Variable Waits:
cv.wait_for(lock, timeout, predicate) - Default Timeout: 1-5 seconds depending on operation
-
Configuration: Via
replication.timeout_msand related config keys
| Module | Interface / File | Purpose |
|---|---|---|
cdc |
include/replication/schema_cdc.h (via cdc/schema_registry) |
Schema change events consumed during logical replication |
utils |
include/utils/ |
Utility helpers (encoding, error codes, logging) |
| Module | Via | Notes |
|---|---|---|
server |
include/replication/replication_manager.h |
Replication admin and status API endpoints |
storage |
include/replication/ (WAL shipping to replicas via CDC/WAL path) |
Storage WAL events propagated to replica nodes |
failover |
include/replication/replication_manager.h, include/replication/raft_v2.h
|
Failover module consults replication state for leader election; auto_failover_manager and disaster_recovery_manager both import replication_manager.h
|
temporal |
include/replication/multi_master_replication.h |
temporal_conflict_resolver imports multi-master replication state to resolve concurrent write conflicts across temporal branches (include/temporal/temporal_conflict_resolver.h:34) |
Files: src/replication/logical_replication.cpp β include/cdc/schema_registry.h (via include/replication/schema_cdc.h)
Contract: Logical replication subscribes to schema change events from CDC schema registry to maintain schema-aware replication slots. Schema version is embedded in each logical event for consumer compatibility validation.
Thread Safety: Schema registry reads are concurrent-safe; logical replication uses shared_mutex (Level 1 in lock hierarchy) for slot access.
Failure Mode: Schema registry unavailable β logical replication pauses the affected slot and emits a lag alert; does not corrupt data.
Files: src/replication/raft_v2.cpp β include/replication/raft_v2.h
Contract: RaftV2 manages leader election and log replication; leader promotion triggers replication_manager failover callbacks. Config changes require quorum before being applied.
Thread Safety: Config state uses Level-2 config_mutex_; election state uses Level-2 per-resource mutex. I/O (WAL append) executes outside all locks per Wave A Block 2 hardening.
Failure Mode: Loss of quorum β cluster read-only; stale leader detection β automatic step-down; WAL failure β abort with explicit error (not silent).
Files: src/replication/async_wal_shipper.cpp β include/replication/async_wal_shipper.h
Contract: WAL segments are queued and shipped to replica endpoints asynchronously. Queue is bounded; backpressure is applied on overflow. All callbacks and network I/O execute outside Level-3 locks.
Thread Safety: Level-3 locks (queue_mutex_, callback_mutex_, stats_mutex_) guard queue and stats; callbacks invoked without any lock held.
Failure Mode: Network failure β retried with exponential backoff up to configured budget; queue overflow β oldest entry dropped with sequence gap marker; lag alert fired.
Files: src/replication/conflict_resolution.cpp β include/replication/conflict_resolution.h, include/replication/crdt_types.h
Contract: On concurrent writes from multiple masters, conflict resolver applies strategy (HLC/LWW/CRDT) to produce deterministic merge outcome. Resolver is called synchronously on the apply path.
Thread Safety: CRDT merge operations are stateless and concurrent-safe; LWW comparisons are lock-free.
Failure Mode: Unresolvable conflict (strategy mismatch) β operation flagged for manual review in audit log; data not silently overwritten.
-
Verified files (with lock hierarchy annotations):
- src/replication/replication_slot.cpp (Level 1β2, lock-free I/O)
- src/replication/raft_v2.cpp (Level 1β2, fixed WAL lock violation)
- src/replication/event_stream.cpp (Level 1β2, callbacks outside locks)
- src/replication/async_wal_shipper.cpp (Level 3, timeout-guarded worker)
- src/replication/logical_replication.cpp (Level 1β2, shared_mutex)
- src/replication/multi_tier_replication.cpp (Level 1β2, scope-optimized)
-
Verified architecture claims:
- orchestration + propagation/conflict + observability/policy plane split
- explicit failure boundaries for init/promotion/slot/conflict behaviors
- module-local ownership of replication-domain behavior surfaces
- NEW (Wave A Block 2): strict 3-level lock hierarchy enforced
- NEW (Wave A Block 2): all blocking I/O executes lock-free
- NEW (Wave A Block 2): timeout guards on all waits
- NEW (Wave A Block 2): zero circular lock ordering scenarios
ThemisDB 1.9.0-beta Β· Home Β· Module-Index Β· GitHub Β· Issues
ThemisDB 1.9.0-beta Β· Home Β· Wiki-Index Β· Module-Index Β· FAQ Β· Quick-Reference Β· GitHub Β· Issues Β· Discussions Β· License
- Home
- Hero Articles
- All Wiki Pages
- FAQ
- Edition Comparison
- Repository README
- Changelog
- Roadmap
- Versioning
- Integration Mapping
- Overview
- Readme
- Appendix D Feature Status
- Appendix E Incident Runbooks
- Appendix F AQL Cheatsheet
- Appendix G Configuration
- Appendix H Glossary
- Appendix I Troubleshooting
- Appendix Literatur
- Chapter 00 Genesis
- Chapter 01 Introduction
- Chapter 02 Architecture
- Chapter 03 Multimodel
- Chapter 04 Installation
- Chapter 05 Relational
- Chapter 06 Graph
- Chapter 07 Document
- Chapter 08 Storage Layer
- Chapter 08 Vector
- Chapter 09 Timeseries
- Chapter 10 Enterprise
- Chapter 11 Realtime
- Chapter 12 Computervision
- Chapter 13 Fulltext
- Chapter 14 Geospatial
- Chapter 15 Analytics
- Chapter 16 Ml
- Chapter 16 Sharding
- Chapter 17 LLM Integration
- Chapter 17 Scaling
- Chapter 18 HA
- Chapter 18 Ml
- Chapter 19 Monitoring
- Chapter 19 Monitoring Observability
- Chapter 20 Backup
- Chapter 20 Performance
- Chapter 21 Auth
- Chapter 21 Performance
- Chapter 22 Clients
- Chapter 22 Encryption
- Chapter 23 Testing Qa
- Chapter 24 Ai Ethics
- Chapter 25 Devops Infrastructure
- Chapter 26 Migration Legacy
- Chapter 27 Troubleshooting
- Chapter 28 AQL Reference
- Chapter 29 Analytics Process Mining
- Chapter 30 Deployment Operations
- Chapter 31 API Protocols
- Chapter 32 API Design Rest Principles
- Chapter 32 AQL Oop Implementation
- Chapter 33 Best Practices
- Chapter 34 Query Optimization
- Chapter 35 Data Modeling Patterns
- Chapter 36 Security Hardening
- Chapter 37 Ecosystem Integration
- Chapter 38 Observability Sre
- Chapter 39 Performance Tuning Cookbook
- Chapter 40 Data Governance Compliance
- Chapter 41 Hands On Labs
- Chapter 42 Docs Assistant Usage
- Chapter MVCC Hlc
- Cover
- Cover Book
- Index
- Preface
- Test Links Example
- Batch Operations
- Best Practices
- CRUD Tutorial
- Custom Document Ingestion
- Getting Started Tutorial
- Interactive Examples
- Schema Design
- Video Tutorials
- AQL Reference
- AQL Examples
- AQL Overview
- AQL Feature Roadmap
- AQL Geospatial Guide
- AQL LLM Migration Guide
- AQL API
- AQL Grammar (EBNF)
- AQL Root Overview
- AQL Examples (root)
- API Reference
- API Module README
- OpenAPI Overview
- Client SDK Overview
- SDK Overview
- Operations
- Operations Overview
- Operations Runbook
- Operations Handbook
- ThemisCtl Admin Guide
- Pipeline E2E SOPs
- Docker Overview
- Docker Hub README
- Helm Overview
- Packaging Overview
- Operator Overview
- Security Policy
- Production Hardening Checklist
- Security Hardening Guide
- Encryption Key Management
- Access Control Framework
- Zero Trust Policy
- API Authentication & Authorization
- HSM Production Setup
- PKCS11 Integration
- DSGVO / SOC2 Checklist
- Access Model Runbooks
- Access Model Dashboard
- Maturity Automation Runbook
- Access Review Automation
- Access Model Dashboard
- Access Model Runbooks
- Rights Revocation
- Dr Checklists
- Dr Testing
- Incident Response Playbook
- Incident Response Testing
- GPU Oom Recovery
- Grammar Debugging
- Metrics Scrape Troubleshooting
- Model Swap Procedure
- Quota Tuning
- Subagent Deployment
- Logging Configuration
- Content Model
- Crypto & Keys
- Feature Flags Reference
- Modular Architecture Roadmap
- Modularization Guide
- Module Architecture Index
- PostgreSQL Wire Protocol
- Query Scheduling
- Raft Consensus Design
- Resource Pooling
- Source Directory Guide
- Unified Access Model
- E1 001 Layered Retrieval Design
- E1 002 Ann Abstraction Strategy
- E1 003 Tensor Summary Types
- E1 004 Lora Package Distinction
- E1 005 Model Switch Compatibility
- E1 006 Federated Tensor Summaries
- E2 001 Evaluation Framework Design
- E2 002 Hardware Profile Strategy
- E2 003 Query Planner Routing Model
- E2 004 Approximation Governance Rules
- E2 005 Cross Layer Fallback Confidence Policy
- E3 001 Distributed Tensor Design
- E3 002 Manifest Coordination Strategy
- E3 003 Recovery And Erasure Choice
- E3 004 Tensor Fabric Infrastructure
- Contributing
- Contributing (root)
- Code of Conduct
- Support
- Maintainers
- CTest Guide
- Build Quick Reference
- Developer Wiki Index
- Build / Test / CI
- Module Index
- Branching Strategy
- Release Strategy
- CI Policy Gates Wave C
- Disabled Stub Policy
- Docs PR Policy
- GA Promotion Sign Off
- Github Milestones Setup
- Governance Policies Phase1
- GPU Self Hosted Runner Requirements
- Hardening Phase 1 2 Summary 2026 09 23
- Maturity Claim Verification Checklist
- Maturity Evidence Registry
- Merge Gate Bot Config
- Merge Gate Status Live
- Phase 1 Closure Report
- Phase 1 Infrastructure Deployment
- Phase 1 Infrastructure Deployment Complete
- Phase 3 Baseline Capture
- Phase 3 Refinement Spec
- Phase 4 Sign Off And Closure
- Phase Closure Policy
- Phase Dependency Graph
- Phase3 Enforcement Runbook
- Plugin Submodule Rollback
- PR Version Targeting
- PR Version Targeting Backfill
- Production Ready 2026 Delivery Plan
- Publish Workflow Audit 2026 09 23
- Query Module Status
- Readme
- Release Governance
- Release Promotion Gate Policy
- Release Validation Checklist
- Root Hygiene Policy
- SBOM Approved Versions
- Security Compliance Audit Report 2026 08 10
- Security Module 5671 Evidence Summary
- Sharding P6 Residual Risk Acceptance
- Sourcecode Compliance Governance
- Src Module Documentation Compliance 2026 09 20
- Updates Development Status Sign Off
- Wave C Implementation Complete
- Wave C Implementation Plan
- Wave C Ml Exit Gate Sign Off
- Wave C Policy Gate Evidence
- Wiki Publish Tracking Guide
- Blob Storage
- Cuda
- Ethics Ai
- Exporters
- Huggingface
- Image Analysis
- Importers
- RPC
- Scraper
- Themisdb Ai Watermark Detector
- User Storage Encrypted
- Chimera Architecture
- Chimera Future
- Chimera Readme
- Chimera Roadmap
- Covina Fastapi Ingestion Architecture
- Covina Fastapi Ingestion Future
- Covina Fastapi Ingestion Roadmap
- Vcc Base Architecture
- Vcc Base Future
- Vcc Base Roadmap
- Vcc Clara Ingestion Architecture
- Vcc Clara Ingestion Future
- Vcc Clara Ingestion Roadmap
- Vcc Veritas Architecture
- Vcc Veritas Future
- Vcc Veritas Roadmap
- 01 Hello World
- 02 Todo App
- 03 Contact Manager
- 04 Inventory System
- 05 Time Series Monitor
- 06 Graph Social Network
- 07 Vector Search Documents
- 08 Dms Erp System
- 09 Iot Sensor Network
- 10 Drone Image Analysis
- 11 Blog Wiki
- 12 Expense Tracker
- 13 Recipe Manager
- 14 Ecommerce Catalog
- 15 Event Management
- 16 Kanban Board
- 17 Crm
- 18 Realtime Chat
- 19 Recommendation Engine
- 20 Smart Home
- 21 Coding Platform
- 22 AQL Diagram Tool
- 23 Traveling Salesman
- 24 Moral Philosophy Debates
- API Versioning
- Distributed Sharding
- Feedback Plugins
- Geo
- Gnn
- Image Analysis
- Legal Lora Training
- LLM
- Lora Sync
- Migration
- Nlp
- Performance
- Railway
- Replication
- Rope Visualization
- Sample Product Config
- Security
- Client SDK Overview
- Quickstart
- Sdk Enhancements
- Sdk Implementation Summary
- Test Suite Readme
- Go
- Java
- Javascript
- Php
- Python
- Ruby
- Rust
- Typescript
- 01 Grundlegende Operationen
- 02 AQL Queries
- 03 Graph Daten
- 04 Multimodell Anwendung
- 01 Quickstart Guide
- 02 AQL Referenz Kurzuebersicht
- 03 Datenmodellierung Guide
- 04 Uebungsaufgaben
- 05 Best Practices Guide
- Training Documents
- Training Overview
- 01 Einfuehrung Und Uebersicht
- 02 Datenmodelle Und Architektur
- 03 AQL Abfragesprache
- 04 Installation Und Setup
- 05 Anwendungsbeispiele
- Training Presentations
- Dependencies Readme
- Processmonitor Readme
- Themis.admintools.shared Readme
- Themis.aqlquerybuilder Readme
- Themis.aqlquerybuilder Roadmap
- Themis.auditlogviewer Readme
- Themis.auditlogviewer Roadmap
- Themis.classificationdashboard Readme
- Themis.classificationdashboard Roadmap
- Themis.compliancereports Readme
- Themis.compliancereports Roadmap
- Themis.gisviewer.controlpanel Readme
- Themis.gisviewer.controlpanel Roadmap
- Themis.impactanalysisviewer Readme
- Themis.impactanalysisviewer Roadmap
- Themis.ingestiontool Readme
- Themis.ingestiontool Roadmap
- Themis.keyrotationdashboard Readme
- Themis.keyrotationdashboard Roadmap
- Themis.piimanager Readme
- Themis.piimanager Roadmap
- Themis.retentionmanager Readme
- Themis.retentionmanager Roadmap
- Themis.sagaverifier Readme
- Themis.sagaverifier Roadmap
- Themis.usbadmintool Readme
- Themis.usbadmintool Roadmap
- Architecture Generator Readme
- CI Readme
- CI Roadmap
- Compiler Diagnostics Readme
- Compiler Diagnostics Roadmap
- Completion Readme
- Copilot Ollama Router Readme
- Copilot Ollama Router Roadmap
- Gnn Readme
- Gnn Roadmap
- Rope Visualizer Readme
- Rope Visualizer Roadmap
- Tco Calculator Readme
- Tco Calculator Roadmap
- Tests Readme
- Tests Roadmap
- Themis Config Wx Readme
- Themis Docs Builder Readme
- Wikipedia Ingestion Readme
- Ai Metadata And Provenance
- Build / Test / CI
- Governance And Roadmap
- Developer Wiki Index
- Module Direct Doxygen Check
- Module Doxygen Baseline Summary
- Module Doxygen Batch
- Module Doxygen Coverage Summary
- Module Doxygen Smoke Summary
- Modules And Apis
- Retrieval Direct Doxygen Check
- Soll Ist Gap Summary
- Wiki Delta Report