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(logs): throttle Snuffle queries by bytes read (#102260)

Frank Hamand75feadda5910
diff --git a/docs/published/docs/logs/logql-api.mdx b/docs/published/docs/logs/logql-api.mdx
index 81c94aaf1a48..22642fc65b7b 100644
--- a/docs/published/docs/logs/logql-api.mdx
+++ b/docs/published/docs/logs/logql-api.mdx
@@ -60,7 +60,9 @@ Query errors keep the Loki error format, so Grafana shows them inline.
## Rate limits
-The endpoint shares the [API rate limits](/docs/api#rate-limiting) of the project. Grafana dashboards with many panels count one request per panel per refresh.
+The endpoint uses the project's ClickHouse read-byte budget. Snuffle reports the bytes that ClickHouse read after each query, and that amount is taken from a Redis token bucket. The bucket refills continuously and has a capped balance.
+
+When the budget is empty, the next request returns `429` with `Retry-After`. Grafana dashboards with many panels can use different amounts because each panel is charged for its actual ClickHouse read volume, not one request.
## Self-hosted
diff --git a/posthog/api/snuffle_proxy.py b/posthog/api/snuffle_proxy.py
index 440c70d867cf..368c46a6d469 100644
--- a/posthog/api/snuffle_proxy.py
+++ b/posthog/api/snuffle_proxy.py
@@ -10,6 +10,8 @@ HTTP Basic auth and never exposed to the API caller.
import re
import json
+import threading
+from concurrent.futures import ThreadPoolExecutor
from typing import ClassVar
from django.conf import settings
@@ -24,6 +26,8 @@ from rest_framework.parsers import FormParser
from rest_framework.request import Request
from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api_queries_budget import debit
+from posthog.hogql_queries.query_runner import api_queries_budget_enforcement_enabled, get_api_queries_budget_status
from posthog.permissions import PostHogFeatureFlagPermission
from posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle
from posthog.security.outbound_proxy import internal_requests
@@ -35,6 +39,13 @@ logger = structlog.get_logger(__name__)
SNUFFLE_API_FEATURE_FLAG = "logs-metrics-snuffle-api"
TEAM_ID_HEADER = "X-Team-ID"
+SNUFFLE_READ_BYTES_HEADER = "X-Snuffle-ClickHouse-Read-Bytes"
+# Debit outside the response-critical path. The bound limits work retained in a web process if
+# Redis is slow or unavailable; a skipped debit is safe because the budget deliberately fails open.
+SNUFFLE_BUDGET_DEBIT_MAX_PENDING = 8
+_snuffle_budget_debit_slots = threading.BoundedSemaphore(SNUFFLE_BUDGET_DEBIT_MAX_PENDING)
+_snuffle_budget_debit_executor: ThreadPoolExecutor | None = None
+_snuffle_budget_debit_executor_lock = threading.Lock()
# Snuffle also accepts the tenant as a `team_id` parameter, with lower precedence than the header;
# strip it so the forwarded request only ever names the team from the URL. PostHog accepts the
# caller's personal API key as a parameter too, and that must never leave PostHog.
@@ -55,6 +66,54 @@ def _error_response(status_code: int, error_type: str, message: str) -> HttpResp
)
+def _read_bytes_from(upstream: requests.Response) -> int | None:
+ """Read the total ClickHouse bytes that Snuffle reports for this request.
+
+ A missing or malformed header means an older or unhealthy upstream. Metering
+ must fail open in that case, like the shared query budget does.
+ """
+ value = upstream.headers.get(SNUFFLE_READ_BYTES_HEADER)
+ if value is None:
+ return None
+ try:
+ bytes_read = int(value)
+ except (TypeError, ValueError):
+ logger.warning("snuffle_proxy_invalid_read_bytes", value=value)
+ return None
+ return bytes_read if bytes_read >= 0 else None
+
+
+def _get_snuffle_budget_debit_executor() -> ThreadPoolExecutor:
+ # Start the threads in the serving worker rather than in a pre-fork parent process.
+ global _snuffle_budget_debit_executor
+ if _snuffle_budget_debit_executor is None:
+ with _snuffle_budget_debit_executor_lock:
+ if _snuffle_budget_debit_executor is None:
+ _snuffle_budget_debit_executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="snuffle-budget")
+ return _snuffle_budget_debit_executor
+
+
+def schedule_snuffle_budget_debit(team_id: str, bytes_read: int) -> None:
+ """Debit the query budget without delaying a completed Snuffle response."""
+ if not _snuffle_budget_debit_slots.acquire(blocking=False):
+ logger.warning("snuffle_proxy_budget_debit_skipped", team_id=team_id, reason="saturated")
+ return
+
+ def _debit() -> None:
+ try:
+ debit(team_id, bytes_read)
+ except Exception:
+ logger.exception("snuffle_proxy_budget_debit_failed", team_id=team_id)
+ finally:
+ _snuffle_budget_debit_slots.release()
+
+ try:
+ _get_snuffle_budget_debit_executor().submit(_debit)
+ except Exception:
+ _snuffle_budget_debit_slots.release()
+ logger.exception("snuffle_proxy_budget_debit_submit_failed", team_id=team_id)
+
+
class SnuffleProxyViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
"""Base for the team-scoped Prometheus- and Loki-compatible query endpoints.
@@ -72,8 +131,20 @@ class SnuffleProxyViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
permission_classes = [PostHogFeatureFlagPermission]
# The Prometheus and Loki APIs take POST bodies as form fields, the same shape as the query string.
parser_classes = [FormParser]
+ # Kept as a fallback until the upstream version that reports read bytes is deployed.
+ # The byte-budget flag removes these request-count limits before the proxy action runs.
throttle_classes = [ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottle]
+ def _is_api_queries_budget_enforced(self) -> bool:
+ if not hasattr(self, "_api_queries_budget_enforced"):
+ self._api_queries_budget_enforced = api_queries_budget_enforcement_enabled(self.team)
+ return self._api_queries_budget_enforced
+
+ def get_throttles(self):
+ if self._is_api_queries_budget_enforced():
+ return []
+ return super().get_throttles()
+
@extend_schema(exclude=True)
@action(detail=False, methods=["GET", "POST"], url_path=r"api/v1/(?P<path>[A-Za-z0-9_./-]+)")
def proxy(self, request: Request, path: str, **kwargs) -> HttpResponse:
@@ -90,6 +161,17 @@ class SnuffleProxyViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
)
team_id = self.team_id
+ enforcement_enabled = self._is_api_queries_budget_enforced()
+ budget_status = get_api_queries_budget_status(self.team) if enforcement_enabled else None
+ if budget_status is not None and budget_status.remaining_bytes <= 0:
+ response = _error_response(
+ status.HTTP_429_TOO_MANY_REQUESTS,
+ "rate_limited",
+ "ClickHouse query byte budget exhausted. Try again later.",
+ )
+ response["Retry-After"] = str(budget_status.retry_after_seconds)
+ return response
+
method = request.method or "GET"
url = f"{base_url.rstrip('/')}{self.upstream_prefix}/{path}"
params = _forwardable(request.query_params)
@@ -122,8 +204,13 @@ class SnuffleProxyViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
if upstream.status_code >= 500:
logger.warning("snuffle_proxy_upstream_error", team_id=team_id, path=path, status=upstream.status_code)
- return HttpResponse(
+ response = HttpResponse(
upstream.content,
status=upstream.status_code,
content_type=upstream.headers.get("Content-Type", "application/json"),
)
+ bytes_read = _read_bytes_from(upstream)
+ if bytes_read is not None:
+ schedule_snuffle_budget_debit(str(team_id), bytes_read)
+ response["X-PostHog-Query-Bytes-Read"] = str(bytes_read)
+ return response
diff --git a/posthog/api_queries_budget.py b/posthog/api_queries_budget.py
index 089e2329c839..42fb0ce6e241 100644
--- a/posthog/api_queries_budget.py
+++ b/posthog/api_queries_budget.py
@@ -32,6 +32,9 @@ from posthog.redis import get_client
BUDGET_KEY_PREFIX = "@posthog/api-queries-budget/"
# A bucket nobody touches for a week is rebuilt full on the next read, so the key can expire.
BUDGET_TTL_SECONDS = 7 * 24 * 3600
+# Budget checks run on request paths and fail open, so they must not inherit the longer timeout
+# used by Redis callers that can safely wait for blocking commands.
+BUDGET_REDIS_TIMEOUT_SECONDS = 1.0
API_QUERIES_BUDGET_ERRORS_COUNTER = Counter(
"posthog_api_queries_budget_errors_total",
@@ -83,6 +86,13 @@ def _bucket_key(team_id: str) -> str:
return f"{BUDGET_KEY_PREFIX}team/{team_id}"
+def _budget_redis_client():
+ return get_client(
+ socket_timeout=BUDGET_REDIS_TIMEOUT_SECONDS,
+ socket_connect_timeout=BUDGET_REDIS_TIMEOUT_SECONDS,
+ )
+
+
# KEYS[1] bucket, ARGV[1] now in seconds, ARGV[2] bytes per hour, ARGV[3] capacity, ARGV[4] ttl.
# A missing bucket starts full. The floor is one hour of refill. Capacity and floor are stored so
# a debit that arrives before any read (a chargeable query that did not go through the query
@@ -119,7 +129,7 @@ return tostring(tokens)
def refill_and_read(team_id: str, spec: BudgetSpec, now: Optional[float] = None) -> Optional[float]:
try:
- result = get_client().eval(
+ result = _budget_redis_client().eval(
_REFILL_AND_READ,
1,
_bucket_key(team_id),
@@ -142,7 +152,7 @@ def debit(team_id: str, bytes_read: int) -> Optional[float]:
return None
free = _free_spec()
try:
- result = get_client().eval(
+ result = _budget_redis_client().eval(
_DEBIT,
1,
_bucket_key(team_id),
@@ -164,7 +174,7 @@ LIMITED_EVENT_INTERVAL_SECONDS = 3600
def claim_limited_event(team_id: str) -> bool:
try:
return bool(
- get_client().set(
+ _budget_redis_client().set(
f"{BUDGET_KEY_PREFIX}limited-event/{team_id}", "1", nx=True, ex=LIMITED_EVENT_INTERVAL_SECONDS
)
)
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index f60dc163029b..85e9c41eed03 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -432,6 +432,15 @@ def _api_queries_budget_enforcement_enabled(team: Team) -> bool:
return False
+def api_queries_budget_enforcement_enabled(team: Team) -> bool:
+ """Whether the read-byte budget rejects API requests for this team.
+
+ Kept separate from the query runner so other ClickHouse API proxies use the
+ same staged rollout without depending on its private helper.
+ """
+ return _api_queries_budget_enforcement_enabled(team)
+
+
@frozen
class BudgetStatus:
remaining_bytes: float
diff --git a/posthog/redis.py b/posthog/redis.py
index fc835c7a364d..102c5e96dd4e 100644
--- a/posthog/redis.py
+++ b/posthog/redis.py
@@ -13,7 +13,7 @@ from redis.asyncio.retry import Retry
from redis.backoff import ExponentialBackoff
-_client_map: Dict[str, Any] = {}
+_client_map: Dict[str | tuple[str, float, float], Any] = {}
_test_async_client_map: Dict[str, Any] = {} # For test mode, where we don't need per-loop isolation
_test_fake_server_map: Dict[str, Any] = {} # Shared FakeServer per url so sync + async fake clients see one store
@@ -26,14 +26,29 @@ def _get_test_fake_server(redis_url: str):
return _test_fake_server_map[redis_url]
-def get_client(redis_url: Optional[str] = None) -> redis.Redis:
- """Return a *synchronous* Redis client (singleton per redis_url)."""
+def get_client(
+ redis_url: Optional[str] = None,
+ *,
+ socket_timeout: Optional[float] = None,
+ socket_connect_timeout: Optional[float] = None,
+) -> redis.Redis:
+ """Return a synchronous Redis client, cached by URL and optional timeouts."""
redis_url = redis_url or settings.REDIS_URL
if redis_url is None:
raise ImproperlyConfigured("REDIS_URL is not configured")
- if not _client_map.get(redis_url):
+ client_socket_timeout = settings.REDIS_SOCKET_TIMEOUT_SECONDS if socket_timeout is None else socket_timeout
+ client_socket_connect_timeout = (
+ settings.REDIS_SOCKET_CONNECT_TIMEOUT_SECONDS if socket_connect_timeout is None else socket_connect_timeout
+ )
+ cache_key: str | tuple[str, float, float] = (
+ redis_url
+ if socket_timeout is None and socket_connect_timeout is None
+ else (redis_url, client_socket_timeout, client_socket_connect_timeout)
+ )
+
+ if not _client_map.get(cache_key):
if settings.TEST:
# This import is only used in tests, we don't want to import it in production
import fakeredis
@@ -43,8 +58,8 @@ def get_client(redis_url: Optional[str] = None) -> redis.Redis:
client = redis.from_url(
redis_url,
db=0,
- socket_timeout=settings.REDIS_SOCKET_TIMEOUT_SECONDS,
- socket_connect_timeout=settings.REDIS_SOCKET_CONNECT_TIMEOUT_SECONDS,
+ socket_timeout=client_socket_timeout,
+ socket_connect_timeout=client_socket_connect_timeout,
)
else:
client = None
@@ -52,9 +67,9 @@ def get_client(redis_url: Optional[str] = None) -> redis.Redis:
if client is None:
raise ImproperlyConfigured("Redis not configured!")
- _client_map[redis_url] = client
+ _client_map[cache_key] = client
- return _client_map[redis_url]
+ return _client_map[cache_key]
_loop_clients: "weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, Dict[str, Any]]" = weakref.WeakKeyDictionary()
diff --git a/posthog/test/test_api_queries_budget.py b/posthog/test/test_api_queries_budget.py
index c219a14e7ea4..5dfacef06dac 100644
--- a/posthog/test/test_api_queries_budget.py
+++ b/posthog/test/test_api_queries_budget.py
@@ -12,6 +12,7 @@ from parameterized import parameterized
from posthog.api_queries_budget import (
API_QUERIES_BUDGET_ERRORS_COUNTER,
BUDGET_KEY_PREFIX,
+ BUDGET_REDIS_TIMEOUT_SECONDS,
BudgetSpec,
QueryCost,
budget_spec_for,
@@ -50,6 +51,15 @@ class TestBudgetSpecFor(SimpleTestCase):
@override_settings(API_QUERIES_BUDGET_FREE_BYTES_PER_HOUR=70, API_QUERIES_BUDGET_CAPACITY_HOURS=24)
class TestTokenBucket(BaseTest):
+ def test_budget_redis_calls_use_a_one_second_timeout(self):
+ with patch("posthog.api_queries_budget.get_client") as get_client:
+ refill_and_read("team-a", SPEC)
+
+ get_client.assert_called_once_with(
+ socket_timeout=BUDGET_REDIS_TIMEOUT_SECONDS,
+ socket_connect_timeout=BUDGET_REDIS_TIMEOUT_SECONDS,
+ )
+
def test_fresh_bucket_starts_full(self):
assert refill_and_read("team-a", SPEC, now=1000.0) == 7200.0
diff --git a/posthog/test/test_redis.py b/posthog/test/test_redis.py
index c30bf1a977d5..2e1480a66e3d 100644
--- a/posthog/test/test_redis.py
+++ b/posthog/test/test_redis.py
@@ -120,6 +120,18 @@ class TestRedis(TestCase):
socket_connect_timeout=settings.REDIS_SOCKET_CONNECT_TIMEOUT_SECONDS,
)
+ def test_sync_redis_client_can_use_shorter_socket_timeouts(self):
+ with patch("redis.from_url") as mock_from_url:
+ with self.settings(TEST=False, REDIS_URL="redis://mocked:6379"):
+ get_client(socket_timeout=1.0, socket_connect_timeout=1.0)
+
+ mock_from_url.assert_called_once_with(
+ "redis://mocked:6379",
+ db=0,
+ socket_timeout=1.0,
+ socket_connect_timeout=1.0,
+ )
+
def test_same_loop_returns_cached_client_test_mode(self):
"""In test mode, calling get_async_client twice returns the same cached instance."""
diff --git a/products/logs/backend/test/test_loki_api.py b/products/logs/backend/test/test_loki_api.py
index 43d27c34cbfc..1368c2b1c818 100644
--- a/products/logs/backend/test/test_loki_api.py
+++ b/products/logs/backend/test/test_loki_api.py
@@ -1,12 +1,13 @@
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
-from django.test import override_settings
+from django.test import SimpleTestCase, override_settings
import requests
from parameterized import parameterized
from rest_framework import status
+import posthog.api.snuffle_proxy as snuffle_proxy
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
@@ -22,7 +23,7 @@ def _upstream(status_code: int = 200, body: bytes = b'{"status":"success","data"
response = MagicMock(spec=requests.Response)
response.status_code = status_code
response.content = body
- response.headers = {"Content-Type": "application/json; charset=utf-8"}
+ response.headers = {"Content-Type": "application/json; charset=utf-8", "X-Snuffle-ClickHouse-Read-Bytes": "1234"}
return response
@@ -39,6 +40,9 @@ class TestLokiQueryApi(APIBaseTest):
ff_patcher = patch("posthoganalytics.feature_enabled", return_value=True)
ff_patcher.start()
self.addCleanup(ff_patcher.stop)
+ debit_patcher = patch("posthog.api.snuffle_proxy.schedule_snuffle_budget_debit")
+ self.schedule_budget_debit = debit_patcher.start()
+ self.addCleanup(debit_patcher.stop)
@parameterized.expand([("bare", "query_range"), ("trailing_slash", "query_range/")])
def test_get_is_forwarded_with_team_header_and_credentials(self, _name: str, path: str):
@@ -50,6 +54,7 @@ class TestLokiQueryApi(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert response["Content-Type"] == "application/json; charset=utf-8"
assert response.content == b'{"status":"success","data":{}}'
+ assert response["X-PostHog-Query-Bytes-Read"] == "1234"
self.request_mock.assert_called_once()
method, url = self.request_mock.call_args.args
kwargs = self.request_mock.call_args.kwargs
@@ -66,6 +71,35 @@ class TestLokiQueryApi(APIBaseTest):
assert kwargs["timeout"] == 12
assert kwargs["data"] is None
+ def test_read_bytes_are_debited_from_the_project_budget(self):
+ response = self.client.get(f"{self.base}/query", {"query": '{service_name="api"}'})
+
+ assert response.status_code == status.HTTP_200_OK
+ self.schedule_budget_debit.assert_called_once_with(str(self.team.pk), 1234)
+ assert "X-PostHog-Query-Budget-Remaining-Bytes" not in response
+
+ @patch("posthog.api.snuffle_proxy.api_queries_budget_enforcement_enabled", return_value=True)
+ @patch("posthog.api.snuffle_proxy.get_api_queries_budget_status")
+ def test_exhausted_byte_budget_refuses_before_reaching_snuffle(self, budget_status, enforced):
+ budget_status.return_value = MagicMock(remaining_bytes=0, retry_after_seconds=42)
+
+ response = self.client.get(f"{self.base}/query", {"query": '{service_name="api"}'})
+
+ assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
+ assert response["Retry-After"] == "42"
+ enforced.assert_called_once_with(self.team)
+ budget_status.assert_called_once_with(self.team)
+ self.request_mock.assert_not_called()
+
+ @patch("posthog.api.snuffle_proxy.api_queries_budget_enforcement_enabled", return_value=False)
+ @patch("posthog.api.snuffle_proxy.get_api_queries_budget_status")
+ def test_disabled_byte_budget_does_not_read_budget_status(self, budget_status, enforced):
+ response = self.client.get(f"{self.base}/query", {"query": '{service_name="api"}'})
+
+ assert response.status_code == status.HTTP_200_OK
+ enforced.assert_called_once_with(self.team)
+ budget_status.assert_not_called()
+
def test_post_form_body_is_forwarded(self):
body = "query=%7Bservice_name%3D%22api%22%7D&start=1&end=2"
response = self.client.post(f"{self.base}/query_range", body, content_type="application/x-www-form-urlencoded")
@@ -192,3 +226,18 @@ class TestLokiQueryApi(APIBaseTest):
assert response.status_code == status.HTTP_401_UNAUTHORIZED
self.request_mock.assert_not_called()
+
+
+class TestSnuffleBudgetDebit(SimpleTestCase):
+ @patch("posthog.api.snuffle_proxy.debit")
+ @patch("posthog.api.snuffle_proxy._get_snuffle_budget_debit_executor")
+ def test_debit_runs_after_scheduling(self, executor, debit_mock):
+ pending: list = []
+ executor.return_value.submit.side_effect = pending.append
+
+ snuffle_proxy.schedule_snuffle_budget_debit("1", 1234)
+
+ debit_mock.assert_not_called()
+ (debit_task,) = pending
+ debit_task()
+ debit_mock.assert_called_once_with("1", 1234)