๐Ÿ“Š Data Engineering

Materialize

A streaming database

Detailed Explanation

Materialize is a streaming database that can run standard SQL queries on streaming data in real time. It uses Incremental View Maintenance technology to update query results immediately when data changes.

Key Features of Materialize

  • Streaming SQL: Supports standard PostgreSQL-compatible SQL
  • Incremental computation: Efficient updates by recomputing only the changed data
  • Materialized Views: Keeps query results up to date in real time
  • Kafka-native: Connects directly to Kafka streams
  • Millisecond latency: Supports real-time analytics queries

Materialize vs Other Solutions

CharacteristicsMaterializeFlink SQLksqlDB
SQL CompatibilityPostgreSQLANSI SQLKSQL
Join ComplexityMultiple tablesLimitedLimited
LatencyMillisecondsMilliseconds to secondsMilliseconds to seconds
State ManagementBuilt-inRocksDBRocksDB
Ease of UseHigh (SQL)MediumHigh

Code Example

Connecting to a Kafka Stream and Real-Time Aggregation

-- Materialize ์ŠคํŠธ๋ฆฌ๋ฐ SQL ์˜ˆ์ œ

-- 1. Kafka ์†Œ์Šค ์—ฐ๊ฒฐ ์ƒ์„ฑ
CREATE CONNECTION kafka_connection TO KAFKA (
    BROKER 'kafka:9092',
    SECURITY PROTOCOL = 'SASL_SSL',
    SASL MECHANISMS = 'PLAIN',
    SASL USERNAME = SECRET kafka_username,
    SASL PASSWORD = SECRET kafka_password
);

-- 2. ์ฃผ๋ฌธ ์ด๋ฒคํŠธ ์ŠคํŠธ๋ฆผ ์†Œ์Šค ์ƒ์„ฑ
CREATE SOURCE orders_source
FROM KAFKA CONNECTION kafka_connection (
    TOPIC 'orders'
)
FORMAT JSON
WITH (
    TIMESTAMP FIELD = 'order_time',
    RETENTION = '7d'
);

-- 3. ์ƒํ’ˆ ์ •๋ณด ์ŠคํŠธ๋ฆผ ์†Œ์Šค ์ƒ์„ฑ
CREATE SOURCE products_source
FROM KAFKA CONNECTION kafka_connection (
    TOPIC 'products'
)
FORMAT JSON;

-- 4. ์‹ค์‹œ๊ฐ„ ์ฃผ๋ฌธ ๋ทฐ ์ƒ์„ฑ
CREATE MATERIALIZED VIEW orders AS
SELECT
    (data->>'order_id')::int AS order_id,
    (data->>'customer_id')::int AS customer_id,
    (data->>'product_id')::int AS product_id,
    (data->>'quantity')::int AS quantity,
    (data->>'price')::decimal AS price,
    (data->>'order_time')::timestamp AS order_time
FROM orders_source;

-- 5. ์ƒํ’ˆ ์ •๋ณด ๋ทฐ ์ƒ์„ฑ
CREATE MATERIALIZED VIEW products AS
SELECT
    (data->>'product_id')::int AS product_id,
    data->>'product_name' AS product_name,
    data->>'category' AS category,
    (data->>'unit_price')::decimal AS unit_price
FROM products_source;

-- 6. ์‹ค์‹œ๊ฐ„ ๋งค์ถœ ์ง‘๊ณ„ (1์‹œ๊ฐ„ ์œˆ๋„์šฐ)
CREATE MATERIALIZED VIEW hourly_sales AS
SELECT
    date_trunc('hour', order_time) AS hour,
    p.category,
    COUNT(*) AS order_count,
    SUM(o.quantity) AS total_quantity,
    SUM(o.quantity * o.price) AS total_revenue
FROM orders o
JOIN products p ON o.product_id = p.product_id
WHERE order_time > now() - INTERVAL '24 hours'
GROUP BY date_trunc('hour', order_time), p.category;

-- 7. ์‹ค์‹œ๊ฐ„ ๊ณ ๊ฐ๋ณ„ ๊ตฌ๋งค ํ˜„ํ™ฉ
CREATE MATERIALIZED VIEW customer_metrics AS
SELECT
    customer_id,
    COUNT(*) AS total_orders,
    SUM(quantity * price) AS total_spent,
    AVG(quantity * price) AS avg_order_value,
    MAX(order_time) AS last_order_time
