View a markdown version of this page

Amazon MWAA 환경에서 Aurora PostgreSQL 데이터베이스 정리 - Amazon Managed Workflows for Apache Airflow

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Amazon MWAA 환경에서 Aurora PostgreSQL 데이터베이스 정리

Amazon Managed Workflows for Apache Airflow는 Aurora PostgreSQL 데이터베이스를 Apache Airflow 메타데이터 베이스로 사용하며, 여기서 DAG가 실행되고 작업 인스턴스가 저장됩니다. 다음 샘플 코드는 Amazon MWAA 환경의 전용 Aurora PostgreSQL 데이터베이스에서 항목을 정기적으로 정리합니다.

중요

Apache Airflow v3는 작업 코드에서 직접 메타데이터 데이터베이스 액세스를 제한합니다. 작업자는 더 이상 메타데이터 데이터베이스에 연결할 수 없으며, DAG 또는 작업 코드는 Apache Airflow 데이터베이스 세션 또는 모델을 직접 가져오거나 사용할 수 없습니다. 이 변경 사항은 보안 및 확장성을 개선합니다. 그러나 Apache Airflow v2에서 작동하는 DAG 기반 데이터베이스 정리 접근 방식은 Apache Airflow v3 환경에서 작동하지 않습니다.

대신 Amazon MWAA airflow db clean CLI 엔드포인트를 통해 CLI 명령을 사용하여 메타데이터 데이터베이스 정리를 수행합니다.

참고

시간이 지남에 따라 메타데이터 데이터베이스는 이전 레코드, XCom 데이터 및 오래된 작업 데이터를 누적합니다. 이러한 성장은 데이터베이스 연결을 사용하고, 환경을 느리게 하며, 작업을 지연시킵니다. 이러한 문제를 방지하려면 정기적인 메타데이터 정리를 실행합니다.

버전

이 페이지의 코드 샘플은 Amazon MWAA에서 지원되는 Apache Airflow v2 및 v3에만 해당됩니다. 지원되는 Apache Airflow 버전을 참조하세요.

사전 조건

이 페이지의 이 샘플 코드를 사용하려면 다음 항목이 필요합니다.

종속성

이 코드 예제를 Apache Airflow v2와 함께 사용하려면 추가 종속성이 필요하지 않습니다. aws-mwaa-docker-images를 사용하여 Apache Airflow를 설치합니다.

코드 샘플

다음 예제에서는 Amazon MWAA 환경에서 메타데이터 데이터베이스를 정리하는 방법을 보여줍니다.

Apache Airflow v3.0.6 to 3.2.1
중요 고려 사항
  • 정리가 도달하는 거리를 제어--clean-before-timestamp하려면를 지정해야 합니다. ISO 8601 형식의 타임스탬프(예: 2025-01-01T00:00:00+00:00)를 사용합니다.

  • 정리를 특정 테이블로 제한--tables하도록를 지정하는 것이 좋습니다. 생략하면 명령이 지원되는 모든 테이블을 정리합니다.

  • 작은 범위부터 시작 - 이전 --clean-before-timestamp 값(환경 생성 날짜에 가까움)과 단일 테이블을 먼저 사용합니다. 이렇게 하면 정리가 가장 오래된 레코드로만 제한됩니다. 명령은 지정된 타임스탬프 이전의 모든 항목을 삭제하므로 최신 타임스탬프를 사용하면 삭제 범위가 커집니다. 프로세스에 대한 신뢰도를 얻으면서 타임스탬프를 점진적으로 앞으로 이동합니다.

  • 대규모 정리는 데이터베이스 성능에 영향을 미칠 수 있습니다. 대량의 레코드를 삭제하면 Aurora PostgreSQL 데이터베이스에 부담이 가중되고 환경의 응답성에 영향을 미칠 수 있습니다. --batch-size 파라미터를 사용하여 트랜잭션 크기를 제어하고 트래픽이 적은 기간에는 정리를 실행하는 것이 좋습니다. 프로덕션 환경에서 실행할 때는 주의해야 합니다.

종속 테이블 동작

로 테이블을 지정하면 명령--tables에 지정된 테이블과 외래 키 관계가 있는 종속(하위) 테이블이 자동으로 포함됩니다. 하위 테이블 레코드는 먼저 삭제된 다음 상위 테이블 레코드를 삭제하여 외래 키 제약 조건을 충족합니다. 예를 들어를 지정하면 task_instance, task_instance_history, task_state_store, 및 xcom--tables dag_run도 정리됩니다. 이러한 테이블은 외래 키를 dag_run 통해 참조deadline하기 때문입니다.

다음 표에는 종속성 체인이 요약되어 있습니다.

지정된 테이블 정리된 추가 테이블(종속)
dag_run task_instance, task_instance_history, xcom, task_state_store, deadline
dag dag_version, deadline
task_instance task_instance_history, xcom
trigger task_instance, task_instance_history, xcom
dag_version task_instance, task_instance_history, xcom, dag_run

종속 항목이 없는 테이블(예: log, job, import_error, sla_miss)은 지정된 경우 격리된 상태로 정리됩니다.

--dry-run를 사용하여 정리를 커밋하기 전에 영향을 받을 테이블과 행 수를 정확히 확인합니다.

에 사용 가능한 파라미터 airflow db clean

다음 표에서는에 사용할 수 있는 파라미터를 설명합니다airflow db clean.

파라미터 설명 기본값
--clean-before-timestamp (필수) 데이터가 제거되기 전의 날짜 또는 타임스탬프입니다. 시간대가 제공되지 않으면 Apache Airflow 기본 시간대가 가정됩니다. 예시: 2025-01-01T00:00:00+00:00 없음
--tables 또는 -t 유지 관리를 수행할 테이블 이름(쉼표로 구분). 옵션에는 dag_run, task_instance, task_instance_history, log, job, xcom, import_error, task_reschedule, trigger, dag, sla_miss, dag_versioncallback_request, celery_taskmeta, celery_tasksetmeta, asset_event, deadline, , revoked_token, task_state_store, , connection_test_request가 포함됩니다. _xcom_archive 없음
--batch-size 단일 트랜잭션에서 삭제하거나 보관할 최대 행 수입니다. 값이 낮을수록 장기 실행 잠금은 줄어들지만 배치 수는 증가합니다. 없음
--dry-run 실제로 데이터를 삭제하지 않고 모의 실행을 수행합니다. 초기 테스트에 권장됩니다. False
--skip-archive 아카이브 테이블에서 제거된 레코드를 보존하지 마십시오. 기본적으로는 제거된 레코드를 영구적으로 삭제하는 대신 아카이브 테이블(예_<table>_archive: _dag_run_archive)로 db clean 이동합니다. 이렇게 하면 안전망이 제공됩니다. 보관된 데이터를 검사하거나,를 사용하여 내보내거나airflow db export-archived, 나중에를 사용하여 삭제할 수 있습니다airflow db drop-archived. --skip-archive이 설정되면이 중간 단계 없이 레코드가 영구적으로 삭제됩니다. False
--dag-ids 지정된 DAG IDs. 없음
--exclude-dag-ids 지정된 DAG IDs와 관련된 데이터를 정리하지 마세요. 없음
-y, --yes 확인 프롬프트를 건너뜁니다. Amazon MWAA를 통한 비대화형 CLI 실행에 필요합니다. False
-v, --verbose 로깅 출력을 더 상세하게 만듭니다. False

사용 가능한 파라미터에 대한 자세한 내용은 Apache Airflow 웹 사이트의 CLI 및 env 변수 참조를 참조하세요.

코드 샘플

다음 예제에서는 Amazon MWAA CLI 엔드포인트를 airflow db clean 통해를 호출하는 방법을 보여줍니다. CLI 토큰 생성에 대한 자세한 내용은 섹션을 참조하세요Apache Airflow CLI 토큰 생성.

Python 스크립트 사용:

import boto3 import base64 import requests # Replace with your environment name and AWS Region mwaa_env_name = "YOUR_ENVIRONMENT_NAME" region = "YOUR_REGION" # Configure cleanup scope clean_before_timestamp = "2025-06-01T00:00:00+00:00" tables = "dag_run,task_instance,log,job,xcom" # Build the Airflow CLI command # -y flag is required to skip interactive confirmation prompt airflow_cmd = f"db clean --clean-before-timestamp {clean_before_timestamp} --tables {tables} -y" # Create a CLI token client = boto3.client("mwaa", region_name=region) cli_token_response = client.create_cli_token(Name=mwaa_env_name) cli_token = cli_token_response["CliToken"] web_server_hostname = cli_token_response["WebServerHostname"] # Invoke the Airflow CLI through the MWAA endpoint url = f"https://{web_server_hostname}/aws_mwaa/cli" response = requests.post( url, headers={ "Authorization": f"Bearer {cli_token}", "Content-Type": "text/plain", }, data=airflow_cmd, ) # Parse and display the results stdout_message = base64.b64decode(response.json()["stdout"]).decode("utf-8") stderr_message = base64.b64decode(response.json()["stderr"]).decode("utf-8") print(f"Status code: {response.status_code}") print(f"stdout:\n{stdout_message}") print(f"stderr:\n{stderr_message}")
드라이 런 예제(권장 첫 번째 단계)

실제 정리를 수행하기 전에를와 함께 실행--dry-run하여 삭제할 내용을 확인합니다.

AIRFLOW_CMD="db clean --clean-before-timestamp 2025-06-01T00:00:00+00:00 --tables dag_run,task_instance --dry-run -y"
Apache Airflow v2.7.2 to 2.11.2
from airflow import DAG from airflow.models.param import Param from airflow.operators.bash_operator import BashOperator from airflow.utils.dates import days_ago from datetime import datetime, timedelta # Note: Database commands might time out if running longer than 5 minutes. If this occurs, please increase the MAX_AGE_IN_DAYS (or change # timestamp parameter to an earlier date) for initial runs, then reduce on subsequent runs until the desired retention is met. MAX_AGE_IN_DAYS = 30 # To clean specific tables, please provide a comma-separated list per # https://airflow.apache.org/docs/apache-airflow/stable/cli-and-env-variables-ref.html#clean # A value of None will clean all tables TABLES_TO_CLEAN = None with DAG( dag_id="clean_db_dag", schedule_interval=None, catchup=False, start_date=days_ago(1), params={ "timestamp": Param( default=(datetime.now()-timedelta(days=MAX_AGE_IN_DAYS)).strftime("%Y-%m-%d %H:%M:%S"), type="string", minLength=1, maxLength=255, ), } ) as dag: if TABLES_TO_CLEAN: bash_command="airflow db clean --clean-before-timestamp '{{ params.timestamp }}' --tables '"+TABLES_TO_CLEAN+"' --skip-archive --yes" else: bash_command="airflow db clean --clean-before-timestamp '{{ params.timestamp }}' --skip-archive --yes" cli_command = BashOperator( task_id="bash_command", bash_command=bash_command )