Apache Hudi: A Complete Guide to Building Data Lakehouses
Author: Ruby AbdullahApache Hudi (Hadoop Upserts Deletes and Incrementals) is an open-source data lakehouse platform that brings database-like capabilities to data lakes. It enables ACID transactions, record-level inserts, updates, and deletes on data stored in cloud storage or HDFS, making it possible to build reliable, high-performance data pipelines on top of open file formats like Apache Parquet and ORC.
1. Introduction
What is Apache Hudi?
Apache Hudi is a transactional data lake platform that provides stream and batch data processing with incremental data pipelines on self-managing database layers. Originally developed at Uber in 2016 to solve the problem of managing petabyte-scale datasets in their data lake, Hudi was donated to the Apache Software Foundation and graduated as a top-level project in 2020.
At its core, Hudi provides three essential capabilities:
- Upsert support: Unlike traditional data lake formats that only support append operations, Hudi allows you to efficiently update and delete individual records.
- Incremental processing: Hudi tracks changes at the record level, enabling you to process only the data that has changed since the last pipeline run.
- ACID transactions: All operations are atomic, ensuring data consistency even when multiple writers and readers access the same dataset concurrently.
Why Apache Hudi Matters
Traditional data lakes suffer from several well-known problems. Updating or deleting individual records requires rewriting entire partitions, which is both slow and expensive. There is no built-in mechanism for tracking changes over time, making it difficult to implement CDC (Change Data Capture) pipelines. Concurrent reads and writes can lead to data corruption or inconsistent results.
Hudi solves these problems by adding a thin management layer on top of standard file formats. This layer maintains metadata about the dataset, tracks the timeline of operations, and provides efficient indexing for record-level mutations. The result is a data lakehouse that combines the scalability and cost-effectiveness of a data lake with the transactional guarantees of a data warehouse.
Hudi vs. Delta Lake vs. Apache Iceberg
Hudi is one of three major open table formats alongside Delta Lake and Apache Iceberg. While all three provide ACID transactions and schema evolution, Hudi differentiates itself with its first-class support for record-level upserts, its built-in indexing mechanisms (such as Bloom filters and HBase indexes), and its mature incremental processing capabilities.
2. Installation and Setup
Prerequisites
Before getting started, ensure you have the following installed:
- Java 8 or 11
- Apache Spark 3.x
- Python 3.7+
- pip (Python package manager)
Installing PySpark with Hudi
The simplest way to get started with Hudi is through PySpark. Install PySpark first:
pip install pyspark==3.4.1
When launching PySpark, you need to include the Hudi package. Create a helper script or use the following command:
pyspark \
--packages org.apache.hudi:hudi-spark3.4-bundle2.12:0.14.1 \
--conf "spark.serializer=org.apache.spark.serializer.KryoSerializer" \
--conf "spark.sql.catalog.sparkcatalog=org.apache.spark.sql.hudi.catalog.HoodieCatalog" \
--conf "spark.sql.extensions=org.apache.spark.sql.hudi.HoodieSparkSessionExtension"
Programmatic Setup in Python
For production scripts and notebooks, configure the Spark session programmatically:
from pyspark.sql import SparkSession
spark = SparkSession.builder \
.appName("HudiTutorial") \
.config("spark.jars.packages", "org.apache.hudi:hudi-spark3.4-bundle2.12:0.14.1") \
.config("spark.serializer", "org.apache.spark.serializer.KryoSerializer") \
.config("spark.sql.catalog.sparkcatalog",
"org.apache.spark.sql.hudi.catalog.HoodieCatalog") \
.config("spark.sql.extensions",
"org.apache.spark.sql.hudi.HoodieSparkSessionExtension") \
.config("spark.sql.warehouse.dir", "/tmp/hudi-warehouse") \
.master("local[]") \
.getOrCreate()
spark.sparkContext.setLogLevel("WARN")
print(f"Spark version: {spark.version}")
print("Hudi is ready to use.")
Verifying the Installation
Run a quick check to confirm everything is working:
# Create a simple DataFrame
data = [("1", "Alice", 30), ("2", "Bob", 25)]
columns = ["id", "name", "age"]
df = spark.createDataFrame(data, columns)
Write as a Hudi table
hudioptions = {
"hoodie.table.name": "testtable",
"hoodie.datasource.write.recordkey.field": "id",
"hoodie.datasource.write.precombine.field": "age",
"hoodie.datasource.write.operation": "upsert",
}
df.write.format("hudi") \
.options(hudioptions) \
.mode("overwrite") \
.save("/tmp/hudi-warehouse/testtable")
Read it back
spark.read.format("hudi").load("/tmp/hudi-warehouse/testtable").show()
If you see the two records printed without errors, your Hudi environment is correctly configured.
3. Core Concepts
Table Types: Copy on Write vs. Merge on Read
Hudi supports two storage table types, each optimized for different workload patterns.
Copy on Write (CoW)
In a CoW table, every write operation creates a new version of the affected Parquet files. When you update a record, Hudi rewrites the entire file that contains that record with the updated data merged in.
Characteristics:
- Write amplification is higher because files are rewritten on every update
- Read performance is excellent because readers always see clean, compacted Parquet files
- No separate compaction step is needed
- Best suited for read-heavy workloads where data is updated infrequently
# CoW table configuration
cowoptions = {
"hoodie.table.name": "orderscow",
"hoodie.datasource.write.table.type": "COPYONWRITE",
"hoodie.datasource.write.recordkey.field": "orderid",
"hoodie.datasource.write.precombine.field": "updatedat",
"hoodie.datasource.write.partitionpath.field": "orderdate",
}
Merge on Read (MoR)
In a MoR table, updates are first written to row-based delta log files (Avro format). These logs are periodically merged with the base Parquet files during a compaction process.
Characteristics:
- Write performance is significantly better because updates go to small log files
- Readers can choose between reading the latest compacted snapshot (faster) or the real-time view (includes uncompacted updates)
- Requires a compaction strategy to periodically merge logs into base files
- Best suited for write-heavy workloads or streaming ingestion scenarios
# MoR table configuration
moroptions = {
"hoodie.table.name": "eventsmor",
"hoodie.datasource.write.table.type": "MERGEONREAD",
"hoodie.datasource.write.recordkey.field": "eventid",
"hoodie.datasource.write.precombine.field": "eventtimestamp",
"hoodie.datasource.write.partitionpath.field": "eventdate",
"hoodie.compact.inline": "true",
"hoodie.compact.inline.max.delta.commits": "5",
}
Timeline
The Hudi timeline is a log of all operations performed on a table. Each action on the timeline records when the operation started, its status (requested, inflight, or completed), and metadata about what changed. This timeline is the foundation for Hudi's time travel and incremental query capabilities.
Record Key and Precombine Field
Every Hudi table requires two critical field configurations:
- Record Key: The unique identifier for each record, similar to a primary key in a relational database.
- Precombine Field: When two records have the same record key, Hudi uses this field to determine which record to keep. The record with the higher precombine value wins.
4. Basic Usage: Creating Hudi Tables
Creating a CoW Table with Sample Data
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, DoubleType
from datetime import datetime
Define schema
schema = StructType([
StructField("orderid", StringType(), False),
StructField("customername", StringType(), True),
StructField("product", StringType(), True),
StructField("quantity", IntegerType(), True),
StructField("price", DoubleType(), True),
StructField("orderdate", StringType(), True),
StructField("updatedat", StringType(), True),
])
Sample data
orders = [
("ORD001", "Alice Johnson", "Laptop", 1, 1299.99, "2026-01-15", "2026-01-15T10:00:00"),
("ORD002", "Bob Smith", "Keyboard", 2, 79.99, "2026-01-15", "2026-01-15T11:30:00"),
("ORD003", "Carol White", "Monitor", 1, 449.99, "2026-01-16", "2026-01-16T09:15:00"),
("ORD004", "David Brown", "Mouse", 3, 29.99, "2026-01-16", "2026-01-16T14:20:00"),
("ORD005", "Eva Green", "Headphones", 1, 199.99, "2026-01-17", "2026-01-17T08:45:00"),
]
dforders = spark.createDataFrame(orders, schema)
Hudi write options
tablename = "orders"
basepath = "/tmp/hudi-warehouse/orders"
hudioptions = {
"hoodie.table.name": tablename,
"hoodie.datasource.write.recordkey.field": "orderid",
"hoodie.datasource.write.precombine.field": "updatedat",
"hoodie.datasource.write.partitionpath.field": "orderdate",
"hoodie.datasource.write.table.type": "COPYONWRITE",
"hoodie.datasource.write.operation": "insert",
}
Write the initial dataset
dforders.write.format("hudi") \
.options(hudioptions) \
.mode("overwrite") \
.save(basepath)
print("Hudi table created successfully.")
spark.read.format("hudi").load(basepath).show(truncate=False)
Creating a Non-Partitioned Table
For smaller datasets or when partition pruning is not needed:
hudioptionsnopartition = {
"hoodie.table.name": "products",
"hoodie.datasource.write.recordkey.field": "productid",
"hoodie.datasource.write.precombine.field": "lastmodified",
"hoodie.datasource.write.partitionpath.field": "",
"hoodie.datasource.write.keygenerator.class":
"org.apache.hudi.keygen.NonpartitionedKeyGenerator",
}
5. CRUD Operations
Insert
Insert new records into an existing Hudi table:
neworders = [
("ORD006", "Frank Miller", "Webcam", 1, 89.99, "2026-01-18", "2026-01-18T10:00:00"),
("ORD007", "Grace Lee", "USB Hub", 2, 34.99, "2026-01-18", "2026-01-18T11:00:00"),
]
df
new = spark.createDataFrame(neworders, schema)
insert
options = {
"hoodie.table.name": tablename,
"hoodie.datasource.write.recordkey.field": "orderid",
"hoodie.datasource.write.precombine.field": "updatedat",
"hoodie.datasource.write.partitionpath.field": "orderdate",
"hoodie.datasource.write.operation": "insert",
}
dfnew.write.format("hudi") \
.options(insertoptions) \
.mode("append") \
.save(basepath)
print("New records inserted.")
print(f"Total records: {spark.read.format('hudi').load(basepath).count()}")
Update
Update existing records by writing records with matching record keys:
# Update Alice's order: change quantity and price
updatedorders = [
("ORD001", "Alice Johnson", "Laptop Pro", 1, 1599.99,
"2026-01-15", "2026-01-19T09:00:00"),
]
dfupdate = spark.createDataFrame(updatedorders, schema)
updateoptions = {
"hoodie.table.name": tablename,
"hoodie.datasource.write.recordkey.field": "orderid",
"hoodie.datasource.write.precombine.field": "updatedat",
"hoodie.datasource.write.partitionpath.field": "orderdate",
"hoodie.datasource.write.operation": "upsert",
}
dfupdate.write.format("hudi") \
.options(updateoptions) \
.mode("append") \
.save(basepath)
Verify the update
spark.read.format("hudi").load(basepath) \
.filter("orderid = 'ORD001'") \
.show(truncate=False)
Upsert
Upsert combines insert and update in a single operation. Records with existing keys are updated; new keys are inserted.
# Mix of new and existing records
upsertdata = [
# Update existing order (ORD002)
("ORD002", "Bob Smith", "Mechanical Keyboard", 2, 129.99,
"2026-01-15", "2026-01-20T10:00:00"),
# New order
("ORD008", "Hannah Park", "Tablet", 1, 599.99,
"2026-01-20", "2026-01-20T14:00:00"),
]
dfupsert = spark.createDataFrame(upsertdata, schema)
upsertoptions = {
"hoodie.table.name": tablename,
"hoodie.datasource.write.recordkey.field": "orderid",
"hoodie.datasource.write.precombine.field": "updatedat",
"hoodie.datasource.write.partitionpath.field": "orderdate",
"hoodie.datasource.write.operation": "upsert",
}
dfupsert.write.format("hudi") \
.options(upsertoptions) \
.mode("append") \
.save(basepath)
print("Upsert completed.")
spark.read.format("hudi").load(basepath).orderBy("orderid").show(truncate=False)
Delete
Hudi supports both soft deletes and hard deletes:
# Hard delete: remove records permanently
deletedata = [("ORD004", "", "", 0, 0.0, "2026-01-16", "2026-01-21T00:00:00")]
dfdelete = spark.createDataFrame(deletedata, schema)
deleteoptions = {
"hoodie.table.name": tablename,
"hoodie.datasource.write.recordkey.field": "orderid",
"hoodie.datasource.write.precombine.field": "updatedat",
"hoodie.datasource.write.partitionpath.field": "orderdate",
"hoodie.datasource.write.operation": "delete",
}
dfdelete.write.format("hudi") \
.options(deleteoptions) \
.mode("append") \
.save(basepath)
Verify deletion
remaining = spark.read.format("hudi").load(basepath)
print(f"Records after delete: {remaining.count()}")
remaining.orderBy("orderid").show(truncate=False)
Soft Delete
With soft deletes, the record remains but all non-key fields are set to null:
softdeleteoptions = {
"hoodie.table.name": table
name,
"hoodie.datasource.write.recordkey.field": "orderid",
"hoodie.datasource.write.precombine.field": "updatedat",
"hoodie.datasource.write.partitionpath.field": "orderdate",
"hoodie.datasource.write.operation": "upsert",
"hoodie.datasource.write.payload.class":
"org.apache.hudi.common.model.EmptyHoodieRecordPayload",
}
6. Advanced Usage
Time Travel Queries
Hudi maintains a timeline of all commits, allowing you to query data as it existed at any point in time.
# List all commits on the timeline
import os
timelinepath = os.path.join(basepath, ".hoodie")
commits = spark.read.format("hudi").load(basepath) \
.select("hoodiecommittime").distinct() \
.orderBy("hoodiecommittime") \
.collect()
print("Available commits:")
for c in commits:
print(f" {c.hoodiecommittime}")
Query data as of a specific commit timestamp
Replace with an actual commit timestamp from the list above
firstcommit = commits[0].hoodiecommittime
dfhistorical = spark.read.format("hudi") \
.option("as.of.instant", firstcommit) \
.load(basepath)
print(f"\nData as of commit {firstcommit}:")
dfhistorical.show(truncate=False)
You can also use a human-readable timestamp:
# Query data as it existed at a specific date/time
dfpointintime = spark.read.format("hudi") \
.option("as.of.instant", "2026-01-18T12:00:00.000") \
.load(basepath)
dfpointintime.show(truncate=False)
Incremental Queries
Incremental queries allow you to fetch only the records that changed between two commits. This is essential for building efficient ETL pipelines.
# Get changes since a specific commit
begintime = commits[0].hoodiecommittime # start commit (exclusive)
dfincremental = spark.read.format("hudi") \
.option("hoodie.datasource.query.type", "incremental") \
.option("hoodie.datasource.read.begin.instanttime", begintime) \
.load(basepath)
print(f"Records changed since {begintime}:")
dfincremental.select(
"orderid", "customername", "product", "price",
"hoodiecommittime", "hoodieisdeleted"
).show(truncate=False)
To get changes within a specific time window:
# Changes between two commits
begintime = commits[0].hoodiecommittime
endtime = commits[-1].hoodiecommittime
dfwindow = spark.read.format("hudi") \
.option("hoodie.datasource.query.type", "incremental") \
.option("hoodie.datasource.read.begin.instanttime", begintime) \
.option("hoodie.datasource.read.end.instanttime", endtime) \
.load(basepath)
print(f"Changes between {begintime} and {endtime}:")
dfwindow.show(truncate=False)
Change Data Capture (CDC)
Hudi 0.14+ provides native CDC support that captures before and after images of changed records:
# Enable CDC on table creation
cdcoptions = {
"hoodie.table.name": "orderscdc",
"hoodie.datasource.write.recordkey.field": "orderid",
"hoodie.datasource.write.precombine.field": "updatedat",
"hoodie.datasource.write.partitionpath.field": "orderdate",
"hoodie.table.cdc.enabled": "true",
"hoodie.table.cdc.supplemental.logging.mode": "DATABEFOREAFTER",
}
Read CDC changes
dfcdc = spark.read.format("hudi") \
.option("hoodie.datasource.query.type", "incremental") \
.option("hoodie.datasource.query.incremental.format", "cdc") \
.option("hoodie.datasource.read.begin.instanttime", begintime) \
.load(basepath)
CDC provides op (operation type), tsms, before, and after columns
dfcdc.show(truncate=False)
Spark SQL Support
Hudi integrates with Spark SQL, allowing you to use standard SQL statements:
# Register the table in the catalog
spark.sql(f"""
CREATE TABLE IF NOT EXISTS hudiorders
USING hudi
LOCATION '{basepath}'
""")
Standard SQL queries
spark.sql("SELECT FROM hudiorders WHERE price > 100 ORDER BY price DESC").show()
SQL-based updates (requires Spark 3.1+)
spark.sql("""
UPDATE hudiorders
SET price = 149.99
WHERE orderid = 'ORD007'
""")
SQL-based deletes
spark.sql("""
DELETE FROM hudiorders
WHERE orderid = 'ORD005'
""")
Verify changes
spark.sql("SELECT FROM hudiorders ORDER BY orderid").show()
7. Integration with Other Systems
Apache Hive Integration
Hudi tables can be synced to the Hive Metastore, making them accessible to any Hive-compatible tool:
hivesyncoptions = {
"hoodie.datasource.hivesync.enable": "true",
"hoodie.datasource.hivesync.database": "default",
"hoodie.datasource.hivesync.table": "orders",
"hoodie.datasource.hivesync.mode": "hms",
"hoodie.datasource.hivesync.partitionfields": "orderdate",
"hoodie.datasource.hivesync.partitionextractorclass":
"org.apache.hudi.hive.MultiPartKeysValueExtractor",
}
Merge hivesyncoptions with your existing write options
alloptions = {hudioptions, hivesyncoptions}
dforders.write.format("hudi") \
.options(alloptions) \
.mode("overwrite") \
.save(basepath)
For MoR tables, Hive sync creates two views:
ordersro(read-optimized): queries only compacted Parquet filesordersrt(real-time): merges log files with Parquet at query time
Presto and Trino Integration
Presto and Trino can query Hudi tables registered in the Hive Metastore. Use the Hive connector:
-- In Trino/Presto (after Hive sync)
SELECT orderid, customername, product, price
FROM hive.default.orders
WHERE orderdate = '2026-01-15'
ORDER BY price DESC;
For Trino 411+, there is a native Hudi connector that provides better performance:
# catalog/hudi.properties
connector.name=hudi
hive.metastore.uri=thrift://metastore-host:9083
AWS Glue Integration
For cloud deployments, Hudi can sync with the AWS Glue Data Catalog:
gluesyncoptions = {
"hoodie.datasource.hivesync.enable": "true",
"hoodie.datasource.hivesync.mode": "glue",
"hoodie.datasource.hivesync.database": "mydatabase",
"hoodie.datasource.hivesync.table": "orders",
"hoodie.datasource.hivesync.region": "us-east-1",
}
This allows tools like Amazon Athena, Redshift Spectrum, and AWS EMR to query Hudi tables directly.
8. Best Practices
Choosing Between CoW and MoR
| Factor | Copy on Write | Merge on Read |
|--------|--------------|---------------|
| Read latency | Low | Medium (real-time view) |
| Write latency | High | Low |
| Storage overhead | Moderate | Higher (log files) |
| Compaction needed | No | Yes |
| Best for | Batch workloads, dashboards | Streaming ingestion, CDC |
Rule of thumb: Start with CoW unless you have a clear need for low-latency writes. Move to MoR when write performance becomes a bottleneck.
Indexing Strategy
Hudi supports multiple index types. Choosing the right one has a significant impact on upsert performance:
- Bloom Index (default): Uses bloom filters stored in Parquet footers. Works well for most batch workloads. No external dependencies.
- Simple Index: Joins incoming records against the entire dataset. Suitable for small tables but does not scale well.
- HBase Index: Stores the record key to file mapping in an HBase table. Best for very large datasets with global uniqueness requirements.
- Bucket Index: Hash-based partitioning that eliminates the need for index lookups. Excellent for very high-throughput streaming workloads.
# Configure bucket index for high-throughput workloads
bucketindexoptions = {
"hoodie.index.type": "BUCKET",
"hoodie.bucket.index.num.buckets": "8",
"hoodie.bucket.index.hash.field": "orderid",
}
Compaction Tuning for MoR Tables
For MoR tables, compaction is critical. Tune these parameters based on your workload:
compactionoptions = {
"hoodie.compact.inline": "true",
"hoodie.compact.inline.max.delta.commits": "5",
"hoodie.compaction.strategy":
"org.apache.hudi.table.action.compact.strategy.BoundedIOCompactionStrategy",
"hoodie.compaction.target.io": "512000", # 500 MB target per compaction
}
For production workloads, consider running compaction asynchronously using a separate Spark job rather than inline compaction, which blocks the writer.
Partition Strategy
- Use date-based partitions (e.g.,
yyyy/MM/dd) for time-series data - Keep the number of files per partition between 1 and 10 for optimal read performance
- Use
hoodie.clusteringto reorganize data within partitions for better query performance
File Sizing
Configure target file sizes to balance between parallelism and small-file overhead:
filesizingoptions = {
"hoodie.parquet.max.file.size": "125829120", # 120 MB
"hoodie.parquet.small.file.limit": "104857600", # 100 MB
"hoodie.copyonwrite.insert.split.size": "500000",
}
Schema Evolution
Hudi supports schema evolution, allowing you to add, rename, or delete columns without rewriting the entire dataset:
# Enable schema evolution
schemaoptions = {
"hoodie.datasource.write.reconcile.schema": "true",
"hoodie.schema.on.read.enable": "true",
}
When adding new columns, existing data files will return null for the new columns until they are rewritten during compaction or clustering.
Monitoring and Metrics
Enable metrics reporting to track the health of your Hudi tables:
metricsoptions = {
"hoodie.metrics.on": "true",
"hoodie.metrics.reporter.type": "CONSOLE",
# For production, use JMX, Graphite, Prometheus, or Datadog
# "hoodie.metrics.reporter.type": "PROMETHEUS",
}
Key metrics to monitor include commit duration, number of records written, file sizes, and compaction lag for MoR tables.
9. Conclusion
Apache Hudi transforms a simple data lake into a fully functional data lakehouse with ACID transactions, efficient upserts, and powerful incremental processing capabilities. Whether you are building a batch ETL pipeline that needs to handle late-arriving data, a streaming ingestion system that requires low-latency writes, or an analytics platform that needs point-in-time queries, Hudi provides the tools to get it done.
The key takeaways from this tutorial are:
Apache Hudi continues to evolve rapidly, with features like native Kafka Connect integration, improved metadata table indexing, and enhanced multi-table transaction support on the roadmap. By adopting Hudi today, you position your data platform to take advantage of these improvements as they become available.
For more information, consult the official Apache Hudi documentation at https://hudi.apache.org/docs/overview and the Hudi GitHub repository at https://github.com/apache/hudi.