seon99il

Data Engineering

Apache Spark Deep Dive: repartition & coalesce

6분 소요

Spark를 통해 연산을 하다 보면 파티션이 과다하게 많거나 너무 적은 상황이 있을 수 있습니다. 이럴 때 repartition과 coalesce를 통해 파티션 개수를 수정할 수 있습니다.

repartition과 coalesce는 모두 파티션 개수를 설정해주는 함수이지만, coalesce의 경우 파티션의 개수를 줄이는 것만 가능하다는 차이점이 있습니다.

이해를 돕기 위해 AQE 설정 및 Broadcast를 false로 두고 확인해보겠습니다.

from pyspark.sql import SparkSession, functions as F
from pyspark.sql.types import *

spark = SparkSession.builder \
    .master("local[*]") \
    .appName("PartitionKeyExample") \
    .config("spark.sql.adaptive.enabled", "false")\
    .getOrCreate()

AQE가 켜져 있으면, Spark는 물리적 실행 계획(Physical Plan)을 AdaptiveSparkPlanExec이라는 래퍼(Wrapper) 노드로 감싸기 때문에, repartition을 호출하면 셔플(Shuffle)이 계획되지만, AQE는 런타임 통계를 바탕으로 파티션 수를 동적으로 줄이거나(coalesce), 조인 전략을 바꿀 수 있는 상태로 대기하여 정확한 확인이 어려울 수 있습니다.

Repartition

numPartitions 또는 cols를 사용하여 하나의 파티션을 N개의 파티션으로 나눌 수 있습니다.

# def repartition(  # type: ignore[misc]
#         self, numPartitions: Union[int, "ColumnOrName"], *cols: "ColumnOrName"
#     ) -> "DataFrame":

users_df = users_df.repartition(F.col("user_id"))

다음과 같이 컬럼명만 정의할 경우 기본 설정 값(파티션 수)을 따라 200개로 파티션이 repartition됩니다.

# Print partition Num
users_df.rdd.getNumPartitions()

# 200
# Print partition type
print("Plain after partition:", users_df
      ._jdf.queryExecution()
      .executedPlan()
      .outputPartitioning()
      )

# Plain after partition: hashpartitioning(user_id#41, 200)

repartition의 경우 파티션을 늘리거나 줄일 수 있습니다.

Repartition 후 group by

여기서 user_id로 파티셔닝된 데이터를 group by(agg)해보겠습니다.

이해를 돕기 위해 100개의 파티션으로 repartition 하겠습니다.

users_df = users_df.repartition(100, F.col("user_id"))

users_df.rdd.getNumPartitions()

# 100
result = users_df.groupBy("user_id").count()
result.show()

number of partitions: 100

앞에서 repartition(100, "user_id")이 정상적으로 동작하는 것을 확인할 수 있습니다.

Repartition 후 Join

그럼 이제 사용자 정보를 user_id를 기준으로 repartition 후 주문 정보와 user_id를 기준으로 Join해보겠습니다.

orders_df = spark.read.parquet("./data/work/orders")

orders_df.rdd.getNumPartitions()
# 1

이미 user_id로 파티셔닝된 사용자 데이터와 주문 데이터를 Join하면 어떤 결과가 나올까요?

result = orders_df.join(users_df, on="user_id", how="inner")
result.show()

Exchange

두 테이블 모두 200개의 파티션으로 파티셔닝된 후 SortMergeJoin된 걸 확인할 수 있습니다.

Spark가 기본값인 200으로 통일하기 위해 앞에 정의한 repartition(100, "user_id")를 제거해줬습니다.

Spark에서 Join 시에는 Partition의 Key(user_id)와 Partition의 수(100)가 모두 같을 때만 같은 파티셔닝 전략으로 취급합니다.

orders_df = orders_df.repartition(100, F.col("user_id"))
print("Plain:", orders_df
                ._jdf
                .queryExecution()
                .executedPlan()
                .outputPartitioning())

# Plain: hashpartitioning(user_id#243, 100)

print("Plain:", users_df
      ._jdf.queryExecution()
      .executedPlan()
      .outputPartitioning()
      )

# Plain: hashpartitioning(user_id#41, 100)

위 경우는 user_id 뒤의 #41, #243으로 키가 맞지 않기 때문에 역시 200개로 셔플링 됩니다.

Coalesce

Coalesce는 Partition의 수를 줄이는 것만 가능합니다. 또한 줄이는 수만 설정할 수 있고 특정 컬럼을 지정할 수 없습니다.

# def coalesce(self, numPartitions: int) -> "DataFrame":

df.coalesce(2)

사용자 정보를 user_id를 기준으로 group by하는 예제로 돌아가보겠습니다.

users_df = users_df.coalesce(2)

result = users_df.groupBy("user_id").count()
result.show()

Query

실행된 Query를 보면 이전의 Repartition과 다르게 coalesce가 추가된 걸 볼 수 있습니다. 하지만 조금 다른 점은 여전히 user_id를 기준으로 파티셔닝되는 모습을 볼 수 있습니다.

Repartition vs Coalesce (Map Side vs Reduce Side)

Repartition과 Coalesce는 같은 파티션 수 변경이라는 작업을 하지만 동작하는 위치가 다릅니다.

Spark의 Shuffle은 Map Side와 Reduce Side에서 2단계의 Stage를 통해 동작합니다.

Apache Spark: Spark Shuffle Deep Dive — Spark에서 Shuffle이 어떤 단계를 거쳐서 일어나고 각 단계마다 파티션 수가 어떻게 변하는지 알아보겠습니다.

Map Side에서는 특정 키가 하나의 파티션에만 존재할 수 있도록 셔플링하며, Reduce Side에서는 파티션당 하나의 Task(slot)를 할당하고 각 Task는 모든 업스트림에서 자신이 담당하는 파티션만 가져와서 작업을 처리합니다.

Map Side: Repartition (Shuffle Write)

Repartition은 Map Side에서 동작하며 업스트림에서 들어온 데이터를 몇 개의 파티션 or Key를 기준으로 분할할지 결정합니다.

이렇기 때문에 이전의 파티션 수와 상관없이 파티션 수를 늘리거나 줄일 수 있으며, 어떤 키를 기준으로 파티셔닝할지 선택할 수 있습니다.

Reduce Side: Coalesce (Shuffle Read)

반면 coalesce는 Reduce Side에서 동작합니다. Map Side에서 나눠놓은 파티션을 기존에는 Partition = Task 1:1로 Task를 실행시켜야 하지만 이것을 몇 개로 줄일지 결정할 수 있습니다.

200개로 나눠진 Partition을 coalesce(10) 하게 된다면, 여전히 200개로 나누지만 이 데이터를 10개씩 묶어서(예: task1: [0 ~ 19], task2: [20 ~ 39]) 적은 Task를 생성하여 해당 데이터를 처리할 수 있습니다.

이렇게 동작하기 때문에 업스트림의 파티션 수(200)보다 많은 값으로 파티션 수를 설정할 수 없습니다.

AQE(Adaptive Query Execution): Shuffle Read (Coalesce)

AQE를 사용하게 되면 Shuffle Read 단계에서의 coalesce를 데이터의 크기에 따라 동적으로 설정해줍니다.

Shuffle Read 단계에서 기존에는 200개의 Task가 실행되어야 하지만 AQE에서 데이터의 크기를 보고 모든 파티션을 하나의 Task에서 처리하도록 쿼리 플랜을 변경한 걸 확인할 수 있습니다.

AQE: Dynamically coalescing shuffle partitions 환경 변수들

  • spark.sql.adaptive.coalescePartitions.enabled (default: True): 셔플 후 파티션 수를 동적으로 줄이며 파티션의 크기는 아래 변수(advisoryPartitionSizeInBytes)로 맞추려 시도
  • spark.sql.adaptive.advisoryPartitionSizeInBytes (default: 64MB): 셔플링 후 파티션 수를 줄일 때 목표로 하는 파티션의 크기
  • spark.sql.adaptive.coalescePartitions.parallelismFirst (default: True): 병렬성 보장을 위해 위의 목표 크기가 무시되고 아래 minPartitionSize만 보장
  • spark.sql.adaptive.coalescePartitions.initialPartitionNum (default: None): Coalescing 전의 파티션 수. 없으면 spark.sql.shuffle.partitions로 설정

Coalesce를 사용 시 고려해야 할 점

Coalesce를 사용하게 되면 이전에 파티셔닝 기록(key, numOfPartition)이 사라지기 때문에 같은 key, numOfPartition을 기준으로 처리하더라도 파티셔닝이 다시 한 번 발생할 수 있습니다.

print("Plain after partition:", users_df
      ._jdf.queryExecution()
      .executedPlan()
      .outputPartitioning()
      )

# Plain after partition: hashpartitioning(user_id#423, 100)

user_id#423, 100으로 hashpartitioning된 것을 보장함. 다른 user_id#423, 100으로 파티셔닝된 테이블과 JOIN한다면 셔플링이 발생하지 않음

users_df = users_df.coalesce(2)

print("Plain after partition:", users_df
      ._jdf.queryExecution()
      .executedPlan()
      .outputPartitioning()
      )

# Plain after partition: UnknownPartitioning(2)

UnknownPartitioning이 되어 user_id#423, 100으로 파티셔닝된 테이블과 JOIN 한다면 다시 파티셔닝해야 함

coalesce(1)로 모든 파티션을 하나로 합치게 될 경우 UnknownPartitioning이 아닌 SinglePartition이 됩니다.

Join 시 두 테이블 모두 SinglePartition일 경우 Shuffle이 발생하지 않지만 다른 하나의 테이블의 파티셔닝 조건(key, num)이 다르다면 역시 통일된 파티션 조건으로 셔플링이 발생합니다.

한쪽만 Coalesce했을 경우 모두 사용자 아이디를 기준으로 셔플링 됨

양쪽 모두 SinglePartition(coalesce(1))로 만들 경우 shuffle이 발생하지 않음

File Write 시 Coalesce 사용하기

Coalesce는 File을 최종적으로 write 할 때 사용하면 이점이 있습니다.

Spark는 기본적으로 이전에 만들어둔 파티셔닝을 따라서 파티션을 만듭니다.

작은 파일(10MB) 2개로 존재하는 사용자 데이터를 Spark에서 읽게 되면, 이것을 하나로 합쳐서 1개의 Partition으로 읽는 것이 아닌 기존의 파티션 방식인 2개의 Partition으로 읽게 됩니다.

이러한 문제는 작은 파일 문제를 발생시켜 성능이 저하될 수 있으며, 이러한 문제를 방지하기 위해 최종적으로 파일을 쓸 때 coalesce를 통해 적당한 Partition 단위로 파일을 쓰는 것이 좋습니다.

이전 글

전체 글 보기 →

댓글