๐Ÿ“Š Data Engineering

Data Lakehouse

Data Lakehouse

An architecture that combines a data lake and a warehouse. A unified data platform supporting ACID transactions and schema management.

Detailed Explanation

Data Lakehouse is a next-generation data architecture that combines the flexibility and scalability of a Data Lake with the data management capabilities and performance of a Data Warehouse. Traditionally, a two-tier architecture was common, in which raw data was stored in a Data Lake and data for analytics was separately ETLed into a Data Warehouse. A Lakehouse eliminates this redundant storage and complex data movement, and allows all data workloads to be handled on a single platform.

The core technologies of a Lakehouse are the open table formats Delta Lake, Apache Iceberg, and Apache Hudi. On top of object storage (S3, ADLS, GCS), they provide warehouse-level features such as ACID transactions, schema evolution, time travel, and concurrency control. This makes reliable data management possible while retaining the cost efficiency of file-based storage. In particular, a metadata layer makes it possible to manage Parquet files like tables.

A Lakehouse architecture can perform BI analytics, real-time streaming, and machine learning on a single copy of data, which ensures data consistency. In the past, data scientists worked with raw data in the Lake while analysts worked with refined data in the Warehouse, and this frequently caused the same metric to be calculated differently. A Lakehouse realizes a Single Source of Truth and thereby resolves this data silo problem.

Major Lakehouse platforms include Databricks (based on Delta Lake), Snowflake (with Iceberg support), AWS Lake Formation, and Google BigLake. They provide SQL query engines (Spark SQL, Trino, Presto), streaming processing (Structured Streaming), and ML workloads (MLflow, Feature Store) in an integrated manner. Recently, data governance and access control are also being strengthened through unified catalogs such as Unity Catalog and Nessie.

Code Example

An example that uses ACID transactions, schema evolution, and time travel in a Delta Lake-based Data Lakehouse.

Python (PySpark + Delta Lake - Lakehouse Architecture)
# Data Lakehouse ๊ตฌํ˜„ (Delta Lake ๊ธฐ๋ฐ˜)
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *
from delta import *
from delta.tables import DeltaTable

# Spark Session with Delta Lake
spark = SparkSession.builder \
    .appName("DataLakehouse") \
    .config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") \
    .config("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog") \
    .config("spark.databricks.delta.retentionDurationCheck.enabled", "false") \
    .getOrCreate()

LAKEHOUSE_PATH = "s3a://company-lakehouse"

# ============================================
# 1. Delta Table ์ƒ์„ฑ (ACID ํŠธ๋žœ์žญ์…˜ ์ง€์›)
# ============================================
def create_delta_table():
    """ํŒŒํ‹ฐ์…˜๊ณผ Z-Order ์ตœ์ ํ™”๊ฐ€ ์ ์šฉ๋œ Delta ํ…Œ์ด๋ธ” ์ƒ์„ฑ"""

    # ์Šคํ‚ค๋งˆ ์ •์˜
    schema = StructType([
        StructField("order_id", StringType(), False),
        StructField("customer_id", StringType(), False),
        StructField("product_id", StringType(), False),
        StructField("quantity", IntegerType(), True),
        StructField("amount", DecimalType(10, 2), True),
        StructField("order_date", DateType(), False),
        StructField("status", StringType(), True),
        StructField("region", StringType(), True)
    ])

    # Delta ํ…Œ์ด๋ธ” ์ƒ์„ฑ (SQL)
    spark.sql(f"""
        CREATE TABLE IF NOT EXISTS lakehouse.orders (
            order_id STRING NOT NULL,
            customer_id STRING NOT NULL,
            product_id STRING NOT NULL,
            quantity INT,
            amount DECIMAL(10, 2),
            order_date DATE NOT NULL,
            status STRING,
            region STRING
        )
        USING DELTA
        PARTITIONED BY (order_date)
        LOCATION '{LAKEHOUSE_PATH}/orders'
        TBLPROPERTIES (
            'delta.autoOptimize.optimizeWrite' = 'true',
            'delta.autoOptimize.autoCompact' = 'true',
            'delta.dataSkippingNumIndexedCols' = '8'
        )
    """)

    print("Delta table created with auto-optimization")

