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(egress): route Browserless calls through a gated transport (#92939)

Lucas Ricoya73bfdbdf645
diff --git a/posthog/egress/README.md b/posthog/egress/README.md
index 4877be26c87e..50f68ef47f0e 100644
--- a/posthog/egress/README.md
+++ b/posthog/egress/README.md
@@ -106,6 +106,18 @@ One scrape is one credit, so those numbers cap a bill as much as a rate; they ar
Every Firecrawl call runs on a sheddable lane: what gets scraped is derived from user-supplied input and callers can do without the scrape, so nothing in this domain runs `CRITICAL`.
`FIRECRAWL_API_KEY` authenticates every call as a bearer token; an instance without one makes no request at all (`FirecrawlNotConfigured`).
+Browserless (`browserless/`) meters **concurrent sessions**, not requests, and a session is held for the whole page load: a few seconds for a screenshot, tens of seconds for a Lighthouse audit.
+So its budget counts browser loads asked of one fleet, and the ceilings are small next to an API budget: `BROWSERLESS_EGRESS_PER_MINUTE_BUDGET` (default 120) and `BROWSERLESS_EGRESS_HOURLY_BUDGET` (default 2,000).
+Browserless publishes no rate-limit headers at all — its `X-Response-*` headers describe the page it fetched, not the API's budget — so, like logo.dev and Firecrawl, the budgets are static operator ceilings and the rate-limit gauges stay unset.
+
+The identity is the **fleet**: a hash of host and token together.
+Either alone is wrong. The same credential against a different host is a different set of workers, and a self-hosted fleet often carries no token, which would collapse every such deployment onto one budget if the token were the whole identity.
+The fleet is also what actually runs out: two callers pointed at one Browserless draw from one pool of workers whatever product they serve, so a narrower key would let each stay inside its own limit and still exhaust the fleet between them.
+
+This domain is where priority earns its keep, because its callers differ sharply in urgency.
+Heatmap screenshots run `NORMAL` — somebody is watching a spinner — while background consumers such as the Signals scout's Lighthouse audits run `BATCH` and are shed first, which is what leaves headroom for the render a person is waiting on.
+A denied call raises `BrowserlessEgressBudgetExhausted`; the heatmap caller maps it to its existing retryable error, under its own failure cause so a busy fleet is not read as a broken one.
+
Harmonic (`harmonic/`) meters one account-wide rate limit, and an instance holds a single API key, so it uses one constant scope like the two above.
The budget is a single per-second ceiling read from settings at acquire time: `HARMONIC_EGRESS_PER_SECOND_BUDGET` (default 15).
Harmonic documents a per-second limit for most endpoints and answers 429 above it, reporting the current limit and remaining allowance in `X-Ratelimit-Limit-Second` and `X-Ratelimit-Remaining-Second` on every response.
diff --git a/posthog/egress/browserless/__init__.py b/posthog/egress/browserless/__init__.py
new file mode 100644
index 000000000000..6f4e16f78302
--- /dev/null
+++ b/posthog/egress/browserless/__init__.py
@@ -0,0 +1 @@
+"""Gated, recorded egress to a Browserless fleet."""
diff --git a/posthog/egress/browserless/limiter.py b/posthog/egress/browserless/limiter.py
new file mode 100644
index 000000000000..77839d934881
--- /dev/null
+++ b/posthog/egress/browserless/limiter.py
@@ -0,0 +1,40 @@
+"""Outbound Browserless budget, keyed by the fingerprint of the fleet's token.
+
+Browserless meters concurrent sessions rather than requests, and a session is held for the whole
+page load: a few seconds for a screenshot, tens of seconds for a Lighthouse audit. So the budget
+below counts browser loads asked of one fleet, not API chatter, and the ceilings are small next
+to a typical API budget.
+
+The fleet is the unit because that is what actually runs out. Two callers pointed at one
+Browserless draw from one pool of workers whatever team or product they serve, so keying on
+anything narrower would let them each stay inside their own limit and still exhaust the fleet
+between them. Callers pointed at separate fleets fingerprint differently and never interfere.
+"""
+
+from django.conf import settings
+
+from posthog.egress.limiter.outbound import get_outbound_rate_limiter
+from posthog.egress.limiter.policies import Priority, RatePolicy, register_policy
+
+BROWSERLESS_DOMAIN = "browserless"
+
+
+def _browserless_policy(_key: str) -> RatePolicy:
+ return RatePolicy(
+ limits=(
+ (int(getattr(settings, "BROWSERLESS_EGRESS_PER_MINUTE_BUDGET", 120)), 60.0),
+ (int(getattr(settings, "BROWSERLESS_EGRESS_HOURLY_BUDGET", 2_000)), 3600.0),
+ ),
+ in_memory_divider=4,
+ )
+
+
+register_policy(BROWSERLESS_DOMAIN, _browserless_policy)
+
+
+def consume_browserless_sync(scope: str, *, priority: Priority, source: str) -> bool:
+ return get_outbound_rate_limiter().consume_sync(
+ f"{BROWSERLESS_DOMAIN}:fleet:{scope}",
+ priority=priority,
+ source=source,
+ )
diff --git a/posthog/egress/browserless/observability.py b/posthog/egress/browserless/observability.py
new file mode 100644
index 000000000000..b674517fef16
--- /dev/null
+++ b/posthog/egress/browserless/observability.py
@@ -0,0 +1,79 @@
+"""Browserless outbound request telemetry.
+
+Browserless returns no rate-limit headers. Its `X-Response-*` headers describe the page it
+fetched, not the API's own budget, so there is nothing to read a remaining count or a reset time
+out of, and the snapshot below stays empty rather than inventing one. Volume, status, and latency
+are what this domain can honestly report; the gauges exist because the shared metric set declares
+them, and they simply stay unset. Verified against the hosted fleet, which returns a bare 200
+with no `X-RateLimit-*` and no `Retry-After`.
+"""
+
+from collections.abc import Mapping
+
+import requests
+from prometheus_client import Counter, Gauge
+
+from posthog.egress.browserless.limiter import BROWSERLESS_DOMAIN
+from posthog.egress.observability.observability import (
+ EgressMetrics,
+ EgressObservability,
+ RateLimitSnapshot,
+ register_egress_observability,
+ unpack_requests_response,
+)
+
+_metrics = EgressMetrics(
+ request_counter=Counter(
+ "browserless_requests",
+ "Outbound Browserless requests.",
+ labelnames=["scope", "method", "endpoint", "status_code", "source"],
+ ),
+ remaining_gauge=Gauge(
+ "browserless_rate_limit_remaining",
+ "Unused: Browserless publishes no rate-limit headers.",
+ labelnames=["scope", "resource"],
+ ),
+ limit_gauge=Gauge(
+ "browserless_rate_limit_limit",
+ "Unused: Browserless publishes no rate-limit headers.",
+ labelnames=["scope", "resource"],
+ ),
+ reset_gauge=Gauge(
+ "browserless_rate_limit_reset_at",
+ "Unused: Browserless publishes no rate-limit headers.",
+ labelnames=["scope", "resource"],
+ ),
+)
+
+
+def _parse_browserless_rate_limit(_headers: Mapping[str, str] | None, _url: str | None) -> RateLimitSnapshot:
+ return RateLimitSnapshot(resource="session")
+
+
+browserless_egress = EgressObservability(BROWSERLESS_DOMAIN, _metrics, _parse_browserless_rate_limit)
+register_egress_observability(browserless_egress)
+
+
+def record_browserless_response(
+ response: requests.Response,
+ *,
+ source: str,
+ scope: str,
+ method: str,
+ endpoint: str,
+) -> None:
+ primitives = unpack_requests_response(response)
+ browserless_egress.record_response(
+ primitives.status_code,
+ primitives.headers,
+ source=source,
+ scope=scope,
+ method=method,
+ endpoint=endpoint,
+ request_method=primitives.request_method,
+ request_url=primitives.request_url,
+ )
+
+
+def record_browserless_exception(*, source: str, scope: str, method: str, endpoint: str, url: str) -> None:
+ browserless_egress.record_exception(source=source, scope=scope, method=method, endpoint=endpoint, url=url)
diff --git a/posthog/egress/browserless/transport.py b/posthog/egress/browserless/transport.py
new file mode 100644
index 000000000000..18d3f2f3c1fc
--- /dev/null
+++ b/posthog/egress/browserless/transport.py
@@ -0,0 +1,103 @@
+"""Gated, recorded transport for calls to a Browserless fleet."""
+
+import hashlib
+from typing import Any
+from urllib.parse import urlsplit
+
+import requests
+
+from posthog.egress.browserless.limiter import consume_browserless_sync
+from posthog.egress.browserless.observability import record_browserless_exception, record_browserless_response
+from posthog.egress.limiter.policies import Priority
+from posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient
+
+
+class BrowserlessEgressBudgetExhausted(EgressBudgetExhausted):
+ pass
+
+
+def fleet_scope(url: str, token: str) -> str:
+ """Identify the pool of browsers a call actually competes for.
+
+ Host and token together, because either alone is wrong. The same credential against a
+ different host is a different set of workers, and a self-hosted fleet often has no token at
+ all, which would collapse every such deployment onto one shared budget if the token were the
+ whole identity.
+
+ Hashed rather than stored plainly because the token is a secret and the scope is a metric
+ label: it reaches Prometheus, and from there dashboards and alerts.
+ """
+ host = urlsplit(url).hostname or ""
+ if not host and not token:
+ return ""
+ return hashlib.sha256(f"{host}|{token}".encode()).hexdigest()[:16]
+
+
+class BrowserlessClient(EgressClient):
+ def _standard_headers(self) -> dict[str, str]:
+ return {"Content-Type": "application/json"}
+
+ def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:
+ return consume_browserless_sync(scope, priority=priority, source=source)
+
+ def _record_response(
+ self, response: requests.Response, *, source: str, scope: str | None, method: str, endpoint: str | None
+ ) -> None:
+ record_browserless_response(
+ response,
+ source=source,
+ scope=scope or "",
+ method=method,
+ endpoint=endpoint or "unknown",
+ )
+
+ def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:
+ record_browserless_exception(
+ source=source,
+ scope=scope or "",
+ method=method,
+ endpoint=endpoint or "unknown",
+ url=url,
+ )
+
+ def _budget_exhausted_error(self, scope: str) -> BrowserlessEgressBudgetExhausted:
+ return BrowserlessEgressBudgetExhausted("Browserless egress budget exhausted")
+
+
+_browserless_client = BrowserlessClient()
+
+
+def browserless_request(
+ method: str,
+ url: str,
+ *,
+ token: str,
+ source: str,
+ endpoint: str,
+ priority: Priority = Priority.NORMAL,
+ timeout: float | tuple[float, float] | None = None,
+ session: requests.Session | None = None,
+ **kwargs: Any,
+) -> requests.Response:
+ """One Browserless call, gated against the fleet's budget and recorded.
+
+ The token stays in `url`'s query string, which is where Browserless wants it: its REST routes
+ do not accept an `Authorization` header. It is passed separately as well so the fleet can be
+ fingerprinted without parsing it back out of the url.
+
+ `priority` is the lever that matters here. Every caller draws on one budget per fleet, so a
+ background consumer should ask as `BATCH` and be shed first, leaving the headroom for work
+ somebody is waiting on. Raises `BrowserlessEgressBudgetExhausted` when the fleet's budget is
+ spent; the limiter does not block, so backing off is the caller's job.
+ """
+ return _browserless_client.request(
+ method,
+ url,
+ source=source,
+ scope=fleet_scope(url, token),
+ priority=priority,
+ endpoint=endpoint,
+ timeout=timeout,
+ session=session,
+ **kwargs,
+ )
diff --git a/posthog/egress/test/test_browserless_transport.py b/posthog/egress/test/test_browserless_transport.py
new file mode 100644
index 000000000000..08452c37a177
--- /dev/null
+++ b/posthog/egress/test/test_browserless_transport.py
@@ -0,0 +1,89 @@
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+import requests
+from parameterized import parameterized
+
+from posthog.egress.browserless.transport import BrowserlessEgressBudgetExhausted, browserless_request, fleet_scope
+from posthog.egress.limiter.policies import Priority
+
+_TOKEN = "s3cret-fleet-token"
+_URL = "https://browserless.example.com/screenshot?token=s3cret-fleet-token"
+
+
+def _ok_response() -> requests.Response:
+ response = requests.Response()
+ response.status_code = 200
+ return response
+
+
+class TestBrowserlessFleetScope(SimpleTestCase):
+ def test_the_token_never_reaches_the_scope_label(self) -> None:
+ # The scope is a Prometheus label, so it travels to dashboards and alerts.
+ scope = fleet_scope(_URL, _TOKEN)
+
+ assert _TOKEN not in scope
+ assert len(scope) == 16
+
+ @parameterized.expand(
+ [
+ # Same credential, different fleet: separate pools of workers, so separate budgets.
+ ("different_host", "https://other.example.com/screenshot", _TOKEN),
+ # Same fleet, rotated credential. Splitting here costs one window of over-admission,
+ # which beats keying on the host alone and merging two unrelated deployments.
+ ("different_token", _URL, "rotated-token"),
+ ]
+ )
+ def test_a_different_fleet_gets_a_different_budget(self, _name: str, url: str, token: str) -> None:
+ assert fleet_scope(url, token) != fleet_scope(_URL, _TOKEN)
+
+ def test_a_tokenless_fleet_is_still_identified_by_host(self) -> None:
+ # Self-hosted Browserless often runs with no token. Falling back to an empty scope would
+ # make the base client identity-blind and drop every such deployment out of the budget.
+ assert fleet_scope("https://browserless.internal/screenshot", "") != ""
+
+
+class TestBrowserlessTransport(SimpleTestCase):
+ def test_a_call_is_gated_on_its_fleet_and_recorded(self) -> None:
+ with (
+ patch("posthog.egress.browserless.transport.consume_browserless_sync", return_value=True) as consume,
+ patch("requests.request", return_value=_ok_response()) as request,
+ patch("posthog.egress.browserless.transport.record_browserless_response") as record,
+ ):
+ browserless_request(
+ "POST",
+ _URL,
+ token=_TOKEN,
+ source="heatmap_screenshot",
+ endpoint="screenshot",
+ priority=Priority.NORMAL,
+ json={"url": "https://example.com"},
+ )
+
+ assert consume.call_args.args[0] == fleet_scope(_URL, _TOKEN)
+ assert consume.call_args.kwargs["priority"] is Priority.NORMAL
+ # The token stays in the query string: Browserless rejects it as an Authorization header.
+ assert "Authorization" not in request.call_args.kwargs["headers"]
+ assert request.call_args.args[1] == _URL
+ assert record.called
+
+ def test_a_sheddable_call_raises_when_the_fleet_budget_is_spent(self) -> None:
+ # The whole point of one budget per fleet: a background consumer is turned away before it
+ # takes the session a waiting render needs.
+ with (
+ patch("posthog.egress.browserless.transport.consume_browserless_sync", return_value=False),
+ patch("requests.request") as request,
+ ):
+ with self.assertRaises(BrowserlessEgressBudgetExhausted):
+ browserless_request(
+ "POST",
+ _URL,
+ token=_TOKEN,
+ source="signals_lighthouse",
+ endpoint="performance",
+ priority=Priority.BATCH,
+ json={"url": "https://posthog.com/pricing"},
+ )
+
+ request.assert_not_called()
diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.py
index 74778354e7a0..0e794a1855ed 100644
--- a/posthog/settings/integrations.py
+++ b/posthog/settings/integrations.py
@@ -185,6 +185,13 @@ PANDADOC_DPA_TEMPLATE_ID = get_from_env("PANDADOC_DPA_TEMPLATE_ID", "")
UNLAYER_API_KEY = get_from_env("UNLAYER_API_KEY", "")
UNLAYER_API_BASE_URL = get_from_env("UNLAYER_API_BASE_URL", "https://api.unlayer.com")
+# Outbound budget for one Browserless fleet, shared by every caller pointed at it. Browserless
+# meters concurrent sessions, and a session is held for the whole page load, so these count
+# browser loads rather than API calls. Sized above normal draw: the budget is there to stop one
+# consumer exhausting the fleet, not to pace healthy traffic.
+BROWSERLESS_EGRESS_PER_MINUTE_BUDGET = get_from_env("BROWSERLESS_EGRESS_PER_MINUTE_BUDGET", 120, type_cast=int)
+BROWSERLESS_EGRESS_HOURLY_BUDGET = get_from_env("BROWSERLESS_EGRESS_HOURLY_BUDGET", 2000, type_cast=int)
+
HEATMAP_BROWSERLESS_URL = get_from_env("HEATMAP_BROWSERLESS_URL", "")
HEATMAP_BROWSERLESS_TOKEN = get_from_env("HEATMAP_BROWSERLESS_TOKEN", "")
# Browserless /screenshot session cap (ms); must stay under the plan's max-timeout.
diff --git a/products/web_analytics/backend/tasks/heatmap_screenshot.py b/products/web_analytics/backend/tasks/heatmap_screenshot.py
index cd465fd788e0..59d7a116ef1b 100644
--- a/products/web_analytics/backend/tasks/heatmap_screenshot.py
+++ b/products/web_analytics/backend/tasks/heatmap_screenshot.py
@@ -14,6 +14,8 @@ from celery import Task, shared_task
from celery.exceptions import SoftTimeLimitExceeded
from prometheus_client import Counter, Gauge, Histogram
+from posthog.egress.browserless.transport import BrowserlessEgressBudgetExhausted, browserless_request
+from posthog.egress.limiter.policies import Priority
from posthog.exceptions_capture import capture_exception
from posthog.ph_client import ph_scoped_capture
from posthog.scoping_audit import skip_team_scope_audit
@@ -101,6 +103,8 @@ def _classify_failure(e: BaseException) -> str:
return "not_configured"
if e.cause in ("empty_body", "non_image", "non_jpeg", "oversized"):
return "validation_error"
+ if e.cause == "egress_budget_exhausted":
+ return "egress_budget_exhausted"
if e.cause == "request_exception":
return "browserless_timeout"
if e.status_code is not None:
@@ -414,7 +418,31 @@ def _browserless_screenshot(
width_bucket = _width_bucket(width)
started = time.monotonic()
try:
- response = requests.post(endpoint_url, json=body, timeout=timeout)
+ # NORMAL, not BATCH: somebody is waiting on this render. Background consumers of the same
+ # fleet ask as BATCH and are shed first, which is what leaves headroom for this call.
+ response = browserless_request(
+ "POST",
+ endpoint_url,
+ token=settings.HEATMAP_BROWSERLESS_TOKEN,
+ source="heatmap_screenshot",
+ endpoint="screenshot",
+ priority=Priority.NORMAL,
+ json=body,
+ timeout=timeout,
+ )
+ except BrowserlessEgressBudgetExhausted as e:
+ # Transient by nature: the budget refills on its own, so the existing retry path is the
+ # right answer. Given its own cause so a starved fleet is not read as a broken one.
+ elapsed = time.monotonic() - started
+ HEATMAP_BROWSERLESS_REQUEST_SECONDS.labels(outcome="error", width_bucket=width_bucket).observe(elapsed)
+ logger.warning(
+ "heatmap_screenshot.browserless_request",
+ width=width,
+ outcome="error",
+ cause="egress_budget_exhausted",
+ latency_ms=round(elapsed * 1000),
+ )
+ raise BrowserlessTransientError(str(e), cause="egress_budget_exhausted") from None
except Exception as e:
elapsed = time.monotonic() - started
HEATMAP_BROWSERLESS_REQUEST_SECONDS.labels(outcome="error", width_bucket=width_bucket).observe(elapsed)
diff --git a/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py b/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py
index 4749c190a348..d8942581672b 100644
--- a/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py
+++ b/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py
@@ -89,13 +89,13 @@ class TestHeatmapScreenshotTask(APIBaseTest):
)
@override_settings(**BROWSERLESS_SETTINGS)
- @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")
- def test_a_captured_error_page_fails_the_heatmap_instead_of_being_stored(self, mock_requests: MagicMock) -> None:
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")
+ def test_a_captured_error_page_fails_the_heatmap_instead_of_being_stored(self, mock_browserless: MagicMock) -> None:
# The render is a valid JPEG of the host's error page, so without the page status this looked
# like a healthy heatmap and the user was shown a picture of a 429.
resp = _make_response(_jpeg(b"err"))
resp.headers = {"content-type": "image/png", "x-response-code": "429"}
- mock_requests.post.return_value = resp
+ mock_browserless.return_value = resp
heatmap = self._make_heatmap()
with self.assertRaises(PageHttpStatusError):
@@ -109,34 +109,34 @@ class TestHeatmapScreenshotTask(APIBaseTest):
@parameterized.expand([("blocking_on", True), ("blocking_off", False)])
@override_settings(**BROWSERLESS_SETTINGS, HEATMAP_BROWSERLESS_BLOCK_ADS=False)
- @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")
def test_per_heatmap_consent_blocking_flows_into_body(
- self, _name: str, block_consent_modals: bool, mock_requests: MagicMock
+ self, _name: str, block_consent_modals: bool, mock_browserless: MagicMock
) -> None:
- mock_requests.post.return_value = _make_response(_jpeg(b"1024"))
+ mock_browserless.return_value = _make_response(_jpeg(b"1024"))
heatmap = self._make_heatmap(block_consent_modals=block_consent_modals)
generate_heatmap_screenshot(heatmap.id)
- body = mock_requests.post.call_args.kwargs["json"]
+ body = mock_browserless.call_args.kwargs["json"]
if block_consent_modals:
assert body["blockConsentModals"] is True
else:
assert "blockConsentModals" not in body
@override_settings(**BROWSERLESS_SETTINGS)
- @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")
- def test_uses_rest_screenshot_api(self, mock_requests: MagicMock) -> None:
- mock_requests.post.return_value = _make_response(_jpeg(b"1024"))
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")
+ def test_uses_rest_screenshot_api(self, mock_browserless: MagicMock) -> None:
+ mock_browserless.return_value = _make_response(_jpeg(b"1024"))
heatmap = self._make_heatmap()
generate_heatmap_screenshot(heatmap.id)
- mock_requests.post.assert_called_once()
- endpoint = mock_requests.post.call_args.args[0]
+ mock_browserless.assert_called_once()
+ endpoint = mock_browserless.call_args.args[1]
assert "/screenshot" in endpoint
assert "token=secret-token" in endpoint
- body = mock_requests.post.call_args.kwargs["json"]
+ body = mock_browserless.call_args.kwargs["json"]
assert body["url"] == "https://example.com"
assert body["viewport"]["width"] == 1024
@@ -156,9 +156,9 @@ class TestHeatmapScreenshotTask(APIBaseTest):
assert event["groups"]["project"] == str(self.team.id)
@override_settings(**BROWSERLESS_SETTINGS)
- @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")
- def test_one_request_per_width(self, mock_requests: MagicMock) -> None:
- mock_requests.post.side_effect = [
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")
+ def test_one_request_per_width(self, mock_browserless: MagicMock) -> None:
+ mock_browserless.side_effect = [
_make_response(_jpeg(b"320")),
_make_response(_jpeg(b"768")),
_make_response(_jpeg(b"1024")),
@@ -168,8 +168,8 @@ class TestHeatmapScreenshotTask(APIBaseTest):
generate_heatmap_screenshot(heatmap.id)
# One /screenshot request per width, each carrying its own viewport width
- assert mock_requests.post.call_count == 3
- bodies = [call.kwargs["json"] for call in mock_requests.post.call_args_list]
+ assert mock_browserless.call_count == 3
+ bodies = [call.kwargs["json"] for call in mock_browserless.call_args_list]
assert [body["viewport"]["width"] for body in bodies] == [320, 768, 1024]
# Narrow widths render as a touch/mobile viewport
assert bodies[0]["viewport"]["isMobile"] is True
@@ -182,26 +182,26 @@ class TestHeatmapScreenshotTask(APIBaseTest):
assert snaps == {320: _jpeg(b"320"), 768: _jpeg(b"768"), 1024: _jpeg(b"1024")}
@override_settings(**BROWSERLESS_SETTINGS)
- @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")
- def test_skips_widths_that_are_already_rendered(self, mock_requests: MagicMock) -> None:
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")
+ def test_skips_widths_that_are_already_rendered(self, mock_browserless: MagicMock) -> None:
# A promoted prewarm arrives with its preview width already captured — only the missing widths
# should render, and the reused bytes must be left untouched.
- mock_requests.post.return_value = _make_response(_jpeg(b"768"))
+ mock_browserless.return_value = _make_response(_jpeg(b"768"))
heatmap = self._make_heatmap(target_widths=[768, 1024])
HeatmapSnapshot.objects.create(heatmap=heatmap, width=1024, content=_jpeg(b"preview"))
generate_heatmap_screenshot(heatmap.id)
- mock_requests.post.assert_called_once()
- assert mock_requests.post.call_args.kwargs["json"]["viewport"]["width"] == 768
+ mock_browserless.assert_called_once()
+ assert mock_browserless.call_args.kwargs["json"]["viewport"]["width"] == 768
heatmap.refresh_from_db()
assert heatmap.status == SavedHeatmap.Status.COMPLETED
snaps = {s.width: s.content for s in HeatmapSnapshot.objects.filter(heatmap=heatmap)}
assert snaps == {768: _jpeg(b"768"), 1024: _jpeg(b"preview")}
@override_settings(**BROWSERLESS_SETTINGS)
- @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")
- def test_reenqueues_followup_when_widths_grow_during_render(self, mock_requests: MagicMock) -> None:
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")
+ def test_reenqueues_followup_when_widths_grow_during_render(self, mock_browserless: MagicMock) -> None:
# A create can promote this prewarm to more widths while its single preview width renders. The
# task must not mark 'completed' with widths still owed — it finishes them in a follow-up run.
heatmap = self._make_heatmap(target_widths=[1024])
@@ -210,7 +210,7 @@ class TestHeatmapScreenshotTask(APIBaseTest):
SavedHeatmap.objects.filter(id=heatmap.id).update(target_widths=[768, 1024])
return _make_response(_jpeg(b"1024"))
- mock_requests.post.side_effect = render_then_grow
+ mock_browserless.side_effect = render_then_grow
with patch(
"products.web_analytics.backend.tasks.heatmap_screenshot.generate_heatmap_screenshot.delay"
@@ -222,10 +222,10 @@ class TestHeatmapScreenshotTask(APIBaseTest):
mock_delay.assert_called_once_with(heatmap.id)
@override_settings(**BROWSERLESS_SETTINGS)
- @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")
- def test_failure_on_later_width_marks_failed_and_keeps_earlier_widths(self, mock_requests: MagicMock) -> None:
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")
+ def test_failure_on_later_width_marks_failed_and_keeps_earlier_widths(self, mock_browserless: MagicMock) -> None:
# First width succeeds, second width's request fails
- mock_requests.post.side_effect = [_make_response(_jpeg(b"320")), Exception("boom on second width")]
+ mock_browserless.side_effect = [_make_response(_jpeg(b"320")), Exception("boom on second width")]
heatmap = self._make_heatmap(target_widths=[320, 768])
@@ -275,15 +275,15 @@ class TestBrowserlessScreenshotRequest(SimpleTestCase):
]
)
@override_settings(**BROWSERLESS_SETTINGS)
- @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")
def test_reports_the_pages_own_status_from_the_response_header(
- self, _name: str, headers: dict[str, str], expected: int | None, mock_requests: MagicMock
+ self, _name: str, headers: dict[str, str], expected: int | None, mock_browserless: MagicMock
) -> None:
# Browserless answers 200 with a valid JPEG even when the page it rendered returned 429, so
# this header is the only thing that distinguishes a heatmap from a picture of an error page.
resp = _make_response(_jpeg(b"img"))
resp.headers = {"content-type": "image/png", **headers}
- mock_requests.post.return_value = resp
+ mock_browserless.return_value = resp
content, page_status = _browserless_screenshot(
"https://host/screenshot?token=t", "https://ex.com", 1024, block_consent_modals=False
@@ -298,18 +298,18 @@ class TestBrowserlessScreenshotRequest(SimpleTestCase):
HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS=30000,
HEATMAP_BROWSERLESS_BLOCK_ADS=False,
)
- @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")
def test_posts_full_page_body_with_viewport_width(
- self, _name: str, width: int, is_mobile: bool, mock_requests: MagicMock
+ self, _name: str, width: int, is_mobile: bool, mock_browserless: MagicMock
) -> None:
- mock_requests.post.return_value = _make_response(_jpeg(b"img"))
+ mock_browserless.return_value = _make_response(_jpeg(b"img"))
content, _ = _browserless_screenshot(
"https://host/screenshot?token=t", "https://example.com", width, block_consent_modals=True
)
assert content == _jpeg(b"img")
- body = mock_requests.post.call_args.kwargs["json"]
+ body = mock_browserless.call_args.kwargs["json"]
assert body["url"] == "https://example.com"
assert body["viewport"]["width"] == width
assert body["viewport"]["isMobile"] is is_mobile
@@ -319,35 +319,35 @@ class TestBrowserlessScreenshotRequest(SimpleTestCase):
assert body["blockConsentModals"] is True
assert "blockAds" not in body
# (connect, read) timeout tuple wired from settings
- assert mock_requests.post.call_args.kwargs["timeout"] == (30.0, 210.0)
+ assert mock_browserless.call_args.kwargs["timeout"] == (30.0, 210.0)
@override_settings(
HEATMAP_BROWSERLESS_TIMEOUT_MS=180000,
HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS=30000,
HEATMAP_BROWSERLESS_BLOCK_ADS=True,
)
- @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")
- def test_block_ads_added_to_body_when_enabled(self, mock_requests: MagicMock) -> None:
- mock_requests.post.return_value = _make_response()
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")
+ def test_block_ads_added_to_body_when_enabled(self, mock_browserless: MagicMock) -> None:
+ mock_browserless.return_value = _make_response()
_browserless_screenshot(
"https://host/screenshot?token=t", "https://example.com", 1024, block_consent_modals=False
)
- assert mock_requests.post.call_args.kwargs["json"]["blockAds"] is True
+ assert mock_browserless.call_args.kwargs["json"]["blockAds"] is True
@override_settings(
HEATMAP_BROWSERLESS_TIMEOUT_MS=180000,
HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS=30000,
HEATMAP_BROWSERLESS_BLOCK_ADS=False,
)
- @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")
- def test_cloud_only_fields_omitted_when_disabled(self, mock_requests: MagicMock) -> None:
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")
+ def test_cloud_only_fields_omitted_when_disabled(self, mock_browserless: MagicMock) -> None:
# The self-hosted OSS browserless image rejects bodies carrying these cloud-only fields,
# so disabling them must omit the keys entirely rather than send false.
- mock_requests.post.return_value = _make_response()
+ mock_browserless.return_value = _make_response()
_browserless_screenshot(
"https://host/screenshot?token=t", "https://example.com", 1024, block_consent_modals=False
)
- body = mock_requests.post.call_args.kwargs["json"]
+ body = mock_browserless.call_args.kwargs["json"]
assert "blockAds" not in body
assert "blockConsentModals" not in body
@@ -357,13 +357,13 @@ class TestBrowserlessScreenshotRequest(SimpleTestCase):
HEATMAP_BROWSERLESS_TIMEOUT_MS=180000,
HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS=30000,
)
- @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")
- def test_failure_redacts_token(self, mode: str, mock_requests: MagicMock) -> None:
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")
+ def test_failure_redacts_token(self, mode: str, mock_browserless: MagicMock) -> None:
endpoint = "https://host/screenshot?token=secret-token&timeout=180000"
if mode == "non_200":
- mock_requests.post.return_value = _make_response(b"", status=401, text="Unauthorized token=secret-token")
+ mock_browserless.return_value = _make_response(b"", status=401, text="Unauthorized token=secret-token")
else:
- mock_requests.post.side_effect = Exception("ECONNREFUSED https://host/screenshot?token=secret-token")
+ mock_browserless.side_effect = Exception("ECONNREFUSED https://host/screenshot?token=secret-token")
with self.assertRaises(BrowserlessError) as ctx:
_browserless_screenshot(endpoint, "https://example.com", 1024, block_consent_modals=False)
@@ -381,12 +381,12 @@ class TestBrowserlessScreenshotRequest(SimpleTestCase):
]
)
@override_settings(HEATMAP_BROWSERLESS_TIMEOUT_MS=180000, HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS=30000)
- @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")
def test_rejects_invalid_200_body(
- self, _name: str, content: bytes, content_type: str, mock_requests: MagicMock
+ self, _name: str, content: bytes, content_type: str, mock_browserless: MagicMock
) -> None:
# A 200 that isn't a real JPEG must not be stored and served as image/jpeg.
- mock_requests.post.return_value = _make_response(content, content_type=content_type)
+ mock_browserless.return_value = _make_response(content, content_type=content_type)
with self.assertRaises(BrowserlessError):
_browserless_screenshot(
"https://host/screenshot?token=t", "https://example.com", 1024, block_consent_modals=False
@@ -394,9 +394,9 @@ class TestBrowserlessScreenshotRequest(SimpleTestCase):
@override_settings(HEATMAP_BROWSERLESS_TIMEOUT_MS=180000, HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS=30000)
@patch("products.web_analytics.backend.tasks.heatmap_screenshot.HEATMAP_SCREENSHOT_MAX_BYTES", 8)
- @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")
- def test_rejects_oversized_body_as_permanent(self, mock_requests: MagicMock) -> None:
- mock_requests.post.return_value = _make_response(_jpeg(b"way over the cap"))
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")
+ def test_rejects_oversized_body_as_permanent(self, mock_browserless: MagicMock) -> None:
+ mock_browserless.return_value = _make_response(_jpeg(b"way over the cap"))
with self.assertRaises(BrowserlessPermanentError):
_browserless_screenshot(
"https://host/screenshot?token=t", "https://example.com", 1024, block_consent_modals=False
diff --git a/products/web_analytics/backend/test/test_heatmap_screenshots.py b/products/web_analytics/backend/test/test_heatmap_screenshots.py
index 4bb7e0cad446..06cbbb28ab9c 100644
--- a/products/web_analytics/backend/test/test_heatmap_screenshots.py
+++ b/products/web_analytics/backend/test/test_heatmap_screenshots.py
@@ -16,6 +16,8 @@ from rest_framework import status
from rest_framework.test import APIClient
from posthog.auth import mint_export_renderer_token
+from posthog.egress.browserless.transport import BrowserlessEgressBudgetExhausted
+from posthog.egress.limiter.policies import Priority
from posthog.models import Team
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
@@ -25,6 +27,11 @@ from products.exports.backend.models.exported_asset import ExportedAsset
from products.web_analytics.backend.api.heatmaps_api import SavedHeatmapCaptureRequestSerializer
from products.web_analytics.backend.heatmap_preflight import PreflightResult
from products.web_analytics.backend.models import HeatmapSnapshot, SavedHeatmap
+from products.web_analytics.backend.tasks.heatmap_screenshot import (
+ BrowserlessTransientError,
+ _browserless_screenshot,
+ _classify_failure,
+)
class TestHeatmapsAPI(APIBaseTest):
@@ -707,3 +714,46 @@ class TestSavedHeatmapCaptureRequestSerializer(SimpleTestCase):
data["width"] = 1024
serializer = SavedHeatmapCaptureRequestSerializer(data=data)
self.assertFalse(serializer.is_valid())
+
+
+class TestBrowserlessEgressBudget(SimpleTestCase):
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")
+ def test_a_spent_fleet_budget_is_retryable_and_named_as_itself(self, browserless_request: MagicMock) -> None:
+ # A starved fleet refills on its own, so this must stay on the retry path rather than
+ # being classified permanent. It carries its own cause so the failure metric separates
+ # "the fleet is busy" from "Browserless is broken", which want different responses.
+ browserless_request.side_effect = BrowserlessEgressBudgetExhausted("Browserless egress budget exhausted")
+
+ with self.settings(
+ HEATMAP_BROWSERLESS_TOKEN="t",
+ HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS=1000,
+ HEATMAP_BROWSERLESS_TIMEOUT_MS=30000,
+ HEATMAP_BROWSERLESS_BLOCK_ADS=False,
+ ):
+ with self.assertRaises(BrowserlessTransientError) as caught:
+ _browserless_screenshot(
+ "https://browserless.example.com/screenshot?token=t", "https://x.test", 1024, False
+ )
+
+ assert caught.exception.cause == "egress_budget_exhausted"
+ assert _classify_failure(caught.exception) == "egress_budget_exhausted"
+
+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.browserless_request")
+ def test_the_render_asks_on_the_lane_a_person_is_waiting_on(self, browserless_request: MagicMock) -> None:
+ # NORMAL, not BATCH: shedding this one makes somebody stare at a spinner. Background
+ # consumers of the same fleet ask as BATCH so they yield to it.
+ browserless_request.side_effect = BrowserlessEgressBudgetExhausted("spent")
+
+ with self.settings(
+ HEATMAP_BROWSERLESS_TOKEN="t",
+ HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS=1000,
+ HEATMAP_BROWSERLESS_TIMEOUT_MS=30000,
+ HEATMAP_BROWSERLESS_BLOCK_ADS=False,
+ ):
+ with self.assertRaises(BrowserlessTransientError):
+ _browserless_screenshot(
+ "https://browserless.example.com/screenshot?token=t", "https://x.test", 1024, False
+ )
+
+ assert browserless_request.call_args.kwargs["priority"] is Priority.NORMAL
+ assert browserless_request.call_args.kwargs["source"] == "heatmap_screenshot"