PySpark · S04

셔플, 브로드캐스트 조인, 쏠림

공고에 "Spark 튜닝(파티셔닝, 셔플·메모리 최적화)"이 자주 나옵니다. 400만 행을 만들어 셔플 파티션 수, 조인 방식, 한 고객에게 데이터가 몰린 경우를 직접 재 봤습니다. PySpark 4.3.0, local[4](코어 4개)에서 세 번 실행해 가장 빠른 값을 적었습니다.


# S04. 셔플 파티션 수, 브로드캐스트 조인, 데이터 쏠림(skew)과 소금치기(salting)를 직접 재 봅니다.
import time
from pyspark.sql import SparkSession, functions as F
spark = (SparkSession.builder.master("local[4]").config("spark.driver.memory", "3g")
         .config("spark.sql.session.timeZone", "Asia/Seoul").getOrCreate())
spark.sparkContext.setLogLevel("ERROR")

def timed(label, df):
    t0 = time.perf_counter(); n = df.count(); t = time.perf_counter() - t0
    print(f"  {label:38s} {t:5.2f}초  (결과 {n:,}행)"); return t

def best(label, make, k=3):
    return min(timed(label, make()) for _ in range(k))

# 주문 400만 행. 절반이 고객 42번 한 명에게 몰려 있습니다(대형 거래처 같은 상황).
orders = (spark.range(4_000_000)
          .withColumn("customer_id", F.when(F.col("id") % 2 == 0, F.lit(42)).otherwise((F.col("id") % 5000) + 1))
          .withColumn("amount", (F.col("id") % 97) * 100)).cache()
orders.count()
customers = spark.range(1, 5001).withColumnRenamed("id", "customer_id").withColumn("region", F.expr("element_at(array('서울','부산','대구','광주'), cast(customer_id % 4 + 1 as int))"))

print("1) 셔플 파티션 수")
spark.conf.set("spark.sql.adaptive.enabled", "false")
for n in [200, 8]:
    spark.conf.set("spark.sql.shuffle.partitions", n)
    agg = orders.groupBy("customer_id").agg(F.sum("amount").alias("s"))
    best(f"AQE 끔, shuffle.partitions={n}", lambda: agg)
    print("    결과 파티션 수:", agg.rdd.getNumPartitions())
spark.conf.set("spark.sql.adaptive.enabled", "true"); spark.conf.set("spark.sql.shuffle.partitions", 200)
agg = orders.groupBy("customer_id").agg(F.sum("amount").alias("s"))
best("AQE 켬, shuffle.partitions=200", lambda: agg)
print("    결과 파티션 수(AQE가 합침):", agg.rdd.getNumPartitions())

print("2) 조인 방식")
spark.conf.set("spark.sql.adaptive.enabled", "false")
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)
smj = orders.join(customers, "customer_id")
print("    계획:", "SortMergeJoin" if "SortMergeJoin" in smj._jdf.queryExecution().executedPlan().toString() else "?")
best("정렬 병합 조인(SortMergeJoin)", lambda: smj)
bhj = orders.join(F.broadcast(customers), "customer_id")
print("    계획:", "BroadcastHashJoin" if "BroadcastHashJoin" in bhj._jdf.queryExecution().executedPlan().toString() else "?")
best("브로드캐스트 조인(작은 표를 모든 작업에 복사)", lambda: bhj)

print("3) 쏠림(skew)")
from pyspark.sql import Window
spark.conf.set("spark.sql.adaptive.enabled", "false"); spark.conf.set("spark.sql.shuffle.partitions", 8)
sizes = orders.repartition(8, "customer_id").rdd.glom().map(len).collect()
print("    고객 기준으로 8개로 나눈 파티션별 행 수:", sizes)
uniform = (spark.range(4_000_000).withColumn("customer_id", (F.col("id") % 2500) * 2 + 2)
           .withColumn("amount", (F.col("id") % 97) * 100)).cache(); uniform.count()
