πŸ“Š Data Engineering

Data Lake

Data Lake

A repository that stores raw data in its original form. Accepts both structured and unstructured data. S3-based.

Detailed Explanation

A Data Lake is a centralized repository that can store structured, semi-structured, and unstructured data in its raw form. Unlike a traditional data warehouse, which stores only structured data according to a predefined schema, a data lake adopts a Schema-on-Read approach, storing data first and applying the schema at the time of analysis. This flexibility makes it possible to quickly ingest and store large volumes of data generated from diverse sources.

A data lake architecture is generally designed as a three-tier structure of Bronze (Raw), Silver (Cleansed), and Gold (Curated). The Bronze layer stores raw data as it is, the Silver layer performs cleansing and transformation, and the Gold layer stores aggregated data that can be used immediately for business analytics. This layered approach is called the Medallion Architecture, and it enables data quality management and governance to be carried out systematically.

Object storage such as AWS S3, Azure Data Lake Storage (ADLS), and Google Cloud Storage (GCS) is used as the main implementation technology. These can store petabyte-scale data at low cost, and compute and storage can be separated so that each can be scaled independently. Columnar formats such as Parquet, ORC, and Avro are widely used as data formats, which can significantly improve analytical query performance.

For a data lake to operate successfully, a data catalog, metadata management, access control, and data quality monitoring are essential. Data can be discovered and managed through AWS Glue Data Catalog, Apache Hive Metastore, Unity Catalog, and others. A data lake operated without proper governance can become a "Data Swamp," so it is important to establish data quality and governance policies from the initial design stage.

Code Example

This is an example of implementing the Medallion Architecture on an AWS S3-based Data Lake and processing data with PySpark.

Python (PySpark - Data Lake Architecture)
# Data Lake Medallion Architecture κ΅¬ν˜„
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *
from delta import *  # Delta Lake μ‚¬μš© μ‹œ
import boto3

# Spark Session 생성 (S3 연동)
spark = SparkSession.builder \
    .appName("DataLakePipeline") \
    .config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") \
    .config("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog") \
    .config("spark.hadoop.fs.s3a.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem") \
    .config("spark.hadoop.fs.s3a.aws.credentials.provider",
            "com.amazonaws.auth.DefaultAWSCredentialsProviderChain") \
    .getOrCreate()

# Data Lake 경둜 μ •μ˜
DATA_LAKE_BUCKET = "s3a://company-data-lake"
BRONZE_PATH = f"{DATA_LAKE_BUCKET}/bronze"
SILVER_PATH = f"{DATA_LAKE_BUCKET}/silver"
GOLD_PATH = f"{DATA_LAKE_BUCKET}/gold"

# ============================================
# Bronze Layer: μ›μ‹œ 데이터 μˆ˜μ§‘
# ============================================
def ingest_to_bronze(source_path: str, table_name: str):
    """μ›μ‹œ 데이터λ₯Ό Bronze λ ˆμ΄μ–΄μ— 적재"""

    # λ‹€μ–‘ν•œ 포맷 지원
    if source_path.endswith('.json'):
        df = spark.read.json(source_path)
    elif source_path.endswith('.csv'):
        df = spark.read.option("header", "true").csv(source_path)
    elif source_path.endswith('.parquet'):
        df = spark.read.parquet(source_path)
    else:
        # 슀트리밍 데이터 (Kafka λ“±)
        df = spark.read.format("kafka") \
            .option("kafka.bootstrap.servers", "kafka:9092") \
            .option("subscribe", source_path) \
            .load()

    # 메타데이터 μΆ”κ°€
    df_with_metadata = df \
        .withColumn("_ingestion_timestamp", current_timestamp()) \
        .withColumn("_source_file", lit(source_path)) \
        .withColumn("_ingestion_date", current_date())

    # Bronze λ ˆμ΄μ–΄μ— μ €μž₯ (νŒŒν‹°μ…˜: λ‚ μ§œλ³„)
    bronze_table_path = f"{BRONZE_PATH}/{table_name}"
    df_with_metadata.write \
        .format("delta") \
        .mode("append") \
        .partitionBy("_ingestion_date") \
        .save(bronze_table_path)

    print(f"Ingested {df_with_metadata.count()} records to Bronze: {table_name}")
    return bronze_table_path