FROM orders
WHERE order_time > now() - INTERVAL '30 days'
GROUP BY customer_id;

Real-Time Anomaly Detection Query

-- ์‹ค์‹œ๊ฐ„ ์ด์ƒ ํƒ์ง€๋ฅผ ์œ„ํ•œ Materialized Views

-- 1๋ถ„ ๋‹จ์œ„ ๊ฑฐ๋ž˜๋Ÿ‰ ๋ชจ๋‹ˆํ„ฐ๋ง
CREATE MATERIALIZED VIEW transaction_rate AS
SELECT
    date_trunc('minute', order_time) AS minute,
    COUNT(*) AS transaction_count,
    SUM(price * quantity) AS total_value
FROM orders
WHERE order_time > now() - INTERVAL '1 hour'
GROUP BY date_trunc('minute', order_time);

-- ์ด์ƒ ๊ฑฐ๋ž˜ ํƒ์ง€ (ํ‰๊ท ์˜ 3๋ฐฐ ์ด์ƒ)
CREATE MATERIALIZED VIEW anomaly_alerts AS
WITH stats AS (
    SELECT
        AVG(transaction_count) AS avg_count,
        STDDEV(transaction_count) AS stddev_count
    FROM transaction_rate
    WHERE minute > now() - INTERVAL '24 hours'
)
SELECT
    t.minute,
    t.transaction_count,
    t.total_value,
    'HIGH_VOLUME' AS alert_type
FROM transaction_rate t, stats s
WHERE t.minute > now() - INTERVAL '5 minutes'
  AND t.transaction_count > s.avg_count + 3 * s.stddev_count;

-- ๊ณ ๊ฐ๋ณ„ ์ด์ƒ ํ–‰๋™ ํƒ์ง€ (5๋ถ„ ๋‚ด 10๊ฑด ์ด์ƒ ์ฃผ๋ฌธ)
CREATE MATERIALIZED VIEW suspicious_customers AS
SELECT
    customer_id,
    COUNT(*) AS order_count_5min,
    SUM(price * quantity) AS total_value_5min
FROM orders
WHERE order_time > now() - INTERVAL '5 minutes'
GROUP BY customer_id
HAVING COUNT(*) > 10;

Connecting to Materialize with Python

# Python์—์„œ Materialize ์‚ฌ์šฉํ•˜๊ธฐ (psycopg2)
import psycopg2
import pandas as pd
from psycopg2 import sql
import time

# Materialize ์—ฐ๊ฒฐ (PostgreSQL ํ”„๋กœํ† ์ฝœ ์‚ฌ์šฉ)
conn = psycopg2.connect(
    host="materialize.example.com",
    port=6875,
    user="materialize",
    password="secret",
    database="materialize"
)
conn.autocommit = True

def execute_query(query):
    """์ฟผ๋ฆฌ ์‹คํ–‰ ๋ฐ ๊ฒฐ๊ณผ ๋ฐ˜ํ™˜"""
    with conn.cursor() as cur:
        cur.execute(query)
        if cur.description:
            columns = [desc[0] for desc in cur.description]
            return pd.DataFrame(cur.fetchall(), columns=columns)
        return None

# Materialized View ์ƒ์„ฑ
create_view_sql = """
CREATE MATERIALIZED VIEW IF NOT EXISTS realtime_dashboard AS
SELECT
    date_trunc('minute', order_time) AS minute,
    COUNT(*) AS orders,
    SUM(price * quantity) AS revenue
FROM orders
WHERE order_time > now() - INTERVAL '1 hour'
GROUP BY date_trunc('minute', order_time)
ORDER BY minute DESC
"""
execute_query(create_view_sql)

# ์‹ค์‹œ๊ฐ„ ์ฟผ๋ฆฌ ๊ฒฐ๊ณผ ์กฐํšŒ
def get_dashboard_data():
    """๋Œ€์‹œ๋ณด๋“œ ๋ฐ์ดํ„ฐ ์กฐํšŒ"""
    df = execute_query("SELECT * FROM realtime_dashboard LIMIT 60")
    return df

