📊Data Engineering

Big Data

Big Data

Data of large volume, high velocity, and diverse forms. Defined by the 3Vs (Volume, Velocity, Variety). Processed with Hadoop and Spark.

Detailed Explanation

Big Data refers to large-scale data sets that are difficult to manage with traditional data processing tools. It is characterized by the 3Vs: Volume (large volume, petabytes and beyond), Velocity (high-speed generation, real-time streaming), and Variety (diverse formats: structured/unstructured/semi-structured). Recently, it has been extended to the 5Vs by adding Veracity (accuracy) and Value.

The core technology of big data processing is distributed computing. Apache Hadoop processes petabyte-scale data with HDFS (distributed file system) and MapReduce (distributed processing framework). Apache Spark provides performance more than 100 times faster than Hadoop MapReduce through in-memory processing, and is currently the de facto standard for batch/streaming analytics.

Apache Kafka (message queue), Apache Flink (stream processing), and Spark Streaming are used for real-time streaming processing. In cloud environments, managed services such as AWS EMR, Google Dataproc, and Azure HDInsight make it possible to process big data without the burden of infrastructure operations. Databricks is gaining popularity as a Spark-based unified analytics platform.

Big data is the foundation for training AI/ML models. Large-scale training data determines model performance, and large language models such as GPT are trained on text data of hundreds of billions of tokens. In diverse fields such as IoT, social media, financial transactions, and medical records, big data analytics is driving business decision-making and innovation.

Code Example

PySpark Big Data Processing
# Apache Spark를 활용한 빅데이터 처리 예시
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.window import Window
from pyspark.ml.feature import VectorAssembler
from pyspark.ml.classification import RandomForestClassifier
from pyspark.ml import Pipeline

# Spark 세션 생성 (클러스터 모드)
spark = SparkSession.builder \
    .appName("BigDataAnalytics") \
    .config("spark.sql.adaptive.enabled", "true") \
    .config("spark.sql.shuffle.partitions", "200") \
    .config("spark.executor.memory", "8g") \
    .config("spark.executor.cores", "4") \
    .config("spark.dynamicAllocation.enabled", "true") \
    .getOrCreate()

# 1. 대용량 데이터 로드 (페타바이트 규모)
# Parquet 형식으로 효율적 컬럼 읽기
events_df = spark.read \
    .parquet("s3://datalake/events/year=2024/") \
    .filter(col("event_date") >= "2024-01-01")

print(f"총 레코드 수: {events_df.count():,}")
print(f"파티션 수: {events_df.rdd.getNumPartitions()}")

# 2. 3V 특성 활용
# Volume: 수십억 건 데이터 병렬 처리
# Velocity: 시간 단위 파티션으로 증분 처리
# Variety: JSON, 로그, 트랜잭션 데이터 통합

# 복잡한 집계 연산 (분산 처리)
user_metrics = events_df \
    .groupBy("user_id", "event_date") \
    .agg(
        count("*").alias("event_count"),
        countDistinct("session_id").alias("session_count"),
        sum("revenue").alias("total_revenue"),
        collect_set("event_type").alias("event_types"),
        avg("page_load_time").alias("avg_load_time")
    )

# 3. 윈도우 함수로 시계열 분석
window_spec = Window \
    .partitionBy("user_id") \
    .orderBy("event_date") \
    .rowsBetween(-6, 0)  # 7일 이동 윈도우

user_trends = user_metrics \
    .withColumn("rolling_avg_revenue",
                avg("total_revenue").over(window_spec)) \
    .withColumn("revenue_growth",
                (col("total_revenue") - lag("total_revenue", 1).over(
                    Window.partitionBy("user_id").orderBy("event_date")
                )) / lag("total_revenue", 1).over(
                    Window.partitionBy("user_id").orderBy("event_date")
                ))

# 4. 대규모 ML 파이프라인 (분산 학습)
# 특성 벡터 생성
assembler = VectorAssembler(
    inputCols=["event_count", "session_count", "total_revenue", "avg_load_time"],
    outputCol="features"
)

# 분산 학습 (수백만 샘플)
rf = RandomForestClassifier(
    labelCol="churn_label",
    featuresCol="features",
    numTrees=100,
    maxDepth=10,
    seed=42
)

pipeline = Pipeline(stages=[assembler, rf])
model = pipeline.fit(user_trends.filter(col("churn_label").isNotNull()))

# 5. 결과 저장 (최적화된 형식)
user_trends.write \
    .partitionBy("event_date") \
    .mode("overwrite") \
    .format("delta") \
    .option("mergeSchema", "true") \
    .save("s3://datalake/gold/user_metrics/")

# 6. 실시간 스트리밍 처리 (Kafka 연동)
streaming_df = spark.readStream \
    .format("kafka") \
    .option("kafka.bootstrap.servers", "kafka:9092") \
    .option("subscribe", "user-events") \
    .option("startingOffsets", "latest") \
    .load()

# 스트림 변환
processed_stream = streaming_df \
    .select(from_json(col("value").cast("string"), schema).alias("data")) \
    .select("data.*") \
    .withWatermark("timestamp", "10 minutes") \
    .groupBy(window("timestamp", "5 minutes"), "user_id") \
    .agg(count("*").alias("event_count"))

# 스트림 출력 (Delta Lake)
query = processed_stream.writeStream \
    .format("delta") \
    .outputMode("append") \
    .option("checkpointLocation", "s3://checkpoints/user_counts/") \
    .trigger(processingTime="1 minute") \
    .start("s3://datalake/streaming/user_counts/")

print("Streaming query started...")

Practical Conversation

PM: The daily aggregation job takes 8 hours. Can't we make it faster?
Data Engineer: You can optimize the Spark settings. The current number of shuffle partitions is 200, which is too few for the data size. If you increase it to 2000 and enable AQE (Adaptive Query Execution), it should be reduced to under 2 hours.
PM: We also need to consider cloud costs.
Data Engineer: Using spot instances can reduce costs by 70%. With Dynamic Allocation, you allocate only as many resources as needed, and you can run jobs outside of peak hours.
Interviewer: How do you solve the Data Skew problem in Spark?
Candidate: When data is concentrated on a particular key, only some partitions take a long time. You distribute it by adding a random suffix to the key with the salting technique, or enable AQE's skew join optimization. A broadcast join is also effective for small tables.
Interviewer: What is the difference between Hadoop and Spark?
Candidate: Hadoop MapReduce is disk-based and stores the result of every stage. Spark keeps intermediate results in memory through in-memory processing, so it is more than 100 times faster for iterative computations. Currently, Spark is the standard for both batch and streaming.

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Developer: I used collect() and got an OOM.
Senior: collect() pulls the entire dataset into driver memory. You should never use it with big data. Instead, fetch only a sample with take(n), or save in a distributed manner with write(). If you only need the aggregated result, call collect() after agg().
Developer: How do I decide the number of partitions?
Senior: In general, 2-4 times the total number of cores in the cluster is appropriate. 128MB-1GB per partition is ideal. If you turn on AQE with spark.sql.adaptive.enabled=true, automatic optimization also happens.

Cautions

  • collect() and toPandas() cause OOM with big data. Use distributed storage or sampling.
  • Data Skew concentrates load on specific partitions. Solve it with salting, broadcast join, and AQE.
  • For small-scale data, a big data stack only adds overhead. Choose tools that fit the data size.
  • Using columnar formats such as Parquet and Delta Lake greatly improves storage and query performance.
  • Using Dynamic Allocation and spot instances can reduce cloud costs by 70% or more.

Learn More