Apache Hudi
A streaming data lake platform
A streaming data lake platform
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.
# 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 μμ
μλ£")
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."