# SUBSCRIBE๋ฅผ ์‚ฌ์šฉํ•œ ์‹ค์‹œ๊ฐ„ ์ŠคํŠธ๋ฆฌ๋ฐ (๋ณ€๊ฒฝ ์‚ฌํ•ญ ํ‘ธ์‹œ)
def subscribe_to_changes():
    """๋ทฐ ๋ณ€๊ฒฝ์‚ฌํ•ญ์„ ์‹ค์‹œ๊ฐ„์œผ๋กœ ๊ตฌ๋…"""
    with conn.cursor() as cur:
        # SUBSCRIBE ์‹œ์ž‘
        cur.execute("SUBSCRIBE (SELECT * FROM realtime_dashboard)")

        print("์‹ค์‹œ๊ฐ„ ๊ตฌ๋… ์‹œ์ž‘...")
        while True:
            # ๋ณ€๊ฒฝ์‚ฌํ•ญ ์ˆ˜์‹ 
            cur.execute("FETCH ALL FROM realtime_dashboard")
            rows = cur.fetchall()

            for row in rows:
                mz_timestamp, mz_diff, minute, orders, revenue = row
                action = "INSERT" if mz_diff > 0 else "DELETE"
                print(f"[{action}] minute={minute}, orders={orders}, revenue={revenue}")

# ์—ฐ๊ฒฐ ์ข…๋ฃŒ
def cleanup():
    conn.close()

dbt + Materialize Integration

# dbt_project.yml
name: 'streaming_analytics'
version: '1.0.0'
profile: 'materialize'

models:
  streaming_analytics:
    +materialized: materializedview  # Materialize ์ „์šฉ


# profiles.yml
materialize:
  target: dev
  outputs:
    dev:
      type: materialize
      host: materialize.example.com
      port: 6875
      user: materialize
      password: "{{ env_var('MZ_PASSWORD') }}"
      database: materialize
      schema: analytics
-- models/customer_lifetime_value.sql
-- dbt ๋ชจ๋ธ: ์‹ค์‹œ๊ฐ„ ๊ณ ๊ฐ ์ƒ์•  ๊ฐ€์น˜

{{ config(materialized='materializedview') }}

WITH customer_orders AS (
    SELECT
        customer_id,
        order_id,
        order_time,
        price * quantity AS order_value
    FROM {{ source('kafka', 'orders') }}
),

customer_stats AS (
    SELECT
        customer_id,
        COUNT(DISTINCT order_id) AS total_orders,
        SUM(order_value) AS total_revenue,
        MIN(order_time) AS first_order,
        MAX(order_time) AS last_order,
        AVG(order_value) AS avg_order_value
    FROM customer_orders
    GROUP BY customer_id
)

SELECT
    customer_id,
    total_orders,
    total_revenue,
    first_order,
    last_order,
    avg_order_value,
    -- ๊ฐ„๋‹จํ•œ CLV ๊ณ„์‚ฐ (์‹ค์ œ๋กœ๋Š” ๋” ๋ณต์žกํ•œ ๋ชจ๋ธ ์‚ฌ์šฉ)
    total_revenue *
        GREATEST(1, EXTRACT(EPOCH FROM (now() - first_order)) /
                    EXTRACT(EPOCH FROM (last_order - first_order + INTERVAL '1 day')))
        AS estimated_clv
FROM customer_stats
WHERE total_orders > 0

Practical Conversation Example

Data Engineer: "I need to build a real-time dashboard, and I want to query Kafka data with SQL. Flink SQL looks complicated to set up..."
Senior Engineer: "Try Materialize. It uses the PostgreSQL protocol, so it's compatible with your existing tools, and if you know SQL, you can do stream processing."
Data Engineer: "What's the difference between a Materialized View and a regular View?"
Senior Engineer: "A Materialized View stores its results, so it returns them immediately when queried. When the data changes, Materialize updates it incrementally and automatically. That's why you can see even complex aggregations with millisecond latency."
Data Engineer: "How does it compare to ksqlDB?"
Senior Engineer: "ksqlDB is Kafka-only, and its SQL syntax is a bit different. Materialize is PostgreSQL-compatible, so complex JOINs and subqueries work well too. But Materialize uses a bit more resources."

Cautions

Resource Management

  • Materialized Views keep state in memory - many views put a strain on memory
  • Complex JOINs can cause a sharp increase in memory usage
  • DROP unused views to release resources

Query Design

  • Aggregations without an INTERVAL cause unbounded state growth
  • Always adding a time window condition is recommended
  • Creating indexes improves query performance

Operational Considerations

  • Kafka source offset management - beware of duplicate data on restart
  • Schema changes require recreating sources/views
  • The commercial version offers a cloud-managed service

Related Terms

Learn More