매시간 추가로 쌓이는 작은 파일 압축하기
읽는 데 약 28분분 걸린다, 9절에 3개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.10판을 번역한 것이다. 원문 읽기
이 장에서는 테이블이 가진 데이터 파일의 수를 세는 방법과, Delta Lake, DuckLake, Iceberg에서 그 파일들을 더 적은 수의 파일로 병합하는 방법, 그리고 각 병합 후 디스크에 무엇이 남는지를 설명한다. 문제는 적재에서 시작된다. 첫 번째 장의 pageviews 테이블은 세 가지 형식 각각에 한 시간에 한 번씩 적재된다. 적재 한 번은 커밋 한 번이며, 커밋마다 고유한 데이터 파일이 새로 쓰인다. 데이터 파일은 테이블의 행을 담고 있는 Parquet 파일이다.
매시간 append하면 작은 파일이 남는다
행을 append하는 커밋은 매번 데이터 파일을 하나 이상 쓴다. 한 시간에 한 번 적재하는 테이블에는 하루에 데이터 파일이 24개 생기며, 각 파일에는 한 시간 분량의 행이 들어 있다. 여기서는 파일당 약 500행이다. 쿼리는 필터로 건너뛰지 못하는 모든 파일을 열어야 하고, 파일을 열 때마다 시간이 든다. 테이블의 메타데이터도 목록에 올리는 파일 수만큼 커진다. 각 포맷이 현재 버전이 사용하는 모든 데이터 파일의 기록을 유지하기 때문이다. 따라서 전체 행 수가 많지 않아도 작은 파일이 많으면 읽기와 계획 수립에 비용이 든다.
파일 수는 시간이 지날수록 늘어나므로 지켜봐야 할 수치다. 파일 크기도 중요하지만, 바이트 단위 크기는 실행할 때마다 달라지므로 이 책은 파일 크기를 출력하지 않는다. 파일 수를 세는 것은 컴팩션이 제대로 되었는지 확인하는 정직한 방법이기도 하다. 컴팩션 전후로 행은 같아야 하고, 파일 수는 줄어야 한다.
해결책은 컴팩션이다. 컴팩션은 작은 데이터 파일 여러 개를 더 적은 수의 큰 파일로 다시 쓴다. 컴팩션도 다른 커밋과 마찬가지로 하나의 커밋이다. 대체 파일을 쓰고, 메타데이터에 그 파일을 등록하며, 테이블의 이력이 여전히 참조하는 동안에는 기존 파일을 디스크에 남겨 둔다. 기존 파일을 언제 지울 수 있는지는 7장에서 다룬다.
세 포맷은 컴팩션을 호출하는 방법이 서로 다르다. 아래 표는 이 장에서 만드는 시간별 파일 여섯 개에 각 포맷이 한 일을 보여 준다.
| 포맷 | 호출 | 이전 파일 수 | 이후 파일 수 |
|---|---|---|---|
| Delta Lake | optimize.compact() |
6 | 1 |
| DuckLake | ducklake_merge_adjacent_files |
6 | 1 |
| Iceberg | table.overwrite(table.scan().to_arrow_batch_reader()) |
6 | 1 |
표의 수치는 각 예제가 출력한 값이다. 각 예제는 잘라 낸 데이터의 여섯 시간 분량을 시간당 한 번씩 파티션이 없는 테이블에 적재하므로, 각 포맷은 적재마다 데이터 파일 하나로 시작한다. 4장의 파티션 테이블은 다르게 동작할 것이다. 컴팩션을 지원하는 포맷에서는 파티션마다 따로 컴팩션하기 때문이다. 이 장에서는 파일 수의 원인이 하나만 되도록 테이블에 파티션을 두지 않는다.
DuckLake의 수치는 설정을 하나 더 해야 의미가 있다. 여기서 시간별 적재는 각각 약 500행이며, 이는 1장이 인라이닝 기준으로 제시한 행 수 한도를 넘는다. 따라서 기본 설정으로도 어차피 파일로 기록된다. 그래도 DuckLake 예제는 인라이닝을 끈 채로 연결한다. 그 장에서 설명한 설정이며, 파일 수가 적재 한 번에 우연히 몇 행이 들어 있는지와 무관하게 하기 위해서다.
작업 규칙: 적재할 때마다 각 테이블의 데이터 파일 수를 세고, 파일이 생기는 속도와 독자가 필요로 하는 파일 크기를 기준으로 컴팩션 일정을 잡는다. 매시간 적재하면 테이블당 하루에 파일이 24개 생기므로, 처음에는 하루에 한 번 컴팩션하는 것이 무난하다. 이것은 측정값이 아니라 경험칙이다. 실제 읽기 시간이나 파일 수가 필요성을 보여 줄 때에만 더 자주 컴팩션한다.
optimize.compact()로 압축하기
Delta Lake는 위 표에 나온 세 형식 가운데 첫 번째이다. Delta Lake의 deltalake 라이브러리는 압축을 테이블의 optimize 속성에 둔다. 이 속성의 compact() 메서드는 테이블의 작은 데이터 파일들을 더 큰 파일로 다시 쓰고, 지표를 담은 딕셔너리를 반환한다. 이 딕셔너리에는 추가된 파일과 제거된 파일의 개수, 그리고 이 책이 출력하지 않는 크기 필드가 들어 있다.
여섯 시간 분량을 Delta 테이블에 시간마다 한 번씩 추가해 적재한 뒤, 테이블이 나열하는 파일을 세고, 압축하고, 다시 센다. 각 개수는 테이블의 현재 버전에 대한 자체 파일 목록에서 얻는다.
1"""Load six hourly appends into a Delta Lake table, compact it, and count its files and rows before and after.2The point rests on the file-count lines, and on the row count read from the version before the compaction."""34from deltalake import DeltaTable, write_deltalake56from lib.lakehouse import delta_file_count, new_warehouse, read_cut_hour, read_delta789def main():10 with new_warehouse() as wh:11 path = str(wh.root / "delta" / "pageviews_hourly")12 for hour in range(6):13 write_deltalake(path, read_cut_hour(hour), mode="append")1415 table = DeltaTable(path)16 version_before = table.version() # the version the read at the end goes back to17 print(f"files before compaction: {delta_file_count(table)}") # counts the files this version lists, not the disk1819 metrics = table.optimize.compact() # a dict; numFilesAdded and numFilesRemoved are the two counts printed below20 print(f"files added by compaction: {metrics['numFilesAdded']}")21 print(f"files removed by compaction: {metrics['numFilesRemoved']}")2223 table = DeltaTable(path)24 print(f"files after compaction: {delta_file_count(table)}")25 print(f"rows after compaction: {len(read_delta(path))}")26 before = read_delta(path, version=version_before)27 print(f"rows at the version before compaction: {len(before)}")28 parquet = list((wh.root / "delta").rglob("*.parquet")) # every file on disk, including ones the current version dropped29 print(f"parquet files on disk after compaction: {len(parquet)}")303132if __name__ == "__main__":33 main()
python file-counts-before-after.pyfiles before compaction: 6
files added by compaction: 1
files removed by compaction: 6
files after compaction: 1
rows after compaction: 2999
rows at the version before compaction: 2999
parquet files on disk after compaction: 7
압축은 행이 아니라 파일을 바꾼다. 테이블은 호출 전에 데이터 파일 6개를, 호출 후에 1개를 나열하며, 현재 버전을 읽으면 2999개 행이 반환된다. 행은 이전과 같고 파일만 줄었다.
호출이 반환하는 지표도 같은 변화를 라이브러리 쪽에서 센 것이다. 추가된 파일은 1개, 제거된 파일은 6개이다.
압축은 이전 파일을 지우지 않았다. 호출 이전의 버전으로 읽으면 테이블은 여전히 2999개 행을 모두 반환한다. 그 버전이 이전 파일을 가리키고 있기 때문이다. 호출 후 디렉터리에는 Parquet 파일이 7개 있다. 이전 파일 여섯 개와 새 파일 한 개이다. Delta Lake는 보존 중인 어떤 버전도 사용하지 않는 파일을 vacuum라는 별도 단계에서 제거하며, 이 단계는 7장에서 다룬다. 그 단계가 실행되기 전까지 압축은 디스크의 파일을 줄이지 못하고 파일을 추가할 뿐이다.
여기서 Delta 읽기는 이 책의 모든 Delta 읽기와 마찬가지로 라이브러리의 쿼리 빌더를 거친다. 요점이 파일 수이므로 행은 개수만으로 비교한다.
작업 규칙: Delta 테이블은 첫 번째 절에서 정한 주기(시간 단위 적재라면 매일)에 맞추어 압축하고, 그 뒤에 파일 수를 확인한다. 무언가를 제거하기 전에 7장의 보존 규칙을 읽는다. 압축은 커밋을 하나 추가하고 이전 파일은 그대로 두므로, vacuum이 실행되기 전까지는 저장 공간이 늘어난다.
DuckLake의 컴팩션
DuckLake는 SQL에서 호출하는 유지 관리 함수로 컴팩션을 제공한다. 이 함수는 호출 한 번으로 실행되며, 병합한 각 테이블에 대해 무엇을 했는지 알려 주는 행을 반환한다. 다음 부분에서는 이 함수와 함수가 건너뛰는 한 가지 경우를 설명한다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Merge adjacent files
ducklake_merge_adjacent_files takes a catalog, and optionally a table name and a schema name, which the call needs when the table is not in the main schema. Without a table name it merges the files of every table. The DuckLake documentation says the function can "merge multiple Parquet files into a single Parquet file that holds data inserted by multiple snapshots" (DuckLake documentation: Merge Files). The merge also works without expiring snapshots, and it does not delete the old files at once. Both points matter for the rest of this chapter. Because the merge does not expire snapshots, every older snapshot still refers to the old files.
What does the merge leave for a snapshot from before it? The example below reads one. It attaches the catalog with inlining off, inserts the six hours one insert each, and calls the merge once. The table lives in the wiki schema, so the call names it. It reads the snapshot number before the merge, so it can read the table as it was at that point.
1"""Merge six DuckLake data files, then read a snapshot from before the merge to see what the merge left behind.2The point rests on the data-file lines, and on the row count read at the earlier snapshot."""34from lib.lakehouse import (5 DUCKLAKE_ALIAS,6 NAMESPACE,7 TABLE,8 connect_ducklake,9 create_ducklake_table,10 ducklake_file_count,11 new_warehouse,12 read_cut_hour,13)141516def main():17 with new_warehouse() as wh:18 lake = connect_ducklake(wh.con)19 create_ducklake_table(lake, wh.root) # inlining is off here, so every insert writes a data file20 table = f"{DUCKLAKE_ALIAS}.{NAMESPACE}.{TABLE}"21 for hour in range(6):22 lake.register("hour", read_cut_hour(hour))23 lake.execute(f"INSERT INTO {table} SELECT * FROM hour")24 lake.unregister("hour")25 # the newest snapshot before the merge, which the read at the end goes back to26 before = lake.execute(f"SELECT max(snapshot_id) FROM ducklake_snapshots('{DUCKLAKE_ALIAS}')").fetchall()[0][0]27 print(f"data files before merge: {ducklake_file_count(lake, DUCKLAKE_ALIAS, TABLE)}")2829 # the schema is named because the table is not in main; the call returns one row30 result = lake.execute(31 f"CALL ducklake_merge_adjacent_files('{DUCKLAKE_ALIAS}', '{TABLE}', schema => '{NAMESPACE}')"32 ).fetchall()33 # the row's fields: schema, table, files merged, files created34 print(f"files merged: {result[0][2]}")35 print(f"files created: {result[0][3]}")36 print(f"data files after merge: {ducklake_file_count(lake, DUCKLAKE_ALIAS, TABLE)}")37 print(f"rows after merge: {lake.execute(f'SELECT count(*) FROM {table}').fetchall()[0][0]}")38 old = lake.execute(f"SELECT count(*) FROM {table} AT (VERSION => {before})").fetchall()[0][0]39 print(f"rows at the snapshot before merge: {old}")40 # every Parquet file under the data path, including the ones the table no longer lists41 parquet = list((wh.root / f"{DUCKLAKE_ALIAS}_data").rglob("*.parquet"))42 print(f"parquet files on disk after merge: {len(parquet)}")434445if __name__ == "__main__":46 main()
python compact-ducklake.pydata files before merge: 6
files merged: 6
files created: 1
data files after merge: 1
rows after merge: 2999
rows at the snapshot before merge: 2999
parquet files on disk after merge: 7
The merge's result row says what it did: 6 files merged into 1 file. The table lists 1 data file afterwards, down from 6. The row also names the schema and the table, so a merge aimed at the wrong table shows before anything else is read.
The old snapshot still reads. A count taken at the snapshot before the merge returns 2999 rows, the same count the current table returns. The Parquet files on disk number 7, the six the inserts wrote and the one the merge wrote. The six old files stay on disk until the cleanup in chapter 7 removes them.
The merge skips a file that has a delete file attached. A delete file is a record of deleted rows, which DuckLake writes instead of rewriting the data file when rows are deleted. Chapter 5 writes delete files in DuckLake, so this limit applies there. The DuckLake documentation names ducklake_rewrite_data_files as the call that rewrites those files, and its default delete_threshold is 0.95, which rewrites a file only when that share of its rows is deleted (DuckLake documentation: Rewrite Files with Deletes). The default is a value you should choose for your own data, not accept without a look.
Working rule: Run ducklake_merge_adjacent_files after the inserts for a period are done, and read the file count it returns. A merge does not remove deleted rows, so for a table with delete files, call ducklake_rewrite_data_files with a delete_threshold that you chose for that table, and check the result.
테이블을 다시 써서 압축하기
pyiceberg의 고정된 버전에서 Iceberg의 압축은 덮어쓰기를 통한 재작성이다. 이 장에서는 테이블 전체를 다시 쓰는데, 이는 파티션이 없는 테이블에 해당하는 경우다. 스캔으로 테이블을 읽고, 스캔이 반환한 행으로 테이블을 덮어쓴다. 덮어쓰기는 그 행을 대체 데이터 파일로 쓰고, 이전 파일은 현재 스냅샷에서 빠진다. 이 방법은 이 책에서 Iceberg에 대해 다루는 유일한 압축 경로이며, 없는 호출을 대신하는 우회 방법이다. 이에 대해서는 다음 부분에서 설명한다.
재작성은 그 결과로 남은 것을 보고 판단한다. 아래 검사는 추가 6번과 덮어쓰기 1번을 거친 뒤 테이블의 파일과 행을 읽고, 재작성 이전의 스냅샷도 읽는다.
1"""Rewrite an unpartitioned Iceberg table by overwriting it with its own scan, then check its data files, its snapshot2history and a snapshot from before the rewrite. The point rests on the data-file lines and on the row count of snapshot 6."""34from lib.lakehouse import (5 create_iceberg_table,6 iceberg_file_count,7 new_warehouse,8 read_cut_hour,9 scan_arrow,10 snapshot_labels,11)121314def main():15 with new_warehouse() as wh:16 table = create_iceberg_table(wh)17 for hour in range(6):18 table.append(read_cut_hour(hour))19 last_append = table.current_snapshot().snapshot_id # the snapshot after the sixth append20 print(f"data files before rewrite: {iceberg_file_count(table)}")2122 # a batch reader, so the rows are not all read into one Arrow table first23 table.overwrite(table.scan().to_arrow_batch_reader())24 print(f"data files after rewrite: {iceberg_file_count(table)}")25 print(f"rows after rewrite: {len(scan_arrow(table))}")2627 # sorted by sequence number, which puts the snapshots in commit order28 snapshots = sorted(table.snapshots(), key=lambda snapshot: snapshot.sequence_number)29 # labels count up in commit order, so the sixth append is snapshot 630 labels = snapshot_labels([snapshot.snapshot_id for snapshot in snapshots])31 operations = [snapshot.summary.operation.value for snapshot in snapshots]32 print("snapshot operations in order: " + ", ".join(operations))33 print(f"{labels[last_append]} rows: {len(scan_arrow(table, snapshot_id=last_append))}")34 # every Parquet file in the warehouse, including those that only older snapshots still hold35 parquet = list((wh.root / "warehouse").rglob("*.parquet"))36 print(f"parquet files on disk after rewrite: {len(parquet)}")373839if __name__ == "__main__":40 main()
python iceberg-rewrite-by-overwrite.pydata files before rewrite: 6
data files after rewrite: 1
rows after rewrite: 2999
snapshot operations in order: append, append, append, append, append, append, delete, append
snapshot 6 rows: 2999
parquet files on disk after rewrite: 7
데이터 파일은 6개에서 1개로 줄어들며, 테이블의 독자는 더 적은 파일에서 같은 방식으로 읽어 같은 2999개의 행을 얻는다. 재작성은 스냅샷 두 개를 추가하는 하나의 커밋이다. 커밋 순서대로 나열한 작업은 추가 6번에 이어 delete와 append이다. delete 스냅샷은 테이블에서 모든 데이터 파일을 제거하고, append 스냅샷은 다시 쓴 파일을 추가한다. 현재 스냅샷은 한 번만 이동하므로 어떤 독자도 빈 테이블을 보지 않지만, 이력에는 두 스냅샷이 모두 남는다. 이처럼 파일 전체를 삭제하는 것은 5장에서 Iceberg 삭제에 대해 설명한 copy-on-write 동작이다.
재작성 이전의 스냅샷은 여전히 모든 행을 읽는다. 레이블은 커밋 순서대로 스냅샷에 번호를 매기므로, 스냅샷 6은 재작성 직전의 마지막 추가다. 이 스냅샷에서 읽으면 테이블은 여전히 2999개의 행을 반환한다. 디스크에 있는 Parquet 파일은 7개이며, 이는 이전 파일 여섯 개와 재작성이 쓴 파일 하나다. 이전 스냅샷을 만료시키는 방법과 그 스냅샷이 아직 보유한 것을 세는 방법은 7장에서 다룬다.
작업 규칙: Iceberg 테이블은 재작성하는 동안 다른 어떤 작성자도 그 테이블에 커밋하지 않을 때에만 덮어쓰기로 다시 쓴다. 파티션이 없는 테이블에서는 이 예제처럼 스캔을 스트리밍한다. 파티션이 있는 테이블에서는 스캔을 to_arrow()로 읽어야 하므로, 스캔 전체가 작업의 메모리에 들어가야 한다. 스트리밍 리더는 한 번만 읽을 수 있다. 커밋이 실패하면 다음 시도를 위해 새 리더를 만든다. 재작성할 때마다 파일 수와 행 수를 확인하고, 결과를 확인할 때까지는 재작성 이전의 스냅샷을 보관한다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Why pyiceberg has no rewrite call
The pyiceberg API documentation lists overwrite among its table operations (PyIceberg API documentation). Its one sentence on compaction is in the note on fast appends, and it is about metadata: the page says that metadata compaction is planned. It says nothing about data files. Its only maintenance call is expire_snapshots, which chapter 7 covers. The source of pyiceberg 0.12.0, in pyiceberg/table/__init__.py, has no method that compacts or rewrites data files. Its write operations are append, overwrite, delete, upsert, dynamic_partition_overwrite and add_files. Every one except add_files writes data files, and add_files registers files that already exist and writes none. dynamic_partition_overwrite, and overwrite with an overwrite_filter, can replace the rows of one partition, so a partitioned table can be rewritten one partition at a time. A compaction is therefore a rewrite built from those operations.
The rewrite has a memory cost that the file counts do not show, and the way the scan is read decides it. table.scan().to_arrow() reads the whole current snapshot into one Arrow table in memory before the overwrite starts. The rewrite above passes table.scan().to_arrow_batch_reader() instead, and pyiceberg documents that a streamed overwrite is microbatched by write.target-file-size-bytes, so its memory stays bounded. Streaming works only on unpartitioned tables, which this chapter uses. A partitioned table has to be read with to_arrow(), so memory must hold all of its rows at once. The bound is pyiceberg's documented behaviour, not a measurement made here.
The rewrite also reads every file and writes every file, including the ones that were already large enough. A table whose files are mostly the right size gets no benefit from it. This is the reason to use it only when the file count has grown and the table fits in memory.
Working rule: Check the pyiceberg release notes at each upgrade for a compaction call, because a call would replace the overwrite rewrite in this chapter. Until then, treat the overwrite as a batch job, run it when no other writer is committing, and for a partitioned table budget memory for the whole scan.
압축을 신뢰하기 전에 매번 확인한다
이 장의 예제들은 모두 합쳐 네 가지를 출력하며, 이 네 가지가 어떤 압축을 실행하든 그 뒤에 확인해야 할 항목이다. 첫째는 테이블 자체의 목록에서 얻은 파일 수다. 둘째는 현재 버전의 행 수이며, 압축 전의 행 수와 일치해야 한다. 셋째는 압축 이전 버전 또는 스냅샷의 행 수이며, 여전히 읽혀야 한다. 넷째는 테이블 위치 아래에 있는 Parquet 파일의 수이며, 파일 수보다 정리를 기다리는 이전 파일의 수만큼 많아야 한다.
처음 두 가지 확인은 압축이 주장한 대로 동작했고 행을 바꾸지 않았음을 보여 준다. 셋째 확인은 이력이 여전히 동작함을 보여 주며, 이전 버전을 고정해 두고 읽는 독자에게 중요하다. 넷째 확인은 압축이 디스크에 무엇을 남겼는지 보여 준다. 첫째와 넷째는 서로 다른 곳에서 얻으며, 이 책의 예제는 두 값을 모두 출력한다. 그래서 불일치가 하나의 숫자 속에 숨지 않고 출력에 드러난다. 넷째 값은 DuckLake 테이블에서는 7이고 Iceberg 테이블에서는 7이며, 각각 목록에 남아 있는 파일보다 하나씩 많다. 처음 세 가지 확인을 통과한 압축은 이런 수치 때문에 잘못이라고 할 수 없다. 남은 여분의 파일은 7장에서 정리하는 대상이다.
라이브러리마다 고유한 파일 목록이 있다. Delta 예제는 현재 버전의 URI를 세고, DuckLake 예제는 카탈로그에 테이블의 파일을 묻고, Iceberg 예제는 테이블의 파일 점검 항목을 센다. 이 세 숫자는 메타데이터에서 읽으므로 두 번째 출처인 디렉터리 목록에 의존하지 않는다. 두 출처가 일치하지 않으면 (파일 수가 예상한 차이와 다르면) 멈추고 다음 압축을 실행하기 전에 원인을 찾는다.
확인에 실패하면 작업을 중단하고 테이블을 그대로 둔다. 첫 번째 압축을 고치려고 두 번째 압축을 실행하지 않는다. 실행할 때마다 커밋이 생기므로 두 번째 실행은 이력을 읽기 더 어렵게 만든다. 테이블의 이력에서 커밋을 순서대로 읽고, 행 수를 바꾼 커밋을 찾아 그다음 대응을 결정한다. 오류 이전의 상태는 테이블이 아직 그것을 담고 있을 때 더 쉽게 살펴볼 수 있다.
작업 규칙: 압축할 때마다 행 수를 압축 이전의 행 수와 비교하고, 압축 이전의 버전 하나를 읽어 본다. 행 수를 바꾸는 압축은 그 테이블에서 다른 어떤 작업을 실행하기 전에 고쳐야 할 오류다.
운영 환경에서 무엇이 잘못되는가
저장 공간은 줄어들기 전에 먼저 늘어난다. 이 장의 모든 컴팩션은 교체용 파일을 새로 쓰고 기존 파일은 디스크에 남겨 둔다. 파일 수가 이를 보여 준다. DuckLake 병합 후 테이블은 데이터 파일을 1개로 나열하지만 디스크에는 Parquet 파일이 7개 남아 있고, Iceberg 재작성 후 테이블은 1개로 나열하지만 디스크에는 7개가 남아 있다. 만료 단계 없이 컴팩션만 실행하면 저장 비용은 이전보다 높아진다. 만료와 정리를 컴팩션과 함께 계획하고, 둘을 모두 마친 뒤에 디스크를 측정한다. 실행할 때마다 디스크는 커지는데 테이블의 행 수와 파일 수는 그대로라면 이 문제가 생긴 것이다.
삭제된 행은 재작성으로 처리하기 전까지 남아 있다. 병합 절에서 보았듯이 DuckLake 병합은 삭제 파일이 있는 파일을 건너뛴다. 삭제가 있는 테이블을 병합만 하면 그 파일들은 그대로 남는다. 이런 파일에는 ducklake_rewrite_data_files를 사용하되, 임계값은 직접 정한다. 병합만으로는 삭제된 행이 파일 안에 여전히 있다는 사실이 드러나지 않으므로 전후의 행 수를 측정한다. 병합할 때마다 삭제 파일이 있는 파일의 수가 변하지 않는지 지켜본다.
동시 쓰기 작업은 여기서 검증하지 않았다. 이 장의 예제는 한 번에 하나의 작성자만 실행하며, 커밋과 겹치는 컴팩션은 시험하지 않는다. 겹치는 경우는 사용하는 엔진에서 직접 시험하고, 그 시험을 마치기 전까지는 어떤 작성자도 커밋하지 않는 시간대에 컴팩션을 예약한다. 세 가지 중에서는 Iceberg 재작성이 가장 위험하다. 테이블 전체를 읽은 다음 다시 써야 하기 때문이다. 겹침이 실패하면 작성자나 컴팩션 쪽에서 오류가 나타나겠지만, 이 책은 그런 오류를 재현하지 못했다.
너무 자주 하면 커밋 비용이 들고, 너무 드물게 하면 읽기 비용이 든다. 컴팩션 한 번은 곧 커밋 한 번이며, 커밋마다 메타데이터가 늘어난다. 적재할 때마다 컴팩션하면 적재 한 번당 커밋 수가 두 배가 된다. 한 달에 한 번 컴팩션하면 작은 파일이 한 달 동안 쌓인다. 앞의 경우는 커밋 수가 적재 횟수보다 빠르게 늘어나는 모습으로, 뒤의 경우는 파일 수에 따라 쿼리 시간이 늘어나는 모습으로 나타난다. 이는 자신의 테이블에서 측정해야 하는 절충이며, 예제가 증명하는 규칙이 아니다.
파일 수 목표는 파일 크기 목표가 아니다. 매우 큰 파일 하나는 읽는 쪽에 병렬로 처리할 작업을 줄이고, 파일 수준 통계로 가지치기할 수 있는 파일도 줄인다. 이 예제들은 파일 수를 목표로 삼으며 파일 크기는 출력하지 않는다. 이는 읽는 쪽에 대한 판단이므로 목표는 해당 테이블을 읽는 쪽의 쿼리 시간으로 정해야 한다. 매우 큰 파일 하나를 만든 컴팩션 뒤에 쿼리 시간이 나빠지면 경고 신호다.
작업 규칙: 컴팩션은 만료 및 정리와 따로 두지 말고 함께 예약한다. 매번 실행한 뒤 점검 절의 네 가지 점검을 수행하고, 행 수가 바뀌거나 동시 작성자가 실패하면 예약을 중단한다.
이 장에서 내린 결정
- 각 포맷은 해당 라이브러리의 호출을 사용하며, 이 장의 어떤 예제도 Iceberg나 Delta Lake용 DuckDB 확장을 사용하지 않는다. 읽기와 쓰기는 Python 라이브러리와 DuckDB의 DuckLake 지원을 거치므로, 각 개수는 파일을 쓴 도구에서 나온다.
- DuckLake 예제는 데이터 인라이닝을 끈 상태로 연결한다. 인라이닝을 끄면 적재 크기와 관계없이 모든 개수가 파일 개수가 된다.
- 파일 개수는 각 라이브러리가 제공하는 파일 목록에서 얻는다. 디스크의 Parquet 개수는 두 번째 확인 수단이며, 파일 크기는 출력하지 않는다.
- 테이블은 파티션을 나누지 않았으므로 각 개수의 원인은 적재 횟수 하나뿐이다. 파티션을 나눈 경우는 파티션 진화를 다루는 장에서 다룬다.
- pyiceberg 0.12.0에는 컴팩션 호출이 없으므로 Iceberg 컴팩션은 덮어쓰기에 의한 재작성으로 수행한다. 이 재작성은 스캔을 스트리밍하며, pyiceberg는 파티션을 나누지 않은 테이블에서 이를 허용한다. 이 장은 이 우회 방법과, 파티션을 나눈 테이블에 여전히 남는 메모리 비용을 밝힌다.
- 이 장에서는 스냅숏을 만료시키거나 파일을 제거하지 않는다. 7장에서 두 작업을 모두 수행하며, 이 장의 개수가 그 작업의 출발점이 된다.
- 작업 규칙의 일정은 출발점이다. 적절한 간격은 테이블에 파일이 도착하는 속도와 테이블을 읽는 쪽(리더)이 파일에 요구하는 크기에 따라 달라지므로, 이 책은 최적의 간격을 주장하지 않는다.
이 판의 이 장
2026.11.10판예제 통과 2026년 11월 20이 장에서 3개 예제개 중 3개가 통과한다
영어판 2026.11.10판을 번역한 것이다.