# ============================================
# Silver Layer: 데이터 μ •μ œ 및 λ³€ν™˜
# ============================================
def transform_to_silver(bronze_table: str, silver_table: str):
    """Bronze 데이터λ₯Ό μ •μ œν•˜μ—¬ Silver λ ˆμ΄μ–΄λ‘œ λ³€ν™˜"""

    bronze_path = f"{BRONZE_PATH}/{bronze_table}"
    silver_path = f"{SILVER_PATH}/{silver_table}"

    # Bronze 데이터 읽기
    df_bronze = spark.read.format("delta").load(bronze_path)

    # 데이터 μ •μ œ 및 λ³€ν™˜
    df_silver = df_bronze \
        .dropDuplicates(["id"]) \
        .filter(col("id").isNotNull()) \
        .withColumn("email", lower(trim(col("email")))) \
        .withColumn("phone", regexp_replace(col("phone"), "[^0-9]", "")) \
        .withColumn("created_at", to_timestamp(col("created_at"))) \
        .withColumn("_processed_timestamp", current_timestamp())

    # 데이터 ν’ˆμ§ˆ 검증
    quality_checks = {
        "null_check": df_silver.filter(col("id").isNull()).count() == 0,
        "email_format": df_silver.filter(~col("email").rlike("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}$")).count() == 0,
        "duplicate_check": df_silver.count() == df_silver.dropDuplicates(["id"]).count()
    }

    print("Data Quality Checks:", quality_checks)

    # Silver λ ˆμ΄μ–΄μ— Merge (Upsert)
    if DeltaTable.isDeltaTable(spark, silver_path):
        delta_table = DeltaTable.forPath(spark, silver_path)
        delta_table.alias("target").merge(
            df_silver.alias("source"),
            "target.id = source.id"
        ).whenMatchedUpdateAll() \
         .whenNotMatchedInsertAll() \
         .execute()
    else:
        df_silver.write.format("delta").mode("overwrite").save(silver_path)

    return silver_path

# ============================================
# Gold Layer: λΉ„μ¦ˆλ‹ˆμŠ€ 집계 데이터
# ============================================
def aggregate_to_gold(silver_tables: list, gold_table: str):
    """Silver 데이터λ₯Ό μ§‘κ³„ν•˜μ—¬ Gold λ ˆμ΄μ–΄ 생성"""

    # μ—¬λŸ¬ Silver ν…Œμ΄λΈ” 쑰인
    df_users = spark.read.format("delta").load(f"{SILVER_PATH}/users")
    df_orders = spark.read.format("delta").load(f"{SILVER_PATH}/orders")
    df_products = spark.read.format("delta").load(f"{SILVER_PATH}/products")

    # λΉ„μ¦ˆλ‹ˆμŠ€ λ©”νŠΈλ¦­ 집계
    df_gold = df_orders \
        .join(df_users, "user_id") \
        .join(df_products, "product_id") \
        .groupBy(
            date_trunc("month", col("order_date")).alias("month"),
            col("category"),
            col("region")
        ) \
        .agg(
            countDistinct("user_id").alias("unique_customers"),
            count("order_id").alias("total_orders"),
            sum("amount").alias("total_revenue"),
            avg("amount").alias("avg_order_value"),
            percentile_approx("amount", 0.5).alias("median_order_value")
        ) \
        .withColumn("_aggregation_timestamp", current_timestamp())

    # Gold λ ˆμ΄μ–΄μ— μ €μž₯
    gold_path = f"{GOLD_PATH}/{gold_table}"
    df_gold.write \
        .format("delta") \
        .mode("overwrite") \
        .partitionBy("month") \
        .save(gold_path)

    return gold_path

