Continuous Aggregates & Downsampling
Continuous Aggregates bring TimescaleDB-style materialized views to MynaDB. Define a query once and MynaDB automatically keeps the results up to date as new data arrives. The query engine transparently rewrites incoming queries to read from the pre-computed aggregate whenever possible, dramatically reducing query latency for dashboards and monitoring workloads.
Instead of running expensive GROUP BY time_bucket(...) queries on every dashboard refresh,
define the aggregation once and let MynaDB maintain the results incrementally. Typical speedups range
from 10x to 100x for time-bucketed queries over large datasets.
Creating Aggregates
Use the SQL-like CREATE CONTINUOUS AGGREGATE syntax to define a materialized view over
your time series data. Each aggregate requires a time_bucket() call and at least one
aggregation function.
-- Create a 5-minute rollup of CPU metrics
CREATE CONTINUOUS AGGREGATE cpu_5m
WITH (refresh_interval = '1m')
AS
SELECT
time_bucket(time, 300000000000, 0) AS bucket,
host,
AVG(usage) AS avg_usage,
MAX(usage) AS max_usage,
MIN(usage) AS min_usage,
COUNT(*) AS sample_count
FROM cpu
GROUP BY time_bucket(time, 300000000000, 0), host;
Key elements of the definition:
| Element | Description |
|---|---|
cpu_5m |
Name of the continuous aggregate (must be unique within the database) |
refresh_interval |
How often to refresh the materialized data (e.g., 1m, 5m, 1h) |
time_bucket() |
Required bucketing function that defines the output granularity |
| Aggregation functions | AVG, MAX, MIN, SUM, COUNT, first_value, last_value |
Using the API
You can also create aggregates via the HTTP API:
# Create a continuous aggregate via API
curl -X POST http://localhost:7000/aggregates/mydb \
-H "Content-Type: application/json" \
-d '{
"name": "cpu_5m",
"query": "SELECT time_bucket(time, 300000000000, 0) AS bucket, host, AVG(usage) AS avg_usage, MAX(usage) AS max_usage, MIN(usage) AS min_usage, COUNT(*) AS sample_count FROM cpu GROUP BY time_bucket(time, 300000000000, 0), host",
"refresh_interval_secs": 60
}'
Automated Downsampling
Continuous Aggregates enable automated downsampling policies that reduce data granularity over time. This is essential for managing storage costs while retaining long-term visibility. Define multiple aggregates at different granularities to build a tiered rollup pipeline.
-- Tier 1: Raw data (kept for 7 days via retention policy)
-- 1-minute resolution
-- Tier 2: 5-minute rollup (kept for 30 days)
CREATE CONTINUOUS AGGREGATE cpu_5m
WITH (refresh_interval = '1m')
AS
SELECT
time_bucket(time, 300000000000, 0) AS bucket,
host,
AVG(usage) AS avg_usage,
MAX(usage) AS max_usage,
MIN(usage) AS min_usage,
first_value(usage, time) AS first_usage,
last_value(usage, time) AS last_usage,
COUNT(*) AS sample_count
FROM cpu
GROUP BY time_bucket(time, 300000000000, 0), host;
-- Tier 3: 1-hour rollup (kept for 1 year)
CREATE CONTINUOUS AGGREGATE cpu_1h
WITH (refresh_interval = '5m')
AS
SELECT
time_bucket(time, 3600000000000, 0) AS bucket,
host,
AVG(usage) AS avg_usage,
MAX(usage) AS max_usage,
MIN(usage) AS min_usage,
COUNT(*) AS sample_count
FROM cpu
GROUP BY time_bucket(time, 3600000000000, 0), host;
The tiered approach follows a common pattern:
| Tier | Granularity | Retention | Use Case |
|---|---|---|---|
| Raw data | Original (e.g., 1s) | 7 days | Debugging, incident investigation |
| Tier 1 aggregate | 5 minutes | 30 days | Recent dashboards, alerting |
| Tier 2 aggregate | 1 hour | 1 year | Capacity planning, trend analysis |
Query Rewriting
When query_rewriting_enabled is set to true, the query engine automatically
detects when an incoming query can be satisfied by a continuous aggregate and rewrites the query plan
to read from the materialized view instead of scanning raw data.
How It Works
- A query arrives that uses
time_bucket()orGROUP BY time()on a source table. - The query rewriter checks if a continuous aggregate exists for that table with a matching or coarser bucket size.
- If the aggregate's bucket size evenly divides the requested bucket size, the query is rewritten to read from the aggregate.
- Aggregation functions in the original query are translated to operate on the pre-aggregated columns.
-- Original query (user writes this)
SELECT
time_bucket(time, 3600000000000, 0) AS hour,
host,
AVG(usage) AS avg_cpu
FROM cpu
WHERE time >= NOW() - INTERVAL '24 hours'
GROUP BY time_bucket(time, 3600000000000, 0), host;
-- Rewritten query (engine executes this internally)
-- Reads from the 5-minute aggregate and re-aggregates to 1 hour
SELECT
time_bucket(bucket, 3600000000000, 0) AS hour,
host,
SUM(avg_usage * sample_count) / SUM(sample_count) AS avg_cpu
FROM cpu_5m
WHERE bucket >= NOW() - INTERVAL '24 hours'
GROUP BY time_bucket(bucket, 3600000000000, 0), host;
Rewriting Rules
| Original Function | Rewritten To | Requirement |
|---|---|---|
AVG(col) |
SUM(avg_col * count) / SUM(count) |
Aggregate must include AVG and COUNT |
SUM(col) |
SUM(sum_col) |
Aggregate must include SUM |
COUNT(*) |
SUM(count_col) |
Aggregate must include COUNT |
MIN(col) |
MIN(min_col) |
Aggregate must include MIN |
MAX(col) |
MAX(max_col) |
Aggregate must include MAX |
You can verify whether query rewriting is being applied by using the
/explain endpoint:
# Check if the query uses a continuous aggregate
curl "http://localhost:7000/explain/mydb?sql=SELECT+time_bucket(time,3600000000000,0)+AS+hour,+host,+AVG(usage)+FROM+cpu+GROUP+BY+1,2&verbose=true"
# Look for "ContinuousAggregate: cpu_5m" in the logical plan
Configuration
Enable and tune continuous aggregates in your config.toml:
[continuous_aggregates]
# Enable the continuous aggregates feature
enabled = true
# How often the background job checks for aggregates that need refreshing (seconds)
refresh_check_interval_secs = 60
# Maximum number of aggregates refreshed concurrently
max_concurrent_refreshes = 4
# Automatically rewrite queries to use aggregates when beneficial
query_rewriting_enabled = true
| Parameter | Default | Description |
|---|---|---|
enabled |
false |
Master switch for the continuous aggregates feature. When disabled, existing aggregates are not refreshed and query rewriting is inactive. |
refresh_check_interval_secs |
60 |
Interval in seconds between background refresh checks. Lower values increase freshness at the cost of higher CPU usage. |
max_concurrent_refreshes |
4 |
Maximum number of aggregate refresh jobs running in parallel. Increase for systems with many aggregates and available CPU cores. |
query_rewriting_enabled |
true |
When enabled, the query engine automatically rewrites qualifying queries to use materialized views. Can be disabled to force queries against raw data. |
API Endpoints
Manage continuous aggregates through the REST API:
| Endpoint | Method | Description |
|---|---|---|
/aggregates/:db |
GET | List all continuous aggregates for a database |
/aggregates/:db |
POST | Create a new continuous aggregate |
/aggregates/:db/:name |
DELETE | Delete a continuous aggregate and its materialized data |
/aggregates/:db/:name/refresh |
POST | Manually trigger an immediate refresh |
List Aggregates
# List all continuous aggregates
curl http://localhost:7000/aggregates/mydb
# Response
{
"aggregates": [
{
"name": "cpu_5m",
"source_table": "cpu",
"bucket_interval_ns": 300000000000,
"refresh_interval_secs": 60,
"state": "active",
"last_refresh": "2026-02-13T10:15:00Z",
"watermark": 1739440500000000000
},
{
"name": "cpu_1h",
"source_table": "cpu",
"bucket_interval_ns": 3600000000000,
"refresh_interval_secs": 300,
"state": "active",
"last_refresh": "2026-02-13T10:10:00Z",
"watermark": 1739438400000000000
}
],
"count": 2
}
Create an Aggregate
# Create a 1-hour rollup of memory metrics
curl -X POST http://localhost:7000/aggregates/mydb \
-H "Content-Type: application/json" \
-d '{
"name": "memory_1h",
"query": "SELECT time_bucket(time, 3600000000000, 0) AS bucket, host, AVG(used) AS avg_used, MAX(used) AS max_used, AVG(total) AS avg_total FROM memory GROUP BY time_bucket(time, 3600000000000, 0), host",
"refresh_interval_secs": 300
}'
# Response
{
"status": "created",
"name": "memory_1h",
"message": "Continuous aggregate created. First refresh will begin within 60 seconds."
}
Delete an Aggregate
# Delete a continuous aggregate
curl -X DELETE http://localhost:7000/aggregates/mydb/cpu_5m
# Response
{
"status": "deleted",
"name": "cpu_5m",
"message": "Continuous aggregate and materialized data removed."
}
Manual Refresh
# Trigger an immediate refresh
curl -X POST http://localhost:7000/aggregates/mydb/cpu_5m/refresh
# Response
{
"status": "refreshing",
"name": "cpu_5m",
"message": "Refresh started. New data will be available shortly."
}
Monitoring
Track the health and performance of your continuous aggregates using the list endpoint and server logs.
Aggregate States
| State | Description |
|---|---|
active |
Aggregate is healthy and being refreshed on schedule. |
refreshing |
A refresh is currently in progress. |
error |
The last refresh failed. Check logs for details. The system will retry on the next interval. |
disabled |
The aggregate exists but is not being refreshed (e.g., feature disabled in config). |
Key Metrics
The list endpoint returns useful fields for monitoring each aggregate:
- last_refresh - Timestamp of the most recent successful refresh. A stale timestamp may indicate a problem.
- watermark - The highest timestamp (in nanoseconds) that has been materialized. Data after this point is not yet in the aggregate.
- state - Current state of the aggregate (see table above).
Log Messages
The refresh job emits structured log entries at info level. Key messages to watch for:
# Successful refresh
INFO continuous_aggregates::job: Refreshed aggregate name="cpu_5m" rows=1842 duration_ms=234 watermark=1739440500000000000
# Refresh error
ERROR continuous_aggregates::job: Failed to refresh aggregate name="cpu_5m" error="table not found: cpu" retries=3
# Query rewriting applied
DEBUG continuous_aggregates::query_rewriter: Rewrote query to use aggregate original_table="cpu" aggregate="cpu_5m"
Use the Grafana integration to visualize aggregate refresh latency and watermark lag. See the Monitoring page for pre-built dashboard panels.