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(batch-exports): Track queue wait time in new histogram (#65236)

Tomás Farías Santanadd45360547d5
diff --git a/products/batch_exports/backend/temporal/metrics.py b/products/batch_exports/backend/temporal/metrics.py
index 9ce54873cb4d..3996ac72de79 100644
--- a/products/batch_exports/backend/temporal/metrics.py
+++ b/products/batch_exports/backend/temporal/metrics.py
@@ -20,6 +20,27 @@ from temporalio.worker import (
from posthog.temporal.common.logger import get_write_only_logger
+BATCH_EXPORT_ACTIVITY_TYPES = {
+ "copy_into_redshift_activity_from_stage",
+ "export_to_file_download_bucket_with_temporary_credentials",
+ "insert_into_bigquery_activity_from_stage",
+ "insert_into_databricks_activity_from_stage",
+ "insert_into_internal_stage_activity",
+ "insert_into_postgres_activity_from_stage",
+ "insert_into_redshift_activity",
+ "insert_into_redshift_activity_from_stage",
+ "insert_into_s3_activity_from_stage",
+ "insert_into_snowflake_activity_from_stage",
+}
+BATCH_EXPORT_WORKFLOW_TYPES = {
+ "s3-export",
+ "bigquery-export",
+ "snowflake-export",
+ "redshift-export",
+ "postgres-export",
+ "databricks-export",
+}
+
LOGGER = get_write_only_logger(__name__)
@@ -57,28 +78,41 @@ def get_export_finished_metric(status: str, model: str) -> MetricCounter:
)
-BATCH_EXPORT_ACTIVITY_TYPES = {
- "insert_into_internal_stage_activity",
- "insert_into_s3_activity_from_stage",
- "insert_into_snowflake_activity_from_stage",
- "insert_into_redshift_activity",
- "insert_into_redshift_activity_from_stage",
- "copy_into_redshift_activity_from_stage",
- "insert_into_postgres_activity_from_stage",
- "insert_into_databricks_activity_from_stage",
-}
-BATCH_EXPORT_WORKFLOW_TYPES = {
- "s3-export",
- "bigquery-export",
- "snowflake-export",
- "redshift-export",
- "postgres-export",
- "databricks-export",
-}
-
Attributes = dict[str, str | int | float | bool]
+def get_metric_meter(additional_attributes: Attributes | None = None) -> MetricMeter:
+ """Return a meter depending on in which context we are."""
+ basic_attributes: Attributes = {}
+
+ if activity.in_activity():
+ meter = activity.metric_meter()
+
+ activity_info = activity.info()
+ if (workflow_type := activity_info.workflow_type) is not None:
+ basic_attributes["workflow_type"] = workflow_type
+ basic_attributes["activity_type"] = activity_info.activity_type
+
+ elif workflow.in_workflow():
+ meter = workflow.metric_meter()
+ basic_attributes["workflow_type"] = workflow.info().workflow_type
+
+ else:
+ if settings.DEBUG or settings.TEST:
+ return MetricMeter.noop
+
+ raise RuntimeError("Not within workflow or activity context")
+
+ if additional_attributes:
+ attributes: Attributes = {**basic_attributes, **additional_attributes}
+ else:
+ attributes = basic_attributes
+
+ meter = meter.with_additional_attributes(attributes)
+
+ return meter
+
+
class BatchExportsMetricsInterceptor(Interceptor):
"""Interceptor to emit Prometheus metrics for batch exports."""
@@ -95,8 +129,7 @@ class BatchExportsMetricsInterceptor(Interceptor):
class _BatchExportsMetricsActivityInboundInterceptor(ActivityInboundInterceptor):
async def execute_activity(self, input: ExecuteActivityInput) -> typing.Any:
- activity_info = activity.info()
- activity_type = activity_info.activity_type
+ activity_type = activity.info().activity_type
if activity_type not in BATCH_EXPORT_ACTIVITY_TYPES:
return await super().execute_activity(input)
@@ -127,8 +160,6 @@ class _BatchExportsMetricsActivityInboundInterceptor(ActivityInboundInterceptor)
histogram_attributes: Attributes = {
"interval": interval,
}
- if activity_info.workflow_type is not None:
- histogram_attributes["workflow_type"] = activity_info.workflow_type
meter = get_metric_meter(histogram_attributes)
@@ -151,7 +182,7 @@ class _BatchExportsMetricsActivityInboundInterceptor(ActivityInboundInterceptor)
name="batch_exports_activity_success_attempts",
description="Counter tracking the attempts it took to complete activities",
)
- attempts_success_counter.add(activity_info.attempt)
+ attempts_success_counter.add(activity.info().attempt)
return result
@@ -284,21 +315,6 @@ class ExecutionTimeRecorder:
self.bytes_processed = None
-def get_metric_meter(additional_attributes: Attributes | None = None) -> MetricMeter:
- """Return a meter depending on in which context we are."""
- if activity.in_activity():
- meter = activity.metric_meter()
- elif workflow.in_workflow():
- meter = workflow.metric_meter()
- else:
- raise RuntimeError("Not within workflow or activity context")
-
- if additional_attributes:
- meter = meter.with_additional_attributes(additional_attributes)
-
- return meter
-
-
def log_execution_time(
log_message: str,
name: str,
diff --git a/products/batch_exports/backend/temporal/spmc.py b/products/batch_exports/backend/temporal/spmc.py
index b456fa63cf18..aef1028f884b 100644
--- a/products/batch_exports/backend/temporal/spmc.py
+++ b/products/batch_exports/backend/temporal/spmc.py
@@ -1,4 +1,5 @@
import math
+import time
import uuid
import typing
import asyncio
@@ -9,6 +10,7 @@ import collections.abc
from django.conf import settings
import pyarrow as pa
+from temporalio.common import MetricHistogram
from posthog.schema import EventPropertyFilter, HogQLPropertyFilter, HogQLQueryModifiers, MaterializationMode
@@ -27,6 +29,7 @@ from posthog.temporal.common.clickhouse import get_client
from posthog.temporal.common.logger import get_write_only_logger
from products.batch_exports.backend.service import BackfillDetails
+from products.batch_exports.backend.temporal.metrics import get_metric_meter
from products.batch_exports.backend.temporal.record_batch_model import RecordBatchModel
from products.batch_exports.backend.temporal.sql import (
SELECT_FROM_DISTRIBUTED_EVENTS_RECENT,
@@ -42,6 +45,13 @@ from products.batch_exports.backend.temporal.sql import (
LOGGER = get_write_only_logger(__name__)
+class QueuedRecordBatch(typing.NamedTuple):
+ """A record batch in queue, tracking the time it entered."""
+
+ record_batch: pa.RecordBatch
+ enqueued_at: int
+
+
class RecordBatchQueue(asyncio.Queue):
"""A queue of pyarrow RecordBatch instances limited by bytes."""
@@ -50,14 +60,28 @@ class RecordBatchQueue(asyncio.Queue):
self._bytes_size = 0
self._schema_set = asyncio.Event()
self.record_batch_schema: pa.Schema | None = None
+ self._histogram: MetricHistogram | None = None
# This is set by `asyncio.Queue.__init__` calling `_init`
- self._queue: collections.deque
+ self._queue: collections.deque[QueuedRecordBatch]
+
+ @property
+ def histogram(self) -> MetricHistogram:
+ if self._histogram is None:
+ meter = get_metric_meter()
+ self._histogram = meter.create_histogram(
+ "batch_exports_queue_wait_time", description="Time spent by record batches waiting in queue"
+ )
+ return self._histogram
def _get(self) -> pa.RecordBatch:
"""Override parent `_get` to keep track of bytes."""
- item = self._queue.popleft()
- self._bytes_size -= item.get_total_buffer_size()
- return item
+ record_batch, enqueued_at = self._queue.popleft()
+ self._bytes_size -= record_batch.get_total_buffer_size()
+
+ queued_time = time.perf_counter_ns() - enqueued_at
+ self.histogram.record(queued_time)
+
+ return record_batch
def _put(self, item: pa.RecordBatch) -> None:
"""Override parent `_put` to keep track of bytes."""
@@ -66,7 +90,7 @@ class RecordBatchQueue(asyncio.Queue):
if not self._schema_set.is_set():
self.set_schema(item)
- self._queue.append(item)
+ self._queue.append(QueuedRecordBatch(item, time.perf_counter_ns()))
def set_schema(self, record_batch: pa.RecordBatch) -> None:
"""Used to keep track of schema of events in queue."""
diff --git a/products/batch_exports/backend/tests/temporal/test_metrics.py b/products/batch_exports/backend/tests/temporal/test_metrics.py
index 5c8f32644d21..7d0b7c1bc866 100644
--- a/products/batch_exports/backend/tests/temporal/test_metrics.py
+++ b/products/batch_exports/backend/tests/temporal/test_metrics.py
@@ -111,9 +111,7 @@ async def test_interceptor_calls_histogram_metrics(
retry_policy=RetryPolicy(maximum_attempts=1),
)
- mocked_meter.assert_any_call(
- {"interval": "hour", "status": "COMPLETED", "exception": "", "workflow_type": "postgres-export"}
- )
+ mocked_meter.assert_any_call({"interval": "hour", "status": "COMPLETED", "exception": ""})
mocked_meter.return_value.create_histogram_timedelta.assert_any_call(
name="batch_exports_workflow_interval_execution_latency",
description="Histogram tracking execution latency for batch export workflows by interval",