Cluster Architecture

MynaDB uses a disaggregated architecture with four distinct node types: Meta nodes for Raft-based consensus and metadata coordination, Router nodes for stateless request routing, Data nodes for storage and query execution, and an optional Admin node for cluster management. Table-level routing keeps the metadata footprint small while enabling horizontal scaling across hundreds of data nodes.

Prerequisites: This page assumes you have read the Cluster Getting Started guide and have a running local cluster. For production deployment guidance, see Cluster Scaling.

Architecture Overview

The following diagram shows all four node types and their interactions. Clients connect through a load balancer to Router nodes, which coordinate with Meta nodes for table ownership and route data operations to the appropriate Data nodes. Data nodes persist Parquet files to shared object storage (S3, MinIO, or OSS). The Admin node connects to Meta for discovery and forwards management requests to individual data nodes.

                                    Clients
                  (InfluxDB Line Protocol / SQL / Arrow Flight / MySQL)
                                       |
                                       v
                              +------------------+
                              |  Load Balancer   |
                              |  (HAProxy/Nginx) |
                              +--------+---------+
                                       |
                  +--------------------+--------------------+
                  |                    |                    |
                  v                    v                    v
          +---------------+    +---------------+    +---------------+
          |  Router Node  |    |  Router Node  |    |  Router Node  |
          |  HTTP  :7000  |    |  HTTP  :7010  |    |  HTTP  :7020  |
          |  Flight:7001  |    |  Flight:7011  |    |  Flight:7021  |
          |  MySQL :7002  |    |  MySQL :7012  |    |  MySQL :7022  |
          |  [ShardCache] |    |  [ShardCache] |    |  [ShardCache] |
          +-------+-------+    +-------+-------+    +-------+-------+
                  |                    |                    |
                  |  Arrow Flight DoPut/DoGet              |
                  +--------------------+--------------------+
                                       |
                  +--------------------+--------------------+
                  |                    |                    |
                  v                    v                    v
          +---------------+    +---------------+    +---------------+
          |  Data Node 1  |    |  Data Node 2  |    |  Data Node N  |
          |  Primary      |    |  Primary      |    |  Standby      |
          |  [DataCache]  |    |  [DataCache]  |    |  [DataCache]  |
          |  [WAL]        |    |  [WAL]        |    |  [read-only]  |
          |  [QueryEngine]|    |  [QueryEngine]|    |  [QueryEngine]|
          +-------+-------+    +-------+-------+    +-------+-------+
                  |                    |                    |
                  +--------------------+--------------------+
                                       |
                  +--------------------------------------------+
                  |       SHARED OBJECT STORAGE                |
                  |       (S3 / MinIO / Alibaba OSS)           |
                  |                                            |
                  |  {catalog}/{schema}/{table}/date=YYYY-MM-DD|
                  |    /node_id={id}/L0_*.parquet              |
                  +--------------------------------------------+

  +-------------------+                         +-------------------+
  |   Admin Node      | ---- Meta Discovery --> |   Meta Node 1     |
  |   HTTP :18080     |                         |   (Raft Leader)   |
  |   [Web Console]   |                         |   gRPC :6001      |
  |   [Query Editor]  |                         |   [sled DB]       |
  +-------------------+                         +--------+----------+
          |                                              |
          | HTTP forwarding                    Raft Log Replication
          | to Data Nodes                              |
          v                                   +--------+----------+
  +-------------------+                       |                   |
  |  Data Node APIs   |               +-------+------+    +-------+------+
  |  /query, /tables  |               | Meta Node 2  |    | Meta Node 3  |
  |  /schema, /stats  |               | (Follower)   |    | (Follower)   |
  +-------------------+               | gRPC :6101   |    | gRPC :6201   |
                                      | [sled DB]    |    | [sled DB]    |
                                      +--------------+    +--------------+

  Router <------ Event Stream (NodeRegistered, TableOwnershipChanged) ------- Meta
  Router ------> MetaCommand (RegisterTable, AcquireLock, Heartbeat) ------> Meta
        

Meta Nodes (Raft Consensus)

Meta nodes form the coordination backbone of the cluster. They maintain a strongly consistent, replicated metadata store using the Raft consensus protocol. Every piece of cluster state — node registrations, table ownership, distributed locks, and leader elections — is replicated across all Meta nodes via Raft log entries.

Raft Configuration

The Raft parameters control leader election timing and log compaction. These defaults are tuned for low-latency local networks. For cross-datacenter deployments, increase the election timeouts proportionally to the round-trip time between Meta nodes.

toml
[meta.raft]
heartbeat_interval_ms = 150          # Leader sends heartbeats at this interval
election_timeout_min_ms = 300        # Minimum election timeout (randomized)
election_timeout_max_ms = 500        # Maximum election timeout (randomized)
snapshot_threshold = 10000           # Compact Raft log after this many entries
max_payload_entries = 300            # Max entries per AppendEntries RPC
replication_lag_threshold = 5000     # Warn if follower is this far behind

# Derived timing:
#   Heartbeat:         150ms
#   Election timeout:  300-500ms (randomized per node)
#   Failover time:     ~500-650ms (election timeout + 1 heartbeat)

The election timeout must be at least 2x the heartbeat interval to avoid spurious elections. The randomized range (300-500ms) ensures that when a leader fails, followers do not all start elections simultaneously, reducing the chance of split votes.

State Machine

The Raft state machine is backed by sled, an embedded key-value store that provides crash-safe persistent storage. All cluster metadata is organized under well-defined key prefixes:

Key Prefix Value Type Description
/raft/vote Vote Current term and voted-for candidate (Raft protocol state)
/raft/log/{index} LogEntry Raft log entries indexed by log position; compacted after snapshot
/raft/snapshot Snapshot Serialized state machine snapshot for log compaction and new-node catch-up
/nodes/{node_id} NodeInfo Node registration: role, state, mode, addresses, lease expiry, capabilities
/tables/{catalog}/{schema}/{table} TableMeta Table ownership: owner nodes, partition count, total bytes, version counter
/locks/{key} LockEntry Distributed locks with TTL: holder node, acquired_at, expires_at
/events/{sequence} ClusterEvent Ordered event stream for cache invalidation and Router notification
/leader/campaign/{role} LeaderEntry Leader election for background tasks (compaction, retention) — separate from Raft leader

MetaCommand Types

All mutations to the Meta state machine are expressed as MetaCommand variants. These commands are proposed to the Raft leader, replicated to a quorum of followers, and then applied to the state machine. The following table lists every command type:

Command Issued By Description
RegisterNode Data / Router Register a new node with its role, addresses, and capabilities. Creates a lease with TTL.
DeregisterNode Admin / Node Gracefully remove a node from the cluster. Triggers table reassignment if the node owned tables.
Heartbeat Data / Router Renew the node lease. Includes current load metrics (CPU, memory, open connections, table count).
UpdateNodeState Admin / Node Transition a node between states (Active, Draining, Retiring, etc.).
RegisterTable Router / Data Register a new table in the metadata catalog. Assigns initial ownership to the requesting data node.
AddTableOwner Router Add a secondary owner for a table (for standby replication or read scaling).
RefreshOwnerTTL Data Renew ownership TTL for a table. Prevents ownership from expiring during normal operation.
RemoveTableOwner Router / Admin Remove a node from a table's owner list (e.g., during node drain or manual reassignment).
ReassignTable Meta (internal) Move table ownership to a different data node. Triggered by node failure or load balancing.
AcquireLock Data / Router Acquire a distributed lock with a TTL. Used for compaction coordination and write serialization.
ReleaseLock Data / Router Release a previously acquired lock. Automatically released if the holder's lease expires.
Campaign Data Campaign for a named leader role (e.g., compaction leader). Only one node wins per role.
Publish Data / Meta Publish a cluster event to the event stream for Router cache updates and Admin notifications.
ExpireLeases Meta (timer) Periodic command that removes expired node leases and ownership entries. Runs on the Raft leader every 5 seconds.

Leader Election

Raft leader election in the Meta cluster is automatic and requires no manual intervention. When the current leader becomes unavailable (crash, network partition, or graceful shutdown), the remaining followers detect the absence of heartbeats and begin a new election.

Election Timeline
T=0ms     Leader sends last heartbeat
T=150ms   Heartbeat interval passes, no new heartbeat
T=300ms   Follower A's election timeout fires (randomized: 300-500ms)
T=300ms   Follower A increments term, votes for self, sends RequestVote RPCs
T=310ms   Follower B receives RequestVote, grants vote (has not voted this term)
T=310ms   Follower A receives majority vote, becomes new leader
T=320ms   New leader sends heartbeat to establish authority
T=320ms   New leader begins accepting MetaCommand proposals

Total failover time: ~320ms (best case) to ~650ms (worst case)

The Raft leader is responsible for all state machine mutations. In addition, certain background tasks run exclusively on the Raft leader to avoid duplicate work:

Event Stream

The Meta cluster publishes an ordered stream of cluster events. Router nodes subscribe to this stream to keep their local ShardCache up to date without polling. Events are assigned monotonically increasing sequence numbers and are retained for a configurable duration (default: 5 minutes).

Event Type Triggered By Consumer Action
NodeRegistered RegisterNode Router adds new data node to its connection pool
NodeStateChanged UpdateNodeState, lease expiry Router marks node as draining or removes it from routing targets
TableOwnershipChanged RegisterTable, ReassignTable, RemoveTableOwner Router invalidates ShardCache entry for the affected table
LeaderChanged Raft election, Campaign Admin UI updates leader indicator; data nodes check if they should run background tasks
LockAcquired AcquireLock Data nodes waiting for the same lock can back off immediately
LockReleased ReleaseLock, lease expiry Data nodes waiting for the lock can attempt acquisition
Event Subscription (Router)
// Router subscribes to the Meta event stream on startup.
// The stream is a gRPC server-streaming RPC.
//
// MetaClient::subscribe_events(last_seen_seq) -> Stream<ClusterEvent>
//
// On reconnect, the Router sends its last_seen_seq so Meta can replay
// missed events. If the gap is too large, Meta sends a full snapshot.

let mut stream = meta_client.subscribe_events(last_seq).await?;
while let Some(event) = stream.next().await {
    match event.event_type {
        EventType::TableOwnershipChanged => {
            shard_cache.invalidate(&event.table_key);
        }
        EventType::NodeStateChanged => {
            connection_pool.update_node(&event.node_id, event.new_state);
        }
        // ...
    }
    last_seq = event.sequence;
}

Router Nodes (Request Routing)

Router nodes are the client-facing entry point for all data operations. They are completely stateless — no data is stored locally, and any Router can handle any request. This makes them trivially horizontally scalable behind a load balancer.

Table-Level Routing

MynaDB uses table-level routing rather than file-level or partition-level routing. This is a deliberate design choice that balances routing overhead against granularity. The following table compares the three approaches for a cluster with 100 databases, 100 tables per database, and 365 daily partitions per table, with an average of 16 Parquet files per partition:

Routing Granularity Routing Table Size Metadata Overhead Rebalancing Cost
File-Level ~58,400,000 entries Very High (~2.3 GB RAM) Per-file migration
Partition-Level ~3,650,000 entries High (~146 MB RAM) Per-partition migration
Table-Level (chosen) ~100,000 entries Low (~4 MB RAM) Per-table reassignment

Table-level routing means that all partitions and files for a given table are owned by the same data node (the primary owner). This dramatically simplifies write coordination — the Router only needs to know which node owns the table, not which node owns each individual partition or file. The tradeoff is that very large tables cannot be split across nodes; however, this is rarely a bottleneck because MynaDB's schema strategy (ServiceAsSchema or ServiceAsTable) naturally distributes data across many tables.

ShardCache

The ShardCache is the Router's local, in-memory cache of table-to-node mappings. It is implemented as a DashMap for lock-free concurrent reads and is automatically updated via the Meta event stream.

ShardCache Structure
// Key: "catalog/schema/table" (e.g., "metrics/service_1/cpu")
// Value: CachedTableMeta

struct CachedTableMeta {
    owner_node_id: String,              // Primary owner data node
    secondary_owners: Vec<String>,      // Standby nodes for failover reads
    version: u64,                       // Monotonic version from Meta
    cached_at: Instant,                 // Local cache timestamp
}

// The ShardCache is a DashMap for concurrent access:
//   DashMap<String, CachedTableMeta>
//
// Lookup: O(1) amortized
// Memory: ~40 bytes per entry (key) + ~120 bytes per entry (value)
// 100K tables: ~15.6 MB total

When a Meta event arrives indicating a table ownership change, the Router invalidates the affected cache entry. On the next request for that table, the Router fetches the latest ownership from Meta and populates the cache.

Write Routing Flow

When a client sends data via POST /write/:db, the Router parses the InfluxDB line protocol, groups lines by table (measurement), and routes each group to the appropriate data node. The following diagram illustrates the complete write routing flow:

  Client                  Router                    Meta                    Data Node
    |                       |                        |                         |
    |  POST /write/mydb     |                        |                         |
    |  body: line protocol  |                        |                         |
    |---------------------->|                        |                         |
    |                       |                        |                         |
    |                [1] Parse line protocol          |                         |
    |                    Extract measurement          |                         |
    |                    (e.g., "cpu")                |                         |
    |                       |                        |                         |
    |                [2] Lookup "mydb/default/cpu"    |                         |
    |                    in ShardCache               |                         |
    |                       |                        |                         |
    |              (cache hit)                       |                         |
    |                       |                        |                         |
    |                [4] Convert to RecordBatch       |                         |
    |                    (Arrow columnar format)      |                         |
    |                       |                        |                         |
    |                       |  Arrow Flight DoPut    |                         |
    |                       |--------------------------------------------->   |
    |                       |                        |                   [5] Insert into
    |                       |                        |                       DataCache
    |                       |                        |                   [6] Write to WAL
    |                       |                        |                         |
    |                       |          DoPut OK      |                         |
    |                       |<---------------------------------------------- |
    |                       |                        |                         |
    |    204 No Content     |                        |                         |
    |<----------------------|                        |                         |
    |                       |                        |                         |

  --- If cache miss (new table): ---

    |                       |                        |                         |
    |                [2] Lookup "mydb/default/cpu"    |                         |
    |                    in ShardCache               |                         |
    |                    (MISS)                      |                         |
    |                       |                        |                         |
    |                [3a] Select least-loaded         |                         |
    |                     data node                  |                         |
    |                       |                        |                         |
    |                       |  RegisterTable         |                         |
    |                       |  (mydb/default/cpu     |                         |
    |                       |   owner=data-1)        |                         |
    |                       |----------------------> |                         |
    |                       |                        |  (Raft replicate)       |
    |                       |  OK (version=1)        |                         |
    |                       |<-----------------------|                         |
    |                       |                        |                         |
    |                [3b] Update ShardCache           |                         |
    |                       |                        |                         |
    |                [4] Convert to RecordBatch       |                         |
    |                       | ...continues as above...|                        |
        

If the DoPut to the primary owner fails (connection error, node unavailable), the Router automatically retries the write to a secondary owner. If no secondary owners exist and the primary is unreachable, the Router sends a ReassignTable command to Meta and retries after reassignment.

Query Coordination

Query routing is more complex than write routing because a single SQL query may reference multiple tables owned by different data nodes. The Router implements a fan-out/fan-in pattern:

Query Routing Steps
1. PARSE       Parse the SQL query and extract all referenced table names
               Example: "SELECT * FROM cpu JOIN memory ON cpu.host = memory.host"
               Tables: ["cpu", "memory"]

2. RESOLVE     For each table, look up the owner data node(s) in the ShardCache
               cpu    -> data-1 (primary), data-3 (secondary)
               memory -> data-2 (primary), data-1 (secondary)

3. DETERMINE   Identify the set of unique data nodes that need to participate
               Target nodes: {data-1, data-2}

4. FAN-OUT     Send the full SQL query to each target node via Arrow Flight DoGet
               (parallel, non-blocking)
               data-1: executes locally, returns partial results for cpu + memory
               data-2: executes locally, returns partial results for memory

5. AGGREGATE   Receive RecordBatch streams from all nodes
               Merge partial results (union, then re-apply ORDER BY / LIMIT)

6. RETURN      Stream the final result back to the client
               (Arrow Flight stream, JSON, or MySQL result set)

For queries that reference only a single table (the common case for time series workloads), the Router simply forwards the query to the owner node and streams results back directly — no aggregation step is needed.

Data Nodes (Storage & Execution)

Data nodes are the workhorses of the cluster. They receive writes from Router nodes via Arrow Flight, buffer data in memory, persist to shared object storage, and execute SQL queries using Apache DataFusion. Each data node operates independently — there is no direct communication between data nodes.

