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.

fix(data-warehouse): tune autovacuum on every new queue partition (#111096)

Tom Owersedabdfbcfdd9
diff --git a/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.py b/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.py
index a643937d96d8..e82a27c776c0 100644
--- a/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.py
+++ b/posthog/temporal/tests/warehouse_sources_queue_partition_management/test_activities.py
@@ -443,3 +443,47 @@ async def test_connect_failure_keeps_database_url_out_of_traceback_locals() -> N
hits = _frames_holding(exc_info.value.__traceback__, _SECRET)
assert hits == []
+
+
+ "existing_options, expect_alter",
+ [
+ ("", True),
+ ("autovacuum_vacuum_scale_factor = 0.02, autovacuum_analyze_scale_factor = 0.02", True),
+ (", ".join(activities_module._PARTITION_AUTOVACUUM_OPTIONS), False),
+ ],
+)
+def test_tune_partition_autovacuum_sets_options_once(existing_options: str, expect_alter: bool) -> None:
+ table = f"autovacuum_test_{uuid4().hex[:12]}"
+ partition = f"{table}_20261002"
+ errors: list[str] = []
+
+ with psycopg.Connection.connect(_test_database_conninfo(), autocommit=True) as conn:
+ try:
+ conn.execute(f"CREATE TABLE {table} (id int, created_at timestamptz) PARTITION BY RANGE (created_at)")
+ conn.execute(
+ f"CREATE TABLE {partition} PARTITION OF {table} FOR VALUES FROM ('2026-10-02') TO ('2026-10-03')"
+ )
+ if existing_options:
+ conn.execute(f"ALTER TABLE {partition} SET ({existing_options})")
+
+ statements: list[str] = []
+ real_execute = conn.execute
+
+ def recording_execute(query: Any, *args: Any, **kwargs: Any) -> Any:
+ statements.append(str(query))
+ return real_execute(query, *args, **kwargs)
+
+ with patch.object(conn, "execute", side_effect=recording_execute):
+ activities_module._tune_partition_autovacuum(conn, partition, errors)
+
+ row = conn.execute("SELECT reloptions FROM pg_class WHERE oid = %s::regclass", [partition]).fetchone()
+ assert row is not None
+ options = row[0]
+ finally:
+ conn.execute(f"DROP TABLE IF EXISTS {table}")
+
+ assert errors == []
+ assert set(options) >= set(activities_module._PARTITION_AUTOVACUUM_OPTIONS)
+ assert any(statement.startswith("ALTER TABLE") for statement in statements) is expect_alter
diff --git a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py b/posthog/temporal/warehouse_sources_queue_partition_management/activities.py
index 191487d35d69..d19132c2380d 100644
--- a/posthog/temporal/warehouse_sources_queue_partition_management/activities.py
+++ b/posthog/temporal/warehouse_sources_queue_partition_management/activities.py
@@ -23,6 +23,19 @@ PARTITIONS_AHEAD = 7
RETENTION_DAYS = 7
DEFAULT_PARTITION_DELETE_BATCH_SIZE = 10_000
+# Rows in these tables change state in place two or three times, and each change leaves a dead
+# entry in the partial indexes on latest_state. A scale factor waits for 10% of a partition to be
+# dead, which late in the day is ~150k rows, and the claim query then reads through those entries.
+# A fixed threshold keeps the dead count low and about constant as the daily partition grows.
+_IN_PLACE_UPDATE_TABLES = ("sourcebatch", "queuejob")
+_PARTITION_AUTOVACUUM_OPTIONS = (
+ "autovacuum_vacuum_scale_factor=0",
+ "autovacuum_vacuum_threshold=10000",
+ "autovacuum_analyze_scale_factor=0.02",
+ "autovacuum_vacuum_cost_delay=2",
+ "autovacuum_vacuum_cost_limit=2000",
+)
+
# Deliberately not the lock-takeover sentinel — that string has special
# downstream semantics in the dead-job gate.
RETENTION_STRANDED_ERROR = "batches aged out of retention without being processed"
@@ -102,6 +115,9 @@ def _manage_database_partitions(today: date, errors: list[str]) -> _PartitionCha
except Exception as e:
errors.append(f"Failed to create {partition_name}: {e}")
logger.exception("Failed to create partition", partition=partition_name)
+ continue
+ if table in _IN_PLACE_UPDATE_TABLES:
+ _tune_partition_autovacuum(conn, partition_name, errors)
cutoff = today - timedelta(days=RETENTION_DAYS)
failed_default_expiries: set[str] = set()
@@ -139,6 +155,23 @@ def _manage_database_partitions(today: date, errors: list[str]) -> _PartitionCha
return _PartitionChanges(ensured=ensured, dropped=dropped, alerts=alerts)
+def _tune_partition_autovacuum(conn: psycopg.Connection, partition_name: str, errors: list[str]) -> None:
+ row = conn.execute("SELECT reloptions FROM pg_class WHERE oid = %s::regclass", [partition_name]).fetchone()
+ current = set(row[0] or []) if row else set()
+ if current.issuperset(_PARTITION_AUTOVACUUM_OPTIONS):
+ return
+ # ALTER takes a lock that conflicts with a running autovacuum, so skip it when the options
+ # are already set, and give up quickly rather than queue behind one.
+ try:
+ conn.execute("SET lock_timeout = '5s'")
+ conn.execute(f"ALTER TABLE {partition_name} SET ({', '.join(_PARTITION_AUTOVACUUM_OPTIONS)})")
+ except Exception as e:
+ errors.append(f"Failed to tune autovacuum on {partition_name}: {e}")
+ logger.exception("Failed to tune partition autovacuum", partition=partition_name)
+ finally:
+ conn.execute("RESET lock_timeout")
+
+
def _partition_ddl_database_url() -> str:
# Only the owner of a partitioned table can create its partitions, and the migration role owns the queue tables.
return settings.WAREHOUSE_SOURCES_QUEUE_PARTITION_DATABASE_URL or settings.WAREHOUSE_SOURCES_DATABASE_URL