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.

3.2 KB
Raw Blame
from __future__ import annotations

from abc import ABC, abstractmethod
from dataclasses import dataclass

from llm_gateway.auth.models import AuthenticatedUser
from llm_gateway.config import get_settings


def get_team_multiplier(team_id: int | None) -> int:
    if team_id is None:
        return 1

    return get_settings().team_rate_limit_multipliers.get(team_id, 1)


def get_staff_multiplier(user: AuthenticatedUser) -> int:
    """Elevated rate/cost cap for PostHog staff, applied regardless of which
    team they're acting on — so impersonating a customer doesn't drop the cap.
    Non-staff users get the unmodified base limit (1×)."""
    if not user.is_staff:
        return 1

    return get_settings().staff_rate_limit_multiplier


def get_rate_limit_multiplier(user: AuthenticatedUser) -> int:
    """Effective multiplier: the larger of the user's team multiplier and the
    staff multiplier, so staff keep an elevated cap on any team while configured
    teams keep theirs."""
    return max(get_team_multiplier(user.team_id), get_staff_multiplier(user))


def is_usage_unlimited(user: AuthenticatedUser) -> bool:
    """PostHog staff have no per-user cost cap — the burst/sustained throttles
    neither deny their requests nor report them as rate limited. Spend is still
    recorded for observability; only enforcement is skipped. Gated by a setting
    so it can be switched off without a redeploy. Non-staff users are unaffected."""
    return user.is_staff and get_settings().staff_unlimited_usage


@dataclass
class ThrottleContext:
    user: AuthenticatedUser
    product: str
    request_id: str | None = None
    end_user_id: str | None = None
    code_usage_billed: bool = False
    credits_exhausted: bool = False
    # Set only for sandbox-run tokens; see AuthenticatedUser.sandbox_task_id.
    sandbox_task_id: str | None = None


@dataclass
class ThrottleResult:
    allowed: bool
    status_code: int = 429
    detail: str = "Rate limit exceeded"
    scope: str | None = None
    retry_after: int | None = None
    used_usd: float | None = None
    limit_usd: float | None = None
    # False when retry_after is only a client back-off hint (e.g. exhausted
    # credits, zero limit) — retrying then won't succeed, so user-facing
    # messages must not promise it will.
    retry_after_resets_limit: bool = True

    @classmethod
    def allow(cls) -> ThrottleResult:
        return cls(allowed=True)

    @classmethod
    def deny(
        cls,
        status_code: int = 429,
        detail: str = "Rate limit exceeded",
        scope: str | None = None,
        retry_after: int | None = None,
        used_usd: float | None = None,
        limit_usd: float | None = None,
        retry_after_resets_limit: bool = True,
    ) -> ThrottleResult:
        return cls(
            allowed=False,
            status_code=status_code,
            detail=detail,
            scope=scope,
            retry_after=retry_after,
            used_usd=used_usd,
            limit_usd=limit_usd,
            retry_after_resets_limit=retry_after_resets_limit,
        )


class Throttle(ABC):
    scope: str = "default"

    @abstractmethod
    async def allow_request(self, context: ThrottleContext) -> ThrottleResult: ...