The user wants an architecture design for an HTAP (Hybrid Transactional/Analytical Processing) system.
This is a complex system design problem. I need to cover several specific aspects:
- Workload Classification: How to distinguish between OLTP and OLAP requests.
- Storage Layout: How to handle row-oriented (for OLTP) and column-oriented (for OLAP) data, often involving sharding.
- Replication/Consistency: How to keep data synchronized between the row and column stores while handling the CAP theorem constraints typically relaxed in HTAP (e.g., eventual consistency for analytics vs. strong consistency for transactions).
- Query Routing: Directing traffic to the appropriate engine.
- Freshness SLAs: Guarantees on how recent the analytical data is compared to the transactional data.
- Isolation Handling: Ensuring heavy analytical queries don't kill transaction performance (the 'H' in HTAP).
- Observability: Monitoring the system health and performance.
- Deployment and Testing Steps: Practical implementation details.
High-Level Strategy:
I will structure this as a technical design document (TDD) or an architecture proposal.
I will pick a conceptual architecture similar to TiDB + TiFlash or Snowflake's Hybrid Tables, or Google AlloyDB, but describe it as a generalized, robust system.
1. Workload Classification:
- Heuristic-based: Simple rules (e.g.,
SELECT * with aggregates = OLAP, short PK lookup = OLTP).
- Intent-based: Client hints or connection strings (e.g., read-only replica vs. primary).
- ML-based: Adaptive query processing to learn patterns.
2. Storage Layout (The Core):
- Need a Row Store (e.g., based on Raft/Paxos groups, LSM trees like RocksDB).
- Need a Column Store (e.g., Parquet/Arrow based, vectorized execution).
- The "Delta" Layer: Handling updates in column stores is hard. Usually involves a Write-Ahead Log (WAL) or a Delta Store that merges into the main columnar storage.
3. Replication/Consistency (The Link):
- Synchronous: Too slow for cross-region, but okay within a cluster for HA.
- Asynchronous (Log shipping): Standard for HTAP. The Row Store is the source of truth. Changes are sent to the Column Store via a log (e.g., Kafka, or internal Raft log).
- Replication: Raft is the standard here. The Column Store acts as a "Learner" role in the Raft group.
4. Query Routing:
- A smart proxy or the driver itself.
- Needs to understand table locations.
- Stale Reads: For OLAP, we often accept slightly stale data to avoid locking the row store.
5. Freshness SLAs:
- "Real-time" vs. "Near Real-time" vs. "Batch".
- HTAP aims for "Near Real-time" (seconds) or "Real-time" (milliseconds).
- Mechanism: Lag monitoring. If lag > threshold, route query to Row Store (if possible) or fail/warn.
6. Isolation Handling:
- Resource isolation (CPU/Memory separation).
- Physical Isolation: Separate nodes for Row and Column stores.
- Logical Isolation: Different thread pools.
7. Observability:
- Metrics: Latency (P99), Throughput (QPS), Replication Lag, Error rates.
- Tracing: Distributed tracing (OpenTelemetry) is crucial for seeing the path from Ingestion -> Row Store -> Log -> Column Store -> Query.
8. Deployment & Testing:
- Infrastructure (K8s is standard).
- CI/CD.
- Chaos Engineering (killing nodes during sync).
- Load testing (HammerDB/TPC-C + TPC-H).
Refining the Architecture - "The Raft Learner Pattern"
This is the most robust modern pattern (used by TiDB, CockroachDB with columnar features, etc.).
- Primary: Row Store (RocksDB).
- Replica: Column Store (TiFlash/Parquet).
- Mechanism: Raft protocol. The column store replicates the WAL but applies it asynchronously in columnar format.
Drafting the Content - Section by Section:
- Introduction: Define the goal (break the wall between TP and AP).
- Architecture Diagram (Mental): SQL Gateway -> Optimizer -> [Row Store Nodes (Leader)] --(Raft Log)--> [Column Store Nodes (Learner)].
- Workload Classification: Explain the logic.
- Storage: "Delta-Tree" or " LSM-Tree + Columnar".
- Consistency: Tunable consistency. "Stale reads".
- Routing: The "Smart Client".
- Deployment: Helm charts, Operators.
Self-Correction/Edge Cases:
- Updates/Deletes in Column Store: Column stores hate random writes. I need to mention the "Merge-on-Read" or "Compaction" strategy. The Column Store isn't just static files; it needs a mutable layer (Delta store) on top of immutable segments.
- Freshness: What if the user needs strict consistency (read-after-write) on an Analytical query? The router must be smart enough to check the Raft index. If the Column Store is behind, either wait or route to Row Store (slowly). I will suggest checking "Safe Read Timestamps".
Final Polish:
Use professional terminology (MVCC, Raft, LSM Tree, Vectorization). Structure with clear headings. Ensure the testing section is actionable.
Let's generate the response following this structure. I will create a comprehensive design specification.
This architecture defines a robust HTAP (Hybrid Transactional/Analytical Processing) system. We will base this design on the Delta-Tree architecture pattern (similar to TiDB + TiFlash or Alibaba OceanBase), which allows for a strictly consistent transactional row store and a highly available columnar store simultaneously.
System Architecture: "Chronos-DB"
The architecture separates Compute (Stateless SQL Layers) from Storage (Distributed Data Nodes). The innovation lies in the Storage Node, which maintains dual representations of the data.
1. Workload Classification
To route traffic effectively, the system must classify incoming queries immediately at the Stateless Compute Layer.
- Heuristic Parser: The Gateway parses SQL text.
- OLTP Pattern: Point selects (
WHERE id = ?), short-range scans, high-frequency inserts/updates. Characteristics: Low latency sensitivity, high concurrency.
- OLAP Pattern: Aggregations (
SUM, AVG), GROUP BY, large-range scans, JOINs. Characteristics: High throughput, high CPU/IO cost.
- Cost-Based Optimizer (CBO) Hinting: If the heuristic is ambiguous (e.g., a complex transaction), the CBO estimates the cost based on statistical histograms.
- Decision Logic: If
Estimated Rows > Threshold OR Operations include Aggregations → Route to Columnar Replica.
- Fallback: Default to Row Store for strict consistency unless explicitly flagged as "Read-Only" by the client.
2. Storage Layout: Row vs. Column Shards
We avoid the "one size fits all" problem by using Multi-Model Sharding.
- The Unit of Replication: Data is sharded by Range (e.g.,
Range 1: ID 1-1000).
- Row Store (The Source of Truth):
- Format: LSM-Tree (Log-Structured Merge-Tree) or B+ Tree.
- Optimization: Optimized for random writes and fast point reads.
- Role: Handles all Writes (INSERT/UPDATE/DELETE) and strictly consistent Reads.
- Column Store (The Analytics Engine):
- Format: Columnar chunks (e.g., Parquet-like blocks) organized as a Delta-Tree.
- Structure:
- Delta Layer: A row-store-like buffer for recent writes (to handle real-time ingestion).
- Base Layer: Compressed, sorted, immutable columnar segments.
- Role: Handles heavy analytical queries.
3. Replication & Consistency
We employ Physical Replication via a consensus algorithm to keep stores in sync.
- Consensus Protocol: Raft (or Multi-Raft).
- Replication Topology:
- Leader (Row Store): Receives all writes.
- Follower (Row Store): Replicates the WAL (Write-Ahead Log) for HA (High Availability).
- Learner (Column Store): Subscribes to the Leader's WAL.
- The Sync Mechanism:
- As the Leader commits transactions, it sends the WAL entries to the Columnar Learner.
- The Learner converts row-based log entries into columnar deltas and applies them to its in-memory delta layer.
- Background Compaction: A background process periodically merges the Delta Layer into the Base Columnar Layer.
4. Query Routing & Freshness SLAs
The system supports tunable consistency to balance speed and accuracy.
- Scenario A: Strict Consistency (Transaction Mode)
- Route: Row Store Leader.
- Use Case: "Did the payment succeed?"
- Cost: Higher latency (disk I/O or RPC to Leader).
- Scenario B: Bounded Staleness (Analytical Mode)
- Route: Columnar Learner.
- Use Case: "Real-time sales dashboard."
- SLA: Data is eventually consistent. Typical lag: < 1 second.
- Mechanism: The Gateway queries the Column Store's timestamp. If
CurrentTime - ColumnStoreTS < Threshold, proceed. Otherwise, wait or trigger a mini-sync.
- Scenario C: Time-Travel (Audit Mode)
- Route: Column Store (Historical Partitions).
- Use Case: "What were sales last quarter?"
5. Isolation Handling
The biggest risk in HTAP is Analytical queries locking resources needed by Transactional queries.
- Physical Isolation: Row Stores and Column Stores run on different physical nodes (or distinct container pools). An OOM error in the Column Store (due to a heavy JOIN) cannot kill the Transactional Gateway.
- Resource Groups (cgroups/Namespaces): Within the storage node OS, I/O priority is given to the Row Store (Write path). The Column Store compaction process runs with
ionice idle priority.
- MVCC (Multi-Version Concurrency Control): Writers create new versions; Readers see snapshots. This ensures Analytical queries never block Transactional writes.
6. Observability
A control plane to monitor the health of the hybrid pipeline.
- Key Metrics:
- Replication Lag: (Leader TSO - Learner TSO). If > 2s, alert.
- Compaction Stress: Percentage of data sitting in the "Delta Layer" vs "Base Layer". If Delta is too large, Analytics slow down.
- Routing Hit Rate: Percentage of OLAP queries successfully offloaded to Column Store.
- Tracing: Distributed tracing (OpenTelemetry) spans must cover:
Gateway Parse → Log Replication → Columnar Apply.
- Schema Drift: Monitor to ensure Column Store schemas are strictly synchronized with Row Store schemas.
Deployment Strategy (Kubernetes Native)
Prerequisites: Kubernetes Cluster, Helm 3, Ceph/MinIO (for Shared Blob Storage of Columnar Segments).
Step 1: Infrastructure Setup
Deploy the Cluster using a Topology Spread Constraints to ensure Node isolation.
# Example: Topology for Row Nodes
topologySpreadConstraints:
- maxSkew: 1
topologyKey: node_type
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
store_type: row
Step 2: Deploy PD (Placement Driver)
The "Brain" of the cluster. Manages timestamps (TSO) and routing tables.
helm install pd chronos-db/pd --set replicaCount=3
Step 3: Deploy TiKV (Row Store)
Stateful Sets with fast local SSDs (NVMe).
helm install kv chronos-db/kv --set replicaCount=3 \
--set storage.class=local-nvme \
--set config.role="row-leader"
Step 4: Deploy TiFlash (Column Store)
Deploy the "Learner" nodes. These should have high CPU cores and large HDD/S3 capacity.
helm install flash chronos-db/flash --set replicaCount=2 \
--set storage.class=standard \
--set config.sync-mode="async-wal"
Step 5: Configure Replication
Tell the cluster to create Columnar replicas for specific tables.
-- Run against the SQL Gateway
ALTER DATABASE sales SET TIFLASH_REPLICA=2; -- Create 2 columnar copies
Testing & Validation Steps
1. Functional Testing (Consistency)
- Write-Read Test: Insert data into Row Store. Immediately query Column Store with
SET TRANSACTION READ ONLY TIMESTAMP = NOW(). Verify if data appears (may require waiting for replication lag).
- Failure Injection: Kill the Row Leader. Ensure the Column Store remains readable (even if stale) and the Row Follower promotes to Leader.
2. Performance Testing (HTAP Isolation)
- Tool: Sysbench (for TP) + TPC-H (for AP).
- Phase 1 (Baseline): Run Sysbench only. Record TPS.
- Phase 2 (Conflict): Run Sysbench AND TPC-H simultaneously against Row Store only. TPS will tank.
- Phase 3 (HTAP): Run Sysbench (Row) AND TPC-H (Column) simultaneously.
- Success Criteria: Sysbench TPS remains within 5% of Baseline, while TPC-H queries return in < 5s.
3. Chaos Engineering (Freshness SLA)
- Network Latency: Introduce 100ms artificial latency between Row Leader and Column Learner.
- Verification: Run a continuous read-loop querying the Column Store. Ensure it either returns old data (graceful degradation) or waits, rather than returning errors.
4. Compaction Verification
- Stress Write: Insert 1M rows rapidly.
- Monitor: Watch the "Delta Layer" size grow, then shrink as the background compactor moves it to "Base Columnar".
- Query: Ensure query speed improves after compaction finishes.