# ============================================
# 2. MERGE (Upsert) ์ž‘์—… - CDC ์ฒ˜๋ฆฌ
# ============================================
def merge_cdc_data(cdc_df):
    """Change Data Capture๋ฅผ Delta ํ…Œ์ด๋ธ”์— ๋จธ์ง€"""

    delta_table = DeltaTable.forPath(spark, f"{LAKEHOUSE_PATH}/orders")

    # MERGE INTO - Insert, Update, Delete ํ•œ ๋ฒˆ์— ์ฒ˜๋ฆฌ
    delta_table.alias("target").merge(
        cdc_df.alias("source"),
        "target.order_id = source.order_id"
    ).whenMatchedUpdate(
        condition="source.operation = 'UPDATE'",
        set={
            "quantity": "source.quantity",
            "amount": "source.amount",
            "status": "source.status",
            "region": "source.region"
        }
    ).whenMatchedDelete(
        condition="source.operation = 'DELETE'"
    ).whenNotMatchedInsert(
        condition="source.operation = 'INSERT'",
        values={
            "order_id": "source.order_id",
            "customer_id": "source.customer_id",
            "product_id": "source.product_id",
            "quantity": "source.quantity",
            "amount": "source.amount",
            "order_date": "source.order_date",
            "status": "source.status",
            "region": "source.region"
        }
    ).execute()

    print(f"Merged {cdc_df.count()} CDC records")

# ============================================
# 3. ์Šคํ‚ค๋งˆ ์ง„ํ™” (Schema Evolution)
# ============================================
def evolve_schema():
    """๋ฌด์ค‘๋‹จ ์Šคํ‚ค๋งˆ ๋ณ€๊ฒฝ"""

    # ์ƒˆ ์ปฌ๋Ÿผ ์ถ”๊ฐ€ (์ž๋™ ์Šคํ‚ค๋งˆ ๋จธ์ง€)
    spark.sql(f"""
        ALTER TABLE delta.`{LAKEHOUSE_PATH}/orders`
        ADD COLUMNS (
            discount_rate DECIMAL(5, 2) COMMENT 'ํ• ์ธ์œจ',
            loyalty_points INT COMMENT '์ ๋ฆฝ ํฌ์ธํŠธ'
        )
    """)

    # ์ปฌ๋Ÿผ ํƒ€์ž… ๋ณ€๊ฒฝ (์•ˆ์ „ํ•œ ํ™•์žฅ๋งŒ ๊ฐ€๋Šฅ)
    spark.sql(f"""
        ALTER TABLE delta.`{LAKEHOUSE_PATH}/orders`
        ALTER COLUMN amount TYPE DECIMAL(15, 2)
    """)

    # ์ž๋™ ์Šคํ‚ค๋งˆ ๋จธ์ง€๋กœ ๋ฐ์ดํ„ฐ ์“ฐ๊ธฐ
    new_data_with_extra_column = spark.createDataFrame([
        ("ORD-999", "CUST-1", "PROD-1", 2, 150.00, "2024-01-15", "completed", "์„œ์šธ", 0.1, 150)
    ], ["order_id", "customer_id", "product_id", "quantity", "amount",
        "order_date", "status", "region", "discount_rate", "loyalty_points"])

    new_data_with_extra_column.write \
        .format("delta") \
        .mode("append") \
        .option("mergeSchema", "true") \
        .save(f"{LAKEHOUSE_PATH}/orders")

    print("Schema evolved successfully")

# ============================================
# 4. Time Travel - ๊ณผ๊ฑฐ ๋ฐ์ดํ„ฐ ์กฐํšŒ
# ============================================
def time_travel_queries():
    """Delta Lake ํƒ€์ž„ ํŠธ๋ž˜๋ธ” ๊ธฐ๋Šฅ ํ™œ์šฉ"""

    # ํŠน์ • ๋ฒ„์ „์˜ ๋ฐ์ดํ„ฐ ์กฐํšŒ
    df_version_5 = spark.read \
        .format("delta") \
        .option("versionAsOf", 5) \
        .load(f"{LAKEHOUSE_PATH}/orders")

    print(f"Version 5 record count: {df_version_5.count()}")

    # ํŠน์ • ์‹œ์ ์˜ ๋ฐ์ดํ„ฐ ์กฐํšŒ
    df_yesterday = spark.read \
        .format("delta") \
        .option("timestampAsOf", "2024-01-14 00:00:00") \
        .load(f"{LAKEHOUSE_PATH}/orders")

    # ๋ฒ„์ „ ๊ฐ„ ๋ณ€๊ฒฝ ์‚ฌํ•ญ ํ™•์ธ
    changes = spark.sql(f"""
        SELECT * FROM delta.`{LAKEHOUSE_PATH}/orders`
        VERSION AS OF 10
        EXCEPT
        SELECT * FROM delta.`{LAKEHOUSE_PATH}/orders`
        VERSION AS OF 9
    """)

    print(f"Changes between v9 and v10: {changes.count()} rows")

    # ํ…Œ์ด๋ธ” ํžˆ์Šคํ† ๋ฆฌ ์กฐํšŒ
    history = spark.sql(f"DESCRIBE HISTORY delta.`{LAKEHOUSE_PATH}/orders`")
    history.select("version", "timestamp", "operation", "operationMetrics").show(10)

    # ์ž˜๋ชป๋œ ๋ณ€๊ฒฝ ๋กค๋ฐฑ
    spark.sql(f"""
        RESTORE TABLE delta.`{LAKEHOUSE_PATH}/orders`
        TO VERSION AS OF 8
    """)
    print("Table restored to version 8")

