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(aio): degrade transient DB errors in llm prompt cache to a miss (#71725)

posthog[bot]950f6b350f45
diff --git a/posthog/storage/llm_prompt_cache.py b/posthog/storage/llm_prompt_cache.py
index 5e0145594ca8..66a98686110d 100644
--- a/posthog/storage/llm_prompt_cache.py
+++ b/posthog/storage/llm_prompt_cache.py
@@ -2,11 +2,14 @@ from collections.abc import Iterable
from typing import Any, cast
from django.conf import settings
+from django.db import InterfaceError, OperationalError
from django.db.models import QuerySet
+import structlog
+
from posthog.exceptions_capture import capture_exception
from posthog.models.team.team import Team
-from posthog.storage.hypercache import HyperCache, HyperCacheStoreMissing, KeyType
+from posthog.storage.hypercache import HyperCache, HyperCacheDependencyUnavailable, HyperCacheStoreMissing, KeyType
from posthog.storage.llm_prompt_cache_keys import (
parse_prompt_cache_key,
prompt_label_cache_key,
@@ -21,6 +24,7 @@ from posthog.storage.llm_prompt_cache_payloads import (
serialize_prompt_version,
strip_internal_metadata,
)
+from posthog.utils import capture_exception_throttled
from products.ai_observability.backend.models.llm_prompt import (
LLMPrompt,
@@ -28,9 +32,51 @@ from products.ai_observability.backend.models.llm_prompt import (
annotate_llm_prompt_version_history_metadata,
)
+logger = structlog.get_logger(__name__)
+
# Used in tests; keep as module export.
_serialize_prompt = serialize_prompt
+# Transient DB failures (e.g. a PgBouncer query_wait_timeout under pool pressure) that should
+# degrade to a cache miss rather than surfacing a 500, mirroring the Redis and S3 read tiers.
+_TRANSIENT_DB_ERRORS = (OperationalError, InterfaceError)
+
+# One capture per window across processes. This read is SDK-facing, so a sustained pool-pressure
+# incident would otherwise report once per request and bury everything else in error tracking.
+_DB_UNAVAILABLE_CAPTURE_THROTTLE_KEY = "llm_prompt_cache_db_unavailable_capture_throttle"
+_DB_UNAVAILABLE_CAPTURE_THROTTLE_TTL = 60 # seconds
+
+
+class PromptCacheDatabaseUnavailable(HyperCacheDependencyUnavailable):
+ """Raised by the prompt ``load_fn`` when the Postgres tier is transiently unavailable.
+
+ Subclasses the storage-layer base so HyperCache returns a miss without caching a
+ miss sentinel, which means the next read retries the DB instead of being pinned to
+ "not found" for the whole cache_miss_ttl. That is how the Redis and S3 tiers already
+ degrade, and it is why the raiser has to report the error itself (see
+ ``_record_prompt_db_unavailable``).
+ """
+
+
+def _record_prompt_db_unavailable(exc: BaseException, prompt_name: str) -> None:
+ """Report a transient prompt-DB failure where it is detected.
+
+ HyperCache deliberately does not capture ``HyperCacheDependencyUnavailable``, because it
+ trusts the raiser to have reported it already. Nothing downstream reports it either: a
+ versioned read served over a warm latest entry never reaches the wrapper in
+ ``get_prompt_by_name_from_cache``, so without this the request 404s with only a counter
+ to show the DB was down.
+ """
+ captured = capture_exception_throttled(
+ _DB_UNAVAILABLE_CAPTURE_THROTTLE_KEY, exc, _DB_UNAVAILABLE_CAPTURE_THROTTLE_TTL
+ )
+ logger.exception(
+ "llm_prompt_cache_db_unavailable",
+ prompt_name=prompt_name,
+ exception_captured=captured,
+ capture_throttled=not captured,
+ )
+
def _get_active_prompt_queryset_for_team_id(team_id: int) -> QuerySet[LLMPrompt]:
return annotate_llm_prompt_version_history_metadata(LLMPrompt.objects.filter(team_id=team_id, deleted=False))
@@ -96,23 +142,27 @@ def _load_prompt_cache(cache_key: KeyType) -> dict[str, Any] | HyperCacheStoreMi
team_id, prompt_name, version, label_name = parsed_key
- if label_name is not None:
- labeled_prompt = _get_labeled_prompt_from_db(team_id, prompt_name, label_name)
- if labeled_prompt is None:
- return HyperCacheStoreMissing()
- return _serialize_labeled_prompt(labeled_prompt, label_name)
+ try:
+ if label_name is not None:
+ labeled_prompt = _get_labeled_prompt_from_db(team_id, prompt_name, label_name)
+ if labeled_prompt is None:
+ return HyperCacheStoreMissing()
+ return _serialize_labeled_prompt(labeled_prompt, label_name)
- if version is None:
- prompt = _get_latest_prompt_from_db(team_id, prompt_name)
+ if version is None:
+ prompt = _get_latest_prompt_from_db(team_id, prompt_name)
+ if prompt is None:
+ return HyperCacheStoreMissing()
+ return serialize_prompt(prompt, include_internal=True)
+
+ prompt = _get_prompt_version_from_db(team_id, prompt_name, version)
if prompt is None:
return HyperCacheStoreMissing()
- return serialize_prompt(prompt, include_internal=True)
-
- prompt = _get_prompt_version_from_db(team_id, prompt_name, version)
- if prompt is None:
- return HyperCacheStoreMissing()
- return serialize_prompt_version(prompt, include_internal=True)
+ return serialize_prompt_version(prompt, include_internal=True)
+ except _TRANSIENT_DB_ERRORS as err:
+ _record_prompt_db_unavailable(err, prompt_name)
+ raise PromptCacheDatabaseUnavailable(f"Prompt database unavailable loading {prompt_name}") from err
llm_prompts_hypercache = HyperCache(
@@ -145,6 +195,22 @@ def get_prompt_by_name_from_cache(
prompt_name: str,
version: int | None = None,
label: str | None = None,
+) -> dict[str, Any] | None:
+ try:
+ return _get_prompt_by_name_from_cache(team, prompt_name, version, label)
+ except _TRANSIENT_DB_ERRORS as err:
+ # The direct DB fallbacks below bypass the hypercache tier, so a transient DB failure
+ # here (e.g. a PgBouncer query_wait_timeout) must degrade to a miss like the cache tiers
+ # rather than surfacing a 500 on this SDK-facing read.
+ _record_prompt_db_unavailable(err, prompt_name)
+ return None
+
+
+def _get_prompt_by_name_from_cache(
+ team: Team,
+ prompt_name: str,
+ version: int | None = None,
+ label: str | None = None,
) -> dict[str, Any] | None:
latest_key = prompt_latest_cache_key(team.id, prompt_name)
latest_prompt = llm_prompts_hypercache.get_from_cache(latest_key)
diff --git a/posthog/storage/test/test_llm_prompt_cache.py b/posthog/storage/test/test_llm_prompt_cache.py
index cf28024f445e..7196556f9659 100644
--- a/posthog/storage/test/test_llm_prompt_cache.py
+++ b/posthog/storage/test/test_llm_prompt_cache.py
@@ -3,9 +3,15 @@ from datetime import UTC, datetime, timedelta
from posthog.test.base import BaseTest
from unittest.mock import patch
+from django.db import InterfaceError, OperationalError
from django.utils import timezone
+from parameterized import parameterized
+
+from posthog.storage.hypercache import HyperCacheDependencyUnavailable
from posthog.storage.llm_prompt_cache import (
+ _DB_UNAVAILABLE_CAPTURE_THROTTLE_KEY,
+ _load_prompt_cache,
_serialize_prompt,
get_prompt_by_name_from_cache,
invalidate_prompt_label_cache,
@@ -14,7 +20,8 @@ from posthog.storage.llm_prompt_cache import (
invalidate_prompt_version_cache,
llm_prompts_hypercache,
)
-from posthog.storage.llm_prompt_cache_keys import prompt_latest_cache_key
+from posthog.storage.llm_prompt_cache_keys import prompt_label_cache_key, prompt_latest_cache_key
+from posthog.utils import safe_cache_delete
from products.ai_observability.backend.models.llm_prompt import LLMPrompt, LLMPromptLabel
@@ -26,6 +33,9 @@ class TestLLMPromptCache(BaseTest):
super().setUp()
self._clear_known_latest_cache_keys()
self._clear_known_version_cache_keys()
+ # The DB-unavailable capture is throttled through the cache, so leftover state from an
+ # earlier test would silently throttle the capture a later test asserts on.
+ safe_cache_delete(_DB_UNAVAILABLE_CAPTURE_THROTTLE_KEY)
def tearDown(self):
self._clear_known_latest_cache_keys()
@@ -262,6 +272,53 @@ class TestLLMPromptCache(BaseTest):
self.assertEqual(refreshed["id"], str(new_v1.id))
self.assertNotEqual(refreshed["id"], str(old_v1.id))
+ @parameterized.expand([("operational_error", OperationalError), ("interface_error", InterfaceError)])
+ def test_transient_db_error_on_read_degrades_to_miss(self, _name, error_cls):
+ self.create_prompt_version(name="cached-prompt", version=1, is_latest=True)
+
+ # Cold cache forces the DB tier; a transient failure there (e.g. a PgBouncer
+ # query_wait_timeout) must degrade to a miss rather than bubbling a 500 to the caller.
+ with patch(
+ "posthog.storage.llm_prompt_cache._get_latest_prompt_from_db",
+ side_effect=error_cls("query_wait_timeout"),
+ ):
+ result = get_prompt_by_name_from_cache(self.team, "cached-prompt")
+
+ self.assertIsNone(result)
+
+ @parameterized.expand(
+ [
+ ("latest_operational_error", OperationalError, None),
+ ("latest_interface_error", InterfaceError, None),
+ ("label_operational_error", OperationalError, "production"),
+ ]
+ )
+ def test_load_fn_reports_and_reraises_transient_db_error_as_dependency_unavailable(self, _name, error_cls, label):
+ # HyperCacheDependencyUnavailable is what makes the cache tier return a miss without caching
+ # a miss sentinel, so the next read retries instead of serving "not found" for the whole
+ # cache_miss_ttl. The tier does not report the error, so the load_fn owns the capture:
+ # without it a versioned read over a warm latest entry 404s through an outage silently.
+ #
+ # The label case is here because label resolution is a third DB query on its own branch, so
+ # it has to sit inside the same guard. Landing it outside changes nothing the read-path test
+ # can see, since the wrapper in get_prompt_by_name_from_cache still returns None, so this is
+ # the only place the degrade and the report are pinned down for that branch.
+ if label is None:
+ cache_key = prompt_latest_cache_key(self.team.id, "cached-prompt")
+ db_fn = "_get_latest_prompt_from_db"
+ else:
+ cache_key = prompt_label_cache_key(self.team.id, "cached-prompt", label)
+ db_fn = "_get_labeled_prompt_from_db"
+
+ with (
+ patch("posthog.utils.capture_exception") as mock_capture,
+ patch(f"posthog.storage.llm_prompt_cache.{db_fn}", side_effect=error_cls("query_wait_timeout")),
+ ):
+ with self.assertRaises(HyperCacheDependencyUnavailable):
+ _load_prompt_cache(cache_key)
+
+ mock_capture.assert_called_once()
+
def test_exact_fetch_refreshes_latest_cache_entry_missing_generation_marker(self):
self.create_prompt_version(name="cached-prompt", version=1, is_latest=False, prompt="v1")
self.create_prompt_version(name="cached-prompt", version=2, is_latest=True, prompt="v2")