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.

perf(github): key the branch cache on the installation (#90303)

Raúl Negrón-Otero6d0a4847b96b
diff --git a/posthog/egress/README.md b/posthog/egress/README.md
index 095ab15bade3..433f2aed72f7 100644
--- a/posthog/egress/README.md
+++ b/posthog/egress/README.md
@@ -158,7 +158,7 @@ It is **never** a PostHog DB row id (`Integration.id`).
Several PostHog integration rows can point at the same installation (multiple projects, one org), and GitHub gives that installation one shared budget: key a gauge by the row and one real budget splits into N flip-flopping series; key by the installation and you get one true series.
Per-caller attribution is the `source` label's job, not the identity's.
-> The cache-hit counter in `github_integration_base` is a separate concern (cache efficiency per connection) and legitimately keys by the integration row — it is not egress-budget telemetry.
+> The cache-hit counter in `github_integration_base` is a separate concern (which rows are reading a warm cache) and legitimately keys by the integration row, not by the installation — it is not egress-budget telemetry. The caches it counts are installation-scoped, so a row can record a hit on an entry another row on the same installation filled.
## Identity-blind callers and the PAT scope decision
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index bfd479c16625..c8fba6b024e5 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -187,6 +187,21 @@ class GitHubIntegrationBase:
"""The GitHub App installation ID. Override in subclasses where the field name differs."""
return self.integration.integration_id
+ def _installation_cache_scope(self) -> str:
+ """Cache identity for data GitHub scopes to the installation, not to the PostHog row.
+
+ Many rows can share one installation and they all read it through the same installation
+ token, so keying on the row splits one answer into N copies that each refetch it against the
+ one shared rate-limit budget. Same identity rule as the egress limiter (posthog/egress/README.md).
+ A row with no installation id falls back to its own scope so it cannot read another's entry.
+ """
+ installation_id = self.github_installation_id
+ if installation_id:
+ return f"installation:{installation_id}"
+ # Integration and UserIntegration are separate tables with independent primary keys, so the
+ # row id alone names two different rows.
+ return f"{type(self.integration).__name__}:{self.integration.id}"
+
# --- App-level JWT authentication ---
@classmethod
@@ -1946,7 +1961,7 @@ class GitHubIntegrationBase:
def get_default_branch(self, repository: str) -> str:
"""Get the default branch for a repository."""
repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
- cache_key = f"github_integration:default_branch:{self.integration.id}:{repo_path}"
+ cache_key = f"github_integration:default_branch:{self._installation_cache_scope()}:{repo_path}"
cached = cache.get(cache_key)
if isinstance(cached, str):
@@ -2083,7 +2098,7 @@ class GitHubIntegrationBase:
# --- Cached branch operations ---
def _get_branch_cache_key(self, repo: str) -> str:
- return f"github_integration:branches:{self.integration.id}:{repo.lower()}"
+ return f"github_integration:branches:{self._installation_cache_scope()}:{repo.lower()}"
def _get_branch_cache(self, repo: str) -> dict[str, Any] | None:
cached = cache.get(self._get_branch_cache_key(repo))
diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.py
index 5d494bb07ad3..da5702164a85 100644
--- a/posthog/models/test/integration/test_github.py
+++ b/posthog/models/test/integration/test_github.py
@@ -2,7 +2,7 @@
import time
from datetime import UTC, datetime, timedelta
-from typing import Optional
+from typing import Any, Optional
import pytest
from freezegun import freeze_time
@@ -35,6 +35,7 @@ from posthog.models.integration import (
Integration,
invalidate_github_repository_caches_for_installation,
)
+from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
class TestExtractFailingChecks(SimpleTestCase):
@@ -92,6 +93,16 @@ class TestGitHubIntegrationModel(BaseTest):
sensitive_config=_sensitive_config,
)
+ def create_user_integration(self, installation_id: str, **fields: Any) -> UserIntegration:
+ return UserIntegration.objects.create(
+ user=self.user,
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ integration_id=installation_id,
+ config={"installation_id": installation_id},
+ sensitive_config={"access_token": "ACCESS_TOKEN"},
+ **fields,
+ )
+
def mock_github_client_request(
self,
status_code=201,
@@ -1457,8 +1468,6 @@ class TestGitHubIntegrationModel(BaseTest):
mock_list_all.assert_called_once_with()
def test_invalidate_github_repository_caches_for_installation_clears_team_and_personal_rows(self):
- from posthog.models.user_integration import UserIntegration
-
team_integration = self.create_integration(
{"installation_id": "12345", "account": {"name": "PostHog"}},
{"access_token": "ACCESS_TOKEN"},
@@ -1468,12 +1477,8 @@ class TestGitHubIntegrationModel(BaseTest):
team_integration.repository_cache_updated_at = timezone.now()
team_integration.save(update_fields=["integration_id", "repository_cache", "repository_cache_updated_at"])
- user_integration = UserIntegration.objects.create(
- user=self.user,
- kind=UserIntegration.IntegrationKind.GITHUB,
- integration_id="12345",
- config={"installation_id": "12345"},
- sensitive_config={"access_token": "ACCESS_TOKEN"},
+ user_integration = self.create_user_integration(
+ "12345",
repository_cache=[{"id": 2, "name": "b", "full_name": "org/b"}],
repository_cache_updated_at=timezone.now(),
)
@@ -1597,6 +1602,27 @@ class TestGitHubIntegrationModel(BaseTest):
mock_default_branch.assert_not_called()
assert REGISTRY.get_sample_value("github_integration_cache_accesses_total", labels) == previous_count + 1
+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.get_default_branch")
+ @patch("posthog.models.github_integration_base.GitHubIntegrationBase.list_all_branches")
+ def test_branch_cache_is_shared_across_rows_on_one_installation(
+ self, mock_list_all_branches: MagicMock, mock_default_branch: MagicMock
+ ) -> None:
+ mock_list_all_branches.return_value = ["main", "develop"]
+ mock_default_branch.return_value = "main"
+ repo = "posthog/posthog"
+ integration = self.create_integration(
+ {"installation_id": "INSTALL", "account": {"name": "PostHog"}},
+ {"access_token": "ACCESS_TOKEN"},
+ )
+ user_integration = self.create_user_integration("INSTALL")
+
+ GitHubIntegration(integration).list_cached_branches(repo)
+ branches, default_branch, _ = UserGitHubIntegration(user_integration).list_cached_branches(repo)
+
+ assert branches == ["main", "develop"]
+ assert default_branch == "main"
+ mock_list_all_branches.assert_called_once_with(repo)
+
@patch("posthog.models.integration.github.GitHubIntegration.list_branches")
@patch("posthog.models.integration.github.GitHubIntegration.get_default_branch")
def test_list_cached_branches_filters_search_before_pagination(self, mock_default_branch, mock_list_branches):