: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(billing): keep bulk Harmonic lookups moving under slow responses (#101033)
Matt Brookere7ece89630a0
diff --git a/ee/billing/salesforce_enrichment/enrichment.py b/ee/billing/salesforce_enrichment/enrichment.pyindex 8da0bf669e42..646e65ecf2f9 100644--- a/ee/billing/salesforce_enrichment/enrichment.py+++ b/ee/billing/salesforce_enrichment/enrichment.py@@ -827,7 +827,7 @@ async def enrich_accounts_chunked_async(Standard workflow that:1. Queries chunk of Salesforce accounts (from global Redis cache)- 2. Enriches business domains with Harmonic API (default: 5 concurrent requests)+ 2. Enriches business domains with Harmonic API3. Updates Salesforce in batches of 200 using sObject CollectionsArgs:diff --git a/ee/billing/salesforce_enrichment/harmonic_client.py b/ee/billing/salesforce_enrichment/harmonic_client.pyindex 81040f3d0494..aa78b6bb561d 100644--- a/ee/billing/salesforce_enrichment/harmonic_client.py+++ b/ee/billing/salesforce_enrichment/harmonic_client.py@@ -1,5 +1,6 @@import timeimport asyncio+from contextlib import suppressfrom typing import Any, Optionalfrom django.conf import settings@@ -8,6 +9,7 @@ import aiohttpfrom posthog.dataclasses import frozenfrom posthog.egress.harmonic.limiter import HARMONIC_WINDOW_SECONDS, admission_interval_harmonic, pace_seconds_harmonic+from posthog.egress.harmonic.observability import record_harmonic_admission_waitfrom posthog.egress.harmonic.transport import HarmonicEgressBudgetExhausted, harmonic_requestfrom posthog.egress.limiter.policies import Priorityfrom posthog.exceptions_capture import capture_exception@@ -37,7 +39,7 @@ class HarmonicCompanyLookup:_ENRICHMENT_STATUS_BATCH_SIZE = 50# Caps how many slow lookups can overlap. Admission pacing controls the request rate.-_ENRICH_MAX_CONCURRENT_LOOKUPS = 10+_ENRICH_MAX_CONCURRENT_LOOKUPS = 24_ENRICH_MAX_ATTEMPTS = 3@@ -329,6 +331,7 @@ class AsyncHarmonicClient:async def wait_for_admission() -> None:nonlocal next_admission_at+ admission_started_at = time.monotonic()async with pacing_lock:pace = await asyncio.to_thread(pace_seconds_harmonic, self.priority)# The interval keeps admissions inside the lane even while the limiter cannot yet@@ -336,6 +339,9 @@ class AsyncHarmonicClient:wait = max(pace, next_admission_at - time.monotonic())if wait > 0:await asyncio.sleep(wait)+ total_wait = max(time.monotonic() - admission_started_at, wait)+ with suppress(Exception):+ record_harmonic_admission_wait(total_wait, source=self.source, priority=self.priority)next_admission_at = time.monotonic() + admission_interval_harmonic(self.priority)async def enrich_one(index: int, domain: str) -> None:diff --git a/ee/billing/test/test_harmonic_client.py b/ee/billing/test/test_harmonic_client.pyindex 3a7b55309bdf..27bb9e806fae 100644--- a/ee/billing/test/test_harmonic_client.py+++ b/ee/billing/test/test_harmonic_client.py@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport aiohttpfrom parameterized import parameterized+from prometheus_client import REGISTRYfrom posthog.egress.harmonic.limiter import HARMONIC_WINDOW_SECONDSfrom posthog.egress.harmonic.transport import HarmonicEgressBudgetExhausted@@ -348,11 +349,33 @@ async def test_enrich_companies_batch_spaces_admissions_by_the_lane_interval_desdomains = ["a.com", "b.com", "c.com"]client = _client(priority=Priority.BATCH)mock_request = AsyncMock(side_effect=[_found({"name": d}) for d in domains])+ wait_labels = {"source": "other", "priority": "batch"}+ wait_before = REGISTRY.get_sample_value("harmonic_api_admission_wait_seconds_sum", wait_labels) or 0.0with patch(HARMONIC_REQUEST, new=mock_request):results = await client.enrich_companies_batch(domains)assert results == [{"name": d} for d in domains]assert [call.args[0] for call in mock_sleep.await_args_list] == [0.25, 0.25]+ wait_after = REGISTRY.get_sample_value("harmonic_api_admission_wait_seconds_sum", wait_labels) or 0.0+ assert wait_after - wait_before == pytest.approx(0.5)+++async def test_enrich_companies_batch_keeps_lookup_when_wait_recording_fails() -> None:+ client = _client(priority=Priority.BATCH)+ with (+ patch(PACE_SECONDS_HARMONIC, return_value=0.0),+ patch(ADMISSION_INTERVAL_HARMONIC, return_value=0.0),+ patch(ASYNCIO_TO_THREAD, new=_fake_to_thread),+ patch(HARMONIC_REQUEST, new=AsyncMock(return_value=_found({"name": "a.com"}))),+ patch(+ "ee.billing.salesforce_enrichment.harmonic_client.record_harmonic_admission_wait",+ side_effect=RuntimeError("metric"),+ ),+ ):+ results = await client.enrich_companies_batch(["a.com"])++ assert results == [{"name": "a.com"}]@pytest.mark.asyncio@@ -424,6 +447,60 @@ async def test_enrich_companies_batch_starts_the_next_lookup_as_soon_as_any_slotassert results == [{"name": d} for d in domains]+async def test_enrich_companies_batch_fills_the_request_budget_while_responses_are_delayed() -> None:+ domains = [f"d{i}.example.com" for i in range(20)]+ release_responses = asyncio.Event()+ first_ten_started = asyncio.Event()+ all_requests_started = asyncio.Event()+ started_count = 0+ clock = 0.0++ def current_time() -> float:+ return clock++ async def advance_clock(seconds: float) -> None:+ nonlocal clock+ clock += seconds+ await _REAL_SLEEP(0)++ async def request(*args: Any, **kwargs: Any) -> MagicMock:+ nonlocal started_count+ started_count += 1+ if started_count == 10:+ first_ten_started.set()+ if started_count == len(domains):+ all_requests_started.set()+ await release_responses.wait()+ domain = kwargs["json"]["variables"]["identifiers"]["websiteUrl"].removeprefix("https://")+ return _found({"name": domain})++ client = _client(priority=Priority.BATCH)+ with (+ patch(PACE_SECONDS_HARMONIC, return_value=0.0),+ patch(ADMISSION_INTERVAL_HARMONIC, return_value=0.1),+ patch(MONOTONIC, new=current_time),+ patch(ASYNCIO_SLEEP, new=advance_clock),+ patch(ASYNCIO_TO_THREAD, new=_fake_to_thread),+ patch(HARMONIC_REQUEST, new=request),+ patch("ee.billing.salesforce_enrichment.harmonic_client.record_harmonic_admission_wait") as wait_record,+ ):+ task = asyncio.create_task(client.enrich_companies_batch(domains))+ try:+ await asyncio.wait_for(first_ten_started.wait(), timeout=5.0)+ for _ in range(100):+ if all_requests_started.is_set():+ break+ await _REAL_SLEEP(0)+ assert all_requests_started.is_set()+ finally:+ release_responses.set()+ results = await task++ assert results == [{"name": domain} for domain in domains]+ assert max(call.args[0] for call in wait_record.call_args_list) >= 1.0++@pytest.mark.asyncio@patch(PACE_SECONDS_HARMONIC, return_value=0.0)@patch(ADMISSION_INTERVAL_HARMONIC, new=lambda priority: 0.0)diff --git a/posthog/egress/README.md b/posthog/egress/README.mdindex 74da549d5ef3..41d1d0ca262c 100644--- a/posthog/egress/README.md+++ b/posthog/egress/README.md@@ -125,6 +125,10 @@ Each domain keeps its own metric names, so existing dashboards stay valid.The `source` label (e.g. `integration`, `visual_review`, `warehouse`) carries per-subsystem attribution.Endpoint labels are normalized to bound cardinality: numeric ids are templated out by default, and a domain with structured paths passes its own normalizer, so raw-URL callers don't mint one label per id.+Harmonic also records `harmonic_api_request_duration_seconds` from the start of an HTTP request through response headers, and `harmonic_api_admission_wait_seconds` for waits in the bulk client's pacing loop, including time queued for the pacing lock.+The request duration excludes the local admission wait and response-body parsing.+The weekly Salesforce sweep allows 24 company lookups in flight; each outbound request still draws from the shared BATCH budget.+## Transport`transport/transport.py` holds three bases:diff --git a/posthog/egress/harmonic/README.md b/posthog/egress/harmonic/README.mdindex f68e1a57d8e6..af9bc6688214 100644--- a/posthog/egress/harmonic/README.md+++ b/posthog/egress/harmonic/README.md@@ -21,6 +21,7 @@ The default reserve ladder applies, and it matters here, because the lanes carryThe client is `ee/billing/salesforce_enrichment/harmonic_client.py`.The bulk sweep paces with `pace_seconds_harmonic` and `admission_interval_harmonic` rather than getting denied.+It keeps up to 24 company lookups in flight while each request draws from the shared budget.A denied call raises `HarmonicEgressBudgetExhausted`. A caller that folds exceptions into an enrichment miss must catch it first, or a throttled lookup gets recorded as a company Harmonic does not know.## Rate-limit headers@@ -30,6 +31,9 @@ Production has recorded no value on either gauge, although the recording path seCheck a live response with the API key before you build a dashboard or tune the budget on them.Harmonic documents no reset header, so the domain declares no reset gauge.The counter is `harmonic_api_requests_total`.+`harmonic_api_request_duration_seconds` measures the HTTP request through response headers after admission. It labels source, priority, endpoint, and response or exception outcome.+`harmonic_api_admission_wait_seconds` measures the bulk client's pacing wait, including time queued behind its pacing lock. It labels source and priority.+Unknown sources and endpoints use an `other` label to keep the metric series bounded.## Authdiff --git a/posthog/egress/harmonic/observability.py b/posthog/egress/harmonic/observability.pyindex 14c9e9b87d7a..7f158728588e 100644--- a/posthog/egress/harmonic/observability.py+++ b/posthog/egress/harmonic/observability.py@@ -9,8 +9,9 @@ declares no reset gauge. Production has recorded no value on either gauge yet; sfrom collections.abc import Mapping-from prometheus_client import Counter, Gauge+from prometheus_client import Counter, Gauge, Histogram+from posthog.egress.limiter.policies import Priorityfrom posthog.egress.observability.observability import (EgressMetrics,EgressObservability,@@ -21,6 +22,23 @@ from posthog.egress.observability.observability import (# Harmonic rate-limits the whole account rather than per endpoint, so every observed header# describes the same one resource._RATE_LIMIT_RESOURCE = "account"+_METRIC_SOURCES = frozenset(+ {"harmonic_client", "salesforce_enrichment_bulk", "salesforce_enrichment_debug", "growth_enrichment_provider"}+)+_METRIC_ENDPOINTS = frozenset({"/graphql", "/companies/{id}", "/enrichment_status"})++_request_duration = Histogram(+ "harmonic_api_request_duration_seconds",+ "Time spent waiting for a Harmonic HTTP response, excluding local rate-limit admission waits.",+ labelnames=["source", "priority", "endpoint", "outcome"],+ buckets=(0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 20, 30, 60),+)+_admission_wait = Histogram(+ "harmonic_api_admission_wait_seconds",+ "Time a Harmonic caller waits before attempting a rate-limited request.",+ labelnames=["source", "priority"],+ buckets=(0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10),+)_metrics = EgressMetrics(request_counter=Counter(@@ -50,3 +68,19 @@ def _parse_harmonic_rate_limit(headers: Mapping[str, str] | None, _url: str | Noharmonic_egress = EgressObservability(_metrics, _parse_harmonic_rate_limit)+++def _metric_source(source: str) -> str:+ return source if source in _METRIC_SOURCES else "other"+++def record_harmonic_request_duration(+ seconds: float, *, source: str, priority: Priority, endpoint: str | None, outcome: str+) -> None:+ endpoint_label = endpoint if endpoint in _METRIC_ENDPOINTS else "other"+ outcome_label = "response" if outcome == "response" else "exception"+ _request_duration.labels(_metric_source(source), priority.value, endpoint_label, outcome_label).observe(seconds)+++def record_harmonic_admission_wait(seconds: float, *, source: str, priority: Priority) -> None:+ _admission_wait.labels(_metric_source(source), priority.value).observe(seconds)diff --git a/posthog/egress/harmonic/transport.py b/posthog/egress/harmonic/transport.pyindex f9339db55d9c..a4d31083b4a9 100644--- a/posthog/egress/harmonic/transport.py+++ b/posthog/egress/harmonic/transport.py@@ -3,12 +3,14 @@:class:`posthog.egress.transport.transport.AsyncEgressClient`."""-from typing import Any+import time+from contextlib import suppress+from typing import Any, castimport aiohttpfrom posthog.egress.harmonic.limiter import ACCOUNT_SCOPE_ID, acquire_harmonic-from posthog.egress.harmonic.observability import harmonic_egress+from posthog.egress.harmonic.observability import harmonic_egress, record_harmonic_request_durationfrom posthog.egress.limiter.policies import Priorityfrom posthog.egress.transport.transport import AsyncEgressClient, EgressBudgetExhausted@@ -46,6 +48,33 @@ class HarmonicClient(AsyncEgressClient):_harmonic_client = HarmonicClient()+class _TimedHarmonicSession:+ def __init__(+ self, session: aiohttp.ClientSession, *, source: str, priority: Priority, endpoint: str | None+ ) -> None:+ self._session = session+ self._source = source+ self._priority = priority+ self._endpoint = endpoint++ async def request(self, method: str, url: str, **kwargs: Any) -> aiohttp.ClientResponse:+ started_at = time.perf_counter()+ outcome = "exception"+ try:+ response = await self._session.request(method, url, **kwargs)+ outcome = "response"+ return response+ finally:+ with suppress(Exception):+ record_harmonic_request_duration(+ time.perf_counter() - started_at,+ source=self._source,+ priority=self._priority,+ endpoint=self._endpoint,+ outcome=outcome,+ )++async def harmonic_request(session: aiohttp.ClientSession,method: str,@@ -63,8 +92,11 @@ async def harmonic_request(# Harmonic bills one account-wide budget, so every call carries the same scope. AsyncEgressClient# skips its gate entirely on a falsy scope, and Harmonic has no per-caller identity to gate on# instead, so this constant is what keeps every Harmonic call gated.+ timed_session = cast(+ aiohttp.ClientSession, _TimedHarmonicSession(session, source=source, priority=priority, endpoint=endpoint)+ )return await _harmonic_client.request(- session,+ timed_session,method,url,source=source,diff --git a/posthog/egress/test/test_harmonic.py b/posthog/egress/test/test_harmonic.pyindex e52e5480a632..40c0deac2d99 100644--- a/posthog/egress/test/test_harmonic.py+++ b/posthog/egress/test/test_harmonic.py@@ -1,10 +1,13 @@+import timeimport uuid+import pytestfrom unittest.mock import AsyncMock, patchfrom django.test import SimpleTestCase, override_settingsfrom parameterized import parameterized+from prometheus_client import REGISTRYfrom posthog.egress.harmonic.limiter import HARMONIC_ACCOUNT_KEY, consume_harmonicfrom posthog.egress.harmonic.observability import _parse_harmonic_rate_limit, harmonic_egress@@ -82,9 +85,17 @@ class TestHarmonicRateLimitHeaderParser(SimpleTestCase):async def test_request_gates_before_sending_and_records_the_response() -> None:session = _fake_session(status=201, headers={"X-Ratelimit-Remaining-Second": "9"})+ duration_labels = {"source": "other", "priority": "critical", "endpoint": "/graphql", "outcome": "response"}+ duration_before = REGISTRY.get_sample_value("harmonic_api_request_duration_seconds_sum", duration_labels) or 0++ def grant(_priority: Priority, _source: str) -> bool:+ time.perf_counter()+ return True+with (- patch("posthog.egress.harmonic.transport.acquire_harmonic", AsyncMock(return_value=True)) as acquire,+ patch("posthog.egress.harmonic.transport.acquire_harmonic", AsyncMock(side_effect=grant)) as acquire,patch.object(harmonic_egress, "record_response") as record_response,+ patch("posthog.egress.harmonic.transport.time.perf_counter", side_effect=[100, 105, 106.25]),):response = await harmonic_request(session,@@ -103,6 +114,48 @@ async def test_request_gates_before_sending_and_records_the_response() -> None:record_response.assert_called_once_with(201, {"X-Ratelimit-Remaining-Second": "9"}, source="test", scope="default", method="POST", endpoint="/graphql")+ duration_after = REGISTRY.get_sample_value("harmonic_api_request_duration_seconds_sum", duration_labels) or 0+ assert duration_after - duration_before == 1.25+++async def test_request_duration_records_transport_timeout() -> None:+ session = _fake_session()+ session.request.side_effect = TimeoutError()+ duration_labels = {"source": "other", "priority": "batch", "endpoint": "/graphql", "outcome": "exception"}+ duration_before = REGISTRY.get_sample_value("harmonic_api_request_duration_seconds_sum", duration_labels) or 0+ with (+ patch("posthog.egress.harmonic.transport.acquire_harmonic", AsyncMock(return_value=True)),+ patch("posthog.egress.harmonic.transport.time.perf_counter", side_effect=[10, 12]),+ pytest.raises(TimeoutError),+ ):+ await harmonic_request(+ session,+ "POST",+ "https://api.harmonic.ai/graphql",+ source="test",+ priority=Priority.BATCH,+ endpoint="/graphql",+ )+ duration_after = REGISTRY.get_sample_value("harmonic_api_request_duration_seconds_sum", duration_labels) or 0+ assert duration_after - duration_before == 2+++async def test_request_keeps_transport_error_when_duration_recording_fails() -> None:+ session = _fake_session()+ session.request.side_effect = TimeoutError("network")+ with (+ patch("posthog.egress.harmonic.transport.acquire_harmonic", AsyncMock(return_value=True)),+ patch("posthog.egress.harmonic.transport.record_harmonic_request_duration", side_effect=RuntimeError("metric")),+ pytest.raises(TimeoutError, match="network"),+ ):+ await harmonic_request(+ session,+ "POST",+ "https://api.harmonic.ai/graphql",+ source="test",+ priority=Priority.BATCH,+ endpoint="/graphql",+ )async def test_request_raises_for_a_sheddable_call_when_the_budget_is_denied() -> None: