transformWithState를 사용한 비동기 처리

Python은 transformWithStateasyncio 기반 비동기 처리를 지원합니다. 상태 연산과 사용자 로직을 그룹화 키에서 동시에 실행하고 프로세스 간 통신을 배치함으로써, 비동기 처리는 약간의 코드 변경만으로 동기 처리보다 더 높은 처리량을 제공합니다. 이 처리량 향상을 위해서는 서드파티 비동기 라이브러리가 필요하지 않습니다. 고급 사용자는 비동기 프로그래밍 패턴과 비동기 지원 라이브러리를 통해 애플리케이션을 더욱 최적화할 수 있습니다.

비동기 처리는 마이크로 배치와 실시간 모드 쿼리를 모두 지원합니다. 단일 그룹화 키의 경우, 비동기 처리는 행 순서를 보존합니다. 서로 다른 그룹화 키를 사용하는 작업은 동시에 실행됩니다.

비동기 처리를 사용하려면 동기식 StatefulProcessor 대신 AsyncStatefulProcessor를 구현하세요. API는 AsyncStatefulProcessor 동기식 StatefulProcessor API를 미러링하기 때문에 대부분의 애플리케이션은 비동기 API를 사용하기 위해 약간의 변경만 필요합니다. AsyncStatefulProcessor를 참조하세요.

동기식 transformWithState API와 핵심 개념에 대해서는 'transformWithState를 사용해 맞춤형 stateful 애플리케이션 빌드'를 참조하세요.

Requirements

비동기 처리는 다음과 같은 요구사항을 가집니다:

  • Databricks Runtime 19 이상 또는 환경 버전 6 이상인 서버리스 컴퓨트에서 사용할 수 있습니다.
  • Python 행 기반 transformWithState API에서만 사용 가능합니다. 비동기 처리는 transformWithState 또는 Scala transformWithStateInPandas API에 대해서는 지원되지 않습니다.
  • Lakeflow 파이프라인에서는 PREVIEW 채널을 사용하도록 파이프라인을 설정하세요. 이 요구사항은 클래식과 서버리스 파이프라인 컴퓨팅 모두에 적용됩니다. CURRENT 채널은 비동기 처리를 지원하지 않습니다. 파이프라인 구성 및 channel을(를) 참조하세요.

구현합니다 AsyncStatefulProcessor

동기 StatefulProcessor를 AsyncStatefulProcessor로 변환하려면 다음과 같은 변경을 해야 합니다:

  • API 메서드(init, close, handleInputRows, handleExpiredTimer, 및 handleInitialState)를 async def 키워드로 정의합니다.
  • 상태 및 타이머 값을 await읽고 업데이트하거나 Python의 asyncio 라이브러리를 사용해 이를 실행하세요. 이는 valueState.get()와 같은 상태 연산과 registerTimer와 같은 타이머 연산에 적용됩니다. 상태 객체(예: handle.getValueState)를 생성하는 과정은 동기식으로 유지됩니다.

비동기 처리에 적용되는 고려사항은 다음과 같습니다:

  • 애플리케이션이 멤버 변수나 외부 시스템에 데이터를 저장한다면, Databricks는 동시 실행을 위해 로직을 다시 작성할 것을 권장합니다. handleInputRows 및 handleExpiredTimer는 그룹화 키 전반에 걸쳐 동시에 실행될 수 있으므로, 인터리브 실행은 공유 데이터를 손상시켜서는 안 됩니다. 대부분의 애플리케이션이 이미 이 요구 사항을 충족하고 있습니다.
  • Databricks는 상태 연산에서 오류를 잡거나 억제하지 말 것을 권장합니다. Apache Spark가 이러한 오류를 처리해 줍니다. 상태 연산이 실패하면 Apache Spark가 태스크를 실패로 처리하고 다시 시도합니다.
    • AsyncStatefulProcessor 상태에서는 연산 오류가 자동으로 관리되며 코드에 드러나지 않습니다.
    • 동기식 StatefulProcessor에서는 상태 연산 오류가 코드에서 보고되지만, 이를 억제하면 데이터 정확성이 손상될 수 있습니다.

예시: 각 그룹화 키에 대한 행 수 카운트

다음 예시는 각 그룹화 키의 행 수를 세는 AsyncCountProcessor 집계 함수를 정의합니다. value_schema 변수는 실행 카운트를 저장하는 ValueState의 스키마를 정의합니다. 동기식 StatefulProcessor와 비교할 때, 변경 사항은 각 메서드의 async def 키워드와 await 상태 읽기 및 업데이트 작업입니다. init에서 getValueState 호출은 계속 동기식으로 유지됩니다. 프로세서를 다음 코드와 같이 정의하세요:

from pyspark.sql import Row
from pyspark.sql.streaming import AsyncStatefulProcessor, AsyncStatefulProcessorHandle
from pyspark.sql.types import StructType, StructField, LongType

value_schema = StructType([StructField("count", LongType(), True)])

class AsyncCountProcessor(AsyncStatefulProcessor):
  async def init(self, handle: AsyncStatefulProcessorHandle) -> None:
    self.count = handle.getValueState("count", value_schema)

  async def handleInputRows(self, key, rows, timerValues):
    total = (await self.count.get() or (0,))[0]
    for _ in rows:
      total += 1
    await self.count.update((total,))
    yield Row(action=key[0], count=total)

  async def close(self) -> None:
    pass

