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-import-worker): expose active jobs metric for autoscaling (#67344)

José Sequeirac17173f7f0fb
diff --git a/rust/batch-import-worker/src/job/model.rs b/rust/batch-import-worker/src/job/model.rs
index d0b217203d1d..dbb4649302e9 100644
--- a/rust/batch-import-worker/src/job/model.rs
+++ b/rust/batch-import-worker/src/job/model.rs
@@ -177,6 +177,17 @@ impl JobModel {
}
}
+ /// Count jobs that still need a worker: everything in `running` status, whether
+ /// queued (unleased) or in-flight (leased). This is the autoscaling signal — one
+ /// worker processes one job, so the count maps directly to the desired replica count.
+ pub async fn count_active_jobs(pool: &PgPool) -> Result<i64, Error> {
+ let count: i64 =
+ sqlx::query_scalar("SELECT count(*) FROM posthog_batchimport WHERE status = 'running'")
+ .fetch_one(pool)
+ .await?;
+ Ok(count)
+ }
+
/// Schedule the job for a future retry by pushing leased_until forward and updating messages.
/// Keeps status as 'running' so the main loop can pick it up when the lease expires.
pub async fn schedule_backoff(
diff --git a/rust/batch-import-worker/src/main.rs b/rust/batch-import-worker/src/main.rs
index 258cf2423de5..a0679ab6bf14 100644
--- a/rust/batch-import-worker/src/main.rs
+++ b/rust/batch-import-worker/src/main.rs
@@ -87,6 +87,24 @@ pub async fn main() -> Result<(), Error> {
let context = Arc::new(AppContext::new(&config).await.unwrap());
+ // Periodically report the number of active jobs in the queue so the autoscaler
+ // can scale replicas to match pending + in-flight work. Every replica reports the
+ // same global count; the KEDA trigger collapses them with `max()`.
+ {
+ let context = context.clone();
+ tokio::spawn(async move {
+ let start = tokio::time::Instant::now() + Duration::from_secs(60);
+ let mut interval = tokio::time::interval_at(start, Duration::from_secs(60));
+ loop {
+ interval.tick().await;
+ match JobModel::count_active_jobs(&context.db).await {
+ Ok(count) => metrics::active_jobs(count as f64),
+ Err(e) => warn!("Failed to count active jobs for autoscaling metric: {e:#}"),
+ }
+ }
+ });
+ }
+
let mut manager = Manager::builder("batch-import-worker").build();
let job_handle = manager.register(
diff --git a/rust/batch-import-worker/src/metrics.rs b/rust/batch-import-worker/src/metrics.rs
index 62acbf83111a..f8b2d0e4d6a9 100644
--- a/rust/batch-import-worker/src/metrics.rs
+++ b/rust/batch-import-worker/src/metrics.rs
@@ -3,6 +3,7 @@ pub const BACKOFF_DELAY_SECONDS: &str = "batch_import_backoff_delay_seconds";
pub const UNPAUSE_TOTAL: &str = "batch_import_unpause_total";
pub const STAGING_SWEEP_REMOVED: &str = "batch_import_staging_sweep_removed_total";
pub const STAGING_DIR_BYTES: &str = "batch_import_staging_dir_bytes";
+pub const ACTIVE_JOBS: &str = "batch_import_active_jobs";
use metrics::{counter, gauge, histogram};
@@ -22,3 +23,10 @@ pub fn staging_sweep_removed(count: u64) {
pub fn staging_dir_bytes(bytes: f64) {
gauge!(STAGING_DIR_BYTES).set(bytes);
}
+
+/// Number of batch import jobs currently needing a worker (queued and in-flight).
+/// Reported by every replica off the shared Postgres queue; the KEDA autoscaler
+/// collapses the per-pod duplicates with `max()` to drive replica count.
+pub fn active_jobs(count: f64) {
+ gauge!(ACTIVE_JOBS).set(count);
+}