Registration & Heartbeat

When a data node starts, it registers with the Meta cluster by sending a RegisterNode command with its capabilities and addresses. After registration, it heartbeats every 5 seconds to renew its lease.

Registration & Heartbeat
// On startup:
meta_client.register_node(NodeInfo {
    node_id: "data-1",
    role: Role::Data,
    state: NodeState::Starting,
    mode: NodeMode::Primary,
    advertise_addr: "10.0.1.10:5001",
    http_port: 5000,
    flight_port: 5001,
    backing_standby: None,
}).await?;

// Transition to Active after initialization:
meta_client.update_node_state("data-1", NodeState::Active).await?;

// Heartbeat loop (every 5 seconds):
loop {
    meta_client.heartbeat(HeartbeatPayload {
        node_id: "data-1",
        cpu_usage: 0.45,
        memory_usage_mb: 2048,
        open_connections: 12,
        owned_tables: 1500,
    }).await?;
    tokio::time::sleep(Duration::from_secs(5)).await;
}

// Lease TTL: 15 seconds (3 missed heartbeats = node considered dead)
// Meta will expire the node's lease and reassign its tables

Write Path

The data node write path mirrors the standalone MynaDB write path, with the addition of receiving data via Arrow Flight instead of directly from HTTP clients:

Data Node Write Path
1. RECEIVE     Arrow Flight DoPut with RecordBatch from Router
               (already parsed from line protocol by the Router)

2. VALIDATE    Check that this node is the primary owner for the table
               If not owner: return error, Router will re-route

3. INSERT      Insert RecordBatch into DataCache (in-memory write buffer)
               - Organized by catalog/schema/table/date partition
               - Lock-free concurrent inserts via DashMap

4. WAL         Append to Write-Ahead Log (if WAL enabled)
               - WAL path: {data_dir}/wal/{catalog}/{schema}/{table}/
               - Configurable sync_on_write (true=durable, false=faster)

