๐Ÿ“Š Data Engineering

Spark

Apache Spark

A distributed computing framework for large-scale data processing. Faster than Hadoop thanks to in-memory processing.

Detailed Explanation

Apache Spark is a distributed computing framework developed at UC Berkeley's AMPLab in 2009 that became an Apache top-level project in 2014. With in-memory processing, it is 100 times faster than Hadoop MapReduce, and it provides batch and streaming processing through a unified API.

Its core abstraction is the RDD (Resilient Distributed Dataset), but the DataFrame and Dataset APIs are mainly used today. A DataFrame handles columnar data like SQL, and maximizes performance with Catalyst query optimization and the Tungsten execution engine.

It provides a unified stack consisting of Spark SQL (SQL queries), Spark Streaming (micro-batch streaming), MLlib (machine learning), and GraphX (graph processing). PySpark lets you use Spark from Python, and pandas API on Spark (formerly Koalas) lets you run Pandas code on Spark.

Databricks provides a commercial Spark service, and Spark is used as a managed service on AWS EMR, Google Dataproc, and Azure HDInsight. It is used as the de facto standard for petabyte-scale data processing, ETL pipelines, and ML feature engineering.

Code Example

from pyspark.sql import SparkSession
from pyspark.sql.functions import col, sum, avg, count, when, lit
from pyspark.sql.window import Window

# SparkSession ์ƒ์„ฑ
spark = SparkSession.builder \
    .appName("DataEngineering") \
    .config("spark.sql.adaptive.enabled", "true") \
    .config("spark.sql.shuffle.partitions", "200") \
    .getOrCreate()

# ๋ฐ์ดํ„ฐ ์ฝ๊ธฐ
df = spark.read.parquet("s3://bucket/sales/*.parquet")
# df = spark.read.csv("data.csv", header=True, inferSchema=True)
# df = spark.read.json("data.json")

# ์Šคํ‚ค๋งˆ ํ™•์ธ
df.printSchema()
df.show(5)

# DataFrame ๋ณ€ํ™˜
transformed = df \
    .filter(col("sale_date") >= "2024-01-01") \
    .withColumn("tax", col("amount") * 0.1) \
    .withColumn("total", col("amount") + col("tax")) \
    .withColumn("category_type",
        when(col("amount") > 1000, "high")
        .when(col("amount") > 100, "medium")
        .otherwise("low")
    )

# ๊ทธ๋ฃนํ™” ๋ฐ ์ง‘๊ณ„
summary = transformed \
    .groupBy("region", "category_type") \
    .agg(
        sum("amount").alias("total_sales"),
        avg("amount").alias("avg_sales"),
        count("*").alias("num_transactions")
    ) \
    .orderBy(col("total_sales").desc())

summary.show()

# ์œˆ๋„์šฐ ํ•จ์ˆ˜
window_spec = Window.partitionBy("region").orderBy(col("sale_date"))
df_with_running = df.withColumn(
    "running_total",
    sum("amount").over(window_spec)
).withColumn(
    "rank_in_region",
    row_number().over(window_spec)
)

# SQL ์ฟผ๋ฆฌ ์‚ฌ์šฉ
df.createOrReplaceTempView("sales")
result = spark.sql("""
    SELECT
        region,
        DATE_TRUNC('month', sale_date) AS month,
        SUM(amount) AS monthly_sales
    FROM sales
    WHERE sale_date >= '2024-01-01'
    GROUP BY region, DATE_TRUNC('month', sale_date)
    ORDER BY month, monthly_sales DESC
""")

# Join
customers = spark.read.parquet("s3://bucket/customers/")
joined = df.join(customers, df.customer_id == customers.id, "left")

# ๋ฐ์ดํ„ฐ ์ €์žฅ
summary.write \
    .mode("overwrite") \
    .partitionBy("region") \
    .parquet("s3://bucket/output/summary/")

# Delta Lake ์ €์žฅ (ACID ์ง€์›)
# summary.write.format("delta").mode("overwrite").save("s3://bucket/delta/summary")

# ์บ์‹ฑ (๋ฐ˜๋ณต ์‚ฌ์šฉ ์‹œ)
df.cache()
df.count()  # ์บ์‹œ ํŠธ๋ฆฌ๊ฑฐ

# ์‹คํ–‰ ๊ณ„ํš ํ™•์ธ
df.explain(True)

# ์ข…๋ฃŒ
spark.stop()

# spark-submit์œผ๋กœ ์‹คํ–‰
# spark-submit --master yarn --deploy-mode cluster \
#   --num-executors 10 --executor-memory 4G \
#   etl_job.py

How It's Said in Practice

Senior: "We run the 100GB-a-day log processing as a Spark Job. On EMR with 10 nodes, it finishes within 30 minutes."

Junior: "My Job keeps throwing OOM errors."

Senior: "Increase executor-memory and adjust the number of partitions. Check the shuffle stages with explain(), and see whether you can use a broadcast join."

Interviewer: "Please tell us about your experience with large-scale data processing."

Candidate: "I built an ETL pipeline with PySpark that processes 10TB of logs per day. I minimized shuffles through partitioning and optimized small-table joins with broadcast join. I enabled AQE (Adaptive Query Execution) to optimize at runtime, and added ACID transactions and time travel capabilities with Delta Lake."

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

Reviewer: "collect() pulls all the data to the driver, which causes out-of-memory errors. Use take(100) or show()."

Developer: "It was for debugging, so I'll remove it from the production code."

Cautions

Learn More