Multi-Level Caching
Perfect recall, every time. MynaDB implements a sophisticated multi-level caching architecture — like the myna bird's remarkable memory — to maximize query performance. This guide explains the different cache layers and how to configure them.
Cache Architecture Overview
┌─────────────────────────────────────────────────────────────────────┐
│ 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) │
└───────────────┘ └────────────────┘
Cache Layers Summary
| Cache Layer | Storage | Purpose | Performance Impact |
|---|---|---|---|
| Metadata Manager | Memory + JSON | Catalog, schema, table, partition, file metadata | Eliminates directory scans (10-100x faster planning) |
| Query Result Cache | Memory | SQL query results | Instant response for repeated queries |
| Memtable | Memory | Fresh writes not yet flushed | Immediate query visibility (no flush required) |
| Parquet Disk Cache | Local SSD | Object Store files | 10-100x faster than network fetch |
1. Metadata Manager
The Metadata Manager maintains a complete catalog of all databases, schemas, tables, partitions, and files in memory. This eliminates expensive directory scans and object store listings during query planning.
Architecture
┌─────────────────────────────────────────────────────────────┐
│ Metadata Manager │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
│ │ Catalogs │ │ Schemas │ │ Tables │ │
│ │ HashMap │ │ HashMap │ │ HashMap │ │
│ └─────────────┘ └─────────────┘ └─────────────────────┘ │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │
│ │ Partitions │ │ Files │ │ Partition→Files │ │
│ │ HashMap │ │ HashMap │ │ Reverse Index │ │
│ └─────────────┘ └─────────────┘ └─────────────────────┘ │
│ │
│ ↓ ↓ ↓ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ JSON Snapshot (Periodic Save) │ │
│ │ catalog_snapshot.json │ │
│ └─────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
What's Stored
| Entity | Key | Tracked Information |
|---|---|---|
| CatalogInfo | catalog_name | Name, created_at, schema_count, table_count, total_bytes |
| SchemaInfo | (catalog, schema) | Name, catalog, table_count, total_bytes |
| TableInfo | (catalog, schema, table) | Name, total_rows, total_bytes, partition_count, file_count, min/max timestamp |
| PartitionInfo | (catalog, schema, table, date) | Partition key/value, total_rows, total_bytes, file_count, min/max timestamp |
| FileInfo | file_path | Path, level, size_bytes, row_count, row_groups, partition_key, etag |
Key Features
- Zero Directory Scans: All metadata in memory, no filesystem calls during query planning
- Automatic Persistence: Periodic save to
catalog_snapshot.jsonfor crash recovery - Lazy Registration: New catalogs/schemas/tables auto-created when files are registered
- Aggregated Statistics: Automatic rollup of row counts, bytes, timestamps up the hierarchy
- Fast Partition Pruning: Query
list_partitions_in_range()for date-filtered queries
Snapshot Persistence
{
"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}
]
}
Recovery Flow
Server Startup
│
▼
┌─────────────────┐
│ Load Snapshot? │──────────────────┐
└────────┬────────┘ │ No snapshot
│ Yes ▼
▼ ┌───────────────┐
┌─────────────────┐ │ Full Rescan │
│ Load from JSON │ │ (data_dir) │
└────────┬────────┘ └───────┬───────┘
│ │
▼ ▼
┌─────────────────────────────────────────────┐
│ Metadata Manager Ready │
│ (All queries use in-memory lookups) │
└─────────────────────────────────────────────┘
API Endpoints
# 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
Statistics Response
{
"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. Query Result Cache
Caches the results of SQL queries to avoid re-executing expensive queries.
Configuration
[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
How It Works
- Cache key is computed from: database name + SQL query text
- Results are cached only if query execution time exceeds
min_query_time_ms - Cache is automatically invalidated when data is written to referenced tables
- Entries expire after
ttl_secsseconds
Cache Invalidation
# 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 (Immediate Query Visibility)
The Memtable provides immediate query visibility for fresh writes that haven't been flushed to Parquet yet. Previously, you had to call /flush before querying recent data. Now queries automatically include in-memory data.
How It Works
┌─────────────────────────────────────────────────────────────┐
│ Query Execution │
│ │
│ SELECT * FROM cpu WHERE host = 'server01' │
│ │
│ ┌──────────────┐ ┌──────────────┐ │
│ │MemtableExec │ │ParquetExec │ │
│ │(Fresh Data) │ │(Parquet Files)│ │
│ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │
│ └──────────┬──────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────┐ │
│ │ UnionExec │ │
│ │ (Merge Both) │ │
│ └───────────────┘ │
│ │ │
│ ▼ │
│ Query Results │
│ (Includes ALL data, flushed + unflushed) │
└─────────────────────────────────────────────────────────────┘
Key Features
- Zero-Copy Access: Reads directly from DataCache without copying (Arc-based batches)
- Schema Alignment: Automatically aligns memtable schema with Parquet file schema
- Filter Pushdown: Supports inexact filter pushdown for efficiency
- Streaming Results: Uses RecordBatchStream to avoid collecting all data in memory
Query Behavior
# 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 Disk Cache (Object Store)
When using Object Store backends (S3, MinIO, Aliyun OSS), MynaDB caches Parquet files on local SSD to dramatically reduce network latency. This is essential for production deployments using cloud storage.
Architecture
┌─────────────────────────────────────────────────────────────┐
│ 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) │ │
│ └─────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Configuration
[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
Cache Entry Metadata
Each cached file tracks comprehensive metadata for smart eviction:
{
"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"
}
Smart Eviction Strategy
The cache uses a priority-based eviction algorithm that considers multiple factors:
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.
Cache Flow
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) │
└───────────────────────────────┘
Cache Statistics
# 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
}
Cache Operations
# 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
Best Practices
For High Query Performance
Metadata Manager
- Let the system auto-populate metadata from writes
- Pre-warm on startup for critical databases
- Monitor partition counts for table growth
Query Result Cache
- Enable for dashboard/reporting queries
- Set TTL based on data freshness needs
- Use
min_query_time_msto skip fast queries
Memtable
- Auto-enabled, no configuration needed
- Query immediately after writes
- Adjust
flush_interval_secsfor memory vs freshness
Disk Cache
- Use NVMe SSD for cache directory
- Size to hold 7+ days of hot data
- Monitor hit rate (target >90%)
Memory Sizing Guide
| Deployment Size | Tables | Query Cache | Disk Cache | Recommended RAM |
|---|---|---|---|---|
| Small | <50 | 256 MB | 10 GB | 4 GB |
| Medium | 50-500 | 1 GB | 100 GB | 16 GB |
| Large | 500-5000 | 4 GB | 500 GB | 64 GB |
| Enterprise | >5000 | 16 GB | 1+ TB | 128+ GB |
Object Store Deployment
# 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
Monitoring
Monitor cache effectiveness using the stats endpoint:
# 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