5. REGISTER    If this is a new table, send RegisterTable to Meta
               (table not yet in Meta's catalog)

6. RESPOND     Return success to Router (DoPut acknowledgment)

7. FLUSH       Background task (every flush_interval_secs):
               - Serialize DataCache partitions to Parquet format
               - Upload to S3: {catalog}/{schema}/{table}/date={date}/
                               node_id={id}/L0_{timestamp}.parquet
               - Clear flushed data from DataCache
               - Publish cache invalidation event via Meta

Query Execution

Data nodes execute SQL queries locally using Apache DataFusion. The query engine combines data from two sources: the in-memory DataCache (hot, recently written data) and Parquet files on S3 (cold, flushed data).

Data Node Query Execution
1. RECEIVE     Arrow Flight DoGet with SQL query from Router

2. PARSE       Parse SQL via DataFusion's SQL parser
               Extract table references, date range, predicates

3. PLAN        Create logical plan via DataFusion
               Register table providers:
               - MemtableProvider (DataCache, in-memory hot data)
               - ParquetProvider  (S3 Parquet files, cold data)
               - UnionProvider    (combines both sources)

4. OPTIMIZE    Apply optimization rules:
               - Partition pruning (date range -> skip irrelevant partitions)
               - Predicate pushdown (push filters to Parquet reader)
               - Row group pruning (skip row groups via Parquet statistics)
               - Projection pushdown (read only needed columns)

5. EXECUTE     Execute physical plan via DataFusion ExecutionPipeline
               - Parallel scan of Parquet files
               - Stream merge of hot + cold data

6. RETURN      Stream RecordBatch results back to Router via Arrow Flight

Storage Layout

On shared object storage (S3/MinIO/OSS), Parquet files are organized in a hierarchical directory structure with date partitioning and node-level namespacing:

S3 Storage Layout
{bucket}/
  {catalog}/                              # Database name (e.g., "metrics")
    {schema}/                             # Schema name (e.g., "service_1")
      {table}/                            # Table/measurement (e.g., "cpu")
        date=2026-02-13/                  # Date partition
          node_id=data-1/                 # Node namespace (prevents conflicts)
            L0_1739462400_0001.parquet    # Level 0 (recent flush)
            L0_1739462460_0002.parquet    # Level 0 (another flush)
          node_id=data-2/                 # Different node's files
            L0_1739462400_0001.parquet
        date=2026-02-12/
          node_id=data-1/
            L1_1739376000_0001.parquet    # Level 1 (compacted from L0)
            L2_1739376000_0001.parquet    # Level 2 (compacted from L1)

# File naming convention:
#   L{level}_{timestamp}_{sequence}.parquet
#
# Level 0: Direct flush from DataCache (many small files)
# Level 1: First compaction pass (fewer, larger files)
# Level 2+: Higher compaction levels (fewest, largest files)

The node_id= prefix within each date partition prevents write conflicts when multiple nodes own the same table (primary + standby). During queries, the DataFusion table provider scans all node_id=*/ subdirectories within the requested date partitions.

Compaction

Compaction merges small L0 Parquet files into larger, more query-efficient files at higher levels. MynaDB uses an LSM-tree-inspired leveled compaction strategy:

Level File Size (typical) Source Trigger
L0 1-10 MB DataCache flush Automatic (flush_interval_secs)
L1 50-100 MB L0 compaction When L0 file count exceeds min_files (default: 5)
L2 200-500 MB L1 compaction When L1 file count exceeds threshold
L3+ 500 MB - 1 GB L2+ compaction Configurable up to max_level (default: 5)

In a cluster, compaction is coordinated through Meta distributed locks to prevent two nodes from compacting the same table partition simultaneously:

Distributed Compaction
// LSM compaction: Runs on the table's primary owner node
// Lock key: "compaction/{catalog}/{schema}/{table}/{date}"

let lock_key = format!("compaction/{}/{}/{}/{}", catalog, schema, table, date);
let lock = meta_client.acquire_lock(&lock_key, Duration::from_secs(300)).await?;

// Perform compaction: merge L0 files into L1
compact_partition(catalog, schema, table, date, Level::L0, Level::L1).await?;

meta_client.release_lock(lock).await?;

// Full compaction: Runs ONLY on the elected compaction leader
// (one node in the entire cluster, elected via Campaign command)
// This prevents excessive S3 API calls from parallel full compactions

if is_compaction_leader {
    for table in owned_tables {
        full_compact(table).await?;
    }
}

Admin Node

The Admin node provides a web-based management console for monitoring and operating the cluster. It is entirely optional and has no impact on the data path. The Admin node:

Admin API Endpoints
GET  /api/v1/nodes              # List all registered nodes with health status
GET  /api/v1/nodes/:id          # Get details for a specific node
GET  /api/v1/tables             # List all tables across the cluster
GET  /api/v1/events             # Recent cluster events (paginated)
POST /api/v1/query/:db          # Execute SQL on a specific data node
GET  /api/v1/storage/catalogs   # Browse storage catalogs
GET  /api/v1/storage/info       # Storage backend information

Data Flow Diagrams

Complete Write Path

The following diagram traces a single write request from the client all the way to persistent storage on S3, including the background flush process:

  CLIENT                 ROUTER                  META                  DATA NODE               S3
    |                      |                      |                      |                      |
    | POST /write/mydb     |                      |                      |                      |
    | cpu,host=a val=42.0  |                      |                      |                      |
    |--------------------->|                      |                      |                      |
    |                      |                      |                      |                      |
    |               [1] Parse line protocol        |                      |                      |
    |                   table = "cpu"              |                      |                      |
    |                      |                      |                      |                      |
    |               [2] ShardCache lookup          |                      |                      |
    |                   "mydb/default/cpu"         |                      |                      |
    |                   -> owner: "data-1"         |                      |                      |
    |                      |                      |                      |                      |
    |               [3] Convert to RecordBatch     |                      |                      |
    |                      |                      |                      |                      |
    |                      |  Arrow Flight DoPut   |                      |                      |
    |                      |------------------------------------------->|                      |
    |                      |                      |                      |                      |
    |                      |                      |               [4] Validate ownership        |
    |                      |                      |               [5] Insert into DataCache     |
    |                      |                      |               [6] Append to WAL             |
    |                      |                      |                      |                      |
    |                      |          DoPut OK     |                      |                      |
    |                      |<-------------------------------------------|                      |
    |                      |                      |                      |                      |
    |   204 No Content     |                      |                      |                      |
    |<---------------------|                      |                      |                      |
    |                      |                      |                      |                      |
    .                      .                      .                      .                      .
    . (flush_interval_secs later, background)     .                      .                      .
    .                      .                      .                      .                      .
    |                      |                      |               [7] Serialize DataCache       |
    |                      |                      |                   to Parquet format         |
    |                      |                      |                      |                      |
    |                      |                      |                      |  PUT L0_*.parquet    |
    |                      |                      |                      |--------------------->|
    |                      |                      |                      |                      |
    |                      |                      |                      |         200 OK       |
    |                      |                      |                      |<---------------------|
    |                      |                      |                      |                      |
    |                      |                      |  Publish event:      |                      |
    |                      |                      |  CacheInvalidation   |                      |
    |                      |                      |<---------------------|                      |
    |                      |                      |                      |                      |
    |                      | Event: table updated |                      |                      |
    |                      |<---------------------|                      |                      |
    |                      |                      |                      |                      |
    |               [8] ShardCache: update         |                      |                      |
    |                   version for table          |                      |                      |
    |                      |                      |                      |                      |
        

Complete Query Path

The following diagram shows a multi-table query that requires fan-out to two data nodes, aggregation at the Router, and result streaming back to the client:

  CLIENT                 ROUTER                  DATA-1                DATA-2                  S3
    |                      |                      |                      |                      |
    | POST /query/mydb     |                      |                      |                      |
    | SELECT cpu.host,     |                      |                      |                      |
    |   cpu.value,         |                      |                      |                      |
    |   mem.usage          |                      |                      |                      |
    | FROM cpu             |                      |                      |                      |
    | JOIN memory AS mem   |                      |                      |                      |
    |   ON cpu.host =      |                      |                      |                      |
    |      mem.host        |                      |                      |                      |
    | WHERE date >=       |                      |                      |                      |
    |   '2026-02-10'       |                      |                      |                      |
    |--------------------->|                      |                      |                      |
    |                      |                      |                      |                      |
    |               [1] Parse SQL                  |                      |                      |
    |                   Tables: [cpu, memory]      |                      |                      |
    |                   Date range: >= 2026-02-10 |                      |                      |
    |                      |                      |                      |                      |
    |               [2] ShardCache lookup          |                      |                      |
    |                   cpu    -> data-1           |                      |                      |
    |                   memory -> data-2           |                      |                      |
    |                      |                      |                      |                      |
    |               [3] Fan-out (parallel):        |                      |                      |
    |                      |                      |                      |                      |
    |                      |  DoGet: full SQL     |                      |                      |
    |                      |--------------------->|                      |                      |
    |                      |                      |                      |                      |
    |                      |  DoGet: full SQL     |                      |                      |
    |                      |------------------------------------------->|                      |
    |                      |                      |                      |                      |
    |                      |               [4a] DataFusion plan          |                      |
    |                      |                  Scan DataCache (hot)       |                      |
    |                      |                      |  LIST partitions     |                      |
    |                      |                      |--------------------->|                      |
    |                      |                      |  GET L1_*.parquet    |                      |
    |                      |                      |--------------------->|                      |
    |                      |                      |                      |                      |
    |                      |               [4b] DataFusion plan          |                      |
    |                      |                      |               Scan DataCache (hot)          |
    |                      |                      |                      |  LIST partitions     |
    |                      |                      |                      |--------------------->|
    |                      |                      |                      |  GET L1_*.parquet    |
    |                      |                      |                      |--------------------->|
    |                      |                      |                      |                      |
    |                      |  RecordBatch stream  |                      |                      |
    |                      |<---------------------|                      |                      |
    |                      |                      |                      |                      |
    |                      |  RecordBatch stream  |                      |                      |
    |                      |<-------------------------------------------|                      |
    |                      |                      |                      |                      |
    |               [5] Aggregate partial results  |                      |                      |
    |                   Merge streams              |                      |                      |
    |                   Apply JOIN, ORDER BY       |                      |                      |
    |                      |                      |                      |                      |
    |  JSON result         |                      |                      |                      |
    |  [{host, value,      |                      |                      |                      |
    |    usage}, ...]      |                      |                      |                      |
    |<---------------------|                      |                      |                      |
    |                      |                      |                      |                      |
        

Key Data Structures

The following data structures are the core building blocks of the cluster coordination layer. They are serialized as JSON for Meta storage and gRPC transport.

NodeInfo
struct NodeInfo {
    node_id: String,                // Unique identifier (e.g., "data-1", "router-1")
    role: NodeRole,                 // Data, Router, Admin
    state: NodeState,               // Starting, Active, Draining, Inactive, Retiring, Drained
    mode: NodeMode,                 // Primary (read-write) or Standby (read-only)
    advertise_addr: String,         // Address other nodes use to reach this node
    http_port: u16,                 // HTTP API port
    flight_port: Option<u16>,      // Arrow Flight port (Data and Router only)
    mysql_port: Option<u16>,       // MySQL wire protocol port (Router only)
    backing_standby: Option<String>,// Node ID of the standby backing this primary
    lease_expires_at: u64,          // Unix timestamp (ms) when the lease expires
    registered_at: u64,             // Unix timestamp (ms) when the node first registered
    last_heartbeat: u64,            // Unix timestamp (ms) of the most recent heartbeat
    version: String,                // MynaDB version (e.g., "0.3.0")
    capabilities: Vec<String>,     // ["write", "query", "compact", "flight", "mysql"]
}
NodeState Enum
enum NodeState {
    Starting,    // Node is initializing (loading WAL, warming caches)
    Active,      // Node is fully operational and accepting requests
    Draining,    // Node is finishing in-flight requests but not accepting new ones
    Inactive,    // Node has stopped heartbeating (lease may still be valid)
    Retiring,    // Node is being permanently removed; tables are being reassigned
    Drained,     // Node has completed draining; safe to shut down
}

// State transitions:
//   Starting -> Active          (initialization complete)
//   Active -> Draining          (admin requests graceful shutdown)
//   Active -> Inactive          (missed heartbeats, possible crash)
//   Draining -> Drained         (all in-flight requests completed)
//   Inactive -> Active          (node resumes heartbeating)
//   Inactive -> Retiring        (admin decides to remove the node)
//   Retiring -> Drained         (all tables reassigned)
TableMeta
struct TableMeta {
    catalog: String,                       // Database name (e.g., "metrics")
    schema: String,                        // Schema name (e.g., "service_1")
    table: String,                         // Table/measurement (e.g., "cpu")
    owner_node_ids: Vec<TableOwnerEntry>, // Ordered: primary first, then secondaries
    partition_count: u64,                  // Number of date partitions
    total_bytes: u64,                      // Total size across all partitions
    created_at: u64,                       // Unix timestamp (ms) when table was registered
    updated_at: u64,                       // Unix timestamp (ms) of last metadata change
    version: u64,                          // Monotonically increasing version counter
}

struct TableOwnerEntry {
    node_id: String,                       // Owning data node ID
    role: OwnerRole,                       // Primary or Secondary
    ttl_ms: u64,                           // Ownership TTL in milliseconds (default: 30000)
    expires_at: u64,                       // Unix timestamp (ms) when ownership expires
    assigned_at: u64,                      // Unix timestamp (ms) when ownership was assigned
}

enum OwnerRole {
    Primary,     // Accepts writes and serves queries
    Secondary,   // Read-only, serves queries as failover
}
ClusterEvent
struct ClusterEvent {
    sequence: u64,                  // Monotonically increasing sequence number
    event_type: EventType,          // Type discriminator
    timestamp: u64,                 // Unix timestamp (ms) when event was created
    source_node: Option<String>,   // Node that triggered the event (if applicable)
    payload: EventPayload,          // Event-specific data
}

enum EventType {
    NodeRegistered,
    NodeStateChanged,
    TableOwnershipChanged,
    LeaderChanged,
    LockAcquired,
    LockReleased,
    CacheInvalidation,
}

// Example event payloads:
//
// NodeRegistered:
//   { node_id: "data-3", role: "data", addr: "10.0.1.12:5001" }
//
// TableOwnershipChanged:
//   { table_key: "metrics/service_1/cpu", old_owner: "data-1",
//     new_owner: "data-2", reason: "node_failure" }
//
// CacheInvalidation:
//   { table_key: "metrics/service_1/cpu", partition: "date=2026-02-13",
//     files_added: ["L0_1739462400_0001.parquet"], reason: "flush" }