多级缓存

完美的记忆,每次如一。MynaDB 实现了精密的多级缓存架构 — 如同八哥鸟卓越的记忆力 — 以最大化查询性能。本指南介绍不同的缓存层级及其配置方法。

v0.2.8 新功能:基于内存的元数据管理器(自动持久化)、对象存储的 Parquet 磁盘缓存,以及 Memtable 即时查询最新写入可见性。

缓存架构概览

text
┌─────────────────────────────────────────────────────────────────────┐
│                          Query Engine                                │
│                                                                      │
│  ┌──────────────────┐  ┌──────────────────┐  ┌──────────────────┐   │
│  │ Metadata Manager │  │   Query Cache    │  │    Memtable      │   │
│  │  (Memory + JSON) │  │  (SQL → Results) │  │  (Fresh Writes)  │   │
│  └────────┬─────────┘  └────────┬─────────┘  └────────┬─────────┘   │
│           │                     │                     │              │
│           │     ┌───────────────┴───────────────┐     │              │
│           │     │                               │     │              │
│           ▼     ▼                               ▼     ▼              │
│  ┌───────────────────────────────────────────────────────────────┐  │
│  │              Parquet Disk Cache (Local SSD)                   │  │
│  │         Caches Object Store files for fast local access       │  │
│  └──────────────────────────────┬────────────────────────────────┘  │
│                                 │                                    │
└─────────────────────────────────┼────────────────────────────────────┘
                                  │
                    ┌─────────────┴─────────────┐
                    │                           │
                    ▼                           ▼
           ┌───────────────┐          ┌────────────────┐
           │ Local Storage │          │  Object Store  │
           │   (Parquet)   │          │ (S3/MinIO/OSS) │
           └───────────────┘          └────────────────┘

缓存层级总览

缓存层级 存储位置 用途 性能影响
元数据管理器 内存 + JSON Catalog、Schema、表、分区、文件元数据 消除目录扫描(规划速度提升 10-100 倍)
查询结果缓存 内存 SQL 查询结果 重复查询即时响应
Memtable 内存 尚未刷写的最新写入 即时查询可见性(无需刷写)
Parquet 磁盘缓存 本地 SSD 对象存储文件 比网络获取快 10-100 倍

1. 元数据管理器

元数据管理器在内存中维护所有数据库、Schema、表、分区和文件的完整目录。这消除了查询规划期间昂贵的目录扫描和对象存储列表操作。

架构

text
┌─────────────────────────────────────────────────────────────┐
│                    Metadata Manager                          │
│                                                              │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │
│  │  Catalogs   │  │   Schemas   │  │      Tables         │  │
│  │  HashMap    │  │   HashMap   │  │      HashMap        │  │
│  └─────────────┘  └─────────────┘  └─────────────────────┘  │
│                                                              │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │
│  │ Partitions  │  │    Files    │  │   Partition→Files   │  │
│  │  HashMap    │  │   HashMap   │  │   Reverse Index     │  │
│  └─────────────┘  └─────────────┘  └─────────────────────┘  │
│                                                              │
│         ↓                ↓                   ↓               │
│  ┌─────────────────────────────────────────────────────────┐ │
│  │             JSON Snapshot (Periodic Save)               │ │
│  │              catalog_snapshot.json                       │ │
│  └─────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘

存储内容

实体 键 跟踪信息
CatalogInfo catalog_name 名称、创建时间、Schema 数量、表数量、总字节数
SchemaInfo (catalog, schema) 名称、Catalog、表数量、总字节数
TableInfo (catalog, schema, table) 名称、总行数、总字节数、分区数、文件数、最小/最大时间戳
PartitionInfo (catalog, schema, table, date) 分区键/值、总行数、总字节数、文件数、最小/最大时间戳
FileInfo file_path 路径、级别、字节大小、行数、行组数、分区键、etag

核心特性

快照持久化

