πŸ“Š Data Engineering

Apache Hudi

A streaming data lake platform

Detailed Explanation

Apache Hudi (Hadoop Upserts Deletes and Incrementals) is an open-source data lake platform developed by Uber that efficiently handles record-level insert, update, and delete operations on large-scale analytical datasets. By overcoming immutability, a limitation of traditional data lakes, it supports ACID transactions and incremental data processing.

Hudi provides two table types: Copy-on-Write (CoW) and Merge-on-Read (MoR). CoW rewrites entire files at write time to optimize read performance, while MoR stores changes in delta logs and merges them at read time to minimize write latency. You can choose the appropriate type depending on workload characteristics.

Incremental Processing is a core feature of Hudi that extracts only the changed data and delivers it to downstream pipelines. This eliminates the inefficiency of scanning entire tables and enables near-real-time data processing. It is integrated with various query engines such as Spark, Flink, Presto, and Trino.

Hudi provides enterprise-grade features such as Time Travel, rollback, concurrency control, clustering, and compaction. It is fully compatible with cloud storage on AWS, Azure, and GCP, and can be integrated with CDC tools such as Debezium to reflect database changes in the data lake in real time.

Code Example

# Apache Hudi ν…Œμ΄λΈ” μ„€μ • 및 upsert 예제 (PySpark)
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, lit, current_timestamp

# Spark μ„Έμ…˜ 생성 (Hudi λ²ˆλ“€ 포함)
spark = SparkSession.builder \
    .appName("HudiExample") \
    .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer") \
    .config("spark.sql.catalog.spark_catalog",
            "org.apache.spark.sql.hudi.catalog.HoodieCatalog") \
    .config("spark.sql.extensions",
            "org.apache.spark.sql.hudi.HoodieSparkSessionExtension") \
    .getOrCreate()

# Hudi ν…Œμ΄λΈ” μ„€μ •
hudi_options = {
    # ν…Œμ΄λΈ” κΈ°λ³Έ μ„€μ •
    "hoodie.table.name": "user_events",
    "hoodie.datasource.write.table.type": "COPY_ON_WRITE",  # λ˜λŠ” MERGE_ON_READ

    # λ ˆμ½”λ“œ ν‚€ 및 νŒŒν‹°μ…˜ μ„€μ •
    "hoodie.datasource.write.recordkey.field": "event_id",
    "hoodie.datasource.write.partitionpath.field": "event_date",
    "hoodie.datasource.write.precombine.field": "updated_at",

    # μ“°κΈ° μž‘μ—… μ„€μ •
    "hoodie.datasource.write.operation": "upsert",
    "hoodie.upsert.shuffle.parallelism": 100,

    # 인덱슀 μ„€μ • (Bloom Filter κΈ°λ³Έ)
    "hoodie.index.type": "BLOOM",
    "hoodie.bloom.index.update.partition.path": "true",

    # 파일 크기 μ΅œμ ν™”
    "hoodie.parquet.max.file.size": 128 * 1024 * 1024,  # 128MB
    "hoodie.parquet.small.file.limit": 100 * 1024 * 1024,  # 100MB

    # 메타데이터 ν…Œμ΄λΈ” ν™œμ„±ν™” (μ„±λŠ₯ ν–₯상)
    "hoodie.metadata.enable": "true",
    "hoodie.metadata.index.column.stats.enable": "true"
}

# μƒ˜ν”Œ 데이터 생성
initial_data = [
    ("evt001", "user_1", "click", "2024-01-15", "2024-01-15 10:00:00"),
    ("evt002", "user_2", "purchase", "2024-01-15", "2024-01-15 10:05:00"),
    ("evt003", "user_1", "view", "2024-01-15", "2024-01-15 10:10:00"),
]

df = spark.createDataFrame(
    initial_data,
    ["event_id", "user_id", "event_type", "event_date", "updated_at"]
)

# Hudi ν…Œμ΄λΈ”μ— μ“°κΈ°
table_path = "s3://data-lake/hudi/user_events"

df.write.format("hudi") \
    .options(**hudi_options) \
    .mode("overwrite") \
    .save(table_path)

print("초기 데이터 적재 μ™„λ£Œ")

# Upsert μž‘μ—… (μ—…λ°μ΄νŠΈ + μ‚½μž…)
upsert_data = [
    # κΈ°μ‘΄ λ ˆμ½”λ“œ μ—…λ°μ΄νŠΈ
    ("evt001", "user_1", "click_confirmed", "2024-01-15", "2024-01-15 10:30:00"),
    # μƒˆλ‘œμš΄ λ ˆμ½”λ“œ μ‚½μž…
    ("evt004", "user_3", "signup", "2024-01-15", "2024-01-15 10:35:00"),
]

upsert_df = spark.createDataFrame(
    upsert_data,
    ["event_id", "user_id", "event_type", "event_date", "updated_at"]
)

upsert_df.write.format("hudi") \
    .options(**hudi_options) \
    .mode("append") \
    .save(table_path)

print("Upsert μ™„λ£Œ")

# ============================================
# 증뢄 쿼리 (Incremental Query)
# ============================================
# νŠΉμ • 컀밋 이후 λ³€κ²½λœ λ°μ΄ν„°λ§Œ 쑰회
incremental_options = {
    "hoodie.datasource.query.type": "incremental",
    "hoodie.datasource.read.begin.instanttime": "20240115100000000",
    "hoodie.datasource.read.end.instanttime": "20240115110000000"
}