# ============================================
# 5. ์„ฑ๋Šฅ ์ตœ์ ํ™” (Z-Order, OPTIMIZE)
# ============================================
def optimize_table():
    """์ฟผ๋ฆฌ ์„ฑ๋Šฅ ์ตœ์ ํ™”"""

    # ํŒŒ์ผ ๋ณ‘ํ•ฉ ๋ฐ ์ตœ์ ํ™”
    spark.sql(f"""
        OPTIMIZE delta.`{LAKEHOUSE_PATH}/orders`
        WHERE order_date >= '2024-01-01'
    """)

    # Z-Order ํด๋Ÿฌ์Šคํ„ฐ๋ง (์ž์ฃผ ํ•„ํ„ฐ๋ง๋˜๋Š” ์ปฌ๋Ÿผ)
    spark.sql(f"""
        OPTIMIZE delta.`{LAKEHOUSE_PATH}/orders`
        ZORDER BY (customer_id, product_id)
    """)

    # ๋ถˆํ•„์š”ํ•œ ํŒŒ์ผ ์ •๋ฆฌ (Vacuum)
    spark.sql(f"""
        VACUUM delta.`{LAKEHOUSE_PATH}/orders`
        RETAIN 168 HOURS  -- 7์ผ ๋ณด์กด
    """)

    # ํ…Œ์ด๋ธ” ํ†ต๊ณ„ ์ˆ˜์ง‘
    spark.sql(f"ANALYZE TABLE delta.`{LAKEHOUSE_PATH}/orders` COMPUTE STATISTICS")

    print("Table optimized with Z-Order clustering")

# ============================================
# 6. ์ŠคํŠธ๋ฆฌ๋ฐ + ๋ฐฐ์น˜ ํ†ตํ•ฉ (Unified Processing)
# ============================================
def unified_streaming_batch():
    """๋™์ผ ํ…Œ์ด๋ธ”์—์„œ ์ŠคํŠธ๋ฆฌ๋ฐ๊ณผ ๋ฐฐ์น˜ ๋™์‹œ ์ฒ˜๋ฆฌ"""

    # ์ŠคํŠธ๋ฆฌ๋ฐ ์“ฐ๊ธฐ (Kafka -> Delta)
    kafka_stream = spark.readStream \
        .format("kafka") \
        .option("kafka.bootstrap.servers", "kafka:9092") \
        .option("subscribe", "orders") \
        .load()

    orders_stream = kafka_stream \
        .select(from_json(col("value").cast("string"), order_schema).alias("data")) \
        .select("data.*")

    # Delta ํ…Œ์ด๋ธ”๋กœ ์ŠคํŠธ๋ฆฌ๋ฐ (ACID ๋ณด์žฅ)
    query = orders_stream.writeStream \
        .format("delta") \
        .outputMode("append") \
        .option("checkpointLocation", f"{LAKEHOUSE_PATH}/checkpoints/orders") \
        .trigger(processingTime="1 minute") \
        .start(f"{LAKEHOUSE_PATH}/orders")

    # ๋™์‹œ์— ๋ฐฐ์น˜ ์ฝ๊ธฐ ๊ฐ€๋Šฅ (์ŠคํŠธ๋ฆฌ๋ฐ๊ณผ ์ถฉ๋Œ ์—†์Œ)
    batch_df = spark.read.format("delta").load(f"{LAKEHOUSE_PATH}/orders")
    daily_summary = batch_df \
        .filter(col("order_date") == current_date()) \
        .groupBy("region") \
        .agg(
            count("order_id").alias("orders"),
            sum("amount").alias("revenue")
        )

    print("Streaming and batch processing running concurrently")
    return query

