Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): configure events backfill row groups (#73383)

Bill Guowei Yangb71db96f4e2f
diff --git a/posthog/dags/README_DUCKLINGS.md b/posthog/dags/README_DUCKLINGS.md
index a13359a498a0..1b3b5d4a8c7b 100644
--- a/posthog/dags/README_DUCKLINGS.md
+++ b/posthog/dags/README_DUCKLINGS.md
@@ -85,6 +85,27 @@ To run the full backfill immediately (without waiting for tomorrow):
- `skip_ducklake_registration: true` - Export to S3 only
- `delete_tables: true` - Reset duckling tables first
+#### Rewriting one events day with larger Parquet row groups
+
+Select exactly one daily `<team_id>_YYYY-MM-DD` partition in `duckling_events_backfill_job`, then use this Launchpad configuration:
+
+```yaml
+ops:
+ duckling_events_backfill:
+ config:
+ events_parquet_row_group_size_bytes: 536870912 # 512 MiB
+ target_rows_per_file: 5000000
+ cleanup_existing_partition_data: true
+ skip_ducklake_registration: false
+ delete_tables: false
+```
+
+The 250,000-row target still applies. ClickHouse closes a row group when either the row or byte target is reached, so wide rows may reach the byte target first. The exporter limits fan-out automatically so `fan-out × events_parquet_row_group_size_bytes` does not exceed the nominal 32 GiB row-group buffer budget. A 512 MiB target therefore allows at most 64 writers. The day's row count and `max_s3_file_fanout` can reduce it further. Encoding and other query memory are not included in the 32 GiB estimate; ClickHouse's `max_memory_usage` remains the hard query limit.
+
+The rewrite is not atomic. The existing DuckLake day is removed before export and registration finish, so queries may temporarily see no rows for that day. After a transient failure, rerun the same daily partition with the same configuration. After a memory or resource failure, lower `max_s3_file_fanout` and rerun. Keep `cleanup_existing_partition_data: true` so the retry clears partial registration and regenerates the day from current ClickHouse data. Do not manually delete the run's S3 objects.
+
+To rewrite the active DuckLake day with the default layout, rerun the same day without the row-group and fan-out overrides. This regenerates the day from current ClickHouse data; it does not restore a pinned snapshot or remove old unreferenced run objects from S3.
+
### Resetting a Duckling
To completely reset a duckling's data and re-backfill:
@@ -104,6 +125,9 @@ class DucklingBackfillConfig:
create_tables_if_missing: bool = True # Auto-create events/persons tables
delete_tables: bool = False # DANGER: Drop and recreate tables
dry_run: bool = False # Preview mode, no writes
+ events_parquet_row_group_size_bytes: int = 134_217_728 # Events only; 128 MiB
+ target_rows_per_file: int = 5_000_000 # Target rows per exported file
+ max_s3_file_fanout: int = 256 # Maximum before the automatic buffer-budget limit
```
## Adding a New Duckling
@@ -166,9 +190,10 @@ ClickHouse `PARTITION BY` bucket) instead of one giant per-day object, so reads
parallelism and per-file scans stay cheap. The fan-out is **computed per export** from
a cheap `count()` estimate — `ceil(row_count / target_rows_per_file)`, clamped to
`[1, max_s3_file_fanout]` — so a tens-of-millions-of-rows team-day spreads across many
-~GB-scale files while a tiny team-day stays a single file. Both knobs are tunable per
-run via `DucklingBackfillConfig` (`target_rows_per_file`, `max_s3_file_fanout`). The
-`{_partition_id}` is the bucket id (`0 … fanout-1`); registration globs
+~GB-scale files while a tiny team-day stays a single file. Events exports apply one
+more limit: `floor(32 GiB / events_parquet_row_group_size_bytes)`, which keeps the
+nominal row-group staging buffers within budget. These settings are tunable per run
+via `DucklingBackfillConfig`. The `{_partition_id}` is the bucket id (`0 … fanout-1`); registration globs
`{run_id}_*.parquet` to enumerate every file a run produced.
```text
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.py
index 2f0271c1ed69..02509685a740 100644
--- a/posthog/dags/events_backfill_to_duckling.py
+++ b/posthog/dags/events_backfill_to_duckling.py
@@ -45,6 +45,7 @@ from django.db import DatabaseError
from django.utils import timezone
import psycopg
+import pydantic
import structlog
from clickhouse_driver import Client
from clickhouse_driver.errors import Error as ClickHouseError
@@ -636,23 +637,27 @@ BACKFILL_PERSONS_S3_PREFIX = "backfill/persons"
# MAX_S3_FILE_FANOUT is bounded by WRITER MEMORY, not file count: ClickHouse's
# PartitionedSink keeps one Parquet writer open per active bucket for the whole
# INSERT (a footer is written only at stream close), and a uniform hash key activates
-# all N buckets at once. Each writer buffers at most one in-progress row group, so
-# peak ≈ N × output_format_parquet_row_group_size_bytes (× parallel-encoding
-# overhead). With that byte cap pinned to 128 MiB (see PARQUET_WRITER_SETTINGS),
-# 256 × 128 MiB ≈ 32 GiB stays comfortably under the 100 GiB max_memory_usage ceiling.
+# all N buckets at once. Each writer stages an in-progress row group, while parallel
+# encoding can retain additional groups and buffers. N × the row-group byte target
+# is therefore a nominal staging baseline, not a total-memory bound. Events fan-out
+# is automatically limited to keep that baseline within 32 GiB; ClickHouse's 100 GiB
+# max_memory_usage remains the hard query limit.
# N may exceed ClickHouse's max_partitions_per_insert_block (default 100) safely —
# that limit gates MergeTree part creation, not the s3() PartitionedSink.
TARGET_ROWS_PER_FILE = 5_000_000
MAX_S3_FILE_FANOUT = 256
-# Parquet writer settings shared by every export. The byte cap is the load-bearing one:
-# it bounds each open partition writer's in-progress row group, so aggregate writer
-# memory scales as fan-out × this value (see MAX_S3_FILE_FANOUT). For wide event rows it
-# is also the binding row-group flush trigger (the row pin below only binds for the
-# narrower persons rows, which flush on rows first). 128 MiB row groups stay large enough
-# for efficient DuckLake/DuckDB reads while keeping high-fan-out writes within budget.
+DEFAULT_PARQUET_ROW_GROUP_SIZE_BYTES = 128 * 1024 * 1024
+EVENTS_PARQUET_ROW_GROUP_BUFFER_BUDGET_BYTES = 32 * ONE_GB_IN_BYTES
+
+# Parquet writer defaults shared by every export. The byte target sets the nominal size
+# of each open partition writer's staging row group, so baseline memory scales as fan-out
+# × this value (see MAX_S3_FILE_FANOUT). For wide event rows it is also the binding
+# row-group flush trigger (the row target below only binds for narrower persons rows).
+# Events may override the byte target through DucklingBackfillConfig; persons always use
+# this default.
PARQUET_WRITER_SETTINGS: dict[str, Any] = {
- "output_format_parquet_row_group_size_bytes": 128 * 1024 * 1024, # 128 MiB — bounds per-partition writer memory
+ "output_format_parquet_row_group_size_bytes": DEFAULT_PARQUET_ROW_GROUP_SIZE_BYTES,
"output_format_parquet_row_group_size": 250_000, # secondary cap; binds for narrow persons rows
}
@@ -825,16 +830,28 @@ class DucklingBackfillConfig(Config):
create_tables_if_missing: bool = True
delete_tables: bool = False # Danger: drops and recreates tables, losing all data
dry_run: bool = False
+ events_parquet_row_group_size_bytes: int = pydantic.Field(
+ default=DEFAULT_PARQUET_ROW_GROUP_SIZE_BYTES,
+ gt=0,
+ description="Uncompressed byte target for each Parquet row group written by the events export.",
+ )
# Dynamic S3 fan-out: each export is split into ~ceil(row_count / target_rows_per_file)
- # Parquet files, clamped to [1, max_s3_file_fanout]. Huge team-days produce many
- # right-sized files; tiny ones stay a single file. The fan-out also drives writer
- # memory (peak ≈ fan-out × per-partition row-group buffer; see PARQUET_WRITER_SETTINGS),
- # so for teams with unusually wide rows, lowering target_rows_per_file both keeps files
- # in range AND raises fan-out — pair it with a lower max_s3_file_fanout if memory is tight.
+ # Parquet files, capped by max_s3_file_fanout and the nominal row-group buffer budget.
+ # Huge team-days produce many right-sized files; tiny ones stay a single file.
target_rows_per_file: int = TARGET_ROWS_PER_FILE
max_s3_file_fanout: int = MAX_S3_FILE_FANOUT
+def _events_row_group_buffer_fanout_limit(config: DucklingBackfillConfig) -> int:
+ fanout_limit = EVENTS_PARQUET_ROW_GROUP_BUFFER_BUDGET_BYTES // config.events_parquet_row_group_size_bytes
+ if fanout_limit < 1:
+ raise ValueError(
+ "one events Parquet writer exceeds the 32 GiB nominal row-group buffer budget; "
+ "lower events_parquet_row_group_size_bytes"
+ )
+ return fanout_limit
+
+
def parse_partition_key(key: str) -> tuple[int, str]:
"""Parse a partition key into team_id and date.
@@ -1471,6 +1488,10 @@ def export_events_to_duckling_s3(
Returns:
S3 glob matching every file this run produced for the day, or None if dry_run.
"""
+ row_group_buffer_fanout_limit = _events_row_group_buffer_fanout_limit(config)
+ configured_max_fanout = max(1, config.max_s3_file_fanout)
+ effective_max_fanout = min(configured_max_fanout, row_group_buffer_fanout_limit)
+
year = date.strftime("%Y")
month = date.strftime("%m")
day = date.strftime("%d")
@@ -1497,12 +1518,12 @@ def export_events_to_duckling_s3(
where_clause = f"team_id = {team_id} AND toDate(timestamp) = '{date_str}'"
# Event rows are wide (large properties/person_properties JSON). With PARTITION BY,
- # writer memory is dominated by the per-partition row-group buffers (one open writer
- # per active bucket), so we cap the row group by bytes via PARQUET_WRITER_SETTINGS;
- # the 100 GiB ceiling is headroom on top. See the PARQUET_WRITER_SETTINGS /
- # MAX_S3_FILE_FANOUT comments for the fan-out × buffer memory model.
+ # writer memory includes one row-group staging buffer per active bucket, so the byte
+ # target also derives an automatic fan-out limit. ClickHouse's 100 GiB ceiling covers
+ # encoding and other query memory beyond that nominal baseline.
export_settings = settings.copy()
export_settings.update(PARQUET_WRITER_SETTINGS)
+ export_settings["output_format_parquet_row_group_size_bytes"] = config.events_parquet_row_group_size_bytes
export_settings["max_memory_usage"] = 100 * 1024 * 1024 * 1024 # 100GB, matching the full-persons export
info = f"team_id={team_id}, date={date_str}"
@@ -1510,13 +1531,20 @@ def export_events_to_duckling_s3(
if config.dry_run:
context.log.info(
f"[DRY RUN] Would estimate row count for {info} and fan the export across up to "
- f"{config.max_s3_file_fanout} files (~{config.target_rows_per_file} rows/file) to {s3_glob}"
+ f"{effective_max_fanout} files (~{config.target_rows_per_file} rows/file) to {s3_glob}"
)
return None
# Size the fan-out to this team-day's actual volume.
row_count = _estimate_export_row_count(client, f"SELECT count() FROM events WHERE {where_clause}", settings)
- fanout = _compute_fanout(row_count, config.target_rows_per_file, config.max_s3_file_fanout)
+ configured_fanout = _compute_fanout(row_count, config.target_rows_per_file, configured_max_fanout)
+ fanout = min(configured_fanout, row_group_buffer_fanout_limit)
+
+ if fanout < configured_fanout:
+ context.log.info(
+ f"Limiting events export fan-out from {configured_fanout} to {fanout} writers "
+ "to fit the nominal row-group buffer budget"
+ )
# ClickHouse uses its EC2 instance role - no credentials needed
# The duckling bucket policy allows the ClickHouse EC2 role
@@ -1541,6 +1569,12 @@ def export_events_to_duckling_s3(
s3_glob=s3_glob,
row_count=row_count,
fanout=fanout,
+ configured_fanout=configured_fanout,
+ configured_max_fanout=configured_max_fanout,
+ row_group_buffer_fanout_limit=row_group_buffer_fanout_limit,
+ effective_max_fanout=effective_max_fanout,
+ row_group_target_bytes=config.events_parquet_row_group_size_bytes,
+ nominal_row_group_buffer_bytes=fanout * config.events_parquet_row_group_size_bytes,
)
try:
@@ -2379,6 +2413,8 @@ def _run_duckling_events_backfill(context: AssetExecutionContext, config: Duckli
b. Exports events to the duckling's S3 bucket (ClickHouse EC2 role has bucket access)
c. Registers the Parquet file with the duckling's DuckLake catalog (via cross-account role)
"""
+ _events_row_group_buffer_fanout_limit(config)
+
team_id, dates = parse_partition_key_dates(context.partition_key)
# 16 hex chars (64 bits): the file prefix that scopes each run's glob. The exactly-once
# guarantee is the ranged DELETE, not prefix uniqueness, but a wider prefix makes a
diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.py
index 06fbb27f09b6..4b7d367bec31 100644
--- a/posthog/dags/test_events_backfill_to_duckling.py
+++ b/posthog/dags/test_events_backfill_to_duckling.py
@@ -40,6 +40,7 @@ from posthog.dags.events_backfill_to_duckling import (
_is_transient_s3_error,
_resolve_duckling_target,
_resolve_table_names,
+ _run_duckling_events_backfill,
_set_table_partitioning,
_stale_run_outcome,
_validate_identifier,
@@ -1725,7 +1726,7 @@ class TestExportFanOut:
def target(self):
return DucklingTarget(team_id=2, organization_id="org-1", bucket="bkt", bucket_region="us-east-1")
- def _run_export(self, export_fn, target, row_count, config=None, **kwargs):
+ def _run_export(self, export_fn, target, row_count, config=None, settings=None, **kwargs):
"""Run an export with a stubbed count() result; return (insert_sql, glob, client)."""
client = MagicMock()
# First execute is the count() estimate, second is the INSERT.
@@ -1736,7 +1737,7 @@ class TestExportFanOut:
client=client,
config=config,
target=target,
- settings={},
+ settings=settings or {},
run_id="run1",
**kwargs,
)
@@ -1785,6 +1786,60 @@ class TestExportFanOut:
# 10M / 2M = 5 files (under the lowered cap of 8).
assert "PARTITION BY toString(cityHash64(distinct_id) % 5)" in insert_sql
+ def test_events_export_applies_configured_row_group_size(self, target):
+ row_group_size_bytes = 512 * 1024 * 1024
+ config = DucklingBackfillConfig(
+ dry_run=False,
+ skip_ducklake_registration=True,
+ events_parquet_row_group_size_bytes=row_group_size_bytes,
+ max_s3_file_fanout=64,
+ )
+
+ _insert_sql, _count_sql, _glob, client = self._run_export(
+ export_events_to_duckling_s3,
+ target,
+ row_count=10_000_000,
+ config=config,
+ settings={"output_format_parquet_row_group_size_bytes": 1},
+ team_id=2,
+ date=datetime(2026, 6, 17),
+ )
+
+ export_call = next(call for call in client.execute.call_args_list if "INSERT INTO FUNCTION" in call.args[0])
+ assert export_call.kwargs["settings"]["output_format_parquet_row_group_size_bytes"] == row_group_size_bytes
+ assert export_call.kwargs["settings"]["output_format_parquet_row_group_size"] == 250_000
+
+ def test_events_export_automatically_caps_fanout_to_writer_buffer_budget(self, target):
+ config = DucklingBackfillConfig(
+ events_parquet_row_group_size_bytes=512 * 1024 * 1024,
+ max_s3_file_fanout=MAX_S3_FILE_FANOUT,
+ )
+
+ insert_sql, _count_sql, _glob, _ = self._run_export(
+ export_events_to_duckling_s3,
+ target,
+ row_count=10_000_000_000,
+ config=config,
+ team_id=2,
+ date=datetime(2026, 6, 17),
+ )
+
+ # The 32 GiB nominal staging budget fits at most 64 x 512 MiB writers.
+ assert "PARTITION BY toString(cityHash64(distinct_id) % 64)" in insert_sql
+
+ @patch("posthog.dags.events_backfill_to_duckling._resolve_duckling_target")
+ def test_events_run_rejects_when_one_writer_exceeds_buffer_budget(self, resolve_target):
+ config = DucklingBackfillConfig(
+ events_parquet_row_group_size_bytes=32 * 1024 * 1024 * 1024 + 1,
+ max_s3_file_fanout=1,
+ )
+ context = MagicMock(partition_key="2_2026-06-17")
+
+ with pytest.raises(ValueError, match="one events Parquet writer exceeds the 32 GiB"):
+ _run_duckling_events_backfill(context, config)
+
+ resolve_target.assert_not_called()
+
def test_persons_daily_export_sizes_fanout_and_returns_glob(self, target):
# 15M rows at the 5M-row default target → 3 files.
insert_sql, count_sql, s3_glob, _ = self._run_export(