json
{
  "version": 1,
  "snapshot_at": 1705123456789,
  "catalogs": [
    {"name": "mydb", "created_at": 1705000000000, "schema_count": 3, "table_count": 15}
  ],
  "schemas": [
    {"name": "default", "catalog": "mydb", "table_count": 10}
  ],
  "tables": [
    {"name": "cpu", "schema": "default", "catalog": "mydb",
     "total_rows": 1000000, "total_bytes": 52428800, "partition_count": 7}
  ],
  "partitions": [
    {"partition_key": "2024-01-15", "table": "cpu", "file_count": 3}
  ],
  "files": [
    {"path": "/data/mydb/default/cpu/date=2024-01-15/L0_xxx.parquet",
     "level": 0, "size_bytes": 10485760, "row_count": 100000}
  ]
}

恢复流程

text
Server Startup
      │
      ▼
┌─────────────────┐
│ Load Snapshot?  │──────────────────┐
└────────┬────────┘                  │ No snapshot
         │ Yes                       ▼
         ▼                   ┌───────────────┐
┌─────────────────┐          │ Full Rescan   │
│ Load from JSON  │          │ (data_dir)    │
└────────┬────────┘          └───────┬───────┘
         │                           │
         ▼                           ▼
┌─────────────────────────────────────────────┐
│          Metadata Manager Ready             │
│     (All queries use in-memory lookups)     │
└─────────────────────────────────────────────┘

API 端点

bash
# Get global metadata statistics
curl http://localhost:7000/cache/stats

# Pre-warm metadata for entire catalog (database)
curl -X POST http://localhost:7000/cache/prewarm/mydb

# Pre-warm metadata for specific table
curl -X POST http://localhost:7000/cache/prewarm/mydb/default/cpu

# Clear all caches (triggers rescan on next query)
curl -X POST http://localhost:7000/cache/clear

# Get detailed Parquet file statistics
curl http://localhost:7000/cache/parquet/mydb/default/cpu

统计信息响应

json
{
  "metadata_manager": {
    "catalog_count": 3,
    "schema_count": 12,
    "table_count": 156,
    "partition_count": 2340,
    "file_count": 8920,
    "total_rows": 5847293847,
    "total_bytes": 128849018880
  },
  "query_cache": {
    "entries": 128,
    "hits": 4521,
    "misses": 892,
    "hit_rate": 0.835,
    "memory_usage_bytes": 134217728
  }
}

2. 查询结果缓存

缓存 SQL 查询结果,避免重复执行昂贵的查询。

配置

toml
[query_cache]
# Enable query result caching
enabled = true

# Maximum cache size in MB
max_size_mb = 256

# Maximum number of cached queries
max_entries = 1000

# Cache TTL in seconds (5 minutes)
ttl_secs = 300

# Only cache queries that take longer than this (ms)
min_query_time_ms = 10

工作原理

缓存失效

bash
# Clear only query result cache
curl -X POST http://localhost:7000/cache/clear/results

# Cache is automatically invalidated on:
# - Data writes to a table
# - Compaction of a table
# - Manual flush

3. Memtable(即时查询可见性)

Memtable 为尚未刷写到 Parquet 的最新写入提供即时查询可见性。以前,您需要在查询最近数据之前调用 /flush。现在查询自动包含内存中的数据。

工作原理

text
┌─────────────────────────────────────────────────────────────┐
│                      Query Execution                         │
│                                                              │
│  SELECT * FROM cpu WHERE host = 'server01'                   │
│                                                              │
│         ┌──────────────┐          ┌──────────────┐           │
│         │MemtableExec  │          │ParquetExec   │           │
│         │(Fresh Data)  │          │(Parquet Files)│          │
│         └──────┬───────┘          └──────┬───────┘           │
│                │                         │                    │
│                └──────────┬──────────────┘                    │
│                           │                                   │
│                           ▼                                   │
│                   ┌───────────────┐                           │
│                   │  UnionExec    │                           │
│                   │ (Merge Both)  │                           │
│                   └───────────────┘                           │
│                           │                                   │
│                           ▼                                   │
│                      Query Results                            │
│              (Includes ALL data, flushed + unflushed)         │
└─────────────────────────────────────────────────────────────┘