# ============================================
# 7. Unity Catalog ํ†ตํ•ฉ (๊ฑฐ๋ฒ„๋„Œ์Šค)
# ============================================
def setup_governance():
    """Unity Catalog๋กœ ๋ฐ์ดํ„ฐ ๊ฑฐ๋ฒ„๋„Œ์Šค ์„ค์ •"""

    # ์นดํƒˆ๋กœ๊ทธ ๋ฐ ์Šคํ‚ค๋งˆ ์ƒ์„ฑ
    spark.sql("CREATE CATALOG IF NOT EXISTS main")
    spark.sql("CREATE SCHEMA IF NOT EXISTS main.sales")

    # ๊ด€๋ฆฌ ํ…Œ์ด๋ธ” ์ƒ์„ฑ
    spark.sql("""
        CREATE TABLE IF NOT EXISTS main.sales.orders
        USING DELTA
        AS SELECT * FROM delta.`s3a://company-lakehouse/orders`
    """)

    # ์—ด ์ˆ˜์ค€ ๋ณด์•ˆ (Column Masking)
    spark.sql("""
        ALTER TABLE main.sales.orders
        ALTER COLUMN customer_id SET MASK mask_customer_id
    """)

    # ํ–‰ ์ˆ˜์ค€ ๋ณด์•ˆ (Row-Level Security)
    spark.sql("""
        ALTER TABLE main.sales.orders
        SET ROW FILTER region_filter ON (region)
    """)

    # ์ ‘๊ทผ ๊ถŒํ•œ ์„ค์ •
    spark.sql("GRANT SELECT ON TABLE main.sales.orders TO `analysts`")
    spark.sql("GRANT ALL PRIVILEGES ON TABLE main.sales.orders TO `data_engineers`")

    print("Governance policies applied via Unity Catalog")

# ============================================
# Lakehouse ํŒŒ์ดํ”„๋ผ์ธ ์‹คํ–‰
# ============================================
if __name__ == "__main__":
    create_delta_table()
    evolve_schema()
    optimize_table()
    time_travel_queries()
    setup_governance()

    print("Data Lakehouse setup completed!")

Conversation examples that frequently appear in practice

CTO
"The operating cost of our current pipeline that ETLs from the Data Lake to Redshift is too high. Redundant data storage is also a problem. What benefits would we get from switching to a Lakehouse?"
Data Architect
"If we switch to a Lakehouse, we can analyze data stored in S3 directly with SQL, which can significantly reduce Redshift costs. By applying Delta Lake or Iceberg, data quality can also be managed at a warehouse level through ACID transactions, schema evolution, and time travel. Switching from ETL to ELT also simplifies the pipeline."
Data Scientist
"From the ML team's perspective, if the Feature Store and training data are on the same platform as the analytics data, the data consistency problem is resolved. Currently, the Lake and Warehouse data differ, so it was hard to validate model performance."
Interviewer
"Please explain why a Data Lakehouse can replace the existing 2-tier architecture (Lake + Warehouse)."
Candidate
"In the existing architecture, a Data Lake has the advantages of inexpensive storage and support for diverse data formats, but it has no transaction support and schema management is difficult. A Warehouse has excellent ACID and SQL performance, but its cost is high and its handling of unstructured data is limited. A Lakehouse supports transactions, schema evolution, and time travel on top of object storage through open table formats such as Delta Lake and Iceberg, capturing the advantages of both."
Interviewer
"Are there criteria for choosing among Delta Lake, Iceberg, and Hudi?"
Candidate
"Delta Lake is optimized within the Databricks ecosystem, and its integration with Spark is the strongest. Iceberg is vendor-neutral and has excellent support for various engines such as Trino, Flink, and Snowflake. Its partition evolution and Hidden Partitioning are particularly strong points. Hudi was created at Uber and is strong in Incremental Processing and streaming ingestion. You should choose by considering compatibility with your existing stack and your team's technical capabilities."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

Senior Engineer
"We append to the Delta table every hour, and the number of small files has grown enormously. Query performance is degrading sharply."
Junior Engineer
"Auto-optimization wasn't configured. I'll enable delta.autoOptimize.optimizeWrite and autoCompact, and also schedule a daily OPTIMIZE job."
Senior Engineer
"Good. Also, since we frequently filter by customer_id, apply Z-Order clustering as well. You should also run VACUUM periodically to clean up old version files so that storage costs are managed. However, before running VACUUM, check the period for which time travel is needed and set the retention period."

Cautions

Related Terms

Learn More