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.

6.5 KB
Raw Blame
"""DRF throttles for the endpoints run API.

Requests served from a materialized table get a higher rate budget than inline
ones. That classification is resolved through the facade; the throttle classes
and their request-parsing helpers are pure HTTP concerns and live here.
"""

from rest_framework.exceptions import Throttled
from rest_framework.throttling import SimpleRateThrottle

from posthog.rate_limit import (
    APIQueriesBurstThrottle,
    APIQueriesSustainedThrottle,
    PersonalOrProjectSecretApiKeyRateThrottle,
    ProjectSecretApiKeyTeamRateThrottle,
)

from products.endpoints.backend.facade.api import is_materialized_request, record_throttled_request


def _parse_requested_version(request) -> int | None:
    """Best-effort parse of the targeted version from the request (body first, then query params).

    Mirrors EndpointViewSet._parse_version_param; invalid or absent values fall back to None
    (current version) — the view validates and rejects properly later.
    """
    try:
        body_version = request.data.get("version") if hasattr(request, "data") else None
        raw_version = body_version if body_version is not None else request.query_params.get("version")
        return int(raw_version) if raw_version is not None else None
    except Exception:
        return None


def _get_endpoint_info_from_request(request, view) -> tuple[int | None, str | None, int | None]:
    """Extract team_id, endpoint_name, and requested version from request/view context."""
    team_id = getattr(view, "team_id", None)
    endpoint_name = view.kwargs.get("name") if hasattr(view, "kwargs") else None
    return team_id, endpoint_name, _parse_requested_version(request)


def _is_materialized_endpoint_request(request, view) -> bool:
    """Check if this request will be served from a materialized endpoint version."""
    try:
        body = request.data
    except Exception:
        # A body DRF cannot read takes the inline rate, because the view rejects the request.
        # This has to be the first access to request.data: DRF replaces an unparsable body with
        # an empty one, and an empty body reads as a clean materialized request. An unsupported
        # media type instead raises on every access, and an error that escapes a throttle skips
        # rate accounting for every scope.
        return False
    team_id, endpoint_name, version = _get_endpoint_info_from_request(request, view)
    if not team_id or not endpoint_name:
        return False
    return is_materialized_request(team_id, endpoint_name, version, body)


def _materialized_throttles(request) -> set[type]:
    granted = getattr(request, "endpoint_materialized_throttles", None)
    if granted is None:
        granted = set()
        request.endpoint_materialized_throttles = granted
    return granted


class _MaterializedRateMixin(SimpleRateThrottle):
    """Swaps in the higher materialized-endpoint rate and records 429s, on top of any base throttle.

    Mix in before a SimpleRateThrottle subclass — `allow_request` adjusts the rate/scope for
    materialized endpoints, then defers to the base throttle's own gating (which sits between
    this mixin and SimpleRateThrottle in the MRO).
    """

    materialized_rate: str
    materialized_scope: str
    inline_only = False

    def allow_request(self, request, view):
        materialized = not self.inline_only and _is_materialized_endpoint_request(request, view)
        if materialized:
            _materialized_throttles(request).add(type(self))
            self.rate = self.materialized_rate
            self.scope = self.materialized_scope
            self.num_requests, self.duration = self.parse_rate(self.rate)

        allowed = super().allow_request(request, view)
        if not allowed:
            team_id, endpoint_name, version = _get_endpoint_info_from_request(request, view)
            record_throttled_request(
                team_id, endpoint_name, version, materialized=materialized, scope=self.scope or "unknown"
            )
        return allowed


class EndpointBurstThrottle(_MaterializedRateMixin, PersonalOrProjectSecretApiKeyRateThrottle, APIQueriesBurstThrottle):
    """
    Adaptive burst throttle for endpoints, keyed per credential (personal API key or PSAK).
    Uses higher rate limit for materialized endpoints.
    Non-materialized endpoints share the api_queries_burst bucket.
    """

    materialized_rate = "1200/minute"
    materialized_scope = "materialized_endpoint_burst"


class EndpointSustainedThrottle(
    _MaterializedRateMixin, PersonalOrProjectSecretApiKeyRateThrottle, APIQueriesSustainedThrottle
):
    """
    Adaptive sustained throttle for endpoints, keyed per credential (personal API key or PSAK).
    Uses higher rate limit for materialized endpoints.
    Non-materialized endpoints share the api_queries_sustained bucket.
    """

    materialized_rate = "12000/hour"
    materialized_scope = "materialized_endpoint_sustained"


class EndpointProjectSecretApiKeyTeamBurstThrottle(_MaterializedRateMixin, ProjectSecretApiKeyTeamRateThrottle):
    """Per-team aggregate burst budget across all of a project's PSAKs — same size as the per-key
    budget, so minting extra keys never multiplies a project's total burst capacity."""

    # Own scope (not api_queries_burst) so 429 metrics and cache keys name the bucket that tripped.
    scope = "endpoint_psak_team_burst"
    rate = APIQueriesBurstThrottle.rate
    materialized_rate = EndpointBurstThrottle.materialized_rate
    materialized_scope = "materialized_endpoint_psak_team_burst"


class EndpointProjectSecretApiKeyTeamSustainedThrottle(_MaterializedRateMixin, ProjectSecretApiKeyTeamRateThrottle):
    """Per-team aggregate sustained budget across all of a project's PSAKs."""

    scope = "endpoint_psak_team_sustained"
    rate = APIQueriesSustainedThrottle.rate
    materialized_rate = EndpointSustainedThrottle.materialized_rate
    materialized_scope = "materialized_endpoint_psak_team_sustained"


def charge_inline_rate(request, view) -> None:
    """Bill a run that fell back to inline to the inline budget, or refuse it with a 429.

    A throttle that already charged the inline budget for this request is skipped.
    """
    waits = []
    granted = _materialized_throttles(request)
    for throttle in view.get_throttles():
        if type(throttle) not in granted:
            continue
        throttle.inline_only = True
        if not throttle.allow_request(request, view):
            waits.append(throttle.wait())
    if waits:
        raise Throttled(wait=max((wait for wait in waits if wait is not None), default=None))