incremental_df = spark.read.format("hudi") \
    .options(**incremental_options) \
    .load(table_path)

print("증뢄 λ³€κ²½ 데이터:")
incremental_df.show()

# ============================================
# νƒ€μž„ νŠΈλž˜λΈ” 쿼리
# ============================================
# νŠΉμ • μ‹œμ μ˜ 데이터 쑰회
time_travel_df = spark.read.format("hudi") \
    .option("as.of.instant", "20240115100500000") \
    .load(table_path)

print("νŠΉμ • μ‹œμ  데이터:")
time_travel_df.show()

# ============================================
# Soft Delete κ΅¬ν˜„
# ============================================
delete_options = hudi_options.copy()
delete_options["hoodie.datasource.write.operation"] = "delete"

# μ‚­μ œν•  λ ˆμ½”λ“œ
delete_df = spark.createDataFrame(
    [("evt002", "user_2", "purchase", "2024-01-15", "2024-01-15 11:00:00")],
    ["event_id", "user_id", "event_type", "event_date", "updated_at"]
)

delete_df.write.format("hudi") \
    .options(**delete_options) \
    .mode("append") \
    .save(table_path)

# ============================================
# Compaction μ‹€ν–‰ (MoR ν…Œμ΄λΈ”μš©)
# ============================================
from pyspark.sql import functions as F

# 인라인 μ»΄νŒ©μ…˜ μ„€μ •
mor_options = hudi_options.copy()
mor_options.update({
    "hoodie.datasource.write.table.type": "MERGE_ON_READ",
    "hoodie.compact.inline": "true",
    "hoodie.compact.inline.max.delta.commits": 5,
    "hoodie.compaction.strategy": "org.apache.hudi.table.action.compact.strategy.LogFileSizeBasedCompactionStrategy",
    "hoodie.compaction.target.io": 500 * 1024 * 1024  # 500MB
})

# ============================================
# Clustering (파일 λ ˆμ΄μ•„μ›ƒ μ΅œμ ν™”)
# ============================================
clustering_options = hudi_options.copy()
clustering_options.update({
    "hoodie.clustering.inline": "true",
    "hoodie.clustering.inline.max.commits": 4,
    "hoodie.clustering.plan.strategy.target.file.max.bytes": 1073741824,  # 1GB
    "hoodie.clustering.plan.strategy.sort.columns": "user_id,event_type"
})

# ============================================
# Hudi SQL (Spark SQL μ‚¬μš©)
# ============================================
# ν…Œμ΄λΈ” 생성
spark.sql("""
    CREATE TABLE IF NOT EXISTS user_events_sql (
        event_id STRING,
        user_id STRING,
        event_type STRING,
        event_date STRING,
        updated_at TIMESTAMP
    ) USING hudi
    TBLPROPERTIES (
        'primaryKey' = 'event_id',
        'preCombineField' = 'updated_at',
        'type' = 'cow'
    )
    PARTITIONED BY (event_date)
    LOCATION 's3://data-lake/hudi/user_events_sql'
""")

# MERGE INTO λ¬Έ (Upsert)
spark.sql("""
    MERGE INTO user_events_sql target
    USING source_updates source
    ON target.event_id = source.event_id
    WHEN MATCHED THEN UPDATE SET *
    WHEN NOT MATCHED THEN INSERT *
""")

# νƒ€μž„ νŠΈλž˜λΈ” SQL
spark.sql("""
    SELECT * FROM user_events_sql
    TIMESTAMP AS OF '2024-01-15 10:00:00'
""")

print("Hudi μž‘μ—… μ™„λ£Œ")

How it is used in practice

Data Engineer: "We're loading real-time order data into the data lake, but currently we reload the entire table every day. Is there a more efficient way?"

Tech Lead: "If we adopt Apache Hudi, we can do incremental processing. We can capture only the changes with CDC and upsert them into the Hudi table, and downstream can pull only the changed data with incremental queries."

Data Engineer: "Which table type is better, CoW or MoR?"

Tech Lead: "If reads are heavy and writes are light, CoW is better; if writes are frequent, MoR is better. Our order data has a lot of writes, so let's start with MoR and optimize while adjusting the compaction interval."

Interviewer: "Please explain the differences between the Copy-on-Write and Merge-on-Read table types in Apache Hudi, and the usage scenarios for each."

Candidate: "CoW rewrites entire files on write, so write latency is high but read performance is excellent. It is suitable for cases with heavy reads and light writes, such as analytical workloads. MoR records changes in delta logs and compacts them later, so writes are fast but there is merge overhead at read time. It is suitable for event logs or CDC pipelines that require real-time ingestion. In addition, MoR provides Snapshot Query and Read Optimized Query, so you can choose between freshness and performance."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

Reviewer: "You set the Hudi index type to GLOBAL_BLOOM, but there may be performance issues as the number of partitions grows."

Developer: "Right. GLOBAL_BLOOM has to scan all partitions, so it can be slow. Instead, if you use a BUCKET index, you can scan only specific partitions based on hashing."

Reviewer: "Good. And enabling hoodie.metadata.enable also greatly improves file listing performance. It's especially effective on object storage such as S3."

Cautions

Related Terms

Learn More