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(billing): pace Harmonic bulk lookups per request instead of in lockstep waves (#96708)

Matt Brooker7fda3f15c216
diff --git a/ee/billing/salesforce_enrichment/harmonic_client.py b/ee/billing/salesforce_enrichment/harmonic_client.py
index bac39e9906b6..81040f3d0494 100644
--- a/ee/billing/salesforce_enrichment/harmonic_client.py
+++ b/ee/billing/salesforce_enrichment/harmonic_client.py
@@ -1,3 +1,4 @@
+import time
import asyncio
from typing import Any, Optional
@@ -6,7 +7,7 @@ from django.conf import settings
import aiohttp
from posthog.dataclasses import frozen
-from posthog.egress.harmonic.limiter import pace_seconds_harmonic
+from posthog.egress.harmonic.limiter import HARMONIC_WINDOW_SECONDS, admission_interval_harmonic, pace_seconds_harmonic
from posthog.egress.harmonic.transport import HarmonicEgressBudgetExhausted, harmonic_request
from posthog.egress.limiter.policies import Priority
from posthog.exceptions_capture import capture_exception
@@ -35,8 +36,8 @@ class HarmonicCompanyLookup:
# Harmonic documents this as the per-call cap on /enrichment_status URNs.
_ENRICHMENT_STATUS_BATCH_SIZE = 50
-# Sized under the BATCH lane's share of the per-second budget, so a whole wave is admitted.
-_ENRICH_WAVE_SIZE = 10
+# Caps how many slow lookups can overlap. Admission pacing controls the request rate.
+_ENRICH_MAX_CONCURRENT_LOOKUPS = 10
_ENRICH_MAX_ATTEMPTS = 3
@@ -301,66 +302,66 @@ class AsyncHarmonicClient:
return statuses
async def enrich_companies_batch(self, domains: list[str]) -> list[dict[str, Any] | None]:
- """Enrich multiple domains concurrently, in waves paced against the shared egress budget.
+ """Enrich multiple domains concurrently, one task per domain.
- Pacing is recomputed per wave because pace_seconds reads live limiter state, so a wave that
- finds the budget already drawn down waits for it.
-
- A shed domain is retried in a later wave rather than recorded: callers persist these results
- against a Salesforce account, and a shed means Harmonic was never asked.
+ An asyncio.Semaphore bounds how many lookups run at once (_ENRICH_MAX_CONCURRENT_LOOKUPS); admission
+ for each request is paced individually against the shared egress budget and held at least the
+ lane's admission interval after the previous one, serialized through a lock so only the wait
+ blocks, not the request itself. A domain shed by the egress limiter
+ waits one budget window and retries, up to _ENRICH_MAX_ATTEMPTS. A domain still shed after
+ every attempt is reported to error tracking and left None, distinctly from a genuine
+ not-found or an operational failure (also None): callers persist these results against a
+ Salesforce account, and a shed means Harmonic was never asked.
Args:
domains: List of company domains to enrich
Returns:
- List of company data dicts, same length and order as domains. A slot is None for a
- genuine not-found or an operational failure, and also for a domain still shed after
- every attempt: that last case is reported to error tracking first, since it must not
- look like a genuine miss on inspection there even though the return value can't carry
- the distinction (callers zip this list against the input domains).
+ List of company data dicts, same length and order as domains.
"""
if not domains:
return []
results: list[dict[str, Any] | None] = [None] * len(domains)
- pending = list(range(len(domains)))
-
- for _attempt in range(_ENRICH_MAX_ATTEMPTS):
- if not pending:
- break
-
- denied: list[int] = []
- for wave_start in range(0, len(pending), _ENRICH_WAVE_SIZE):
- wave = pending[wave_start : wave_start + _ENRICH_WAVE_SIZE]
-
- # CRITICAL is never shed by the transport (_raise_if_denied never raises on it), so
- # pacing it would only add latency to an interactive caller for no admission benefit.
- if self.priority is not Priority.CRITICAL:
- pace = pace_seconds_harmonic(self.priority)
- if pace > 0:
- await asyncio.sleep(pace)
-
- wave_results: list[dict[str, Any] | BaseException | None] = await asyncio.gather(
- *(self._enrich_company_by_domain_observing_denial(domains[i]) for i in wave),
- return_exceptions=True,
- )
-
- for index, result in zip(wave, wave_results):
- if isinstance(result, HarmonicEgressBudgetExhausted):
- denied.append(index)
- elif isinstance(result, BaseException):
- capture_exception(result, {"domain": domains[index]})
- else:
- results[index] = result
-
- pending = denied
+ semaphore = asyncio.Semaphore(_ENRICH_MAX_CONCURRENT_LOOKUPS)
+ pacing_lock = asyncio.Lock()
+ next_admission_at = 0.0
+
+ async def wait_for_admission() -> None:
+ nonlocal next_admission_at
+ 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
+ # see the calls this batch admitted but has not consumed.
+ wait = max(pace, next_admission_at - time.monotonic())
+ if wait > 0:
+ await asyncio.sleep(wait)
+ next_admission_at = time.monotonic() + admission_interval_harmonic(self.priority)
+
+ async def enrich_one(index: int, domain: str) -> None:
+ for attempt in range(1, _ENRICH_MAX_ATTEMPTS + 1):
+ async with semaphore:
+ if self.priority is not Priority.CRITICAL:
+ await wait_for_admission()
+
+ try:
+ results[index] = await self._enrich_company_by_domain_observing_denial(domain)
+ return
+ except HarmonicEgressBudgetExhausted:
+ pass
+ except Exception as e:
+ capture_exception(e, {"domain": domain})
+ return
+
+ if attempt < _ENRICH_MAX_ATTEMPTS:
+ await asyncio.sleep(HARMONIC_WINDOW_SECONDS)
- for index in pending:
capture_exception(
HarmonicEgressBudgetExhausted(
f"Harmonic egress budget denied this domain on every attempt ({_ENRICH_MAX_ATTEMPTS})"
),
- {"domain": domains[index]},
+ {"domain": domain},
)
+ await asyncio.gather(*(enrich_one(index, domain) for index, domain in enumerate(domains)))
return results
diff --git a/ee/billing/test/test_harmonic_client.py b/ee/billing/test/test_harmonic_client.py
index 0e781cc5dd35..3a7b55309bdf 100644
--- a/ee/billing/test/test_harmonic_client.py
+++ b/ee/billing/test/test_harmonic_client.py
@@ -1,5 +1,6 @@
import asyncio
-from collections.abc import Collection
+from collections.abc import Callable
+from typing import Any
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
@@ -7,20 +8,33 @@ from unittest.mock import AsyncMock, MagicMock, patch
import aiohttp
from parameterized import parameterized
+from posthog.egress.harmonic.limiter import HARMONIC_WINDOW_SECONDS
from posthog.egress.harmonic.transport import HarmonicEgressBudgetExhausted
from posthog.egress.limiter.policies import Priority
-from ee.billing.salesforce_enrichment.harmonic_client import _ENRICH_WAVE_SIZE, AsyncHarmonicClient
+from ee.billing.salesforce_enrichment.harmonic_client import (
+ _ENRICH_MAX_ATTEMPTS,
+ _ENRICH_MAX_CONCURRENT_LOOKUPS,
+ AsyncHarmonicClient,
+)
HARMONIC_REQUEST = "ee.billing.salesforce_enrichment.harmonic_client.harmonic_request"
PACE_SECONDS_HARMONIC = "ee.billing.salesforce_enrichment.harmonic_client.pace_seconds_harmonic"
ASYNCIO_SLEEP = "ee.billing.salesforce_enrichment.harmonic_client.asyncio.sleep"
+ASYNCIO_TO_THREAD = "ee.billing.salesforce_enrichment.harmonic_client.asyncio.to_thread"
+ADMISSION_INTERVAL_HARMONIC = "ee.billing.salesforce_enrichment.harmonic_client.admission_interval_harmonic"
+MONOTONIC = "ee.billing.salesforce_enrichment.harmonic_client.time.monotonic"
# Captured at import time, before any test patches asyncio.sleep, so the fake sleeps below always
# yield to the real event loop rather than recursing into whichever mock is active when they run.
_REAL_SLEEP = asyncio.sleep
+# Bypasses the real thread pool so pacing stays single-threaded and deterministic under test.
+async def _fake_to_thread(func: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:
+ return func(*args, **kwargs)
+
+
def _response(*, json_data=None, raise_status=None, status=200):
resp = MagicMock()
resp.status = status
@@ -63,74 +77,6 @@ def _http_500():
return _response(raise_status=error)
-# Shared by the patched pace and sleep, so a wave that waits sees the budget refill without the
-# test costing wall-clock time.
-class _FakeClock:
- def __init__(self) -> None:
- self.now = 0.0
-
-
-# Stands in for the Harmonic egress limiter. always_deny and not_found are keyed by the bare
-# domain, so both HARMONIC_DOMAIN_VARIATIONS of one domain share a fate, as they do against the
-# account-wide budget.
-class _FakeGate:
- def __init__(
- self,
- clock: _FakeClock,
- *,
- budget: int,
- window: float = 1.0,
- always_deny: Collection[str] = frozenset(),
- not_found: Collection[str] = frozenset(),
- ) -> None:
- self.clock = clock
- self.budget = budget
- self.window = window
- self.always_deny = always_deny
- self.not_found = not_found
- self.window_start = clock.now
- self.used = 0
-
- def _refill(self) -> None:
- if self.clock.now - self.window_start >= self.window:
- self.window_start = self.clock.now
- self.used = 0
-
- def _admit(self, bare_domain: str) -> bool:
- self._refill()
- if bare_domain in self.always_deny:
- return False
- if self.used >= self.budget:
- return False
- self.used += 1
- return True
-
- def pace_seconds(self, _priority=None) -> float:
- self._refill()
- if self.used < self.budget:
- return 0.0
- return max(0.0, self.window - (self.clock.now - self.window_start))
-
- async def request(self, session, method, url, *, source, priority, endpoint, headers, json, **kwargs):
- website_url = json["variables"]["identifiers"]["websiteUrl"]
- bare_domain = website_url.removeprefix("https://").removeprefix("www.")
- if not self._admit(bare_domain):
- raise HarmonicEgressBudgetExhausted("degrading")
- if bare_domain in self.not_found:
- return _not_found()
- return _found({"name": bare_domain})
-
-
-# Awaits the real asyncio.sleep(0) so the call stays an event-loop suspension point that a
-# pending cancellation can land on.
-def _clock_advancing_sleep(clock: _FakeClock):
- async def fake_sleep(seconds: float) -> None:
- clock.now += seconds
- await _REAL_SLEEP(0)
-
- return fake_sleep
-
-
@pytest.mark.asyncio
async def test_strict_returns_none_when_not_found():
# Both domain variations return a clean companyFound=false.
@@ -372,64 +318,180 @@ async def test_get_enrichment_status_reraises_on_http_error():
@pytest.mark.asyncio
-@patch(PACE_SECONDS_HARMONIC)
+@patch(PACE_SECONDS_HARMONIC, return_value=0.0)
+@patch(ADMISSION_INTERVAL_HARMONIC, new=lambda priority: 0.0)
@patch(ASYNCIO_SLEEP, new_callable=AsyncMock)
-async def test_enrich_companies_batch_repaces_before_each_wave(mock_sleep, mock_pace):
- # A single pace for the whole batch lets a later wave burst past a budget an earlier wave
- # already drew down, so this asserts a pace per wave against live limiter state.
- clock = _FakeClock()
- gate = _FakeGate(clock, budget=_ENRICH_WAVE_SIZE) # exactly one wave's worth per window
- mock_pace.side_effect = gate.pace_seconds
- mock_sleep.side_effect = _clock_advancing_sleep(clock)
-
- domains = [f"d{i}.com" for i in range(_ENRICH_WAVE_SIZE + 5)] # spans two waves
+@patch(ASYNCIO_TO_THREAD, new=_fake_to_thread)
+async def test_enrich_companies_batch_paces_once_per_request(mock_sleep, mock_pace):
+ # A single pace for the whole batch lets a later request burst past a budget an earlier one
+ # already drew down, so this asserts a pace per request against live limiter state.
+ domains = ["a.com", "b.com", "c.com"]
+ client = _client(priority=Priority.NORMAL)
+ mock_request = AsyncMock(side_effect=[_found({"name": d}) for d in domains])
+ with patch(HARMONIC_REQUEST, new=mock_request):
+ results = await client.enrich_companies_batch(domains)
+
+ assert results == [{"name": d} for d in domains]
+ assert mock_pace.call_count == 3
+ mock_sleep.assert_not_awaited()
+
+
+@patch(PACE_SECONDS_HARMONIC, return_value=0.0)
+@patch(ADMISSION_INTERVAL_HARMONIC, new=lambda priority: 0.25)
+@patch(MONOTONIC, new=lambda: 1000.0)
+@patch(ASYNCIO_SLEEP, new_callable=AsyncMock)
+@patch(ASYNCIO_TO_THREAD, new=_fake_to_thread)
+async def test_enrich_companies_batch_spaces_admissions_by_the_lane_interval_despite_headroom(mock_sleep, mock_pace):
+ # pace_seconds reads the window, which does not yet hold the calls this batch admitted but has
+ # not consumed, so headroom alone would let several admissions through at once.
+ domains = ["a.com", "b.com", "c.com"]
client = _client(priority=Priority.BATCH)
- with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=gate.request)):
+ mock_request = AsyncMock(side_effect=[_found({"name": d}) for d in domains])
+ with patch(HARMONIC_REQUEST, new=mock_request):
results = await client.enrich_companies_batch(domains)
assert results == [{"name": d} for d in domains]
- assert mock_pace.call_count > 1
- mock_sleep.assert_awaited_once_with(pytest.approx(1.0))
+ assert [call.args[0] for call in mock_sleep.await_args_list] == [0.25, 0.25]
@pytest.mark.asyncio
-@patch(PACE_SECONDS_HARMONIC)
+@patch(PACE_SECONDS_HARMONIC, return_value=0.0)
+@patch(ADMISSION_INTERVAL_HARMONIC, new=lambda priority: 0.0)
@patch(ASYNCIO_SLEEP, new_callable=AsyncMock)
+@patch(ASYNCIO_TO_THREAD, new=_fake_to_thread)
+async def test_enrich_companies_batch_backs_off_a_full_window_after_a_shed_before_retrying(mock_sleep, mock_pace):
+ # A shed domain must wait out a full budget window before its retry, not just the pace (which
+ # this test sets to 0). Otherwise every attempt fits inside the same instant and none of them
+ # land after the budget actually frees.
+ shed = HarmonicEgressBudgetExhausted("degrading")
+ mock_request = AsyncMock(side_effect=[shed, shed, _found({"name": "a.com"})])
+ client = _client(priority=Priority.BATCH)
+ with patch(HARMONIC_REQUEST, new=mock_request):
+ results = await client.enrich_companies_batch(["a.com"])
+
+ assert results == [{"name": "a.com"}]
+ mock_sleep.assert_awaited_once_with(HARMONIC_WINDOW_SECONDS)
+
+
+@patch(PACE_SECONDS_HARMONIC, return_value=0.0)
+@patch(ADMISSION_INTERVAL_HARMONIC, new=lambda priority: 0.0)
+@patch(ASYNCIO_TO_THREAD, new=_fake_to_thread)
+async def test_enrich_companies_batch_starts_the_next_lookup_as_soon_as_any_slot_frees(mock_pace):
+ # With one more domain than the in-flight cap, the extra lookup must start once any slot
+ # frees, without waiting on the slowest of the first _ENRICH_MAX_CONCURRENT_LOOKUPS.
+ first_started = asyncio.Event()
+ release_first = asyncio.Event()
+ started_domains: list[str] = []
+
+ domains = [f"d{i}.com" for i in range(_ENRICH_MAX_CONCURRENT_LOOKUPS + 1)]
+
+ async def request(
+ session: Any,
+ method: str,
+ url: str,
+ *,
+ source: str,
+ priority: Priority,
+ endpoint: str,
+ headers: dict[str, str],
+ json: dict[str, Any],
+ **kwargs: Any,
+ ) -> MagicMock:
+ website_url = json["variables"]["identifiers"]["websiteUrl"]
+ bare_domain = website_url.removeprefix("https://").removeprefix("www.")
+ started_domains.append(bare_domain)
+ if bare_domain == "d0.com":
+ first_started.set()
+ await release_first.wait()
+ return _found({"name": bare_domain})
+
+ client = _client(priority=Priority.BATCH)
+ with patch(HARMONIC_REQUEST, new=request):
+ task = asyncio.create_task(client.enrich_companies_batch(domains))
+ await first_started.wait()
+ for _ in range(100):
+ if "d10.com" in started_domains:
+ break
+ await _REAL_SLEEP(0)
+
+ assert "d10.com" in started_domains
+
+ release_first.set()
+ results = await task
+
+ assert results == [{"name": d} for d in domains]
+
+
+@patch(PACE_SECONDS_HARMONIC, return_value=0.0)
+@patch(ADMISSION_INTERVAL_HARMONIC, new=lambda priority: 0.0)
+@patch(ASYNCIO_SLEEP, new_callable=AsyncMock)
+@patch(ASYNCIO_TO_THREAD, new=_fake_to_thread)
async def test_enrich_companies_batch_retries_a_denied_domain_in_a_later_attempt(mock_sleep, mock_pace):
- clock = _FakeClock()
- gate = _FakeGate(clock, budget=2) # only the first two of three domains admit on attempt 1
- mock_pace.side_effect = gate.pace_seconds
- mock_sleep.side_effect = _clock_advancing_sleep(clock)
+ deny_count = {"c.com": 0}
+
+ async def request(
+ session: Any,
+ method: str,
+ url: str,
+ *,
+ source: str,
+ priority: Priority,
+ endpoint: str,
+ headers: dict[str, str],
+ json: dict[str, Any],
+ **kwargs: Any,
+ ) -> MagicMock:
+ website_url = json["variables"]["identifiers"]["websiteUrl"]
+ bare_domain = website_url.removeprefix("https://").removeprefix("www.")
+ if bare_domain == "c.com" and deny_count["c.com"] < 2:
+ deny_count["c.com"] += 1
+ raise HarmonicEgressBudgetExhausted("degrading")
+ return _found({"name": bare_domain})
domains = ["a.com", "b.com", "c.com"]
client = _client(priority=Priority.BATCH)
- with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=gate.request)):
+ with patch(HARMONIC_REQUEST, new=request):
results = await client.enrich_companies_batch(domains)
- # c.com was shed on attempt 1 and must come back with a result once the budget refills,
- # not silently become the same None a genuine miss returns.
+ # c.com was shed on attempt 1 and must come back with a result once it is retried, not
+ # silently become the same None a genuine miss returns.
assert results == [{"name": "a.com"}, {"name": "b.com"}, {"name": "c.com"}]
- assert mock_pace.call_count > 1
- mock_sleep.assert_awaited_once_with(pytest.approx(1.0))
+ mock_sleep.assert_awaited_once_with(HARMONIC_WINDOW_SECONDS)
@pytest.mark.asyncio
-@patch(PACE_SECONDS_HARMONIC)
+@patch(PACE_SECONDS_HARMONIC, return_value=0.0)
+@patch(ADMISSION_INTERVAL_HARMONIC, new=lambda priority: 0.0)
@patch(ASYNCIO_SLEEP, new_callable=AsyncMock)
+@patch(ASYNCIO_TO_THREAD, new=_fake_to_thread)
@patch("ee.billing.salesforce_enrichment.harmonic_client.capture_exception")
async def test_enrich_companies_batch_reports_denied_forever_distinctly_from_a_not_found(
mock_capture, mock_sleep, mock_pace
):
- clock = _FakeClock()
- # Budget stays generous throughout: denied.com is denied by always_deny, never by the shared
- # budget, so this isolates "denied on every attempt" from "the budget never had headroom".
- gate = _FakeGate(clock, budget=100, always_deny={"denied.com"}, not_found={"miss.com"})
- mock_pace.side_effect = gate.pace_seconds
- mock_sleep.side_effect = _clock_advancing_sleep(clock)
+ async def request(
+ session: Any,
+ method: str,
+ url: str,
+ *,
+ source: str,
+ priority: Priority,
+ endpoint: str,
+ headers: dict[str, str],
+ json: dict[str, Any],
+ **kwargs: Any,
+ ) -> MagicMock:
+ website_url = json["variables"]["identifiers"]["websiteUrl"]
+ bare_domain = website_url.removeprefix("https://").removeprefix("www.")
+ if bare_domain == "denied.com":
+ raise HarmonicEgressBudgetExhausted("degrading")
+ return _not_found()
domains = ["denied.com", "miss.com"]
client = _client(priority=Priority.BATCH)
- with patch(HARMONIC_REQUEST, new=AsyncMock(side_effect=gate.request)):
+ with patch(HARMONIC_REQUEST, new=request):
results = await client.enrich_companies_batch(domains)
# Both look the same in the return value, since enrich_companies_batch keeps its list
@@ -439,11 +501,13 @@ async def test_enrich_companies_batch_reports_denied_forever_distinctly_from_a_n
captured_domains = [call.args[1]["domain"] for call in mock_capture.call_args_list]
assert captured_domains == ["denied.com"]
assert isinstance(mock_capture.call_args_list[0].args[0], HarmonicEgressBudgetExhausted)
+ # Only the gaps between attempts wait a window; a domain that is out of attempts is reported at once.
+ assert mock_sleep.await_count == _ENRICH_MAX_ATTEMPTS - 1
@pytest.mark.asyncio
@patch(PACE_SECONDS_HARMONIC, return_value=5.0)
-async def test_enrich_companies_batch_propagates_cancellation_during_inter_wave_sleep(mock_pace):
+async def test_enrich_companies_batch_propagates_cancellation_during_pacing_sleep(mock_pace):
sleep_started = asyncio.Event()
async def blocking_sleep(seconds: float) -> None:
@@ -479,10 +543,11 @@ async def test_enrich_companies_batch_skips_pacing_for_critical_priority(mock_sl
@pytest.mark.asyncio
@patch(PACE_SECONDS_HARMONIC, return_value=0.0)
+@patch(ADMISSION_INTERVAL_HARMONIC, new=lambda priority: 0.0)
@patch(ASYNCIO_SLEEP, new_callable=AsyncMock)
@patch("ee.billing.salesforce_enrichment.harmonic_client.capture_exception")
async def test_enrich_companies_batch_names_the_domain_of_an_operational_failure(mock_capture, mock_sleep, mock_pace):
- async def request(session, method, url, *, json, **kwargs):
+ async def request(session: Any, method: str, url: str, *, json: dict[str, Any], **kwargs: Any) -> MagicMock:
website_url = json["variables"]["identifiers"]["websiteUrl"]
if "broken.com" in website_url:
return _graphql_errors()
@@ -499,10 +564,11 @@ async def test_enrich_companies_batch_names_the_domain_of_an_operational_failure
@pytest.mark.asyncio
@patch(PACE_SECONDS_HARMONIC, return_value=0.0)
+@patch(ADMISSION_INTERVAL_HARMONIC, new=lambda priority: 0.0)
@patch(ASYNCIO_SLEEP, new_callable=AsyncMock)
async def test_enrich_companies_batch_with_a_single_domain(mock_sleep, mock_pace):
# _enrich_specific_domain_debug calls enrich_companies_batch with exactly one domain; the
- # wave/retry slicing must not misbehave at that boundary.
+ # concurrency and retry machinery must not misbehave at that boundary.
client = _client(priority=Priority.BATCH)
mock_request = AsyncMock(side_effect=[_found({"name": "PostHog"})])
with patch(HARMONIC_REQUEST, new=mock_request):
diff --git a/posthog/egress/README.md b/posthog/egress/README.md
index 010ee8dc40b5..0d2b1f18d309 100644
--- a/posthog/egress/README.md
+++ b/posthog/egress/README.md
@@ -72,6 +72,8 @@ if pace > 0:
`pace_seconds` returns **0 while a window still holds more than half of that priority's allowance**, so a short run is never slowed for a budget it cannot dent.
Below that it spreads the allowance that is left over the time left in the window, which is the interval that keeps the caller admitted instead of shed.
It reads the same reserved floors admission does, so a `BATCH` caller paces off the share it may actually take, not the whole window.
+A caller that keeps several calls in flight also asks `admission_interval_seconds(key, priority=...)` for the gap between admissions that fits its share of every window, and waits for whichever of the two is longer.
+`pace_seconds` reads the window, so it cannot see calls the caller admitted but has not consumed yet; the interval comes from the policy alone and holds through that gap and through a store outage.
Two things it is not.
It is **advisory** — `acquire`/`consume_sync` remain the only authority on whether a call is admitted, so a bug here cannot over-admit.
@@ -106,7 +108,8 @@ Every Firecrawl call runs on a sheddable lane: what gets scraped is derived from
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 publishes no rate limit we could confirm, so that default is seeded from observed throughput and is meant to be tuned against the rate-limit headers this domain records.
+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.
+The default sits above that so the `BATCH` reserve floor lands the bulk lane near the documented rate, and it is tuned against the values this domain records from those headers.
Harmonic is the first async domain: it subclasses `AsyncEgressClient` rather than `EgressClient`, because its client speaks `aiohttp`.
Its lanes carry very different traffic, so the reserve floor matters: signup enrichment and the ICP re-enrichment sweep run `CRITICAL` inside a short Temporal activity budget, while the Salesforce enrichment sweep runs `BATCH` and yields to them.
diff --git a/posthog/egress/harmonic/limiter.py b/posthog/egress/harmonic/limiter.py
index 5f41c4ca25b2..b3b909db880e 100644
--- a/posthog/egress/harmonic/limiter.py
+++ b/posthog/egress/harmonic/limiter.py
@@ -4,8 +4,10 @@ Harmonic bills one account-wide rate limit — there is one ``HARMONIC_API_KEY``
instance, not one per installation or team — so every call anywhere in the codebase draws from a
single shared budget under the constant key ``harmonic:account:default``.
-Harmonic publishes no rate limit, so the budget is an operator ceiling to tune against the
-rate-limit headers this domain records.
+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. The budget is an operator ceiling tuned against
+the values this domain records from those headers.
Two very different consumers share this budget, so the priority lanes matter:
- CRITICAL (interactive): signup enrichment and the ICP re-enrichment sweep run inside a
@@ -30,6 +32,8 @@ HARMONIC_ACCOUNT_KEY = f"{HARMONIC_DOMAIN}:account:{_ACCOUNT_SCOPE_ID}"
_DEFAULT_PER_SECOND_BUDGET = 15
+HARMONIC_WINDOW_SECONDS = 1.0
+
# Same reserved-floor ladder as the other egress domains: BATCH is denied first as the budget
# fills, then NORMAL, so the interactive lane (CRITICAL) can never be starved by the weekly bulk
# enrichment job saturating the shared counter.
@@ -41,7 +45,7 @@ _RESERVE: dict[Priority, float] = {Priority.BATCH: 0.30, Priority.NORMAL: 0.10}
def _harmonic_policy(_key: str) -> RatePolicy:
per_second = int(getattr(settings, "HARMONIC_EGRESS_PER_SECOND_BUDGET", _DEFAULT_PER_SECOND_BUDGET))
return RatePolicy(
- limits=((per_second, 1.0),),
+ limits=((per_second, HARMONIC_WINDOW_SECONDS),),
in_memory_divider=4,
reserve=_RESERVE,
)
@@ -66,3 +70,9 @@ def pace_seconds_harmonic(priority: Priority = Priority.NORMAL) -> float:
walking pages) so it spreads its share of the budget instead of bursting into it and being
shed. Advisory only — acquire/consume remain the sole admission authority."""
return get_outbound_rate_limiter().pace_seconds(HARMONIC_ACCOUNT_KEY, priority=priority)
+
+
+def admission_interval_harmonic(priority: Priority = Priority.NORMAL) -> float:
+ """Seconds between admissions that keep a steady caller inside this priority's share of the
+ budget, from the policy alone. See OutboundRateLimiter.admission_interval_seconds."""
+ return get_outbound_rate_limiter().admission_interval_seconds(HARMONIC_ACCOUNT_KEY, priority=priority)
diff --git a/posthog/egress/harmonic/observability.py b/posthog/egress/harmonic/observability.py
index 1ee93ea3ae81..8c2cc3ea17ed 100644
--- a/posthog/egress/harmonic/observability.py
+++ b/posthog/egress/harmonic/observability.py
@@ -13,10 +13,10 @@ Harmonic bills one account-wide rate limit rather than a per-installation one, s
metric scope label) and ``_RATE_LIMIT_RESOURCE`` (the rate-limit resource) are two distinct
constants that happen to both be singletons for this domain today.
-Harmonic's own rate-limit header names are not confirmed from public docs (their docs page is a
-client-rendered SPA). The parser below reads the GitHub-style ``X-RateLimit-*`` names plus the
-``X-Ratelimit-*-Second`` variants, and returns None for anything absent or unparseable rather than
-raising — telemetry must never break the request it is recording.
+Harmonic's API reference documents ``X-Ratelimit-Limit-Second`` and ``X-Ratelimit-Remaining-Second``
+on every response. The parser below reads those plus the GitHub-style ``X-RateLimit-*`` names, and
+returns None for anything absent or unparseable rather than raising: telemetry must never break the
+request it is recording.
"""
from collections.abc import Mapping
diff --git a/posthog/egress/limiter/outbound.py b/posthog/egress/limiter/outbound.py
index 328f4a0940b3..afacaf6a8a90 100644
--- a/posthog/egress/limiter/outbound.py
+++ b/posthog/egress/limiter/outbound.py
@@ -73,6 +73,16 @@ class OutboundRateLimiter:
"""
return self._backend.pace_seconds(key, resolve_policy(key), priority)
+ def admission_interval_seconds(self, key: str, *, priority: Priority = Priority.NORMAL) -> float:
+ """Seconds between admissions that keep a steady caller inside its share of every window.
+
+ Derived from the registered policy alone, so it holds when ``pace_seconds`` cannot yet see
+ calls the caller admitted but has not consumed, and when the store is unavailable. A caller
+ that keeps several calls in flight waits for whichever of the two is longer.
+ """
+ policy = resolve_policy(key)
+ return max(period / max(1, count - policy.reserve_amount(priority, count)) for count, period in policy.limits)
+
_limiter: OutboundRateLimiter | None = None
_limiter_lock = threading.Lock()
diff --git a/posthog/egress/test/test_outbound_rate_limiter.py b/posthog/egress/test/test_outbound_rate_limiter.py
index 09f69aeb1b39..9ae63d0e1e15 100644
--- a/posthog/egress/test/test_outbound_rate_limiter.py
+++ b/posthog/egress/test/test_outbound_rate_limiter.py
@@ -274,6 +274,24 @@ def test_pacing_follows_the_tightest_window(limits):
assert limiter.pace_seconds(key) > 0.0
+ "limits,priority,expected",
+ [
+ (((10, 60.0),), Priority.NORMAL, 6.0),
+ # The reserved floor is not part of the share, so BATCH spreads 7 of the 10 over the window.
+ (((10, 60.0),), Priority.BATCH, 60.0 / 7),
+ # The tightest window governs, whichever position it holds.
+ (((100, 60.0), (10, 3600.0)), Priority.NORMAL, 360.0),
+ (((10, 3600.0), (100, 60.0)), Priority.NORMAL, 360.0),
+ ],
+)
+def test_admission_interval_spreads_the_priority_share_over_the_tightest_window(limits, priority, expected):
+ register_policy("test-interval", RatePolicy(limits=limits, reserve={Priority.BATCH: 0.3}))
+ limiter = _fresh_limiter()
+
+ assert limiter.admission_interval_seconds("test-interval:scope:1", priority=priority) == pytest.approx(expected)
+
+
def test_pace_seconds_answers_zero_when_the_store_is_unavailable(monkeypatch):
# Pacing sits in front of every gated call, so a Redis blip must not raise into the caller. The
# in-memory fallback counts one process, so its headroom is not the shared budget's and a wait