# ============================================
# 데이터 μΉ΄νƒˆλ‘œκ·Έ 등둝 (AWS Glue)
# ============================================
def register_to_glue_catalog(table_path: str, database: str, table_name: str):
    """Glue Data Catalog에 ν…Œμ΄λΈ” 등둝"""

    # Glue μΉ΄νƒˆλ‘œκ·Έμ— ν…Œμ΄λΈ” 생성
    spark.sql(f"""
        CREATE TABLE IF NOT EXISTS glue_catalog.{database}.{table_name}
        USING DELTA
        LOCATION '{table_path}'
    """)

    # ν…Œμ΄λΈ” 톡계 μˆ˜μ§‘
    spark.sql(f"ANALYZE TABLE glue_catalog.{database}.{table_name} COMPUTE STATISTICS")

    print(f"Registered table: {database}.{table_name}")

# ============================================
# 데이터 레이크 νŒŒμ΄ν”„λΌμΈ μ‹€ν–‰
# ============================================
if __name__ == "__main__":
    # Bronze: μ›μ‹œ 데이터 μˆ˜μ§‘
    ingest_to_bronze("s3a://raw-data/users/*.json", "users")
    ingest_to_bronze("s3a://raw-data/orders/*.csv", "orders")
    ingest_to_bronze("s3a://raw-data/products/*.parquet", "products")

    # Silver: 데이터 μ •μ œ
    transform_to_silver("users", "users")
    transform_to_silver("orders", "orders")
    transform_to_silver("products", "products")

    # Gold: λΉ„μ¦ˆλ‹ˆμŠ€ 집계
    aggregate_to_gold(
        ["users", "orders", "products"],
        "monthly_sales_summary"
    )

    # Glue Catalog 등둝
    register_to_glue_catalog(f"{GOLD_PATH}/monthly_sales_summary", "analytics", "monthly_sales")

    print("Data Lake Pipeline completed successfully!")

Conversation Examples Frequently Seen in Practice

Data Architect
"Our Data Lake is turning into a Data Swamp. Two years' worth of raw data has piled up in the Bronze layer, but there is no metadata, and we can't tell which data is where."
Data Engineer
"First, let's infer the schema with a Glue Crawler and register it in the Data Catalog. Then we need to properly apply the Medallion Architecture to clarify the responsibilities of each Bronze/Silver/Gold layer, and assign an owner and an SLA to each table."
Data Governance Officer
"We should consider adopting a data catalog such as Unity Catalog or Apache Atlas. We need data lineage tracking, access control, and quality monitoring. In particular, we also need to establish a PII data masking policy."
Interviewer
"Please explain the differences between a Data Lake and a Data Warehouse, and when we should choose a Data Lake."
Candidate
"A Data Warehouse uses a Schema-on-Write approach and stores only structured data that conforms to a predefined schema. A Data Lake, on the other hand, uses a Schema-on-Read approach, storing raw data as it is and applying the schema at the time of analysis. A Data Lake is suitable when you need to quickly ingest large volumes of data from diverse sources, or when you are retaining data whose future use is not yet clear. It is also advantageous for processing unstructured data such as ML/AI training data, IoT sensor data, and log data."
Interviewer
"What strategies can prevent a Data Lake from turning into a Data Swamp?"
Candidate
"First, apply the Medallion Architecture to manage data quality step by step through the Bronze/Silver/Gold layers. Second, manage the metadata, schema, and owner of every dataset through a Data Catalog. Third, build data quality checks into the pipeline so that problematic data does not propagate to the next layer. Fourth, establish a data retention policy to periodically archive or delete unnecessary data."

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

Senior Engineer
"I see you're loading data into the Bronze layer without date partitions. This means the entire dataset has to be scanned, which seriously degrades query performance."
Junior Engineer
"I'll add ingestion_date as the partition key. Would it be fine to organize it with Hive-style partitions (year=2024/month=01/day=15)?"
Senior Engineer
"Yes, and please also consider the small files problem. Streaming ingestion produces many small files, so you need to periodically merge files using Spark's coalesce or Delta Lake's OPTIMIZE command. Around 128MB to 1GB per file is appropriate."

Cautions

Related Terms

Learn More