核心特性

查询行为

bash
# Write data (goes to in-memory cache)
curl -X POST http://localhost:7000/write/mydb \
  -d 'cpu,host=server01 usage=75.5'

# Query IMMEDIATELY - no flush needed!
# This returns the fresh data from memtable
curl 'http://localhost:7000/query/mydb' \
  -d 'SELECT * FROM cpu WHERE host = '\''server01'\'''

# Data is automatically included from:
# 1. In-memory cache (memtable) - fresh writes
# 2. Parquet files - flushed data

4. Parquet 磁盘缓存(对象存储)

当使用对象存储后端(S3、MinIO、阿里云 OSS)时,MynaDB 将 Parquet 文件缓存在本地 SSD 上,大幅降低网络延迟。这对于使用云存储的生产环境部署至关重要。

架构

text
┌─────────────────────────────────────────────────────────────┐
│                      Disk File Cache                         │
│                                                              │
│  ┌─────────────────────────────────────────────────────────┐ │
│  │                  In-Memory State                        │ │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │ │
│  │  │   entries    │  │  total_size  │  │    stats     │  │ │
│  │  │   HashMap    │  │    (u64)     │  │ hits/misses  │  │ │
│  │  └──────────────┘  └──────────────┘  └──────────────┘  │ │
│  └─────────────────────────────────────────────────────────┘ │
│                              │                               │
│                              ▼                               │
│  ┌─────────────────────────────────────────────────────────┐ │
│  │                  Local SSD Storage                      │ │
│  │  /var/cache/mynadb/parquet/                             │ │
│  │    ├── abc123def456.parquet  (cached file)              │ │
│  │    ├── 789ghi012jkl.parquet  (cached file)              │ │
│  │    └── cache_index.json      (metadata)                 │ │
│  └─────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘

配置

toml
[file_cache]
# Enable file caching (essential for Object Store backends)
enabled = true

# Cache directory on local SSD (use NVMe for best performance)
cache_dir = "/var/cache/mynadb/parquet"

# Maximum cache size (100 GB)
max_size_bytes = 107374182400

# Index save interval in seconds (5 minutes)
auto_save_interval_secs = 300

缓存条目元数据

每个缓存文件跟踪全面的元数据以支持智能淘汰:

json
{
  "source_path": "s3://bucket/mydb/default/cpu/date=2024-01-15/L0_xxx.parquet",
  "cache_path": "/var/cache/mynadb/parquet/abc123.parquet",
  "size_bytes": 10485760,
  "etag": "\"d41d8cd98f00b204e9800998ecf8427e\"",
  "cached_at": 1705123456789,
  "last_accessed": 1705234567890,
  "access_count": 42,
  "partition_date": "2024-01-15"
}

智能淘汰策略

缓存使用基于优先级的淘汰算法,综合考虑多个因素:

text
Priority Score = Recency × Frequency × Partition_Bonus

Recency Factors:
  - Accessed in last hour:    100x
  - Accessed today:           50x
  - Accessed this week:       10x
  - Older:                    1x

Partition Date Bonus (time series optimization):
  - Today's partition:        10x
  - Yesterday's partition:    8x
  - This week's partition:    5x
  - This month's partition:   2x
  - Older partitions:         1x

Files with LOWER scores are evicted first.

缓存流程

text
Query needs file: s3://bucket/mydb/default/cpu/date=2024-01-15/L0.parquet
     │
     ▼
┌─────────────────┐
│ Check In-Memory │
│  Entry Index    │
└────────┬────────┘
         │
    ┌────┴────┐
    │ Exists? │
    └────┬────┘
         │
    Yes  │  No
    ┌────┘  └────┐
    │            │
    ▼            ▼
