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(metrics): counter-aware rate and increase aggregations (P5) (#63127)

Daniel Viscaae7a1bac292a
diff --git a/products/metrics/backend/facade/api.py b/products/metrics/backend/facade/api.py
index 1269bf8e27fc..2ee96b508304 100644
--- a/products/metrics/backend/facade/api.py
+++ b/products/metrics/backend/facade/api.py
@@ -21,6 +21,8 @@ _RUNNER_AGGREGATIONS: dict[MetricAggregation, str] = {
MetricAggregation.SUM: "sum",
MetricAggregation.AVG: "avg",
MetricAggregation.COUNT: "count",
+ MetricAggregation.RATE: "rate",
+ MetricAggregation.INCREASE: "increase",
}
diff --git a/products/metrics/backend/metric_query_runner.py b/products/metrics/backend/metric_query_runner.py
index 22dcfb089f8a..125b272b994e 100644
--- a/products/metrics/backend/metric_query_runner.py
+++ b/products/metrics/backend/metric_query_runner.py
@@ -89,7 +89,7 @@ def _aggregation_expr(name: str) -> ast.Expr:
raise ValueError(f"Unsupported aggregation: {name!r}")
-_ALLOWED_AGGREGATIONS: frozenset[str] = frozenset({"sum", "avg", "count", "p95"})
+_ALLOWED_AGGREGATIONS: frozenset[str] = frozenset({"sum", "avg", "count", "p95", "rate", "increase"})
# Target ~60 buckets across the requested range — feels right for a chart.
_TARGET_BUCKET_COUNT = 60
@@ -184,6 +184,40 @@ class MetricQueryRunner:
def run(self) -> list[dict[str, Any]]:
"""Bucketed rows: `{"time", "value", "labels"}`. `labels` carries one
entry per group_by key (always `{}` without group_by)."""
+ if self.aggregation in ("rate", "increase"):
+ query = self._build_counter_query()
+ else:
+ query = self._build_simple_query()
+
+ response = execute_hogql_query(
+ query_type="MetricQuery",
+ query=query,
+ team=self.team,
+ workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now
+ )
+
+ group_count = len(self.group_by)
+ rows: list[dict[str, Any]] = []
+ for row in response.results:
+ rows.append(
+ {
+ "time": row[0].isoformat() if isinstance(row[0], dt.datetime) else row[0],
+ "value": row[1 + group_count],
+ "labels": {group.key: row[1 + index] for index, group in enumerate(self.group_by)},
+ }
+ )
+ return rows
+
+ def _splice_group_columns(self, query: ast.SelectQuery) -> None:
+ """Insert the group_by label columns between `time` and `value` —
+ parse_select placeholders can't express a variable column count."""
+ assert query.group_by is not None
+ for index, group in enumerate(self.group_by):
+ label_expr = ast.Call(name="toString", args=[attribute_field(group.key, scope=group.scope.value)])
+ query.select.insert(1 + index, ast.Alias(alias=f"group_{index}", expr=label_expr))
+ query.group_by.append(ast.Field(chain=[f"group_{index}"]))
+
+ def _build_simple_query(self) -> ast.SelectQuery:
# `metrics` is only registered under the `posthog.` HogQL namespace
# (see posthog/hogql/database/database.py).
query = parse_select(
@@ -210,30 +244,76 @@ class MetricQueryRunner:
},
)
assert isinstance(query, ast.SelectQuery)
- assert query.group_by is not None
-
- # Splice the group_by label columns between `time` and `value` —
- # parse_select placeholders can't express a variable column count.
- for index, group in enumerate(self.group_by):
- label_expr = ast.Call(name="toString", args=[attribute_field(group.key, scope=group.scope.value)])
- query.select.insert(1 + index, ast.Alias(alias=f"group_{index}", expr=label_expr))
- query.group_by.append(ast.Field(chain=[f"group_{index}"]))
-
- response = execute_hogql_query(
- query_type="MetricQuery",
- query=query,
- team=self.team,
- workload=Workload.LOGS, # metrics share the logs ClickHouse workload pool for now
+ self._splice_group_columns(query)
+ return query
+
+ def _build_counter_query(self) -> ast.SelectQuery:
+ """rate/increase: per-underlying-series deltas, then aggregate.
+
+ Each physical series (service_name, resource_fingerprint, datapoint
+ attributes) gets its samples diffed in timestamp order via a window
+ function, Prometheus-style:
+
+ - cumulative temporality: contribution = value - prev, clamped for
+ counter resets (value < prev means the counter restarted, so the
+ post-reset absolute value IS the increase); the first sample of a
+ series contributes 0 (its history is unknown).
+ - delta temporality: each sample already is the increase, so it
+ contributes its own value.
+
+ `increase` sums contributions per bucket; `rate` divides by the
+ bucket length in seconds.
+ """
+ step_seconds = next(step.total_seconds() for name, step, _ in _INTERVAL_LADDER if name == self.interval)
+ divisor = step_seconds if self.aggregation == "rate" else 1.0
+ query = parse_select(
+ """
+ SELECT
+ toStartOfInterval(sample_timestamp, {interval}) AS time,
+ sum(contribution) / {divisor} AS value
+ FROM (
+ SELECT
+ timestamp AS sample_timestamp,
+ attributes AS attributes,
+ resource_attributes AS resource_attributes,
+ multiIf(
+ aggregation_temporality = 'delta', value,
+ isNull(prev_value), 0.0,
+ value >= assumeNotNull(prev_value), value - assumeNotNull(prev_value),
+ value
+ ) AS contribution
+ FROM (
+ SELECT
+ timestamp,
+ value,
+ aggregation_temporality,
+ attributes,
+ resource_attributes,
+ lagInFrame(toNullable(value)) OVER (
+ PARTITION BY service_name, resource_fingerprint, toString(attributes)
+ ORDER BY timestamp ASC
+ ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING
+ ) AS prev_value
+ FROM posthog.metrics
+ WHERE metric_name = {metric_name}
+ AND timestamp >= {date_from}
+ AND timestamp < {date_to}
+ AND {filters}
+ )
+ )
+ GROUP BY time
+ ORDER BY time ASC
+ LIMIT 10000
+ """,
+ placeholders={
+ "interval": _interval_expr(self.interval),
+ "divisor": ast.Constant(value=divisor),
+ "metric_name": ast.Constant(value=self.metric_name),
+ "date_from": ast.Constant(value=self.date_from),
+ "date_to": ast.Constant(value=self.date_to),
+ "filters": _filters_expr(self.filters),
+ },
)
-
- group_count = len(self.group_by)
- rows: list[dict[str, Any]] = []
- for row in response.results:
- rows.append(
- {
- "time": row[0].isoformat() if isinstance(row[0], dt.datetime) else row[0],
- "value": row[1 + group_count],
- "labels": {group.key: row[1 + index] for index, group in enumerate(self.group_by)},
- }
- )
- return rows
+ assert isinstance(query, ast.SelectQuery)
+ self._splice_group_columns(query)
+ return query
diff --git a/products/metrics/backend/presentation/api.py b/products/metrics/backend/presentation/api.py
index db5342f76e2b..8b03bbb3fec8 100644
--- a/products/metrics/backend/presentation/api.py
+++ b/products/metrics/backend/presentation/api.py
@@ -68,9 +68,9 @@ class _MetricQueryBodySerializer(serializers.Serializer):
help_text="Exact metric name to query (e.g. 'http.server.duration').",
)
aggregation = serializers.ChoiceField(
- choices=["sum", "avg", "count", "p95"],
+ choices=["sum", "avg", "count", "p95", "rate", "increase"],
default="sum",
- help_text="Aggregation applied per time bucket.",
+ help_text="Aggregation applied per time bucket. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is).",
)
filters = _MetricFilterSerializer(
many=True,
diff --git a/products/metrics/backend/tests/test_metric_query_runner.py b/products/metrics/backend/tests/test_metric_query_runner.py
index a3fd98a27ce1..82695c6c8b83 100644
--- a/products/metrics/backend/tests/test_metric_query_runner.py
+++ b/products/metrics/backend/tests/test_metric_query_runner.py
@@ -348,7 +348,7 @@ class TestRunMetricQueryFacade(ClickhouseTestMixin, APIBaseTest):
("formula", {"formula": "a / b"}),
(
"unsupported_aggregation",
- {"clauses": (MetricQueryClause(name="a", metric_name="m1", aggregation=MetricAggregation.RATE),)},
+ {"clauses": (MetricQueryClause(name="a", metric_name="m1", aggregation=MetricAggregation.MIN),)},
),
]
)
@@ -586,3 +586,168 @@ class TestGroupBy(ClickhouseTestMixin, APIBaseTest):
series = self._run()
self.assertEqual(len(series), 1)
self.assertEqual(series[0].labels["env"], "dev")
+
+
+class TestRateIncrease(ClickhouseTestMixin, APIBaseTest):
+ CLASS_DATA_LEVEL_SETUP = True
+
+ def setUp(self):
+ super().setUp()
+ sync_execute("TRUNCATE TABLE IF EXISTS metrics1")
+ # Anchor on a minute boundary so bucket membership is deterministic.
+ self.anchor = (timezone.now() - dt.timedelta(minutes=30)).replace(second=0, microsecond=0)
+
+ def _run(self, aggregation: str, **runner_overrides):
+ defaults: dict[str, Any] = {
+ "team": self.team,
+ "metric_name": "requests_total",
+ "aggregation": aggregation,
+ "date_from": self.anchor - dt.timedelta(minutes=1),
+ "date_to": self.anchor + dt.timedelta(minutes=2),
+ "interval": "minute",
+ }
+ defaults.update(runner_overrides)
+ return MetricQueryRunner(**defaults).run()
+
+ def _seed_counter(self, points, **kwargs):
+ seed_metric(
+ team_id=self.team.id,
+ metric_name="requests_total",
+ metric_type="sum",
+ is_monotonic=True,
+ points=points,
+ **kwargs,
+ )
+
+ def test_increase_diffs_cumulative_samples_and_ignores_first(self):
+ self._seed_counter(
+ [
+ (self.anchor + dt.timedelta(seconds=0), 100.0),
+ (self.anchor + dt.timedelta(seconds=15), 105.0),
+ (self.anchor + dt.timedelta(seconds=30), 110.0),
+ (self.anchor + dt.timedelta(seconds=45), 115.0),
+ (self.anchor + dt.timedelta(seconds=60), 120.0),
+ (self.anchor + dt.timedelta(seconds=75), 125.0),
+ ]
+ )
+ rows = self._run("increase")
+ by_time = {row["time"]: row["value"] for row in rows}
+ values = list(by_time.values())
+ # bucket 1: first sample contributes 0, then 5+5+5; bucket 2: 5+5
+ self.assertEqual(values, [15.0, 10.0])
+
+ def test_rate_divides_by_bucket_seconds(self):
+ self._seed_counter(
+ [
+ (self.anchor + dt.timedelta(seconds=0), 0.0),
+ (self.anchor + dt.timedelta(seconds=30), 30.0),
+ ]
+ )
+ rows = self._run("rate")
+ self.assertEqual([row["value"] for row in rows], [0.5])
+
+ def test_counter_reset_counts_post_reset_value(self):
+ self._seed_counter(
+ [
+ (self.anchor + dt.timedelta(seconds=0), 10.0),
+ (self.anchor + dt.timedelta(seconds=15), 20.0),
+ (self.anchor + dt.timedelta(seconds=30), 5.0),
+ (self.anchor + dt.timedelta(seconds=45), 15.0),
+ ]
+ )
+ rows = self._run("increase")
+ # 0 (first) + 10 + 5 (reset: post-reset absolute value) + 10
+ self.assertEqual([row["value"] for row in rows], [25.0])
+
+ def test_delta_temporality_sums_samples_directly(self):
+ self._seed_counter(
+ [
+ (self.anchor + dt.timedelta(seconds=0), 3.0),
+ (self.anchor + dt.timedelta(seconds=15), 4.0),
+ (self.anchor + dt.timedelta(seconds=30), 5.0),
+ ],
+ aggregation_temporality="delta",
+ )
+ rows = self._run("increase")
+ self.assertEqual([row["value"] for row in rows], [12.0])
+
+ def test_deltas_are_computed_per_underlying_series(self):
+ # Two pods with interleaved timestamps; naive global diffing would
+ # produce garbage from the cross-series jumps.
+ self._seed_counter(
+ [
+ (self.anchor + dt.timedelta(seconds=0), 1000.0),
+ (self.anchor + dt.timedelta(seconds=30), 1010.0),
+ ],
+ resource_labels={"k8s.pod.name": "web-1"},
+ )
+ self._seed_counter(
+ [
+ (self.anchor + dt.timedelta(seconds=15), 5.0),
+ (self.anchor + dt.timedelta(seconds=45), 10.0),
+ ],
+ resource_labels={"k8s.pod.name": "web-2"},
+ )
+ rows = self._run("increase")
+ self.assertEqual([row["value"] for row in rows], [15.0])
+
+ def test_rate_composes_with_group_by(self):
+ self._seed_counter(
+ [
+ (self.anchor + dt.timedelta(seconds=0), 0.0),
+ (self.anchor + dt.timedelta(seconds=30), 60.0),
+ ],
+ resource_labels={"k8s.pod.name": "web-1"},
+ )
+ self._seed_counter(
+ [
+ (self.anchor + dt.timedelta(seconds=0), 0.0),
+ (self.anchor + dt.timedelta(seconds=30), 6.0),
+ ],
+ resource_labels={"k8s.pod.name": "web-2"},
+ )
+ rows = self._run(
+ "increase",
+ group_by=(MetricGroupBy(key="k8s.pod.name", scope=AttributeScope.RESOURCE),),
+ )
+ by_pod = {row["labels"]["k8s.pod.name"]: row["value"] for row in rows}
+ self.assertEqual(by_pod, {"web-1": 60.0, "web-2": 6.0})
+
+ def test_rate_via_facade_and_api(self):
+ self._seed_counter(
+ [
+ (self.anchor + dt.timedelta(seconds=0), 0.0),
+ (self.anchor + dt.timedelta(seconds=30), 30.0),
+ ]
+ )
+ series = run_metric_query(
+ team=self.team,
+ request=MetricQueryRequest(
+ clauses=(
+ MetricQueryClause(name="a", metric_name="requests_total", aggregation=MetricAggregation.RATE),
+ ),
+ date_from=self.anchor - dt.timedelta(minutes=1),
+ date_to=self.anchor + dt.timedelta(minutes=2),
+ interval="minute",
+ ),
+ )
+ self.assertEqual([p.value for p in series[0].points], [0.5])
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/metrics/query",
+ data={
+ "query": {
+ "metricName": "requests_total",
+ "aggregation": "increase",
+ "interval": "minute",
+ "dateFrom": (self.anchor - dt.timedelta(minutes=1)).isoformat(),
+ "dateTo": (self.anchor + dt.timedelta(minutes=2)).isoformat(),
+ }
+ },
+ content_type="application/json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ [p["value"] for p in response.json()["results"][0]["points"]],
+ [30.0],
+ )
diff --git a/products/metrics/frontend/generated/api.schemas.ts b/products/metrics/frontend/generated/api.schemas.ts
index 43a30e9319b5..0e09c4b19bb5 100644
--- a/products/metrics/frontend/generated/api.schemas.ts
+++ b/products/metrics/frontend/generated/api.schemas.ts
@@ -28,6 +28,8 @@ export interface AppMetricsTotalsResponseApi {
* * `avg` - avg
* * `count` - count
* * `p95` - p95
+ * * `rate` - rate
+ * * `increase` - increase
*/
export type AggregationEnumApi = (typeof AggregationEnumApi)[keyof typeof AggregationEnumApi]
@@ -36,6 +38,8 @@ export const AggregationEnumApi = {
Avg: 'avg',
Count: 'count',
P95: 'p95',
+ Rate: 'rate',
+ Increase: 'increase',
} as const
/**
@@ -132,12 +136,14 @@ export interface _MetricQueryBodyApi {
* @maxLength 255
*/
metricName: string
- /** Aggregation applied per time bucket.
+ /** Aggregation applied per time bucket. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is).
*
* * `sum` - sum
* * `avg` - avg
* * `count` - count
- * * `p95` - p95 */
+ * * `p95` - p95
+ * * `rate` - rate
+ * * `increase` - increase */
aggregation?: AggregationEnumApi
/** Label predicates ANDed together. Rows must satisfy every filter. */
filters?: _MetricFilterApi[]
diff --git a/products/metrics/frontend/generated/api.zod.ts b/products/metrics/frontend/generated/api.zod.ts
index 5a020c5cae00..0dba4aa53b3b 100644
--- a/products/metrics/frontend/generated/api.zod.ts
+++ b/products/metrics/frontend/generated/api.zod.ts
@@ -28,11 +28,13 @@ export const MetricsQueryCreateBody = /* @__PURE__ */ zod.object({
.max(metricsQueryCreateBodyQueryOneMetricNameMax)
.describe("Exact metric name to query (e.g. 'http.server.duration')."),
aggregation: zod
- .enum(['sum', 'avg', 'count', 'p95'])
- .describe('\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95')
+ .enum(['sum', 'avg', 'count', 'p95', 'rate', 'increase'])
+ .describe(
+ '\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95\n\* `rate` - rate\n\* `increase` - increase'
+ )
.default(metricsQueryCreateBodyQueryOneAggregationDefault)
.describe(
- 'Aggregation applied per time bucket.\n\n\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95'
+ "Aggregation applied per time bucket. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is).\n\n\* `sum` - sum\n\* `avg` - avg\n\* `count` - count\n\* `p95` - p95\n\* `rate` - rate\n\* `increase` - increase"
),
filters: zod
.array(
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 31fbbef6d6f0..c7000dcb4a98 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -8151,6 +8151,8 @@ export namespace Schemas {
* * `avg` - avg
* * `count` - count
* * `p95` - p95
+ * * `rate` - rate
+ * * `increase` - increase
*/
export type AggregationEnum = typeof AggregationEnum[keyof typeof AggregationEnum];
@@ -8160,6 +8162,8 @@ export namespace Schemas {
Avg: 'avg',
Count: 'count',
P95: 'p95',
+ Rate: 'rate',
+ Increase: 'increase',
} as const;
export interface InsightsThresholdBounds {
@@ -45613,12 +45617,14 @@ export namespace Schemas {
* @maxLength 255
*/
metricName: string;
- /** Aggregation applied per time bucket.
+ /** Aggregation applied per time bucket. 'rate' (per-second) and 'increase' are counter-aware: per-series deltas with Prometheus counter-reset handling, temporality-aware (delta-temporality samples count as-is).
*
* * `sum` - sum
* * `avg` - avg
* * `count` - count
- * * `p95` - p95 */
+ * * `p95` - p95
+ * * `rate` - rate
+ * * `increase` - increase */
aggregation?: AggregationEnum;
/** Label predicates ANDed together. Rows must satisfy every filter. */
filters?: _MetricFilter[];