for name, df in [("고르게 퍼진 데이터", uniform), ("고객 42에 절반 몰린 데이터", orders)]:
    best(f"합계 groupBy: {name}", lambda: df.groupBy("customer_id").agg(F.sum("amount")))
# 파티션 하나를 처리하는 데 걸린 시간(파티션 안에서 금액순 정렬). 단계 전체는 가장 느린 파티션을 기다립니다.
import time as _t
def part_time(it):
    t0 = _t.perf_counter(); rows = sorted((r.amount for r in it)); return [(len(rows), round(_t.perf_counter() - t0, 2))]
for name, df in [("고객 기준", orders.repartition(8, "customer_id")),
                 ("고객+소금(0~15) 기준", orders.withColumn("salt", (F.rand(seed=1) * 16).cast("int")).repartition(8, "customer_id", "salt"))]:
    res = df.rdd.mapPartitions(part_time).collect()
    print(f"    {name}: 파티션별 (행 수, 초) {res}  → 가장 느린 파티션 {max(t for _, t in res)}초")
spark.stop()

1) 셔플 파티션 수

설정시간결과 파티션 수
AQE 끔, shuffle.partitions=200(기본값)0.51초200
AQE 끔, shuffle.partitions=80.09초8
AQE 켬, shuffle.partitions=2000.17초1 (AQE가 합침)

결과가 2,500행뿐인데 기본값 200개로 나누면 작은 작업 200개를 만들고 거두는 시간이 더 듭니다. AQE(적응형 쿼리 실행, Spark 3.2부터 기본으로 켜짐)는 실행 중 크기를 보고 작은 파티션을 합칩니다. 데이터가 작으면 파티션 수를 줄이고, 크면 늘립니다.

2) 조인 방식

방식계획에 보이는 이름시간
정렬 병합 조인(양쪽을 키로 셔플·정렬)SortMergeJoin약 0.8초
브로드캐스트 조인(작은 고객 표 5,000행을 모든 작업에 복사)BroadcastHashJoin약 0.06초

한쪽이 작으면 큰 쪽을 셔플하지 않아도 됩니다. Spark는 작은 표(기본 10MB 이하)를 자동으로 브로드캐스트하고, 통계가 없으면 F.broadcast()로 직접 지정합니다. 실행 계획(explain())에서 어느 조인이 골라졌는지 먼저 봅니다.

3) 쏠림(skew)

고객 기준으로 8개로 나눈 파티션별 행 수: [2235200, 268000, 252800, 272800, 248800, 238400, 242400, 241600]
합계 groupBy: 고르게 퍼진 데이터           0.05초
합계 groupBy: 고객 42에 절반 몰린 데이터     0.06초
고객 기준: 파티션별 (행 수, 초) [(2235200, 2.72), (268000, 0.48), ... (241600, 0.3)]  → 가장 느린 파티션 2.72초
고객+소금(0~15) 기준: 파티션별 (행 수, 초) [(502943, 0.83), ... (1004908, 1.22), ...]  → 가장 느린 파티션 1.22초

처음 잰 비교는 틀렸습니다. 처음에는 "그냥 합계"에 repartition을 한 번 더 넣고 "소금 2단계 합계"와 비교해, 소금치기가 4배 빠른 것처럼 나왔습니다. 셔플 횟수가 달라서 생긴 차이였습니다. 튜닝 전후를 비교할 때는 바꾼 것 하나 외에 같은지 실행 계획으로 확인합니다. AQE의 쏠린 조인 자동 처리(skewJoin)도 시험했지만 이 로컬 설정에서는 동작하지 않아 결과에 넣지 않았습니다.

이것만 기억하세요

작은 결과는 셔플 파티션을 줄이고(AQE), 작은 표는 브로드캐스트하고, 쏠림은 "모든 행을 모아야 하는 작업"에서만 문제가 되니 그때 소금을 칩니다.

다음
11. 배치·스트리밍·CDC
이어보기 →