┌─────────┐  ┌─────────────────┐
│ Update  │  │ Fetch from S3   │
│ Access  │  │ (Network Call)  │
│ Stats   │  └────────┬────────┘
└────┬────┘           │
     │                ▼
     │        ┌─────────────────┐
     │        │ Make Room       │
     │        │ (Evict if full) │
     │        └────────┬────────┘
     │                 │
     │                 ▼
     │        ┌─────────────────┐
     │        │ Write to SSD    │
     │        │ + Update Index  │
     │        └────────┬────────┘
     │                 │
     ▼                 ▼
┌───────────────────────────────┐
│ Read from Local SSD           │
│ (Fast: ~0.1ms vs ~50ms S3)    │
└───────────────────────────────┘

缓存统计

bash
# Get disk cache statistics
curl http://localhost:7000/cache/stats | jq '.disk_cache'

# Response:
{
  "file_count": 1523,
  "total_size_bytes": 85899345920,
  "max_size_bytes": 107374182400,
  "hits": 45210,
  "misses": 892,
  "hit_rate": 0.981,
  "evictions": 234,
  "bytes_read_from_cache": 4521000000000,
  "bytes_fetched_from_source": 89200000000
}

缓存操作

bash
# Prefetch files for expected queries (warm cache before dashboard load)
curl -X POST http://localhost:7000/cache/prefetch \
  -H "Content-Type: application/json" \
  -d '{"paths": ["s3://bucket/mydb/default/cpu/date=2024-01-15/*"]}'

# Invalidate cache for specific path prefix (after compaction)
curl -X POST http://localhost:7000/cache/invalidate \
  -H "Content-Type: application/json" \
  -d '{"prefix": "s3://bucket/mydb/default/cpu/date=2024-01-15/"}'

# Clear entire disk cache
curl -X POST http://localhost:7000/cache/clear

# Verify cache integrity (check for orphaned entries)
curl http://localhost:7000/cache/verify

最佳实践

高查询性能配置

元数据管理器

  • 让系统通过写入自动填充元数据
  • 启动时对关键数据库进行预热
  • 监控分区数量以了解表增长情况

查询结果缓存

  • 为仪表板/报表查询启用缓存
  • 根据数据新鲜度需求设置 TTL
  • 使用 min_query_time_ms 跳过快速查询

Memtable

  • 自动启用,无需配置
  • 写入后即可立即查询
  • 调整 flush_interval_secs 平衡内存与新鲜度

磁盘缓存

  • 使用 NVMe SSD 作为缓存目录
  • 容量应能容纳 7 天以上的热数据
  • 监控命中率(目标 >90%)

内存容量规划指南

部署规模 表数量 查询缓存 磁盘缓存 建议内存
小型 <50 256 MB 10 GB 4 GB
中型 50-500 1 GB 100 GB 16 GB
大型 500-5000 4 GB 500 GB 64 GB
企业级 >5000 16 GB 1+ TB 128+ GB

对象存储部署

toml
# Recommended config for S3/MinIO/OSS deployments
[file_cache]
enabled = true
cache_dir = "/mnt/nvme/mynadb-cache"  # NVMe SSD
max_size_bytes = 107374182400          # 100 GB
auto_save_interval_secs = 60           # Frequent saves

[query_cache]
enabled = true
max_size_mb = 1024                     # 1 GB
ttl_secs = 300                         # 5 min TTL
min_query_time_ms = 50                 # Only cache slow queries

监控

通过统计端点监控缓存效果:

bash
# Full cache statistics
curl http://localhost:7000/cache/stats | jq .

# Key metrics to watch:
# - hit_rate: Should be > 80% for effective caching
# - memory_usage: Should not exceed configured limits
# - evictions: High eviction rate may indicate undersized cache