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.

1.6 KB
Raw Blame
from collections.abc import Iterator
from contextlib import contextmanager

from django.conf import settings

from rest_framework.exceptions import Throttled

from posthog.api.query import CONCURRENCY_LIMIT_RETRY_AFTER_SECONDS, CONCURRENCY_LIMIT_USER_MESSAGE
from posthog.clickhouse.client.limit import (
    ConcurrencyLimitExceeded,
    app_org_concurrency_slot,
    get_api_team_rate_limiter,
)
from posthog.clickhouse.query_tagging import get_query_tag_value, is_api_key_access_method
from posthog.constants import AvailableFeature
from posthog.models.team import Team


def _api_key_concurrency_limit(team: Team) -> int | None:
    if not settings.EE_AVAILABLE or not settings.API_QUERIES_ENABLED:
        return None
    feature = team.organization.get_available_feature(AvailableFeature.API_QUERIES_CONCURRENCY)
    return feature.get("limit") if feature else None


@contextmanager
def query_concurrency_slots(team: Team) -> Iterator[None]:
    """Hold the slots a query runner holds, so the log's reads count against the same limits as a query."""
    is_api_key_access = is_api_key_access_method(get_query_tag_value("access_method"))
    try:
        with (
            get_api_team_rate_limiter().run(
                is_api=is_api_key_access,
                team_id=team.pk,
                limit=_api_key_concurrency_limit(team) if is_api_key_access else None,
            ),
            app_org_concurrency_slot(team),
        ):
            yield
    except ConcurrencyLimitExceeded as error:
        raise Throttled(wait=CONCURRENCY_LIMIT_RETRY_AFTER_SECONDS, detail=CONCURRENCY_LIMIT_USER_MESSAGE) from error