비동기 프로세서로 쿼리를 실행하세요

비동기 프로세서로 쿼리를 실행하려면 AsyncStatefulProcessor를 transformWithState에 전달하세요. 쿼리는 동기 경로와 동일한 문법을 사용합니다. 비동기 API와 동기식 API는 동일한 상태 형식을 공유하므로, 같은 체크포인트를 재사용하면서 기존 쿼리를 AsyncStatefulProcessor와 동기식 StatefulProcessor 간에 전환할 수 있습니다.

예시: 샘플 데이터셋에서의 events 이벤트 집계

다음 예시는 AsyncCountProcessor를 events 샘플 데이터셋에 대해 실행합니다. 각 레코드에는 time 필드(에포크 초)와 값이 Open 또는 Close인 action 필드가 있습니다. 쿼리는 각 행동 유형별로 action 그룹화하고 이벤트를 집계합니다. 더 많은 샘플 데이터셋은 샘플 데이터셋을 참조하세요.

input_schema 변수는 소스 레코드의 스키마를 정의하고, output_schema 변수는 프로세서가 방출하는 행의 스키마를 정의합니다. 샘플 데이터셋을 스트림으로 읽으려면, 두 스키마를 모두 정의한 후 다음 코드처럼 쿼리를 시작하세요:

from pyspark.sql.types import StructType, StructField, StringType, LongType

input_schema = StructType([
  StructField("time", LongType(), True),
  StructField("action", StringType(), True),
])

output_schema = StructType([
  StructField("action", StringType(), True),
  StructField("count", LongType(), True),
])

events = (
  spark.readStream.schema(input_schema)
    .option("maxFilesPerTrigger", 10)
    .json("/databricks-datasets/structured-streaming/events")
)

q = (
  events.groupBy("action")
    .transformWithState(
      statefulProcessor=AsyncCountProcessor(),
      outputStructType=output_schema,
      outputMode="Update",
      timeMode="None",
    )
    .writeStream.format("memory")
    .queryName("async_counts")
    .trigger(availableNow=True)
    .start()
)

q.awaitTermination()

쿼리가 완료된 후, 다음 코드에서 각 액션 유형별 누적 개수를 확인하세요:

display(spark.sql("SELECT action, MAX(count) AS count FROM async_counts GROUP BY action ORDER BY action"))

비동기 상태 및 타이머 연산

AsyncStatefulProcessor에서는 값을 읽거나 쓰는 상태 변수 연산과 타이머 연산이 비동기적입니다. 대부분의 연산은 단일 결과를 반환하며, await로 이 결과를 가져옵니다. 컬렉션을 반환하는 연산은 대신 async for로 소비하는 비동기 반복자를 반환합니다. async / await 및 Python의 비동기 반복자에 대한 입문은 Python asyncio 문서를 참조하세요.

다음 표는 await로 검색할 수 있는 단일 결과를 반환하는 연산을 나열합니다:

클래스 사용하는 연산 await
AsyncValueState exists, get, , update, clear
AsyncMapState exists, getValue, containsKey, updateValue, removeKey, clear
AsyncListState exists, put, appendValue, appendListclear
AsyncStatefulProcessorHandle registerTimer, deleteTimer

다음 표는 async for로 가져올 수 있는 비동기 반복기를 반환하는 연산을 나열합니다:

클래스 사용하는 연산 async for
AsyncMapState iterator, keys, values
AsyncListState get
AsyncStatefulProcessorHandle listTimers

예: async for

예를 들어, AsyncListState의 값을 읽으려면 다음 코드와 같이 async for로 반복하여 사용합니다:

total = 0
async for value in self.items.get():
  total += value[0]

상태 객체를 생성하고 상태 변수를 삭제하는 메서드는 동기식으로 유지됩니다: getValueState, getMapState, getListState, 그리고 deleteIfExists.

각 상태 유형에 대한 설명은 사용자 정의 상태 유형을 참조하세요.

비동기 프로그래밍 패턴으로 최적화하기

비동기 처리는 로직이 네트워크 요청과 같은 외부 작업을 기다릴 때 유용합니다. 각 요청을 순서대로 기다리는 대신, asyncio를 사용해 요청을 동시에 실행하여 유휴 시간을 줄이세요.

예시: 동시 요청을 실행합니다. asyncio.gather

다음 예시에서는 asyncio.gather를 사용해 모든 행당 HTTP 요청을 동시에 실행하고 완료될 때까지 기다린 후 최대 점수를 상태에 저장합니다. 프로세서를 다음 코드와 같이 정의하세요:

import asyncio
import aiohttp
from pyspark.sql import Row
from pyspark.sql.streaming import AsyncStatefulProcessor

class HttpScoreRowGatherProcessor(AsyncStatefulProcessor):
  async def init(self, handle):
    self._score_state = handle.getValueState("last_score", "score double")
    self._session = aiohttp.ClientSession()

  async def _fetch_score(self, row) -> float:
    async with self._session.get(
      f"https://api.example.com/score/{row.event_id}"
    ) as resp:
      return (await resp.json())["score"]

  async def handleInputRows(self, key, rows, timerValues):
    user_id = key[0]
    scores = await asyncio.gather(*[self._fetch_score(row) for row in rows])

    max_score = max(scores)
    await self._score_state.update((max_score,))
    yield Row(user_id=user_id, score=max_score)

  async def close(self):
    await self._session.close()