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.

feat(flags): show billable request usage by SDK (#87609)

Patricio7f99d0a4e32d
diff --git a/docs/internal/feature-flags/billing.md b/docs/internal/feature-flags/billing.md
index 373ea6ae4dfc..1b929faa8e5a 100644
--- a/docs/internal/feature-flags/billing.md
+++ b/docs/internal/feature-flags/billing.md
@@ -260,6 +260,20 @@ AND has([%(validity_token)s], replaceRegexpAll(JSONExtractRaw(properties, 'token
| Selective billing | Survey and product tour flags are internal features, not customer-billable |
| SDK breakdown for analytics only | Billing charges per request regardless of SDK; breakdown is for internal analytics |
+## Customer request usage view
+
+The feature flags **Usage** tab shows the existing billing events grouped by SDK and request type. It does not add counters or work to the request path.
+
+- Daily queries cover up to 31 days. Hourly queries cover up to 8 days so calendar-aligned 30-day and 7-day presets fit.
+- Remote evaluation combines `/flags` and legacy `/decide` traffic.
+- Local evaluation combines `/flags/definitions` and its legacy alias.
+- Counts include billable requests only. They are not raw HTTP traffic totals.
+- Local evaluation requests contribute 10 billing units each.
+- The SDK breakdown comes from the request user-agent and unknown SDKs appear as `other`.
+- Aggregation means recent usage can take approximately 30 minutes to appear. Hourly buckets use aggregation event time, so they approximate rather than preserve exact request time.
+
+The view cannot attribute a request to an individual flag lookup. `$feature_flag_called` events describe evaluation activity, but their totals do not map one-to-one to request usage.
+
## Billing service processing
The usage report is sent daily to the billing service (`billing.posthog.com`), which:
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 55eb290b8aa8..66f62be6fed0 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2313,7 +2313,7 @@ snapshots:
errortracking-exceptioncard--exception-card-header-widths--light:
hash: v1.k794b7964.c9d1a5ef4bb29010deec86a6a4b10760ba3e245b819deff4a6b11ce80b8b35e2.NBK6tX4m0khMKb-MRZBfFk87mMQ27hPQ22ZLlzWJtHQ
errortracking-exceptioncard--exception-card-header-widths-with-action--dark:
- hash: v1.k794b7964.bcb5832c034ac672244a43ace893fffbb64953dd8f474929937f52ec27f19b14.mAkQ8uO7PW_ilHWHY_oFF4c0LvQcggDt-iLVdnnJRIs
+ hash: v1.k794b7964.b80263f67c0d7d1e25bc2a91d738d80474ce40c97df64d2636bcc6a5dfa38e97.1uYHWbCS1ez7dIDtoz0c3GGZhBI3vHTN-1zaky50yqI
errortracking-exceptioncard--exception-card-header-widths-with-action--light:
hash: v1.k794b7964.25974971fa0cf2dbe86348ce1144e8b8a0ff7c1a7e172ecc941e6b345144841f.dT_74I4ZqX-DFX_ayPWR8lutK4EVque9Zyjbci6Hj6I
errortracking-exceptioncard--exception-card-no-in-app--dark:
@@ -7112,6 +7112,10 @@ snapshots:
hash: v1.k794b7964.b21df130430a104352e31173ae34feb16146f03d0688631d35f78052114fd3e7.GA0QgvUydkp96bBYC1RIiHsKN8O6Z_3nX1PXnfaBgeA
scenes-app-feature-flags-new-feature-flag-menu--default--light:
hash: v1.k794b7964.c58d12ddf9499563916bb71f41ff70dce9db471379ef2215c8b57a0ac88aa76c.jl03AgPo8iB46wC9k3xNkQwobb5SLJcSwYnOphJUt8Y
+ scenes-app-feature-flags-request-usage-summary-card--billing-units--dark:
+ hash: v1.k794b7964.4bee55e405082cc86dbd6cbaeb89cc1d583174707ba34ebcd95648ad8c32658a.yMqVeg0qnl7x4i2wG3eomTFBZVXVSQCdgHVkoY70t0A
+ scenes-app-feature-flags-request-usage-summary-card--billing-units--light:
+ hash: v1.k794b7964.4c874fa56cb5763308d6014643e745856067d5ae0cd7d14cff6454718555b111.lviDpRxDXwBFa5Z4SbmojXPgplv48hNUG3VUIelmOrw
scenes-app-feature-flags-schedule-timeline--rollout-ramp--dark:
hash: v1.k794b7964.2953688108a239d2ec1fed7e9536ba4fe608d7894111f5eeaf6f8a47339d8aff.sgkcFh_IvnLvMdJI7mdrIZEMQFbXUeRMTQxiWJUpalU
scenes-app-feature-flags-schedule-timeline--rollout-ramp--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 77e01f6b19e2..9df5f99b93b8 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -338,6 +338,7 @@ export const FEATURE_FLAGS = {
FEATURE_FLAG_DRAG_DROP_CONDITIONS: 'feature-flag-drag-drop-conditions', // owner: @gustavo #team-feature-flags
FEATURE_FLAG_EARLY_EXIT: 'feature-flag-early-exit', // owner: @gustavo #team-feature-flags
FEATURE_FLAG_NOTIFICATIONS: 'feature-flag-notifications', // owner: @reecejones #team-platform-features
+ FEATURE_FLAG_REQUEST_USAGE: 'feature-flag-request-usage', // owner: #team-feature-flags
FIELD_NOTES: 'field-notes', // owner: @adamleith
FLAG_EVALUATION_TAGS: 'flag-evaluation-tags', // owner: @dmarticus #team-feature-flags
FLAGGED_FEATURE_INDICATOR: 'flagged-feature-indicator', // owner: @benjackwhite
diff --git a/frontend/src/scenes/billing/BillingLineGraph.tsx b/frontend/src/scenes/billing/BillingLineGraph.tsx
index 7eec52c92291..93bd27399ee4 100644
--- a/frontend/src/scenes/billing/BillingLineGraph.tsx
+++ b/frontend/src/scenes/billing/BillingLineGraph.tsx
@@ -25,7 +25,8 @@ export interface BillingLineGraphProps {
hiddenSeries: number[]
valueFormatter?: (value: number) => string
showLegend?: boolean
- interval?: 'day' | 'week' | 'month'
+ legendInteractive?: boolean
+ interval?: 'hour' | 'day' | 'week' | 'month'
billingPeriodMarkers?: BillingPeriodMarker[]
}
@@ -42,6 +43,7 @@ export function BillingLineGraph({
hiddenSeries,
valueFormatter = defaultFormatter,
showLegend = true,
+ legendInteractive = false,
interval = 'day',
billingPeriodMarkers = NO_MARKERS,
}: BillingLineGraphProps): JSX.Element {
@@ -66,10 +68,10 @@ export function BillingLineGraph({
() => ({
xAxis: { timezone: 'UTC', interval },
yAxis: { tickFormatter: valueFormatter },
- legend: { show: showLegend, position: 'bottom', interactive: false },
+ legend: { show: showLegend, position: 'bottom', interactive: legendInteractive },
tooltip: { sortedByValue: true, valueFormatter, placement: 'cursor' },
}),
- [interval, valueFormatter, showLegend]
+ [interval, valueFormatter, showLegend, legendInteractive]
)
return (
diff --git a/frontend/src/scenes/feature-flags/FeatureFlags.tsx b/frontend/src/scenes/feature-flags/FeatureFlags.tsx
index 572f0ef23a62..f308869f146f 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlags.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlags.tsx
@@ -56,6 +56,7 @@ import {
} from '~/types'
import { featureFlagsEmptyState } from 'products/feature_flags/frontend/emptyState/featureFlagsEmptyState'
+import { FeatureFlagRequestUsage } from 'products/feature_flags/frontend/requestUsage/FeatureFlagRequestUsage'
import { ApprovalsPromoBanner } from './ApprovalsPromoBanner'
import { BulkCopyFlagsModal, BulkCopyToProjectsButton } from './BulkCopyFlagsModal'
@@ -759,6 +760,7 @@ export function FeatureFlags(): JSX.Element {
const { featureFlags: enabledFeatureFlags } = useValues(enabledFeaturesLogic)
const newFeatureFlagUrl = urls.featureFlagTemplates()
const showNotificationsTab = !!enabledFeatureFlags[FEATURE_FLAGS.FEATURE_FLAG_NOTIFICATIONS]
+ const showRequestUsageTab = !!enabledFeatureFlags[FEATURE_FLAGS.FEATURE_FLAG_REQUEST_USAGE]
return (
<SceneContent className="feature_flags">
@@ -811,7 +813,9 @@ export function FeatureFlags(): JSX.Element {
}
/>
<LemonTabs
- activeKey={activeTab}
+ activeKey={
+ activeTab === FeatureFlagsTab.USAGE && !showRequestUsageTab ? FeatureFlagsTab.OVERVIEW : activeTab
+ }
onChange={(newKey) => setActiveTab(newKey)}
sceneInset
tabs={[
@@ -820,6 +824,15 @@ export function FeatureFlags(): JSX.Element {
label: 'Overview',
content: <OverviewTab />,
},
+ ...(showRequestUsageTab
+ ? [
+ {
+ key: FeatureFlagsTab.USAGE,
+ label: 'Request usage',
+ content: <FeatureFlagRequestUsage />,
+ },
+ ]
+ : []),
{
key: FeatureFlagsTab.PROJECTS,
label: 'Projects',
diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts
index 9d2e55f1fc32..3344d74f7258 100644
--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.test.ts
@@ -3,7 +3,9 @@ import { expectLogic } from 'kea-test-utils'
import posthog from 'posthog-js'
import api from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { featureFlagLogic as enabledFeaturesLogic } from 'lib/logic/featureFlagLogic'
import { showApprovalRequiredToast } from 'scenes/approvals/ApprovalRequiredBanner'
import { NEW_FLAG } from 'scenes/feature-flags/featureFlagLogic'
import {
@@ -283,6 +285,56 @@ describe('the feature flags logic', () => {
})
})
+ it('redirects a disabled usage deep link to overview after flags load', async () => {
+ enabledFeaturesLogic.actions.setFeatureFlags([], {})
+
+ await expectLogic(logic, () => {
+ router.actions.push(urls.featureFlags(), { tab: FeatureFlagsTab.USAGE })
+ }).toMatchValues({ activeTab: FeatureFlagsTab.OVERVIEW })
+ expect(router.values.searchParams['tab']).toEqual('overview')
+ })
+
+ it('redirects from usage when the rollout flag is disabled', async () => {
+ router.actions.push(urls.featureFlags())
+ enabledFeaturesLogic.actions.setFeatureFlags([FEATURE_FLAGS.FEATURE_FLAG_REQUEST_USAGE], {
+ [FEATURE_FLAGS.FEATURE_FLAG_REQUEST_USAGE]: true,
+ })
+ logic.actions.setActiveTab(FeatureFlagsTab.USAGE)
+
+ await expectLogic(logic, () => {
+ enabledFeaturesLogic.actions.setFeatureFlags([], {})
+ }).toMatchValues({ activeTab: FeatureFlagsTab.OVERVIEW })
+ expect(router.values.searchParams['tab']).toEqual('overview')
+ })
+
+ it('stays on usage when the rollout flag is enabled', async () => {
+ const flags = {
+ [FEATURE_FLAGS.FEATURE_FLAG_REQUEST_USAGE]: true,
+ }
+ enabledFeaturesLogic.actions.setFeatureFlags([FEATURE_FLAGS.FEATURE_FLAG_REQUEST_USAGE], flags)
+
+ await expectLogic(logic, () => {
+ router.actions.push(urls.featureFlags(), { tab: FeatureFlagsTab.USAGE })
+ }).toMatchValues({ activeTab: FeatureFlagsTab.USAGE })
+
+ await expectLogic(logic, () => {
+ enabledFeaturesLogic.actions.setFeatureFlags([FEATURE_FLAGS.FEATURE_FLAG_REQUEST_USAGE], flags)
+ }).toMatchValues({ activeTab: FeatureFlagsTab.USAGE })
+ expect(router.values.searchParams['tab']).toEqual('usage')
+ })
+
+ it('does not rewrite another scene URL when the rollout flag is disabled', async () => {
+ enabledFeaturesLogic.actions.setFeatureFlags([FEATURE_FLAGS.FEATURE_FLAG_REQUEST_USAGE], {
+ [FEATURE_FLAGS.FEATURE_FLAG_REQUEST_USAGE]: true,
+ })
+ logic.actions.setActiveTab(FeatureFlagsTab.USAGE)
+ router.actions.push('/project/997/experiments/1')
+
+ enabledFeaturesLogic.actions.setFeatureFlags([], {})
+
+ expect(router.values.location.pathname).toEqual('/project/997/experiments/1')
+ })
+
describe('activity deep-link', () => {
it('preserves the activity deep-link param when staying on the history tab', async () => {
router.actions.push(urls.featureFlags(), { tab: 'history', activity: 'some-uuid' })
diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.ts
index d9dbc58e222c..6c6a3de46aae 100644
--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.ts
@@ -6,6 +6,8 @@ import { LemonDialog, PaginationManual } from '@posthog/lemon-ui'
import api, { CountedPaginatedResponse } from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic as enabledFeaturesLogic, FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { objectsEqual } from 'lib/utils/objects'
import { parseNumericArrayFilter, parseTagsFilter, toParams } from 'lib/utils/url'
import { handleFlagApprovalRequired } from 'scenes/feature-flags/updateFlagActiveInProject'
@@ -185,6 +187,8 @@ const clearFlagUpdating = (
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagsLogicValues {
+ enabledFeatureFlags: FeatureFlagsSet // enabledFeaturesLogic
+ receivedFeatureFlags: boolean // enabledFeaturesLogic
currentProjectId: number | null // projectLogic
activeTab: FeatureFlagsTab
breadcrumbs: Breadcrumb[]
@@ -217,6 +221,13 @@ export interface featureFlagsLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface featureFlagsLogicActions {
+ setFeatureFlags: (
+ flags: string[],
+ variants: Record<string, boolean | string>
+ ) => {
+ flags: string[]
+ variants: Record<string, boolean | string>
+ } // enabledFeaturesLogic
closeEnrichAnalyticsNotice: () => {
value: true
}
@@ -411,7 +422,13 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([
props({} as FlagLogicProps),
path(['scenes', 'feature-flags', 'featureFlagsLogic']),
connect(() => ({
- values: [projectLogic, ['currentProjectId']],
+ values: [
+ projectLogic,
+ ['currentProjectId'],
+ enabledFeaturesLogic,
+ ['featureFlags as enabledFeatureFlags', 'receivedFeatureFlags'],
+ ],
+ actions: [enabledFeaturesLogic, ['setFeatureFlags']],
})),
actions({
updateFlag: (flag: FeatureFlagType) => ({ flag }),
@@ -637,6 +654,15 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([
],
}),
listeners(({ actions, values }) => ({
+ setFeatureFlags: () => {
+ if (
+ !values.enabledFeatureFlags[FEATURE_FLAGS.FEATURE_FLAG_REQUEST_USAGE] &&
+ values.activeTab === FeatureFlagsTab.USAGE &&
+ router.values.location.pathname.endsWith(urls.featureFlags())
+ ) {
+ actions.setActiveTab(FeatureFlagsTab.OVERVIEW)
+ }
+ },
updateFlagActive: ({ id, active }) => {
actions.updateFeatureFlag({ id, payload: { active } })
},
@@ -735,7 +761,13 @@ export const featureFlagsLogic = kea<featureFlagsLogicType>([
actions.setActiveTab(FeatureFlagsTab.OVERVIEW)
}
} else if (tabInURL !== values.activeTab) {
- actions.setActiveTab(tabInURL)
+ const availableTab =
+ tabInURL === FeatureFlagsTab.USAGE &&
+ values.receivedFeatureFlags &&
+ !values.enabledFeatureFlags[FEATURE_FLAGS.FEATURE_FLAG_REQUEST_USAGE]
+ ? FeatureFlagsTab.OVERVIEW
+ : tabInURL
+ actions.setActiveTab(availableTab)
}
const { page, created_by_id, active, archived, type, search, order, evaluation_runtime, tags } =
diff --git a/posthog/rate_limit.py b/posthog/rate_limit.py
index ceb9adc8b0a4..2fcba167e70a 100644
--- a/posthog/rate_limit.py
+++ b/posthog/rate_limit.py
@@ -638,6 +638,19 @@ class SessionContextsSustainedRateThrottle(_TeamBucketRateThrottle):
rate = "600/hour"
+# Feature flag request usage scans up to 31 days of billing events in ClickHouse. Its primary
+# caller is the session-authenticated feature flags UI, which the generic ClickHouse throttle
+# pair does not cover. Use a team-wide bucket so users and API keys share one query budget.
+class FeatureFlagRequestUsageBurstRateThrottle(_TeamBucketRateThrottle):
+ scope = "feature_flag_request_usage_burst"
+ rate = "30/minute"
+
+
+class FeatureFlagRequestUsageSustainedRateThrottle(_TeamBucketRateThrottle):
+ scope = "feature_flag_request_usage_sustained"
+ rate = "300/hour"
+
+
# Fingerprint projection runs t-SNE synchronously over up to 250 high-dimensional embeddings.
# Query endpoint defaults only cover personal API keys, so use a team-wide bucket to include
# session callers and prevent forced refreshes from consuming application workers without bound.
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index b7be0d7e3a9f..d8ea33fee353 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -610,6 +610,7 @@ SPECTACULAR_SETTINGS = {
#
# The choices come from a typing.Literal via get_args; there is no class.
"BlockedByEnum": ["x_frame_options", "frame_ancestors"],
+ "FeatureFlagRequestTypeEnum": ["remote_evaluation", "local_evaluation"],
"PropertyFilterTypeEnum": [
"event",
"event_metadata",
diff --git a/products/feature_flags/backend/facade/api.py b/products/feature_flags/backend/facade/api.py
index 3d15d7e74f36..073430deafd5 100644
--- a/products/feature_flags/backend/facade/api.py
+++ b/products/feature_flags/backend/facade/api.py
@@ -4,8 +4,9 @@ Every write routes through ``FeatureFlagSerializer`` — the only path that hono
``@approval_gate``, validation, and activity logging. Consumers (currently experiments)
call these functions instead of driving the serializer and its DRF context by hand.
The read helpers (``user_can_edit_flag``, ``flag_disable_requires_approval``,
-``serialize_flags``) expose the flag API's access-control, approval-policy, and
-representation logic behind the same boundary.
+``serialize_flags``, ``get_feature_flag_request_usage``) expose the flag API's
+access-control, approval-policy, representation, and request-usage logic behind
+the same boundary.
Writes do not enforce access control — that lives at the viewset layer. A caller
acting on behalf of an end user must pre-check ``user_can_edit_flag`` first.
@@ -23,7 +24,8 @@ signal the gate skips on (its policies target human-driven changes, and a reques
caller cannot surface a 409/change request), so ``ApprovalRequired`` is never raised.
"""
-from typing import Any
+from datetime import datetime
+from typing import Any, Literal
from rest_framework.exceptions import ValidationError
@@ -36,6 +38,11 @@ from products.approvals.backend.policies import PolicyEngine
from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer
from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.feature_flags.backend.request_usage import (
+ FeatureFlagRequestType as FeatureFlagRequestType,
+ FeatureFlagRequestUsage as FeatureFlagRequestUsage,
+ query_feature_flag_request_usage,
+)
def _serializer_context(team: Team, user: Any, request: Any | None, *, method: str = "POST") -> dict:
@@ -294,6 +301,14 @@ def serialize_flags(flags: Any, *, context: dict) -> Any:
return FeatureFlagSerializer(flags, many=True, context=context).data
+def get_feature_flag_request_usage(
+ *, team_id: int, date_from: datetime, date_to: datetime, time_interval: Literal["hour", "day"]
+) -> list[FeatureFlagRequestUsage]:
+ return query_feature_flag_request_usage(
+ team_id=team_id, date_from=date_from, date_to=date_to, time_interval=time_interval
+ )
+
+
def flag_is_active(key: str, *, team_id: int | None = None) -> bool:
"""Whether an active flag with this key exists, optionally narrowed to one team.
diff --git a/products/feature_flags/backend/presentation/__init__.py b/products/feature_flags/backend/presentation/__init__.py
new file mode 100644
index 000000000000..ffcf1bef6e39
--- /dev/null
+++ b/products/feature_flags/backend/presentation/__init__.py
@@ -0,0 +1 @@
+"""HTTP presentation layer for feature flags."""
diff --git a/products/feature_flags/backend/presentation/request_usage.py b/products/feature_flags/backend/presentation/request_usage.py
new file mode 100644
index 000000000000..881f0e20827f
--- /dev/null
+++ b/products/feature_flags/backend/presentation/request_usage.py
@@ -0,0 +1,114 @@
+from datetime import datetime, timedelta
+from typing import Literal, cast
+
+from drf_spectacular.utils import OpenApiResponse, extend_schema_serializer
+from rest_framework import serializers, viewsets
+from rest_framework.exceptions import NotFound
+from rest_framework.response import Response
+from rest_framework_dataclasses.serializers import DataclassSerializer
+
+from posthog.schema import ProductKey
+
+from posthog.api.documentation import extend_schema
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.models.user import User
+from posthog.ph_client import feature_enabled_or_false
+from posthog.rate_limit import FeatureFlagRequestUsageBurstRateThrottle, FeatureFlagRequestUsageSustainedRateThrottle
+
+from products.feature_flags.backend.facade.api import (
+ FeatureFlagRequestType,
+ FeatureFlagRequestUsage,
+ get_feature_flag_request_usage,
+)
+
+FEATURE_FLAG_REQUEST_USAGE_FLAG = "feature-flag-request-usage"
+# The shared "Last 7 days" preset starts at midnight seven days ago and ends now,
+# so it can span almost eight elapsed days. Keep this aligned with the frontend limit.
+MAX_HOURLY_RANGE_DAYS = 8
+MAX_DAILY_RANGE_DAYS = 31
+
+
+class FeatureFlagRequestUsageQuerySerializer(serializers.Serializer):
+ date_from = serializers.DateTimeField(help_text="Inclusive start of the usage period.")
+ date_to = serializers.DateTimeField(help_text="Exclusive end of the usage period.")
+ time_interval = serializers.ChoiceField(
+ choices=["hour", "day"],
+ default="day",
+ help_text=f"Time bucket used to group request usage. Hourly queries are limited to {MAX_HOURLY_RANGE_DAYS} days.",
+ )
+
+ def validate(self, attrs: dict[str, object]) -> dict[str, object]:
+ date_from = cast(datetime, attrs["date_from"])
+ date_to = cast(datetime, attrs["date_to"])
+ time_interval = cast(str, attrs["time_interval"])
+ if date_from >= date_to:
+ raise serializers.ValidationError("date_from must be earlier than date_to.")
+
+ maximum_range = timedelta(days=MAX_HOURLY_RANGE_DAYS if time_interval == "hour" else MAX_DAILY_RANGE_DAYS)
+ if date_to - date_from > maximum_range:
+ raise serializers.ValidationError(
+ f"{time_interval.capitalize()} queries are limited to {maximum_range.days} days."
+ )
+ return attrs
+
+
+@extend_schema_serializer(component_name="FeatureFlagRequestUsageItem")
+class FeatureFlagRequestUsageItemSerializer(DataclassSerializer):
+ request_type = serializers.ChoiceField(
+ choices=list(FeatureFlagRequestType),
+ help_text="Remote flag evaluation or local flag-definition request.",
+ )
+
+ class Meta:
+ dataclass = FeatureFlagRequestUsage
+ extra_kwargs = {
+ "bucket": {
+ "help_text": "Start of the UTC billing-aggregation bucket. Hourly buckets approximate request time."
+ },
+ "sdk": {"help_text": "SDK family parsed from the request user agent."},
+ "request_count": {"help_text": "Number of billable requests in this bucket."},
+ "billing_units": {
+ "help_text": "Estimated billing units. Local evaluation requests count as 10 units each."
+ },
+ }
+
+
+@extend_schema_serializer(many=False)
+class FeatureFlagRequestUsageResponseSerializer(serializers.Serializer):
+ results = FeatureFlagRequestUsageItemSerializer(many=True, help_text="Feature flag request usage by SDK.")
+
+
+@extend_schema(extensions={"x-product": ProductKey.FEATURE_FLAGS})
+class FeatureFlagRequestUsageViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ scope_object = "feature_flag"
+ requires_resource_level_access = True
+ throttle_classes = [FeatureFlagRequestUsageBurstRateThrottle, FeatureFlagRequestUsageSustainedRateThrottle]
+
+ @validated_request(
+ query_serializer=FeatureFlagRequestUsageQuerySerializer,
+ responses={200: OpenApiResponse(response=FeatureFlagRequestUsageResponseSerializer)},
+ )
+ def list(self, request: ValidatedRequest, *args: object, **kwargs: object) -> Response:
+ user = cast(User, request.user)
+ if not feature_enabled_or_false(
+ FEATURE_FLAG_REQUEST_USAGE_FLAG,
+ user.distinct_id or str(self.team.uuid),
+ groups={"organization": str(self.team.organization_id), "project": str(self.team.id)},
+ group_properties={
+ "organization": {"id": str(self.team.organization_id)},
+ "project": {"id": str(self.team.id)},
+ },
+ send_feature_flag_events=False,
+ ):
+ raise NotFound("Feature flag request usage is not enabled for this project.")
+
+ query = request.validated_query_data
+ results = get_feature_flag_request_usage(
+ team_id=self.team_id,
+ date_from=cast(datetime, query["date_from"]),
+ date_to=cast(datetime, query["date_to"]),
+ time_interval=cast(Literal["hour", "day"], query["time_interval"]),
+ )
+ payload = FeatureFlagRequestUsageResponseSerializer({"results": results})
+ return Response(payload.data)
diff --git a/products/feature_flags/backend/presentation/test/__init__.py b/products/feature_flags/backend/presentation/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/feature_flags/backend/presentation/test/test_request_usage.py b/products/feature_flags/backend/presentation/test/test_request_usage.py
new file mode 100644
index 000000000000..36eadd35f748
--- /dev/null
+++ b/products/feature_flags/backend/presentation/test/test_request_usage.py
@@ -0,0 +1,138 @@
+from datetime import UTC, datetime
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import Mock, patch
+
+from django.core.cache import cache
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.rate_limit import FeatureFlagRequestUsageBurstRateThrottle
+
+from products.feature_flags.backend.facade.api import FeatureFlagRequestType, FeatureFlagRequestUsage
+from products.feature_flags.backend.presentation.request_usage import FeatureFlagRequestUsageQuerySerializer
+
+
+class TestFeatureFlagRequestUsage(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ feature_flag_patcher = patch(
+ "products.feature_flags.backend.presentation.request_usage.feature_enabled_or_false", return_value=True
+ )
+ feature_flag_patcher.start()
+ self.addCleanup(feature_flag_patcher.stop)
+
+ def tearDown(self) -> None:
+ cache.clear()
+ super().tearDown()
+
+ @parameterized.expand(
+ [
+ ("hour", "2026-08-01T00:00:00Z", "2026-08-09T00:00:01Z"),
+ ("day", "2026-07-01T00:00:00Z", "2026-08-02T00:00:01Z"),
+ ]
+ )
+ def test_rejects_ranges_that_exceed_the_interval_limit(self, interval: str, date_from: str, date_to: str) -> None:
+ serializer = FeatureFlagRequestUsageQuerySerializer(
+ data={"time_interval": interval, "date_from": date_from, "date_to": date_to}
+ )
+
+ assert not serializer.is_valid()
+ assert "non_field_errors" in serializer.errors
+
+ def test_accepts_hourly_range_from_last_seven_days_preset(self) -> None:
+ serializer = FeatureFlagRequestUsageQuerySerializer(
+ data={
+ "time_interval": "hour",
+ "date_from": "2026-08-01T00:00:00Z",
+ "date_to": "2026-08-08T23:59:59Z",
+ }
+ )
+
+ assert serializer.is_valid(), serializer.errors
+
+ def test_rejects_inverted_date_range(self) -> None:
+ serializer = FeatureFlagRequestUsageQuerySerializer(
+ data={
+ "time_interval": "day",
+ "date_from": "2026-08-21T00:00:00Z",
+ "date_to": "2026-08-20T00:00:00Z",
+ }
+ )
+
+ assert not serializer.is_valid()
+ assert serializer.errors["non_field_errors"] == ["date_from must be earlier than date_to."]
+
+ @patch("products.feature_flags.backend.presentation.request_usage.get_feature_flag_request_usage")
+ def test_returns_usage_for_the_project_in_the_url(self, mock_get_usage) -> None:
+ mock_get_usage.return_value = [
+ FeatureFlagRequestUsage(
+ bucket=datetime(2026, 8, 20, tzinfo=UTC),
+ request_type=FeatureFlagRequestType.LOCAL_EVALUATION,
+ sdk="posthog-ruby",
+ request_count=12,
+ billing_units=120,
+ )
+ ]
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/feature_flag_request_usage/",
+ {
+ "date_from": "2026-08-20T00:00:00Z",
+ "date_to": "2026-08-21T00:00:00Z",
+ "time_interval": "hour",
+ },
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["results"][0] == {
+ "bucket": "2026-08-20T00:00:00Z",
+ "request_type": "local_evaluation",
+ "sdk": "posthog-ruby",
+ "request_count": 12,
+ "billing_units": 120,
+ }
+ assert mock_get_usage.call_args.kwargs["team_id"] == self.team.id
+
+ def test_returns_not_found_when_request_usage_flag_is_disabled(self) -> None:
+ with patch(
+ "products.feature_flags.backend.presentation.request_usage.feature_enabled_or_false", return_value=False
+ ):
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/feature_flag_request_usage/",
+ {
+ "date_from": "2026-08-20T00:00:00Z",
+ "date_to": "2026-08-21T00:00:00Z",
+ "time_interval": "hour",
+ },
+ )
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
+
+ @patch("posthog.rate_limit.team_is_allowed_to_bypass_throttle", return_value=False)
+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)
+ @patch("products.feature_flags.backend.presentation.request_usage.get_feature_flag_request_usage", return_value=[])
+ def test_session_requests_are_rate_limited(self, _mock_get_usage, _rate_limit_enabled, _team_can_bypass) -> None:
+ query = {
+ "date_from": "2026-08-20T00:00:00Z",
+ "date_to": "2026-08-21T00:00:00Z",
+ "time_interval": "hour",
+ }
+
+ with patch.object(FeatureFlagRequestUsageBurstRateThrottle, "rate", "1/minute"):
+ first_response = self.client.get(f"/api/projects/{self.team.id}/feature_flag_request_usage/", query)
+ second_response = self.client.get(f"/api/projects/{self.team.id}/feature_flag_request_usage/", query)
+
+ assert first_response.status_code == status.HTTP_200_OK
+ assert second_response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
+
+ def test_request_usage_throttle_uses_one_bucket_per_project(self) -> None:
+ throttle = FeatureFlagRequestUsageBurstRateThrottle()
+ view = Mock(team_id=self.team.id)
+ first_user_request = Mock(user=Mock(is_authenticated=True, pk=1))
+ second_user_request = Mock(user=Mock(is_authenticated=True, pk=2))
+
+ first_cache_key = throttle.get_cache_key(first_user_request, view)
+ assert first_cache_key == throttle.get_cache_key(second_user_request, view)
+ assert str(self.team.id) in first_cache_key
diff --git a/products/feature_flags/backend/request_usage.py b/products/feature_flags/backend/request_usage.py
new file mode 100644
index 000000000000..40ad034b0bf3
--- /dev/null
+++ b/products/feature_flags/backend/request_usage.py
@@ -0,0 +1,135 @@
+import json
+from collections import defaultdict
+from collections.abc import Iterable
+from datetime import datetime
+from enum import StrEnum
+from typing import Literal, cast
+
+from django.conf import settings
+
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.client.connection import ClickHouseUser, Workload
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.constants import FlagRequestType
+from posthog.dataclasses import frozen
+from posthog.models.event.new_events_schema import events_read_table, use_new_events_schema
+from posthog.models.property.util import get_property_string_expr
+from posthog.utils import get_instance_region
+
+from products.feature_flags.backend.flag_analytics import USAGE_EVENT_NAMES
+
+
+class FeatureFlagRequestType(StrEnum):
+ REMOTE_EVALUATION = "remote_evaluation"
+ LOCAL_EVALUATION = "local_evaluation"
+
+
+@frozen
+class FeatureFlagRequestUsage:
+ bucket: datetime
+ request_type: FeatureFlagRequestType
+ sdk: str
+ request_count: int
+ billing_units: int
+
+
+REQUEST_USAGE_QUERY_SETTINGS = {
+ "max_execution_time": 30,
+ "max_bytes_to_read": 10 * 1024 * 1024 * 1024,
+ "max_memory_usage": 2 * 1024 * 1024 * 1024,
+ "max_threads": 4,
+}
+
+FeatureFlagRequestUsageRow = tuple[datetime, Literal["remote_evaluation", "local_evaluation"], int, str]
+
+# Keep aligned with usage_report.py, which applies this multiplier to billed local evaluation requests.
+LOCAL_EVALUATION_BILLING_WEIGHT = 10
+
+
+def parse_sdk_breakdown(raw_sdk_breakdown: str) -> dict[str, int]:
+ try:
+ parsed_breakdown = json.loads(raw_sdk_breakdown) if raw_sdk_breakdown else {}
+ except json.JSONDecodeError:
+ return {}
+ if not isinstance(parsed_breakdown, dict):
+ return {}
+ return {
+ sdk: count
+ for sdk, count in parsed_breakdown.items()
+ if isinstance(sdk, str) and isinstance(count, int) and count >= 0
+ }
+
+
+def aggregate_feature_flag_request_usage(
+ rows: Iterable[FeatureFlagRequestUsageRow],
+) -> list[FeatureFlagRequestUsage]:
+ counts: defaultdict[tuple[datetime, FeatureFlagRequestType, str], int] = defaultdict(int)
+ for bucket, raw_request_type, total_count, raw_sdk_breakdown in rows:
+ request_type = FeatureFlagRequestType(raw_request_type)
+ sdk_breakdown = parse_sdk_breakdown(raw_sdk_breakdown)
+ for sdk, count in sdk_breakdown.items():
+ counts[(bucket, request_type, sdk)] += count
+ counts[(bucket, request_type, "other")] += max(total_count - sum(sdk_breakdown.values()), 0)
+
+ return [
+ FeatureFlagRequestUsage(
+ bucket=bucket,
+ request_type=request_type,
+ sdk=sdk,
+ request_count=request_count,
+ billing_units=request_count
+ * (LOCAL_EVALUATION_BILLING_WEIGHT if request_type == FeatureFlagRequestType.LOCAL_EVALUATION else 1),
+ )
+ for (bucket, request_type, sdk), request_count in sorted(counts.items())
+ if request_count > 0
+ ]
+
+
+def query_feature_flag_request_usage(
+ *, team_id: int, date_from: datetime, date_to: datetime, time_interval: Literal["hour", "day"]
+) -> list[FeatureFlagRequestUsage]:
+ internal_team_id = 1 if get_instance_region() == "EU" else 2
+ validity_token = settings.DECIDE_BILLING_ANALYTICS_TOKEN
+ use_new = use_new_events_schema(None)
+ sdk_breakdown_expr, _ = get_property_string_expr(
+ "events", "sdk_breakdown", "'sdk_breakdown'", "properties", use_new_events_schema=use_new
+ )
+ count_expr, _ = get_property_string_expr("events", "count", "'count'", "properties", use_new_events_schema=use_new)
+ token_expr, _ = get_property_string_expr("events", "token", "'token'", "properties", use_new_events_schema=use_new)
+ bucket_function = "toStartOfHour" if time_interval == "hour" else "toStartOfDay"
+ decide_event = USAGE_EVENT_NAMES[FlagRequestType.DECIDE]
+ local_event = USAGE_EVENT_NAMES[FlagRequestType.LOCAL_EVALUATION]
+
+ with tags_context(product=Product.FEATURE_FLAGS, feature=Feature.QUERY, team_id=team_id):
+ # nosemgrep: clickhouse-fstring-param-audit - bucket function and table expressions are internal fragments
+ rows = sync_execute(
+ f"""
+ SELECT
+ {bucket_function}(timestamp) AS bucket,
+ if(event = %(decide_event)s, 'remote_evaluation', 'local_evaluation') AS request_type,
+ toInt64OrZero({count_expr}) AS total_count,
+ {sdk_breakdown_expr} AS sdk_breakdown
+ FROM {events_read_table(use_new)}
+ WHERE team_id = %(internal_team_id)s
+ AND distinct_id = toString(%(team_id)s)
+ AND event IN (%(decide_event)s, %(local_event)s)
+ AND timestamp >= %(date_from)s AND timestamp < %(date_to)s
+ AND has([%(validity_token)s], {token_expr})
+ ORDER BY bucket, request_type
+ """,
+ {
+ "internal_team_id": internal_team_id,
+ "team_id": team_id,
+ "date_from": date_from,
+ "date_to": date_to,
+ "validity_token": validity_token,
+ "decide_event": decide_event,
+ "local_event": local_event,
+ },
+ workload=Workload.ONLINE,
+ team_id=team_id,
+ settings=REQUEST_USAGE_QUERY_SETTINGS,
+ ch_user=ClickHouseUser.APP,
+ )
+
+ return aggregate_feature_flag_request_usage(cast(list[FeatureFlagRequestUsageRow], rows))
diff --git a/products/feature_flags/backend/routes.py b/products/feature_flags/backend/routes.py
index c27681ab41b3..02972d4d7b13 100644
--- a/products/feature_flags/backend/routes.py
+++ b/products/feature_flags/backend/routes.py
@@ -9,6 +9,7 @@ from products.feature_flags.backend.api import (
staff_team_config,
staff_teams,
)
+from products.feature_flags.backend.presentation import request_usage
def register_routes(routers: RouterRegistry) -> None:
@@ -34,6 +35,12 @@ def register_routes(routers: RouterRegistry) -> None:
routers.projects.register(
r"feature_flags", feature_flag.FeatureFlagViewSet, "project_feature_flags", ["project_id"]
)
+ routers.projects.register(
+ r"feature_flag_request_usage",
+ request_usage.FeatureFlagRequestUsageViewSet,
+ "project_feature_flag_request_usage",
+ ["project_id"],
+ )
routers.projects.register(
r"scheduled_changes", scheduled_change.ScheduledChangeViewSet, "project_scheduled_changes", ["project_id"]
)
diff --git a/products/feature_flags/backend/test/test_request_usage.py b/products/feature_flags/backend/test/test_request_usage.py
new file mode 100644
index 000000000000..b3252022883a
--- /dev/null
+++ b/products/feature_flags/backend/test/test_request_usage.py
@@ -0,0 +1,132 @@
+from datetime import UTC, datetime
+
+from posthog.test.base import ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import patch
+
+from django.test import TestCase
+
+from parameterized import parameterized
+
+from posthog.clickhouse.client.connection import ClickHouseUser
+from posthog.models.organization import Organization
+from posthog.models.team.team import Team
+
+from products.feature_flags.backend.request_usage import (
+ REQUEST_USAGE_QUERY_SETTINGS,
+ aggregate_feature_flag_request_usage,
+ parse_sdk_breakdown,
+ query_feature_flag_request_usage,
+)
+
+
+class TestFeatureFlagRequestUsageQuery(ClickhouseTestMixin, TestCase):
+ @parameterized.expand(
+ [
+ ("missing breakdown", "", [("other", 10)]),
+ ("partial breakdown", '{"posthog-node": 4}', [("other", 6), ("posthog-node", 4)]),
+ ]
+ )
+ def test_attributes_unclassified_billed_requests_to_other(
+ self, _name: str, sdk_breakdown: str, expected: list[tuple[str, int]]
+ ) -> None:
+ results = aggregate_feature_flag_request_usage(
+ [(datetime(2026, 8, 20, tzinfo=UTC), "remote_evaluation", 10, sdk_breakdown)]
+ )
+ assert [(result.sdk, result.request_count) for result in results] == expected
+
+ @parameterized.expand(
+ [
+ ("malformed JSON", "{not-json", {}),
+ ("non-object JSON", "[]", {}),
+ ("invalid values", '{"posthog-node": -1, "posthog-python": "2"}', {}),
+ ("fully attributed", '{"posthog-node": 4, "posthog-python": 6}', {"posthog-node": 4, "posthog-python": 6}),
+ ]
+ )
+ def test_parses_sdk_breakdown(self, _name: str, raw_breakdown: str, expected: dict[str, int]) -> None:
+ assert parse_sdk_breakdown(raw_breakdown) == expected
+
+ @patch("products.feature_flags.backend.request_usage.sync_execute")
+ def test_clickhouse_query_is_scoped_and_weights_local_requests(self, mock_sync_execute) -> None:
+ mock_sync_execute.return_value = [
+ (datetime(2026, 8, 20, tzinfo=UTC), "local_evaluation", 4, '{"posthog-node": 4}')
+ ]
+ results = query_feature_flag_request_usage(
+ team_id=123,
+ date_from=datetime(2026, 8, 20, tzinfo=UTC),
+ date_to=datetime(2026, 8, 21, tzinfo=UTC),
+ time_interval="day",
+ )
+ query, params = mock_sync_execute.call_args.args[:2]
+ assert "distinct_id = toString(%(team_id)s)" in query
+ assert params["team_id"] == 123
+ assert mock_sync_execute.call_args.kwargs["team_id"] == 123
+ assert mock_sync_execute.call_args.kwargs["settings"] == REQUEST_USAGE_QUERY_SETTINGS
+ assert mock_sync_execute.call_args.kwargs["ch_user"] == ClickHouseUser.APP
+ assert results[0].request_count == 4
+ assert results[0].billing_units == 40
+
+ def test_clickhouse_query_executes_against_usage_events(self) -> None:
+ organization = Organization.objects.create(name="Internal analytics")
+ analytics_team = Team.objects.create(id=2, organization=organization, name="Internal analytics")
+ _create_event(
+ team=analytics_team,
+ distinct_id="123",
+ event="decide usage",
+ timestamp=datetime(2026, 8, 20, 12, tzinfo=UTC),
+ properties={
+ "count": 7,
+ "sdk_breakdown": {"posthog-node": 7},
+ "token": "request-usage-test-token",
+ },
+ )
+ _create_event(
+ team=analytics_team,
+ distinct_id="123",
+ event="local evaluation usage",
+ timestamp=datetime(2026, 8, 20, 12, 35, tzinfo=UTC),
+ properties={
+ "count": 3,
+ "sdk_breakdown": {"posthog-python": 3},
+ "token": "request-usage-test-token",
+ },
+ )
+ _create_event(
+ team=analytics_team,
+ distinct_id="123",
+ event="decide usage",
+ timestamp=datetime(2026, 8, 20, 12, 50, tzinfo=UTC),
+ properties={"count": 5, "token": "request-usage-test-token"},
+ )
+ _create_event(
+ team=analytics_team,
+ distinct_id="123",
+ event="decide usage",
+ timestamp=datetime(2026, 8, 20, 12, 45, tzinfo=UTC),
+ properties={
+ "count": 100,
+ "sdk_breakdown": {"wrong-token-sdk": 100},
+ "token": "wrong-token",
+ },
+ )
+ flush_persons_and_events()
+ with self.settings(DECIDE_BILLING_ANALYTICS_TOKEN="request-usage-test-token"):
+ hourly_results = query_feature_flag_request_usage(
+ team_id=123,
+ date_from=datetime(2026, 8, 20, tzinfo=UTC),
+ date_to=datetime(2026, 8, 21, tzinfo=UTC),
+ time_interval="hour",
+ )
+ daily_results = query_feature_flag_request_usage(
+ team_id=123,
+ date_from=datetime(2026, 8, 20, tzinfo=UTC),
+ date_to=datetime(2026, 8, 21, tzinfo=UTC),
+ time_interval="day",
+ )
+
+ assert [(item.request_type.value, item.sdk, item.request_count) for item in hourly_results] == [
+ ("local_evaluation", "posthog-python", 3),
+ ("remote_evaluation", "other", 5),
+ ("remote_evaluation", "posthog-node", 7),
+ ]
+ assert {item.bucket for item in hourly_results} == {datetime(2026, 8, 20, 12, tzinfo=UTC)}
+ assert {item.bucket for item in daily_results} == {datetime(2026, 8, 20, tzinfo=UTC)}
diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.ts
index 1844e0e83ae0..a834dac744d4 100644
--- a/products/feature_flags/frontend/generated/api.schemas.ts
+++ b/products/feature_flags/frontend/generated/api.schemas.ts
@@ -396,6 +396,39 @@ export interface EvaluationContextSuggestionResponseApi {
hidden_from_suggestions: boolean
}
+/**
+ * * `remote_evaluation` - remote_evaluation
+ * * `local_evaluation` - local_evaluation
+ */
+export type FeatureFlagRequestTypeEnumApi =
+ (typeof FeatureFlagRequestTypeEnumApi)[keyof typeof FeatureFlagRequestTypeEnumApi]
+
+export const FeatureFlagRequestTypeEnumApi = {
+ RemoteEvaluation: 'remote_evaluation',
+ LocalEvaluation: 'local_evaluation',
+} as const
+
+export interface FeatureFlagRequestUsageItemApi {
+ /** Remote flag evaluation or local flag-definition request.
+ *
+ * * `remote_evaluation` - remote_evaluation
+ * * `local_evaluation` - local_evaluation */
+ request_type: FeatureFlagRequestTypeEnumApi
+ /** Start of the UTC billing-aggregation bucket. Hourly buckets approximate request time. */
+ bucket: string
+ /** SDK family parsed from the request user agent. */
+ sdk: string
+ /** Number of billable requests in this bucket. */
+ request_count: number
+ /** Estimated billing units. Local evaluation requests count as 10 units each. */
+ billing_units: number
+}
+
+export interface FeatureFlagRequestUsageResponseApi {
+ /** Feature flag request usage by SDK. */
+ results: FeatureFlagRequestUsageItemApi[]
+}
+
/**
* * `engineering` - Engineering
* * `data` - Data
@@ -1884,6 +1917,33 @@ export type EnvironmentsEvaluationContextSuggestionsDestroyParams = {
context_name: string
}
+export type FeatureFlagRequestUsageListParams = {
+ /**
+ * Inclusive start of the usage period.
+ */
+ date_from: string
+ /**
+ * Exclusive end of the usage period.
+ */
+ date_to: string
+ /**
+ * Time bucket used to group request usage. Hourly queries are limited to 8 days.
+ *
+ * * `hour` - hour
+ * * `day` - day
+ * @minLength 1
+ */
+ time_interval?: FeatureFlagRequestUsageListTimeInterval
+}
+
+export type FeatureFlagRequestUsageListTimeInterval =
+ (typeof FeatureFlagRequestUsageListTimeInterval)[keyof typeof FeatureFlagRequestUsageListTimeInterval]
+
+export const FeatureFlagRequestUsageListTimeInterval = {
+ Hour: 'hour',
+ Day: 'day',
+} as const
+
export type FeatureFlagsListParams = {
active?: FeatureFlagsListActive
/**
diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.ts
index da48d809f581..53266a77899d 100644
--- a/products/feature_flags/frontend/generated/api.ts
+++ b/products/feature_flags/frontend/generated/api.ts
@@ -26,6 +26,8 @@ import type {
EvaluationContextSuggestionResponseApi,
FeatureFlagApi,
FeatureFlagCreateRequestSchemaApi,
+ FeatureFlagRequestUsageListParams,
+ FeatureFlagRequestUsageResponseApi,
FeatureFlagStatusResponseApi,
FeatureFlagTestEvaluationRequestApi,
FeatureFlagTestEvaluationResponseApi,
@@ -567,6 +569,33 @@ export const environmentsEvaluationContextSuggestionsDestroy = async (
)
}
+export const getFeatureFlagRequestUsageListUrl = (projectId: string, params: FeatureFlagRequestUsageListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/feature_flag_request_usage/?${stringifiedParams}`
+ : `/api/projects/${projectId}/feature_flag_request_usage/`
+}
+
+export const featureFlagRequestUsageList = async (
+ projectId: string,
+ params: FeatureFlagRequestUsageListParams,
+ options?: RequestInit
+): Promise<FeatureFlagRequestUsageResponseApi> => {
+ return apiMutator<FeatureFlagRequestUsageResponseApi>(getFeatureFlagRequestUsageListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getFeatureFlagsListUrl = (projectId: string, params?: FeatureFlagsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/feature_flags/frontend/requestUsage/FeatureFlagRequestUsage.tsx b/products/feature_flags/frontend/requestUsage/FeatureFlagRequestUsage.tsx
new file mode 100644
index 000000000000..1cbf2273dd7c
--- /dev/null
+++ b/products/feature_flags/frontend/requestUsage/FeatureFlagRequestUsage.tsx
@@ -0,0 +1,267 @@
+import { useActions, useValues } from 'kea'
+
+import { IconDownload } from '@posthog/icons'
+import {
+ LemonBanner,
+ LemonButton,
+ LemonCard,
+ LemonInputSelect,
+ LemonLabel,
+ LemonSegmentedButton,
+ LemonTable,
+ type LemonTableColumns,
+ Link,
+ Spinner,
+} from '@posthog/lemon-ui'
+
+import { DateFilter } from 'lib/components/DateFilter/DateFilter'
+import { IntervalFilterStandalone } from 'lib/components/IntervalFilter'
+import { dateMapping } from 'lib/utils/dateFilters'
+import { BillingLineGraph } from 'scenes/billing/BillingLineGraph'
+
+import {
+ type FeatureFlagRequestTypeFilter,
+ type FeatureFlagRequestUsageInterval,
+ type FeatureFlagRequestUsageMetric,
+ type FeatureFlagRequestUsageSdkTotal,
+ featureFlagRequestUsageLogic,
+} from './featureFlagRequestUsageLogic'
+import { RequestUsageSummaryCard } from './RequestUsageSummaryCard'
+
+const DATE_OPTION_KEYS = new Set(['Today', 'Yesterday', 'Last 24 hours', 'Last 7 days', 'Last 14 days', 'Last 30 days'])
+const DATE_OPTIONS = dateMapping.filter(({ key }) => DATE_OPTION_KEYS.has(key))
+
+export function FeatureFlagRequestUsage(): JSX.Element {
+ const {
+ interval,
+ dateFrom,
+ dateTo,
+ isHourlyAvailable,
+ usageResponse,
+ usageResponseLoading,
+ loadError,
+ dates,
+ series,
+ sdkTotals,
+ sdkOptions,
+ selectedSDKs,
+ requestType,
+ metric,
+ totalRemoteRequests,
+ totalLocalRequests,
+ totalBillingUnits,
+ largestSdk,
+ } = useValues(featureFlagRequestUsageLogic)
+ const { setDates, setInterval, setSelectedSDKs, setRequestType, setMetric, downloadCsv } =
+ useActions(featureFlagRequestUsageLogic)
+
+ const columns: LemonTableColumns<FeatureFlagRequestUsageSdkTotal> = [
+ {
+ title: 'SDK',
+ dataIndex: 'sdk',
+ render: (value, row) => (
+ <LemonButton
+ type="tertiary"
+ size="small"
+ onClick={() => setSelectedSDKs([row.sdk])}
+ tooltip="Show only this SDK"
+ data-attr="feature-flag-request-usage-isolate-sdk"
+ >
+ {value}
+ </LemonButton>
+ ),
+ sorter: (a, b) => a.sdk.localeCompare(b.sdk),
+ },
+ {
+ title: 'Remote requests',
+ dataIndex: 'remoteRequests',
+ align: 'right',
+ render: (value) => (value ?? 0).toLocaleString(),
+ sorter: (a, b) => a.remoteRequests - b.remoteRequests,
+ },
+ {
+ title: 'Local requests',
+ dataIndex: 'localRequests',
+ align: 'right',
+ render: (value) => (value ?? 0).toLocaleString(),
+ sorter: (a, b) => a.localRequests - b.localRequests,
+ },
+ {
+ title: 'Billing units',
+ dataIndex: 'billingUnits',
+ align: 'right',
+ render: (value, { remoteRequests, localRequests }) => (
+ <span>
+ {(value ?? 0).toLocaleString()}{' '}
+ <span className="text-secondary whitespace-nowrap">
+ ({remoteRequests.toLocaleString()} + 10 × {localRequests.toLocaleString()})
+ </span>
+ </span>
+ ),
+ sorter: (a, b) => a.billingUnits - b.billingUnits,
+ },
+ {
+ title: 'Share',
+ dataIndex: 'billingUnitsShare',
+ align: 'right',
+ render: (value) => `${Number(value ?? 0).toFixed(1)}%`,
+ sorter: (a, b) => a.billingUnitsShare - b.billingUnitsShare,
+ },
+ ]
+
+ if (usageResponseLoading && !usageResponse) {
+ return <Spinner className="m-8" />
+ }
+
+ return (
+ <div className="flex flex-col gap-4">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <div>
+ <h2 className="mb-1">Request usage</h2>
+ <p className="text-secondary m-0">Billable feature flag requests grouped by the SDK user agent.</p>
+ </div>
+ <div className="flex items-center gap-2 flex-wrap">
+ <DateFilter
+ dateFrom={dateFrom}
+ dateTo={dateTo}
+ onChange={setDates}
+ dateOptions={DATE_OPTIONS}
+ max={30}
+ allowedRollingDateOptions={['days']}
+ allowFixedRangeWithTime
+ allowTimePrecision
+ />
+ <span className="text-secondary">grouped by</span>
+ <IntervalFilterStandalone
+ interval={interval}
+ onIntervalChange={(value) => setInterval(value as FeatureFlagRequestUsageInterval)}
+ options={[
+ {
+ label: 'Hour',
+ value: 'hour',
+ disabledReason: isHourlyAvailable
+ ? undefined
+ : 'Hourly grouping is available for Last 7 days or shorter ranges.',
+ },
+ { label: 'Day', value: 'day' },
+ ]}
+ />
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconDownload />}
+ onClick={downloadCsv}
+ disabledReason={sdkTotals.length === 0 ? 'No usage data to export' : undefined}
+ data-attr="feature-flag-request-usage-download-csv"
+ >
+ Download CSV
+ </LemonButton>
+ </div>
+ </div>
+
+ {loadError && (
+ <LemonBanner type="error">
+ Couldn't load feature flag request usage. Adjust the date range or grouping and try again. Contact
+ support if it keeps failing.
+ </LemonBanner>
+ )}
+
+ <LemonBanner type="info">
+ This view shows billable requests, not every HTTP request. Remote requests include <code>/flags</code>{' '}
+ and legacy <code>/decide</code> traffic. Local evaluation requests use 10 billing units each. Data can
+ take about 30 minutes to appear, and hourly buckets reflect billing aggregation time rather than exact
+ request time.{' '}
+ <Link to="https://posthog.com/docs/feature-flags/common-questions#billing--usage">
+ Learn how usage is calculated
+ </Link>
+ .
+ </LemonBanner>
+
+ <div className="flex items-end gap-3 flex-wrap border rounded p-3 bg-surface-primary">
+ <div className="flex flex-col gap-1">
+ <LemonLabel>SDKs</LemonLabel>
+ <LemonInputSelect
+ mode="multiple"
+ displayMode="count"
+ bulkActions="select-and-clear-all"
+ className="w-60"
+ value={selectedSDKs}
+ onChange={setSelectedSDKs}
+ placeholder="All SDKs"
+ options={sdkOptions}
+ allowCustomValues={false}
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <LemonLabel>Request type</LemonLabel>
+ <LemonSegmentedButton<FeatureFlagRequestTypeFilter>
+ size="small"
+ value={requestType}
+ onChange={setRequestType}
+ options={[
+ { value: 'all', label: 'All' },
+ { value: 'remote_evaluation', label: 'Remote' },
+ { value: 'local_evaluation', label: 'Local' },
+ ]}
+ />
+ </div>
+ </div>
+
+ {!loadError && (
+ <>
+ <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
+ <RequestUsageSummaryCard label="Remote requests" value={totalRemoteRequests} />
+ <RequestUsageSummaryCard label="Local requests" value={totalLocalRequests} />
+ <RequestUsageSummaryCard label="Billing units" value={totalBillingUnits} />
+ <RequestUsageSummaryCard
+ label="Largest SDK contributor"
+ value={largestSdk?.sdk ?? '—'}
+ footer={
+ largestSdk ? `${largestSdk.billingUnitsShare.toFixed(1)}% of billing units` : undefined
+ }
+ />
+ </div>
+
+ {sdkTotals.length === 0 ? (
+ <LemonBanner type="info">
+ No SDK-level request usage matches these filters. Try a wider date range or clear a filter.
+ </LemonBanner>
+ ) : (
+ <>
+ <LemonCard className="p-4">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <h3 className="m-0">
+ {metric === 'requests' ? 'Requests' : 'Billing units'} over time
+ </h3>
+ <LemonSegmentedButton<FeatureFlagRequestUsageMetric>
+ size="small"
+ value={metric}
+ onChange={setMetric}
+ options={[
+ { value: 'requests', label: 'Requests' },
+ { value: 'billing_units', label: 'Billing units' },
+ ]}
+ />
+ </div>
+ <BillingLineGraph
+ series={series}
+ dates={dates}
+ isLoading={usageResponseLoading}
+ hiddenSeries={[]}
+ interval={interval}
+ />
+ </LemonCard>
+ <LemonTable
+ columns={columns}
+ dataSource={sdkTotals}
+ rowKey="sdk"
+ loading={usageResponseLoading}
+ defaultSorting={{ columnKey: 'billingUnits', order: -1 }}
+ />
+ </>
+ )}
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/products/feature_flags/frontend/requestUsage/RequestUsageSummaryCard.stories.tsx b/products/feature_flags/frontend/requestUsage/RequestUsageSummaryCard.stories.tsx
new file mode 100644
index 000000000000..0f7359497cf4
--- /dev/null
+++ b/products/feature_flags/frontend/requestUsage/RequestUsageSummaryCard.stories.tsx
@@ -0,0 +1,16 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { RequestUsageSummaryCard } from './RequestUsageSummaryCard'
+
+const meta: Meta<typeof RequestUsageSummaryCard> = {
+ title: 'Scenes-App/Feature Flags/Request Usage Summary Card',
+ component: RequestUsageSummaryCard,
+ parameters: { layout: 'padded' },
+}
+export default meta
+
+type Story = StoryObj<typeof RequestUsageSummaryCard>
+
+export const BillingUnits: Story = {
+ args: { label: 'Billing units', value: 123456 },
+}
diff --git a/products/feature_flags/frontend/requestUsage/RequestUsageSummaryCard.tsx b/products/feature_flags/frontend/requestUsage/RequestUsageSummaryCard.tsx
new file mode 100644
index 000000000000..8d2b0fb31d02
--- /dev/null
+++ b/products/feature_flags/frontend/requestUsage/RequestUsageSummaryCard.tsx
@@ -0,0 +1,21 @@
+import type { ReactNode } from 'react'
+
+import { LemonCard } from '@posthog/lemon-ui'
+
+export interface RequestUsageSummaryCardProps {
+ label: string
+ value: number | string
+ footer?: ReactNode
+}
+
+export function RequestUsageSummaryCard({ label, value, footer }: RequestUsageSummaryCardProps): JSX.Element {
+ return (
+ <LemonCard className="p-4">
+ <div className="text-secondary">{label}</div>
+ <div className="text-2xl font-semibold tabular-nums truncate">
+ {typeof value === 'number' ? value.toLocaleString() : value}
+ </div>
+ {footer && <div className="text-secondary tabular-nums">{footer}</div>}
+ </LemonCard>
+ )
+}
diff --git a/products/feature_flags/frontend/requestUsage/featureFlagRequestUsageLogic.test.ts b/products/feature_flags/frontend/requestUsage/featureFlagRequestUsageLogic.test.ts
new file mode 100644
index 000000000000..4a36665b86f4
--- /dev/null
+++ b/products/feature_flags/frontend/requestUsage/featureFlagRequestUsageLogic.test.ts
@@ -0,0 +1,239 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import * as api from '../generated/api'
+import { csvCell, featureFlagRequestUsageLogic } from './featureFlagRequestUsageLogic'
+
+describe('featureFlagRequestUsageLogic', () => {
+ let logic: ReturnType<typeof featureFlagRequestUsageLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/997/feature_flag_request_usage/': {
+ results: [],
+ },
+ },
+ })
+ initKeaTests()
+ logic = featureFlagRequestUsageLogic()
+ logic.mount()
+ })
+
+ afterEach(() => logic.unmount())
+
+ it('builds chart series and SDK totals from remote and local usage', async () => {
+ logic.actions.setDates('2026-08-20', '2026-08-20')
+ logic.actions.loadUsageResponseSuccess({
+ results: [
+ {
+ bucket: '2026-08-20T00:00:00Z',
+ request_type: 'remote_evaluation',
+ sdk: 'posthog-ruby',
+ request_count: 20,
+ billing_units: 20,
+ },
+ {
+ bucket: '2026-08-20T00:00:00Z',
+ request_type: 'local_evaluation',
+ sdk: 'posthog-ruby',
+ request_count: 3,
+ billing_units: 30,
+ },
+ ],
+ })
+
+ await expectLogic(logic).toMatchValues({
+ totalBillingUnits: 50,
+ sdkTotals: [
+ {
+ sdk: 'posthog-ruby',
+ remoteRequests: 20,
+ localRequests: 3,
+ billingUnits: 50,
+ billingUnitsShare: 100,
+ },
+ ],
+ series: [
+ {
+ id: expect.any(Number),
+ label: 'posthog-ruby (remote)',
+ dates: ['2026-08-20T00:00:00.000Z'],
+ data: [20],
+ },
+ {
+ id: expect.any(Number),
+ label: 'posthog-ruby (local)',
+ dates: ['2026-08-20T00:00:00.000Z'],
+ data: [3],
+ },
+ ],
+ })
+ })
+
+ it('applies SDK and request filters to metrics and shares', async () => {
+ logic.actions.setDates('2026-08-20', '2026-08-20')
+ logic.actions.loadUsageResponseSuccess({
+ results: [
+ {
+ bucket: '2026-08-20T00:00:00Z',
+ request_type: 'local_evaluation',
+ sdk: 'posthog-node',
+ request_count: 10,
+ billing_units: 100,
+ },
+ {
+ bucket: '2026-08-20T00:00:00Z',
+ request_type: 'remote_evaluation',
+ sdk: 'posthog-python',
+ request_count: 100,
+ billing_units: 100,
+ },
+ ],
+ })
+ logic.actions.setSelectedSDKs(['posthog-node'])
+ logic.actions.setRequestType('local_evaluation')
+ logic.actions.setMetric('billing_units')
+
+ await expectLogic(logic).toMatchValues({
+ totalBillingUnits: 100,
+ largestSdk: expect.objectContaining({ sdk: 'posthog-node', billingUnitsShare: 100 }),
+ series: [
+ {
+ id: expect.any(Number),
+ label: 'posthog-node (local)',
+ dates: ['2026-08-20T00:00:00.000Z'],
+ data: [100],
+ },
+ ],
+ })
+ })
+
+ it('falls back to daily grouping when the selected range exceeds seven days', async () => {
+ logic.actions.setDates('-24h', null)
+ logic.actions.setInterval('hour')
+ await expectLogic(logic).toMatchValues({ interval: 'hour', isHourlyAvailable: true })
+
+ logic.actions.setDates('-30d', null)
+
+ await expectLogic(logic).toMatchValues({ interval: 'day', isHourlyAvailable: false })
+ })
+
+ it('allows hourly grouping for the Last 7 days preset', async () => {
+ logic.actions.setDates('-7d', null)
+
+ await expectLogic(logic).toMatchValues({ isHourlyAvailable: true })
+ })
+
+ it('fills empty hourly buckets with zero', async () => {
+ logic.actions.setDates('2026-08-20T00:00:00Z', '2026-08-20T02:59:59Z')
+ logic.actions.setInterval('hour')
+ logic.actions.loadUsageResponseSuccess({
+ results: [
+ {
+ bucket: '2026-08-20T01:00:00Z',
+ request_type: 'remote_evaluation',
+ sdk: 'posthog-node',
+ request_count: 20,
+ billing_units: 20,
+ },
+ ],
+ })
+
+ await expectLogic(logic).toMatchValues({
+ dates: ['2026-08-20T00:00:00.000Z', '2026-08-20T01:00:00.000Z', '2026-08-20T02:00:00.000Z'],
+ series: [
+ {
+ id: expect.any(Number),
+ label: 'posthog-node (remote)',
+ dates: ['2026-08-20T00:00:00.000Z', '2026-08-20T01:00:00.000Z', '2026-08-20T02:00:00.000Z'],
+ data: [0, 20, 0],
+ },
+ ],
+ })
+ })
+
+ it('keeps the latest response when requests resolve out of order', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+ let resolveStale: (value: Awaited<ReturnType<typeof api.featureFlagRequestUsageList>>) => void = () => {}
+ let resolveFresh: (value: Awaited<ReturnType<typeof api.featureFlagRequestUsageList>>) => void = () => {}
+ jest.spyOn(api, 'featureFlagRequestUsageList')
+ .mockImplementationOnce(() => new Promise((resolve) => (resolveStale = resolve)))
+ .mockImplementationOnce(() => new Promise((resolve) => (resolveFresh = resolve)))
+
+ logic.actions.loadUsageResponse()
+ logic.actions.loadUsageResponse()
+ resolveFresh({
+ results: [
+ {
+ bucket: '2026-08-20T00:00:00Z',
+ request_type: 'remote_evaluation',
+ sdk: 'fresh-sdk',
+ request_count: 2,
+ billing_units: 2,
+ },
+ ],
+ })
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ expect(logic.values.usageResponse?.results[0].sdk).toBe('fresh-sdk')
+
+ resolveStale({
+ results: [
+ {
+ bucket: '2026-08-19T00:00:00Z',
+ request_type: 'remote_evaluation',
+ sdk: 'stale-sdk',
+ request_count: 1,
+ billing_units: 1,
+ },
+ ],
+ })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.usageResponse?.results[0].sdk).toBe('fresh-sdk')
+ })
+
+ it('keeps series IDs stable when filtering changes the visible series', async () => {
+ logic.actions.setDates('2026-08-20', '2026-08-20')
+ logic.actions.loadUsageResponseSuccess({
+ results: [
+ {
+ bucket: '2026-08-20T00:00:00Z',
+ request_type: 'remote_evaluation',
+ sdk: 'posthog-node',
+ request_count: 20,
+ billing_units: 20,
+ },
+ {
+ bucket: '2026-08-20T00:00:00Z',
+ request_type: 'remote_evaluation',
+ sdk: 'posthog-python',
+ request_count: 10,
+ billing_units: 10,
+ },
+ ],
+ })
+ expect(new Set(logic.values.series.map(({ id }) => id)).size).toBe(2)
+ const pythonSeriesId = logic.values.series.find(({ label }) => label.startsWith('posthog-python'))?.id
+
+ logic.actions.setSelectedSDKs(['posthog-python'])
+
+ expect(logic.values.series).toHaveLength(1)
+ expect(logic.values.series[0].id).toBe(pythonSeriesId)
+ })
+
+ it('clears a load error when a new date range triggers a request', async () => {
+ logic.actions.loadUsageResponseFailure('nope')
+ expect(logic.values.loadError).toBe(true)
+
+ logic.actions.setDates('-7d', null)
+
+ await expectLogic(logic).toMatchValues({ loadError: false })
+ })
+
+ it.each(['=', '+', '-', '@', '\t', '\r'])('neutralizes a leading %p in CSV cells', (prefix) => {
+ expect(csvCell(`${prefix}cmd(1)`)).toBe(`"'${prefix}cmd(1)"`)
+ })
+})
diff --git a/products/feature_flags/frontend/requestUsage/featureFlagRequestUsageLogic.ts b/products/feature_flags/frontend/requestUsage/featureFlagRequestUsageLogic.ts
new file mode 100644
index 000000000000..03bc5466b6d0
--- /dev/null
+++ b/products/feature_flags/frontend/requestUsage/featureFlagRequestUsageLogic.ts
@@ -0,0 +1,370 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { downloadBlob } from 'lib/components/ExportButton/exporter'
+import { dayjs } from 'lib/dayjs'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
+import { projectLogic } from 'scenes/projectLogic'
+
+import * as api from '../generated/api'
+import type { FeatureFlagRequestUsageItemApi, FeatureFlagRequestUsageResponseApi } from '../generated/api.schemas'
+
+export type FeatureFlagRequestUsageInterval = 'hour' | 'day'
+export type FeatureFlagRequestUsageMetric = 'requests' | 'billing_units'
+export type FeatureFlagRequestTypeFilter = 'all' | 'remote_evaluation' | 'local_evaluation'
+
+// DateFilter's "Last 7 days" starts at midnight seven days ago and can therefore
+// span almost eight elapsed days. Keep this aligned with the backend validator.
+export const MAX_HOURLY_RANGE_DAYS = 8
+
+export interface FeatureFlagRequestUsageSeries {
+ id: number
+ label: string
+ data: number[]
+ dates: string[]
+}
+
+export interface FeatureFlagRequestUsageSdkTotal {
+ sdk: string
+ remoteRequests: number
+ localRequests: number
+ billingUnits: number
+ billingUnitsShare: number
+}
+
+interface ResolvedDateRange {
+ dateFrom: dayjs.Dayjs
+ dateTo: dayjs.Dayjs
+}
+
+function resolveDateRange(dateFrom: string, dateTo: string | null): ResolvedDateRange {
+ const parsedDateTo = dateTo ? (dateStringToDayJs(dateTo) ?? dayjs(dateTo)) : null
+ // A date-only value such as "2026-08-20" represents that entire calendar day.
+ const inclusiveDateTo = parsedDateTo && !dateTo?.includes('T') ? parsedDateTo.endOf('day') : parsedDateTo
+ return {
+ dateFrom: dateStringToDayJs(dateFrom) ?? dayjs().subtract(30, 'day'),
+ // The API treats date_to as exclusive, so step past the inclusive picker value.
+ dateTo: inclusiveDateTo ? inclusiveDateTo.add(1, 'millisecond') : dayjs(),
+ }
+}
+
+function seriesLabel(item: FeatureFlagRequestUsageItemApi): string {
+ const evaluationLabel = item.request_type === 'remote_evaluation' ? 'remote' : 'local'
+ return `${item.sdk} (${evaluationLabel})`
+}
+
+function buildDates(dateFrom: string, dateTo: string | null, interval: FeatureFlagRequestUsageInterval): string[] {
+ const range = resolveDateRange(dateFrom, dateTo)
+ const dates: string[] = []
+ let bucket = range.dateFrom.utc().startOf(interval)
+
+ while (bucket.isBefore(range.dateTo)) {
+ dates.push(bucket.toISOString())
+ bucket = bucket.add(1, interval)
+ }
+ return dates
+}
+
+function filterItems(
+ response: FeatureFlagRequestUsageResponseApi | null,
+ selectedSDKs: string[],
+ requestType: FeatureFlagRequestTypeFilter
+): FeatureFlagRequestUsageItemApi[] {
+ return (response?.results ?? []).filter(
+ (item) =>
+ (selectedSDKs.length === 0 || selectedSDKs.includes(item.sdk)) &&
+ (requestType === 'all' || item.request_type === requestType)
+ )
+}
+
+export function csvCell(value: string | number): string {
+ const stringValue = String(value)
+ const formulaSafeValue = /^[=+\-@\t\r]/.test(stringValue) ? `'${stringValue}` : stringValue
+ return `"${formulaSafeValue.replaceAll('"', '""')}"`
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface featureFlagRequestUsageLogicValues {
+ currentProjectId: number | null // projectLogic
+ dateFrom: string
+ dateTo: string | null
+ dates: string[]
+ filteredItems: FeatureFlagRequestUsageItemApi[]
+ interval: FeatureFlagRequestUsageInterval
+ isHourlyAvailable: boolean
+ largestSdk: FeatureFlagRequestUsageSdkTotal | null
+ loadError: boolean
+ metric: FeatureFlagRequestUsageMetric
+ requestType: FeatureFlagRequestTypeFilter
+ sdkOptions: {
+ key: string
+ label: string
+ }[]
+ sdkTotals: FeatureFlagRequestUsageSdkTotal[]
+ selectedSDKs: string[]
+ series: FeatureFlagRequestUsageSeries[]
+ totalBillingUnits: number
+ totalLocalRequests: number
+ totalRemoteRequests: number
+ usageResponse: FeatureFlagRequestUsageResponseApi | null
+ usageResponseLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface featureFlagRequestUsageLogicActions {
+ downloadCsv: () => {
+ value: true
+ }
+ loadUsageResponse: (_: void) => void
+ loadUsageResponseFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadUsageResponseSuccess: (
+ usageResponse: FeatureFlagRequestUsageResponseApi,
+ payload?: void
+ ) => {
+ usageResponse: FeatureFlagRequestUsageResponseApi
+ payload?: void
+ }
+ setDates: (
+ dateFrom: string | null,
+ dateTo: string | null
+ ) => {
+ dateFrom: string | null
+ dateTo: string | null
+ }
+ setInterval: (interval: FeatureFlagRequestUsageInterval) => {
+ interval: FeatureFlagRequestUsageInterval
+ }
+ setMetric: (metric: FeatureFlagRequestUsageMetric) => {
+ metric: FeatureFlagRequestUsageMetric
+ }
+ setRequestType: (requestType: FeatureFlagRequestTypeFilter) => {
+ requestType: FeatureFlagRequestTypeFilter
+ }
+ setSelectedSDKs: (selectedSDKs: string[]) => {
+ selectedSDKs: string[]
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface featureFlagRequestUsageLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ isHourlyAvailable: (dateFrom: string, dateTo: string | null) => boolean
+ sdkOptions: (usageResponse: FeatureFlagRequestUsageResponseApi | null) => {
+ key: string
+ label: string
+ }[]
+ filteredItems: (
+ usageResponse: FeatureFlagRequestUsageResponseApi | null,
+ selectedSDKs: string[],
+ requestType: FeatureFlagRequestTypeFilter
+ ) => FeatureFlagRequestUsageItemApi[]
+ dates: (dateFrom: string, dateTo: string | null, interval: FeatureFlagRequestUsageInterval) => string[]
+ series: (
+ filteredItems: FeatureFlagRequestUsageItemApi[],
+ usageResponse: FeatureFlagRequestUsageResponseApi | null,
+ dates: string[],
+ metric: FeatureFlagRequestUsageMetric,
+ interval: FeatureFlagRequestUsageInterval
+ ) => FeatureFlagRequestUsageSeries[]
+ sdkTotals: (filteredItems: FeatureFlagRequestUsageItemApi[]) => FeatureFlagRequestUsageSdkTotal[]
+ totalRemoteRequests: (filteredItems: FeatureFlagRequestUsageItemApi[]) => number
+ totalLocalRequests: (filteredItems: FeatureFlagRequestUsageItemApi[]) => number
+ totalBillingUnits: (filteredItems: FeatureFlagRequestUsageItemApi[]) => number
+ largestSdk: (sdkTotals: FeatureFlagRequestUsageSdkTotal[]) => FeatureFlagRequestUsageSdkTotal | null
+ }
+}
+
+export type featureFlagRequestUsageLogicType = MakeLogicType<
+ featureFlagRequestUsageLogicValues,
+ featureFlagRequestUsageLogicActions,
+ Record<string, any>,
+ featureFlagRequestUsageLogicMeta
+>
+
+export const featureFlagRequestUsageLogic = kea<featureFlagRequestUsageLogicType>([
+ path(['products', 'featureFlags', 'requestUsage', 'featureFlagRequestUsageLogic']),
+ connect(() => ({ values: [projectLogic, ['currentProjectId']] })),
+ actions({
+ setInterval: (interval: FeatureFlagRequestUsageInterval) => ({ interval }),
+ setDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
+ setMetric: (metric: FeatureFlagRequestUsageMetric) => ({ metric }),
+ setRequestType: (requestType: FeatureFlagRequestTypeFilter) => ({ requestType }),
+ setSelectedSDKs: (selectedSDKs: string[]) => ({ selectedSDKs }),
+ downloadCsv: true,
+ }),
+ loaders(({ values }) => ({
+ usageResponse: [
+ null as FeatureFlagRequestUsageResponseApi | null,
+ {
+ loadUsageResponse: async (_: void, breakpoint) => {
+ if (!values.currentProjectId) {
+ throw new Error('No project selected')
+ }
+ const range = resolveDateRange(values.dateFrom, values.dateTo)
+ const params = {
+ date_from: range.dateFrom.toISOString(),
+ date_to: range.dateTo.toISOString(),
+ time_interval: values.interval,
+ }
+ const response = await api.featureFlagRequestUsageList(String(values.currentProjectId), params)
+ breakpoint()
+ return response
+ },
+ },
+ ],
+ })),
+ reducers({
+ interval: ['day' as FeatureFlagRequestUsageInterval, { setInterval: (_, { interval }) => interval }],
+ dateFrom: ['-30d', { setDates: (_, { dateFrom }) => dateFrom ?? '-30d' }],
+ dateTo: [null as string | null, { setDates: (_, { dateTo }) => dateTo }],
+ metric: ['requests' as FeatureFlagRequestUsageMetric, { setMetric: (_, { metric }) => metric }],
+ requestType: ['all' as FeatureFlagRequestTypeFilter, { setRequestType: (_, { requestType }) => requestType }],
+ selectedSDKs: [[] as string[], { setSelectedSDKs: (_, { selectedSDKs }) => selectedSDKs }],
+ loadError: [
+ false,
+ {
+ loadUsageResponse: () => false,
+ loadUsageResponseSuccess: () => false,
+ loadUsageResponseFailure: () => true,
+ },
+ ],
+ }),
+ selectors({
+ isHourlyAvailable: [
+ (s) => [s.dateFrom, s.dateTo],
+ (dateFrom: string, dateTo: string | null): boolean => {
+ const range = resolveDateRange(dateFrom, dateTo)
+ return range.dateTo.diff(range.dateFrom, 'day', true) <= MAX_HOURLY_RANGE_DAYS
+ },
+ ],
+ sdkOptions: [
+ (s) => [s.usageResponse],
+ (response: FeatureFlagRequestUsageResponseApi | null): { key: string; label: string }[] =>
+ Array.from(new Set(response?.results.map(({ sdk }) => sdk) ?? []))
+ .sort()
+ .map((sdk) => ({ key: sdk, label: sdk })),
+ ],
+ filteredItems: [
+ (s) => [s.usageResponse, s.selectedSDKs, s.requestType],
+ (
+ response: FeatureFlagRequestUsageResponseApi | null,
+ selectedSDKs: string[],
+ requestType: FeatureFlagRequestTypeFilter
+ ): FeatureFlagRequestUsageItemApi[] => filterItems(response, selectedSDKs, requestType),
+ ],
+ dates: [
+ (s) => [s.dateFrom, s.dateTo, s.interval],
+ (dateFrom: string, dateTo: string | null, interval: FeatureFlagRequestUsageInterval): string[] =>
+ buildDates(dateFrom, dateTo, interval),
+ ],
+ series: [
+ (s) => [s.filteredItems, s.usageResponse, s.dates, s.metric, s.interval],
+ (
+ items: FeatureFlagRequestUsageItemApi[],
+ response: FeatureFlagRequestUsageResponseApi | null,
+ dates: string[],
+ metric: FeatureFlagRequestUsageMetric,
+ interval: FeatureFlagRequestUsageInterval
+ ): FeatureFlagRequestUsageSeries[] => {
+ const allLabels = Array.from(new Set(response?.results.map(seriesLabel) ?? [])).sort()
+ const seriesByLabel = new Map<string, Map<string, number>>()
+ for (const item of items) {
+ const label = seriesLabel(item)
+ const values = seriesByLabel.get(label) ?? new Map<string, number>()
+ const value = metric === 'requests' ? item.request_count : item.billing_units
+ const bucket = dayjs(item.bucket).utc().startOf(interval).toISOString()
+ values.set(bucket, (values.get(bucket) ?? 0) + value)
+ seriesByLabel.set(label, values)
+ }
+ return Array.from(seriesByLabel.entries()).map(([label, values]) => ({
+ id: allLabels.indexOf(label),
+ label,
+ dates,
+ data: dates.map((date) => values.get(date) ?? 0),
+ }))
+ },
+ ],
+ sdkTotals: [
+ (s) => [s.filteredItems],
+ (items: FeatureFlagRequestUsageItemApi[]): FeatureFlagRequestUsageSdkTotal[] => {
+ const totals = new Map<string, FeatureFlagRequestUsageSdkTotal>()
+ for (const item of items) {
+ const current = totals.get(item.sdk) ?? {
+ sdk: item.sdk,
+ remoteRequests: 0,
+ localRequests: 0,
+ billingUnits: 0,
+ billingUnitsShare: 0,
+ }
+ if (item.request_type === 'remote_evaluation') {
+ current.remoteRequests += item.request_count
+ } else {
+ current.localRequests += item.request_count
+ }
+ current.billingUnits += item.billing_units
+ totals.set(item.sdk, current)
+ }
+ const totalBillingUnits = Array.from(totals.values()).reduce((sum, item) => sum + item.billingUnits, 0)
+ for (const item of totals.values()) {
+ item.billingUnitsShare = totalBillingUnits === 0 ? 0 : (item.billingUnits / totalBillingUnits) * 100
+ }
+ return Array.from(totals.values()).sort((a, b) => b.billingUnits - a.billingUnits)
+ },
+ ],
+ totalRemoteRequests: [
+ (s) => [s.filteredItems],
+ (items: FeatureFlagRequestUsageItemApi[]): number =>
+ items.reduce(
+ (total, item) => total + (item.request_type === 'remote_evaluation' ? item.request_count : 0),
+ 0
+ ),
+ ],
+ totalLocalRequests: [
+ (s) => [s.filteredItems],
+ (items: FeatureFlagRequestUsageItemApi[]): number =>
+ items.reduce(
+ (total, item) => total + (item.request_type === 'local_evaluation' ? item.request_count : 0),
+ 0
+ ),
+ ],
+ totalBillingUnits: [
+ (s) => [s.filteredItems],
+ (items: FeatureFlagRequestUsageItemApi[]): number =>
+ items.reduce((total, item) => total + item.billing_units, 0),
+ ],
+ largestSdk: [
+ (s) => [s.sdkTotals],
+ (sdkTotals: FeatureFlagRequestUsageSdkTotal[]): FeatureFlagRequestUsageSdkTotal | null =>
+ sdkTotals[0] ?? null,
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ setInterval: () => actions.loadUsageResponse(),
+ setDates: () => {
+ if (!values.isHourlyAvailable) {
+ actions.setInterval('day')
+ } else {
+ actions.loadUsageResponse()
+ }
+ },
+ downloadCsv: () => {
+ const header = ['bucket', 'sdk', 'request_type', 'request_count', 'billing_units']
+ const rows = values.filteredItems.map((item) => [
+ item.bucket,
+ item.sdk,
+ item.request_type,
+ item.request_count,
+ item.billing_units,
+ ])
+ const csv = [header, ...rows].map((row) => row.map(csvCell).join(',')).join('\n')
+ downloadBlob(new Blob([csv], { type: 'text/csv;charset=utf-8' }), `feature-flag-request-usage.csv`)
+ },
+ })),
+ afterMount(({ actions }) => actions.loadUsageResponse()),
+])
diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yaml
index f900bdb2382e..818e70f0208c 100644
--- a/products/feature_flags/mcp/tools.yaml
+++ b/products/feature_flags/mcp/tools.yaml
@@ -287,6 +287,9 @@ tools:
param_overrides:
id:
cast: string-int
+ feature-flag-request-usage-list:
+ operation: feature_flag_request_usage_list
+ enabled: false
feature-flag-unarchive:
operation: feature_flags_unarchive_create
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 88b548ede6b5..d8759786e422 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -40072,6 +40072,39 @@ export namespace Schemas {
bucketing_identifier?: BucketingIdentifierEnum | null;
}
+ /**
+ * * `remote_evaluation` - remote_evaluation
+ * * `local_evaluation` - local_evaluation
+ */
+ export type FeatureFlagRequestTypeEnum = typeof FeatureFlagRequestTypeEnum[keyof typeof FeatureFlagRequestTypeEnum];
+
+
+ export const FeatureFlagRequestTypeEnum = {
+ RemoteEvaluation: 'remote_evaluation',
+ LocalEvaluation: 'local_evaluation',
+ } as const;
+
+ export interface FeatureFlagRequestUsageItem {
+ /** Remote flag evaluation or local flag-definition request.
+ *
+ * * `remote_evaluation` - remote_evaluation
+ * * `local_evaluation` - local_evaluation */
+ request_type: FeatureFlagRequestTypeEnum;
+ /** Start of the UTC billing-aggregation bucket. Hourly buckets approximate request time. */
+ bucket: string;
+ /** SDK family parsed from the request user agent. */
+ sdk: string;
+ /** Number of billable requests in this bucket. */
+ request_count: number;
+ /** Estimated billing units. Local evaluation requests count as 10 units each. */
+ billing_units: number;
+ }
+
+ export interface FeatureFlagRequestUsageResponse {
+ /** Feature flag request usage by SDK. */
+ results: FeatureFlagRequestUsageItem[];
+ }
+
export interface FeatureFlagRolloutSummary {
/** True if the flag is effectively rolled out to everyone, independent of recent evaluation. For boolean flags this means at least one release condition targets 100% with no property filters (or there are no release conditions); for multivariate flags it means a single variant is served to 100% via a fully rolled out release condition. This is the signal for 'fully rolled out' / GA — unlike `status`, which only reflects recent evaluation. */
effectively_full_rollout: boolean;
@@ -96146,6 +96179,33 @@ export namespace Schemas {
source_type?: string;
};
+ export type FeatureFlagRequestUsageListParams = {
+ /**
+ * Inclusive start of the usage period.
+ */
+ date_from: string;
+ /**
+ * Exclusive end of the usage period.
+ */
+ date_to: string;
+ /**
+ * Time bucket used to group request usage. Hourly queries are limited to 8 days.
+ *
+ * * `hour` - hour
+ * * `day` - day
+ * @minLength 1
+ */
+ time_interval?: FeatureFlagRequestUsageListTimeInterval;
+ };
+
+ export type FeatureFlagRequestUsageListTimeInterval = typeof FeatureFlagRequestUsageListTimeInterval[keyof typeof FeatureFlagRequestUsageListTimeInterval];
+
+
+ export const FeatureFlagRequestUsageListTimeInterval = {
+ Hour: 'hour',
+ Day: 'day',
+ } as const;
+
export type FeatureFlagsListParams = {
active?: FeatureFlagsListActive;
/**