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(devex): gate hot-table migrations behind explicit acknowledgment (#62857)

Julian Bez89cfa6e70144
diff --git a/.agents/skills/django-migrations/SKILL.md b/.agents/skills/django-migrations/SKILL.md
index a53b95aaacb3..3a30873b418f 100644
--- a/.agents/skills/django-migrations/SKILL.md
+++ b/.agents/skills/django-migrations/SKILL.md
@@ -16,12 +16,22 @@ If the task is a ClickHouse migration, use `clickhouse-migrations` instead.
## Workflow
-1. **Classify** the change as additive (new nullable column, new table) or risky (drop/rename, `NOT NULL`, indexes, constraints, large data updates, model moves). See also the [cross-language `NOT NULL` hazard](#cross-language-not-null-hazard) below.
+1. **Classify** the change as additive (new nullable column, new table) or risky (drop/rename, `NOT NULL`, indexes, constraints, large data updates, model moves). A change is also risky if it touches a [hot table](#hot-table-hazard), regardless of how additive it looks. See also the [cross-language `NOT NULL` hazard](#cross-language-not-null-hazard) below.
2. **Generate**: `DEBUG=1 ./manage.py makemigrations [app_label]`.
For merge conflicts: `python manage.py rebase_migration <app> && git add <app>/migrations` (`posthog` or `ee`).
3. **Apply safety rules** from `safe-django-migrations.md` — the doc covers multi-phase rollouts, `SeparateDatabaseAndState`, concurrent operations, idempotency, and all risky patterns in detail.
4. **Validate**: `./manage.py sqlmigrate <app> <migration_number>`, run tests, confirm linear migration sequence.
+## Hot table hazard
+
+`posthog_team`, `posthog_user`, `posthog_organization`, and `posthog_project` are read on virtually every request. Any `ALTER TABLE` on them — including a plain nullable `AddField`, which is "safe" everywhere else — needs an `ACCESS EXCLUSIVE` lock, and while that lock request waits behind in-flight queries, every later query on the table queues behind it. Even a metadata-only `ADD COLUMN` can stall site-wide traffic in waves (one per `bin/migrate` retry) until the ALTER wins the lock race. This has caused production 5xx incidents.
+
+Before writing a migration that touches one of these models:
+
+- For `Team`: put domain-specific fields on a Team extension model instead — `posthog/models/team/README.md`. That's a `CREATE TABLE`, no lock on `posthog_team`.
+- `CREATE INDEX CONCURRENTLY` (via `CreateIndexConcurrently`) is fine — `SHARE UPDATE EXCLUSIVE` doesn't block reads or writes.
+- If the field genuinely belongs on the hot table (core identity, cross-product settings, SDK config), the `HotTableAlterPolicy` analyzer blocks the migration in CI until `<app_label>.<migration_name>` is added to `posthog/management/migration_analysis/hot_table_acknowledged_migrations.txt`. That acknowledgment also means coordinating the deploy with infra for a low-traffic window.
+
## Cross-language `NOT NULL` hazard
`posthog_user`, `posthog_team`, and other core tables in the main Postgres database are written by Django **and** by `nodejs/` (plugin-server tests via `insertRow`), `rust/` services, and Temporal workers. Those non-Django writers issue raw `INSERT`s that only list the columns they care about, so any new `NOT NULL` column without a Postgres-level `DEFAULT` will break them with `null value in column "<col>" violates not-null constraint`.
diff --git a/docs/published/handbook/engineering/safe-django-migrations.md b/docs/published/handbook/engineering/safe-django-migrations.md
index 61afb589534f..664fddf0dfea 100644
--- a/docs/published/handbook/engineering/safe-django-migrations.md
+++ b/docs/published/handbook/engineering/safe-django-migrations.md
@@ -12,6 +12,7 @@ This guide explains how to safely perform dangerous Django migration operations
## Table of Contents
+- [Altering Hot Tables](#altering-hot-tables)
- [Dropping Tables](#dropping-tables)
- [Dropping Columns](#dropping-columns)
- [Renaming Tables](#renaming-tables)
@@ -23,6 +24,26 @@ This guide explains how to safely perform dangerous Django migration operations
- [Using SeparateDatabaseAndState](#using-separatedatabaseandstate)
- [General Best Practices](#general-best-practices)
+## Altering Hot Tables
+
+**Problem:** `posthog_team`, `posthog_user`, `posthog_organization`, and `posthog_project` are read on virtually every request. Every `ALTER TABLE` — including the "safe" patterns elsewhere in this guide, like adding a nullable column — needs an `ACCESS EXCLUSIVE` lock. The danger is not the ALTER itself (a nullable `ADD COLUMN` is metadata-only and takes milliseconds once it runs); it's the **lock queue**: while the ALTER waits behind in-flight queries, Postgres queues every later query on the table behind it. On a hot table that means site-wide request pile-ups and 5xx errors until `lock_timeout` cancels the ALTER — and since `bin/migrate` retries with exponential backoff, the stall repeats in waves until the ALTER finally wins the race.
+
+This is not theoretical: a plain nullable `AddField` on `Team` — exactly what this guide's NOT NULL section recommends as the safe pattern — has caused roughly an hour of recurring 5xx waves in production while it lost the lock race retry after retry.
+
+### Safe Approach: Don't Alter the Table
+
+For `Team`, most new fields shouldn't be on the table at all. Domain-specific fields belong on a **Team extension model** (see `posthog/models/team/README.md`) — that's a `CREATE TABLE`, which takes no lock on `posthog_team` whatsoever.
+
+`CREATE INDEX CONCURRENTLY` (via `CreateIndexConcurrently`, see [Adding Indexes](#adding-indexes)) is also fine: it only takes `SHARE UPDATE EXCLUSIVE`, which doesn't block reads or writes.
+
+### If You Genuinely Must Alter a Hot Table
+
+The migration analyzer (`HotTableAlterPolicy`) blocks any DDL on these tables in CI. To accept the risk:
+
+1. Confirm the field really is core (team identity, cross-product settings, SDK config) and not a candidate for an extension model.
+2. Add `<app_label>.<migration_name>` to `posthog/management/migration_analysis/hot_table_acknowledged_migrations.txt` — this is the explicit "I accept the risk" act, and it's visible in review.
+3. Coordinate the deploy with #team-infrastructure for a low-traffic window.
+
## Dropping Tables
**Problem:** `DeleteModel` operations drop tables immediately. This breaks backwards compatibility during deployment and **cannot be rolled back** - once data is deleted, any rollback deployment will fail because the table no longer exists.
@@ -200,6 +221,8 @@ This gives you a clean Python API without the risk of renaming the database colu
2. Backfill data
3. Add NOT NULL constraint
+> **Note:** "safe" here means no table rewrite. On [hot tables](#altering-hot-tables) even a nullable `ADD COLUMN` can stall traffic while it waits for its lock.
+
**Step 1: Add column as nullable**
```python
diff --git a/posthog/management/migration_analysis/hot_table_acknowledged_migrations.txt b/posthog/management/migration_analysis/hot_table_acknowledged_migrations.txt
new file mode 100644
index 000000000000..9d663bf94973
--- /dev/null
+++ b/posthog/management/migration_analysis/hot_table_acknowledged_migrations.txt
@@ -0,0 +1,18 @@
+# Migrations acknowledged to run DDL on a hot table (HotTableAlterPolicy).
+#
+# posthog_team, posthog_user, posthog_organization, and posthog_project are read on
+# virtually every request. Any ALTER TABLE on them takes an ACCESS EXCLUSIVE lock, and
+# while that lock request waits behind in-flight queries, every later query on the table
+# queues behind it - even a metadata-only ADD COLUMN can stall site-wide traffic until
+# lock_timeout cancels it, with each bin/migrate retry repeating the stall.
+#
+# Before adding a line here, check whether the field belongs on a Team extension model
+# instead (posthog/models/team/README.md) - that only creates a new table and needs no
+# acknowledgment.
+#
+# Adding a line means: I understand this migration can stall production traffic while it
+# waits for its lock, and the deploy is coordinated with #team-infrastructure for a
+# low-traffic window.
+#
+# Format: one "<app_label>.<migration_name>" per line, e.g.
+# posthog.1234_team_some_genuinely_core_field
diff --git a/posthog/management/migration_analysis/policies.py b/posthog/management/migration_analysis/policies.py
index ac89f29112d0..cab7571c897b 100644
--- a/posthog/management/migration_analysis/policies.py
+++ b/posthog/management/migration_analysis/policies.py
@@ -6,6 +6,7 @@ Policies enforce architectural decisions and coding standards.
import re
from abc import ABC, abstractmethod
+from pathlib import Path
# Apps owned by PostHog where policies are enforced
POSTHOG_OWNED_APPS = ["posthog", "ee"]
@@ -401,9 +402,159 @@ class ConcurrentIndexIdempotencyPolicy(MigrationPolicy):
return violations
+class HotTableAlterPolicy(MigrationPolicy):
+ """
+ Policy: DDL on hot tables must be explicitly acknowledged.
+
+ Rationale:
+ - posthog_team, posthog_user, posthog_organization, and posthog_project are
+ read on virtually every request.
+ - Any ALTER TABLE on them needs an ACCESS EXCLUSIVE lock. While that lock
+ request waits behind in-flight queries, every later query on the table
+ queues behind it - so even a metadata-only ADD COLUMN of a nullable
+ column can stall site-wide traffic until lock_timeout cancels it, and
+ each bin/migrate retry repeats the stall. This has caused production
+ 5xx incidents.
+ - Most new team fields should not be on Team at all: a Team extension
+ model (posthog/models/team/README.md) only creates a new table, which
+ takes no lock on posthog_team.
+ - When DDL on a hot table is genuinely needed, the author accepts the risk
+ by adding "<app_label>.<migration_name>" to
+ hot_table_acknowledged_migrations.txt - a deliberate, reviewable act
+ that also coordinates the deploy.
+ """
+
+ HOT_MODELS = {"team", "user", "organization", "project"}
+
+ # Op types that carry the target model in `model_name`
+ FIELD_LEVEL_OPS = {
+ "AddField",
+ "RemoveField",
+ "AlterField",
+ "RenameField",
+ "AddConstraint",
+ "RemoveConstraint",
+ "AddIndex",
+ "RemoveIndex",
+ }
+ # Op types that carry the target model in `name`
+ MODEL_LEVEL_OPS = {
+ "DeleteModel",
+ "RenameModel",
+ "AlterModelTable",
+ "AlterUniqueTogether",
+ "AlterIndexTogether",
+ }
+
+ ACKNOWLEDGMENTS_FILE = Path(__file__).with_name("hot_table_acknowledged_migrations.txt")
+
+ # Only ALTER TABLE is matched; CONCURRENTLY index builds take SHARE UPDATE EXCLUSIVE, which
+ # doesn't block reads or writes. Mirrors the Postgres grammar: ALTER TABLE [ IF EXISTS ]
+ # [ ONLY ] [ schema. ] name, with optional double-quoting on the schema and table identifiers.
+ _ALTER_HOT_TABLE = re.compile(
+ r"ALTER\s+TABLE\s+"
+ r"(?:IF\s+EXISTS\s+)?"
+ r"(?:ONLY\s+)?"
+ r'(?:"?\w+"?\s*\.\s*)?' # optional schema qualifier, e.g. public.
+ r'"?(posthog_team|posthog_user|posthog_organization|posthog_project)"?\b',
+ re.IGNORECASE,
+ )
+
+ def check_operation(self, op) -> list[str]:
+ return [] # Checked at migration level (needs the migration label for the acknowledgment hint)
+
+ def check_migration(self, migration) -> list[str]:
+ if not is_posthog_app(migration.app_label, migration):
+ return []
+
+ label = f"{migration.app_label}.{migration.name}"
+ if label in self._acknowledged_migrations():
+ return []
+
+ violations = []
+ for op in self._descend(migration.operations):
+ table = self._hot_table_target(op, migration.app_label)
+ if table:
+ violations.append(self._violation(op, table, label))
+ return violations
+
+ def _acknowledged_migrations(self) -> set[str]:
+ if not self.ACKNOWLEDGMENTS_FILE.exists():
+ return set()
+ lines = self.ACKNOWLEDGMENTS_FILE.read_text().splitlines()
+ return {line.strip() for line in lines if line.strip() and not line.strip().startswith("#")}
+
+ def _descend(self, ops):
+ """Yield operations that emit SQL, descending into SeparateDatabaseAndState.database_operations.
+
+ state_operations never touch the database, so they are not descended.
+ """
+ for op in ops or []:
+ if op.__class__.__name__ == "SeparateDatabaseAndState":
+ yield from self._descend(getattr(op, "database_operations", []) or [])
+ else:
+ yield op
+
+ def _hot_table_target(self, op, app_label: str) -> str | None:
+ """Return the hot table an operation alters, or None."""
+ op_type = op.__class__.__name__
+
+ # The hot models all live in the posthog app; same-named models in
+ # product apps map to different tables.
+ if app_label == "posthog":
+ model_name = None
+ if op_type in self.FIELD_LEVEL_OPS:
+ model_name = getattr(op, "model_name", None)
+ elif op_type in self.MODEL_LEVEL_OPS:
+ model_name = getattr(op, "name", None)
+ if model_name and model_name.lower() in self.HOT_MODELS:
+ return f"posthog_{model_name.lower()}"
+
+ # Hand-written DDL can hit a hot table from any app
+ if op_type == "RunSQL":
+ for attr in ("sql", "reverse_sql"):
+ table = self._hot_table_in_sql(getattr(op, attr, ""))
+ if table:
+ return table
+
+ return None
+
+ def _hot_table_in_sql(self, sql) -> str | None:
+ sql = str(sql)
+ # Strip /* */, -- and # comments so table names inside comments don't match
+ sql = re.sub(r"/\*.*?\*/", "", sql, flags=re.S)
+ sql = re.sub(r"--[^\n]*", "", sql)
+ sql = re.sub(r"#[^\n]*", "", sql)
+
+ for statement in sql.split(";"):
+ # VALIDATE CONSTRAINT only takes SHARE UPDATE EXCLUSIVE, which doesn't block reads or writes
+ if "VALIDATE CONSTRAINT" in statement.upper():
+ continue
+ match = self._ALTER_HOT_TABLE.search(statement)
+ if match:
+ return match.group(1).lower()
+ return None
+
+ def _violation(self, op, table: str, label: str) -> str:
+ return (
+ f'❌ BLOCKED: {op.__class__.__name__} on "{table}" - this table is read on virtually every '
+ "request. Any ALTER TABLE on it takes an ACCESS EXCLUSIVE lock; while that lock request waits "
+ "behind in-flight queries, every later query on the table queues behind it, so even a "
+ "metadata-only ADD COLUMN can stall site-wide traffic until lock_timeout cancels it - and "
+ "each bin/migrate retry repeats the stall. This has caused production 5xx incidents.\n"
+ "Prefer not altering this table at all: new domain-specific team fields belong on a Team "
+ "extension model (see posthog/models/team/README.md), which only creates a new table.\n"
+ f'If this change genuinely must alter {table}, add "{label}" to '
+ "posthog/management/migration_analysis/hot_table_acknowledged_migrations.txt to accept the "
+ "risk, and coordinate the deploy with #team-infrastructure for a low-traffic window.\n"
+ "See https://github.com/PostHog/posthog/blob/master/docs/published/handbook/engineering/safe-django-migrations.md#altering-hot-tables"
+ )
+
+
# Registry of all PostHog policies
POSTHOG_POLICIES = [
UUIDPrimaryKeyPolicy(),
AtomicFalsePolicy(),
ConcurrentIndexIdempotencyPolicy(),
+ HotTableAlterPolicy(),
]
diff --git a/posthog/management/migration_analysis/test/test_risk_analyzer.py b/posthog/management/migration_analysis/test/test_risk_analyzer.py
index f5039a236cf1..eb716bbf02cb 100644
--- a/posthog/management/migration_analysis/test/test_risk_analyzer.py
+++ b/posthog/management/migration_analysis/test/test_risk_analyzer.py
@@ -6,7 +6,7 @@ from parameterized import parameterized
from posthog.management.migration_analysis.analyzer import RiskAnalyzer
from posthog.management.migration_analysis.models import RiskLevel
-from posthog.management.migration_analysis.policies import ConcurrentIndexIdempotencyPolicy
+from posthog.management.migration_analysis.policies import ConcurrentIndexIdempotencyPolicy, HotTableAlterPolicy
def create_mock_operation(op_class, **kwargs):
@@ -2064,3 +2064,184 @@ class TestConcurrentIndexIdempotencyPolicy:
risk = self._analyze([op])
assert not any("non-idempotent" in v for v in risk.policy_violations)
assert risk.level != RiskLevel.BLOCKED
+
+
+class TestHotTableAlterPolicy:
+ """HotTableAlterPolicy blocks unacknowledged DDL on tables read on every request.
+
+ Regression coverage for the prod-us incident where a nullable AddField on
+ Team queued an ACCESS EXCLUSIVE lock behind in-flight queries, stalling all
+ traffic on posthog_team in recurring waves (one per bin/migrate retry).
+ """
+
+ def setup_method(self):
+ self.analyzer = RiskAnalyzer()
+
+ def _analyze(self, operations, app_label="posthog", name="0001_test"):
+ mock_migration = MagicMock()
+ mock_migration.atomic = True
+ mock_migration.app_label = app_label
+ mock_migration.name = name
+ mock_migration.operations = operations
+ return self.analyzer.analyze_migration(mock_migration, f"{app_label}/migrations/{name}.py")
+
+ @parameterized.expand(["team", "user", "organization", "project"])
+ def test_nullable_add_field_on_hot_model_blocked(self, model_name):
+ op = create_mock_operation(
+ migrations.AddField, model_name=model_name, name="optional_field", field=models.IntegerField(null=True)
+ )
+ risk = self._analyze([op])
+ assert risk.level == RiskLevel.BLOCKED
+ assert any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
+ # sorted() so test IDs are stable across runs (pytest-xdist collects by ID)
+ @parameterized.expand(sorted(HotTableAlterPolicy.FIELD_LEVEL_OPS))
+ def test_every_field_level_op_on_hot_model_blocked(self, op_type):
+ op = MagicMock()
+ op.__class__.__name__ = op_type
+ op.model_name = "team"
+ risk = self._analyze([op])
+ assert any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
+ @parameterized.expand(sorted(HotTableAlterPolicy.MODEL_LEVEL_OPS))
+ def test_every_model_level_op_on_hot_model_blocked(self, op_type):
+ op = MagicMock()
+ op.__class__.__name__ = op_type
+ op.name = "team"
+ risk = self._analyze([op])
+ assert any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
+ def test_add_field_on_regular_model_not_flagged(self):
+ op = create_mock_operation(
+ migrations.AddField, model_name="dashboard", name="optional_field", field=models.IntegerField(null=True)
+ )
+ risk = self._analyze([op])
+ assert not any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
+ def test_acknowledged_migration_not_flagged(self, tmp_path, monkeypatch):
+ ack_file = tmp_path / "acks.txt"
+ ack_file.write_text("# comment\nposthog.0001_test\n")
+ monkeypatch.setattr(HotTableAlterPolicy, "ACKNOWLEDGMENTS_FILE", ack_file)
+ op = create_mock_operation(
+ migrations.AddField, model_name="team", name="optional_field", field=models.IntegerField(null=True)
+ )
+ risk = self._analyze([op])
+ assert not any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
+ def test_violation_names_the_acknowledgment_entry(self):
+ op = create_mock_operation(
+ migrations.AddField, model_name="team", name="optional_field", field=models.IntegerField(null=True)
+ )
+ risk = self._analyze([op], name="1234_team_new_field")
+ assert any('"posthog.1234_team_new_field"' in v for v in risk.policy_violations)
+
+ def test_runsql_alter_on_hot_table_blocked(self):
+ op = create_mock_operation(
+ migrations.RunSQL, sql='ALTER TABLE "posthog_team" ADD COLUMN "foo" timestamptz NULL;'
+ )
+ risk = self._analyze([op])
+ assert any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
+ @parameterized.expand(
+ [
+ ("if_exists", "ALTER TABLE IF EXISTS posthog_team ADD COLUMN foo int NULL;"),
+ ("if_exists_quoted", 'ALTER TABLE IF EXISTS "posthog_team" ADD COLUMN foo int NULL;'),
+ ("if_exists_only", "ALTER TABLE IF EXISTS ONLY posthog_team ADD COLUMN foo int NULL;"),
+ ("schema_qualified", "ALTER TABLE public.posthog_team ADD COLUMN foo int NULL;"),
+ ("schema_qualified_quoted", 'ALTER TABLE "public"."posthog_team" ADD COLUMN foo int NULL;'),
+ ("if_exists_schema_qualified", "ALTER TABLE IF EXISTS public.posthog_team ADD COLUMN foo int NULL;"),
+ ]
+ )
+ def test_runsql_alter_variants_on_hot_table_blocked(self, _name, sql):
+ op = create_mock_operation(migrations.RunSQL, sql=sql)
+ risk = self._analyze([op])
+ assert any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
+ def test_runsql_validate_constraint_on_hot_table_not_flagged(self):
+ op = create_mock_operation(migrations.RunSQL, sql='ALTER TABLE "posthog_team" VALIDATE CONSTRAINT "some_fk";')
+ risk = self._analyze([op])
+ assert not any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
+ def test_runsql_hot_table_only_in_comment_not_flagged(self):
+ op = create_mock_operation(
+ migrations.RunSQL,
+ sql='-- cleanup after ALTER TABLE "posthog_team"\nALTER TABLE "posthog_dashboard" ADD COLUMN "foo" int NULL;',
+ )
+ risk = self._analyze([op])
+ assert not any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
+ def test_runsql_alter_on_regular_table_not_flagged(self):
+ op = create_mock_operation(migrations.RunSQL, sql='ALTER TABLE "posthog_dashboard" ADD COLUMN "foo" int NULL;')
+ risk = self._analyze([op])
+ assert not any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
+ @parameterized.expand(["AddIndexConcurrently", "CreateIndexConcurrently"])
+ def test_concurrent_index_on_hot_model_not_flagged(self, op_type):
+ op = MagicMock()
+ op.__class__.__name__ = op_type
+ op.model_name = "team"
+ op.sql = 'CREATE INDEX CONCURRENTLY IF NOT EXISTS "idx" ON "posthog_team" (c)'
+ op.reverse_sql = 'DROP INDEX CONCURRENTLY IF EXISTS "idx"'
+ risk = self._analyze([op])
+ assert not any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
+ def test_alter_model_options_on_hot_model_not_flagged(self):
+ op = MagicMock()
+ op.__class__.__name__ = "AlterModelOptions"
+ op.name = "team"
+ risk = self._analyze([op])
+ assert not any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
+ def test_runsql_inside_separate_database_and_state_blocked(self):
+ db_op = create_mock_operation(
+ migrations.RunSQL, sql='ALTER TABLE "posthog_team" ADD COLUMN "foo" timestamptz NULL;'
+ )
+ sep = create_mock_operation(
+ migrations.SeparateDatabaseAndState, state_operations=[], database_operations=[db_op]
+ )
+ risk = self._analyze([sep])
+ assert any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
+ def test_state_only_add_field_inside_separate_database_and_state_not_flagged(self):
+ state_op = create_mock_operation(
+ migrations.AddField, model_name="team", name="optional_field", field=models.IntegerField(null=True)
+ )
+ sep = create_mock_operation(
+ migrations.SeparateDatabaseAndState, state_operations=[state_op], database_operations=[]
+ )
+ risk = self._analyze([sep])
+ assert not any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
+ def test_third_party_app_not_checked(self):
+ op = create_mock_operation(
+ migrations.AddField, model_name="team", name="optional_field", field=models.IntegerField(null=True)
+ )
+ risk = self._analyze([op], app_label="some_third_party_app")
+ assert not any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
+ def test_hot_model_name_in_product_app_not_flagged(self):
+ """A product app's own model named like a hot model maps to a different table."""
+ op = create_mock_operation(
+ migrations.AddField, model_name="team", name="optional_field", field=models.IntegerField(null=True)
+ )
+ mock_migration = MagicMock()
+ mock_migration.atomic = True
+ mock_migration.app_label = "some_product"
+ mock_migration.name = "0001_test"
+ mock_migration.operations = [op]
+ mock_migration.__module__ = "products.some_product.backend.migrations.0001_test"
+ risk = self.analyzer.analyze_migration(mock_migration, "products/some_product/backend/migrations/0001_test.py")
+ assert not any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
+
+ def test_product_app_runsql_on_hot_table_blocked(self):
+ op = create_mock_operation(
+ migrations.RunSQL, sql='ALTER TABLE "posthog_team" ADD COLUMN "foo" timestamptz NULL;'
+ )
+ mock_migration = MagicMock()
+ mock_migration.atomic = True
+ mock_migration.app_label = "some_product"
+ mock_migration.name = "0001_test"
+ mock_migration.operations = [op]
+ mock_migration.__module__ = "products.some_product.backend.migrations.0001_test"
+ risk = self.analyzer.analyze_migration(mock_migration, "products/some_product/backend/migrations/0001_test.py")
+ assert any("ACCESS EXCLUSIVE" in v for v in risk.policy_violations)
diff --git a/posthog/models/team/README.md b/posthog/models/team/README.md
index ad99f64438c3..68d6d68044d2 100644
--- a/posthog/models/team/README.md
+++ b/posthog/models/team/README.md
@@ -2,6 +2,12 @@
This directory contains the core `Team` model and its extension models.
+## Why this matters: availability, not just hygiene
+
+`posthog_team` is read on virtually every request, so any `ALTER TABLE` on it — even adding a nullable column, which is metadata-only — needs an `ACCESS EXCLUSIVE` lock and can stall site-wide traffic while it waits in the lock queue behind in-flight queries. This has caused production 5xx incidents. An extension model only does a `CREATE TABLE`, which takes no lock on `posthog_team` at all.
+
+The migration analyzer (`HotTableAlterPolicy`) blocks unacknowledged DDL on `posthog_team` in CI; fields that genuinely belong on `Team` need an entry in `posthog/management/migration_analysis/hot_table_acknowledged_migrations.txt`. See the [Altering Hot Tables](../../../docs/published/handbook/engineering/safe-django-migrations.md#altering-hot-tables) guide.
+
## When to add fields to Team vs create an extension
**Add to Team directly** when the field is: