Use asynchronous materialized views for transparent rewriting

Updated at:

Asynchronous materialized views in ApsaraDB for SelectDB support complex queries involving multi-table joins, subqueries, and arbitrary SQL expressions. The optimizer can transparently rewrite qualifying queries to read from these pre-computed views, delivering significant performance improvements for complex analytical workloads.

What are asynchronous materialized views

An asynchronous materialized view is an independent table object defined by an arbitrary SELECT statement. Unlike synchronous materialized views (rollups), asynchronous materialized views:

  • Support multi-table joins, subqueries, window functions, and complex expressions.

  • Are refreshed on a configurable schedule (periodic or triggered) rather than synchronously on each write.

  • Can be partitioned independently and support partition-level incremental refresh.

  • Exist as first-class table objects that can be queried directly or used for transparent rewriting.

Create an asynchronous materialized view

Use the CREATE MATERIALIZED VIEW statement with the desired query definition and refresh properties.

-- Create an async MV that pre-joins orders with customers
CREATE MATERIALIZED VIEW mv_order_customer
REFRESH AUTO ON SCHEDULE EVERY 1 HOUR
DISTRIBUTED BY HASH(order_id) BUCKETS AUTO
AS
SELECT
    o.order_id,
    o.order_date,
    o.amount,
    c.customer_name,
    c.region,
    c.tier
FROM orders_detail o
INNER JOIN customers c ON o.customer_id = c.customer_id;
-- Create a partitioned async MV with incremental refresh
CREATE MATERIALIZED VIEW mv_daily_region_sales
PARTITION BY (order_date)
REFRESH AUTO ON SCHEDULE EVERY 30 MINUTE
DISTRIBUTED BY HASH(region) BUCKETS AUTO
AS
SELECT
    o.order_date,
    c.region,
    SUM(o.amount) AS total_sales,
    COUNT(*) AS order_count
FROM orders_detail o
INNER JOIN customers c ON o.customer_id = c.customer_id
GROUP BY o.order_date, c.region;

Refresh strategies

ApsaraDB for SelectDB provides multiple refresh strategies for asynchronous materialized views:

  • Scheduled refresh: Refreshes at fixed intervals using ON SCHEDULE EVERY N {MINUTE|HOUR|DAY}. Suitable for dashboards that tolerate a bounded staleness window.

  • Manual refresh: Triggered explicitly using REFRESH MATERIALIZED VIEW mv_name. Suitable for batch processing pipelines where refresh timing is controlled externally.

  • Auto refresh: The system detects data changes in base tables and triggers refresh automatically. Use REFRESH AUTO combined with a schedule for optimal freshness.

  • Partition-level incremental refresh: When the MV is partitioned and aligned with a base table partition, only partitions with changed data are refreshed, dramatically reducing refresh cost.

-- Manually trigger a full refresh
REFRESH MATERIALIZED VIEW mv_order_customer COMPLETE;

-- Manually trigger an incremental refresh (only refresh changed partitions)
REFRESH MATERIALIZED VIEW mv_order_customer AUTO;

-- Check refresh task status
SELECT * FROM tasks('type'='mv') WHERE MvName = 'mv_order_customer'
ORDER BY CreateTime DESC LIMIT 5;

-- Check MV definition
SHOW CREATE MATERIALIZED VIEW mv_order_customer;

Transparent rewrite mechanism

When transparent rewriting is enabled, the optimizer attempts to match incoming queries against available asynchronous materialized views. If a match is found, the optimizer rewrites the query to scan the materialized view instead of executing the original multi-table join or aggregation.

For transparent rewriting to succeed:

  • The query must reference only columns available in the materialized view (or derivable from them).

  • The join structure of the query must be a subset of the join structure in the MV definition.

  • Filter conditions must be satisfiable from the MV data (either pre-filtered or post-filterable).

  • The MV data must meet the configured staleness tolerance (controlled by grace_period).

-- Enable transparent rewriting for asynchronous materialized views (enabled by default)
SET enable_materialized_view_rewrite = true;

Verify transparent rewriting

Use EXPLAIN to check whether a query hits a materialized view:

EXPLAIN SELECT region, SUM(amount)
FROM orders o JOIN products p ON o.product_id = p.product_id
GROUP BY region;

-- If the output contains the table name mv_region_daily_sales,
-- the query has been transparently rewritten to the materialized view.

Enable and disable transparent rewriting

Use session variables to fine-tune transparent rewriting behavior:

-- Disable transparent rewriting for debugging
SET enable_materialized_view_rewrite = false;

-- Set the materialized view staleness tolerance in seconds. If the materialized view is not refreshed within this period, it does not participate in rewriting.
ALTER MATERIALIZED VIEW mv_region_daily_sales SET ('grace_period' = '3600');

Manage asynchronous materialized views

-- Set the staleness tolerance to 24 hours. If the materialized view is not refreshed within this period, it does not participate in transparent rewriting.
ALTER MATERIALIZED VIEW mv_region_daily_sales SET ('grace_period' = '86400');

-- Drop the materialized view
DROP MATERIALIZED VIEW mv_region_daily_sales;

-- View the materialized view definition
SHOW CREATE MATERIALIZED VIEW mv_region_daily_sales;

Use cases

  • Multi-table join acceleration: Pre-join frequently queried dimension and fact tables to avoid expensive runtime joins on large datasets.

  • Complex aggregation caching: Pre-compute multi-level aggregations (e.g., daily/weekly/monthly rollups by region) for instant dashboard rendering.

  • Denormalized views: Flatten a normalized schema into a wide table for BI tools that generate simple single-table queries.

Comparison with synchronous materialized views

The following table summarizes the key differences between synchronous and asynchronous materialized views:

  • Query scope: Synchronous MVs support single-table aggregation only. Asynchronous MVs support multi-table joins, subqueries, and complex expressions.

  • Data consistency: Synchronous MVs are strongly consistent (updated in the same transaction). Asynchronous MVs are eventually consistent with configurable staleness.

  • Write impact: Synchronous MVs increase write latency proportionally to the number of views. Asynchronous MVs have no impact on write latency.

  • Maintenance: Synchronous MVs are automatically maintained. Asynchronous MVs require refresh scheduling and monitoring.

  • Recommendation: Use synchronous MVs for simple single-table aggregation with strong consistency requirements. Use asynchronous MVs for multi-table scenarios or when write performance is critical.