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): flags consumer poc (#54202)

Matheus Batista385b64671e23
diff --git a/bin/migrate b/bin/migrate
index 6858d997aae4..6871970e8cca 100755
--- a/bin/migrate
+++ b/bin/migrate
@@ -47,6 +47,15 @@ if [ -d "$SCRIPT_DIR/../rust/bin" ] && [ "${DEPLOYMENT:-}" != "hobby" ]; then
exit 1
fi
fi
+
+ if run_scope "flags-read-store"; then
+ echo "Running flags read store migrations via external non-django migrator..."
+ bash $SCRIPT_DIR/../rust/bin/migrate-flags-read-store
+ if [ $? -ne 0 ]; then
+ echo "Error in rust/bin/migrate-flags-read-store, exiting."
+ exit 1
+ fi
+ fi
fi
if run_scope "clickhouse"; then RUN_CLICKHOUSE=1; else RUN_CLICKHOUSE=0; fi
diff --git a/bin/mprocs.yaml b/bin/mprocs.yaml
index 15f5372879bd..d0684ea1da17 100755
--- a/bin/mprocs.yaml
+++ b/bin/mprocs.yaml
@@ -245,6 +245,14 @@ procs:
layer: Product services
tech: Rust
+ flags-consumer:
+ shell: |-
+ bin/wait-for-docker && \
+ bin/start-rust-service flags-consumer
+ # POC skeleton — opt-in until the CDC consumer logic lands
+ autostart: false
+ ready_pattern: 'listening on *'
+
hypercache-server:
shell: |-
bin/wait-for-docker && \
@@ -452,6 +460,12 @@ procs:
tech: Migrations
# no capability - optional migration
+ migrate-flags-read-store:
+ shell: 'bin/wait-for-docker && bin/migrate --scope=flags-read-store'
+ autostart: false
+ ready_pattern: 'All migrations completed successfully'
+ # no capability - optional migration
+
generate-demo-data:
shell: |-
bin/wait-for-docker && \
diff --git a/bin/start b/bin/start
index 9803641206fd..2698be71ee37 100755
--- a/bin/start
+++ b/bin/start
@@ -97,6 +97,7 @@ export PERSONS_READ_DATABASE_URL=${PERSONS_READ_DATABASE_URL:-$PERSONS_READONLY_
# Using lvh.me instead of localhost for cross-platform compatibility
export ERROR_TRACKING_CYMBAL_BASE_URL=${ERROR_TRACKING_CYMBAL_BASE_URL:-http://lvh.me:3302}
export BEHAVIORAL_COHORTS_DATABASE_URL=${BEHAVIORAL_COHORTS_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/behavioral_cohorts}
+export FLAGS_READ_STORE_DATABASE_URL=${FLAGS_READ_STORE_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/flags_read_store}
export CYCLOTRON_DATABASE_URL=${CYCLOTRON_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/cyclotron}
export CYCLOTRON_NODE_DATABASE_URL=${CYCLOTRON_NODE_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/cyclotron_node}
diff --git a/bin/start-rust-service b/bin/start-rust-service
index 7d2088ba1f1d..c7cd915b0069 100755
--- a/bin/start-rust-service
+++ b/bin/start-rust-service
@@ -186,6 +186,17 @@ case "$RS_SVC" in
export METRICS_PORT=9101
;;
+ flags-consumer)
+ SQLX_QUERY_LEVEL=${SQLX_QUERY_LEVEL:-warn}
+ export RUST_LOG=debug,sqlx::query=$SQLX_QUERY_LEVEL,rdkafka=warn
+ export RUST_BACKTRACE=1
+ export FLAGS_READ_STORE_DATABASE_URL="${FLAGS_READ_STORE_DATABASE_URL:-postgres://posthog:posthog@${PGHOST:-db}:${PGPORT:-5432}/flags_read_store}"
+ export KAFKA_HOSTS="${KAFKA_HOSTS:-localhost:9092}"
+ export KAFKA_CONSUMER_OFFSET_RESET="${KAFKA_CONSUMER_OFFSET_RESET:-earliest}"
+ export METRICS_PORT=9105
+ export DEBUG=1
+ ;;
+
personhog-router-leader)
export RUST_LOG=debug
export RUST_BACKTRACE=1
diff --git a/docker/postgres-init-scripts/create-flags-read-store-db.sh b/docker/postgres-init-scripts/create-flags-read-store-db.sh
new file mode 100755
index 000000000000..134c1dcd3f55
--- /dev/null
+++ b/docker/postgres-init-scripts/create-flags-read-store-db.sh
@@ -0,0 +1,16 @@
+#!/bin/bash
+
+set -e
+set -u
+
+echo "Checking if database 'flags_read_store' exists..."
+DB_EXISTS=$(psql -U "$POSTGRES_USER" -tAc "SELECT 1 FROM pg_database WHERE datname='flags_read_store'")
+
+if [ -z "$DB_EXISTS" ]; then
+ echo "Creating database 'flags_read_store'..."
+ psql -U "$POSTGRES_USER" -c "CREATE DATABASE flags_read_store;"
+ psql -U "$POSTGRES_USER" -c "GRANT ALL PRIVILEGES ON DATABASE flags_read_store TO $POSTGRES_USER;"
+ echo "Database 'flags_read_store' created successfully"
+else
+ echo "Database 'flags_read_store' already exists"
+fi
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 491bb5b50c1a..9229d1ccf75e 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -3477,6 +3477,34 @@ version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
+[[package]]
+name = "flags-consumer"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "axum 0.7.9",
+ "chrono",
+ "clap",
+ "common-alloc",
+ "common-database",
+ "common-kafka",
+ "common-metrics",
+ "envconfig",
+ "lifecycle",
+ "metrics",
+ "metrics-exporter-prometheus",
+ "personhog-common",
+ "rand 0.8.5",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "tokio",
+ "tokio-util",
+ "tracing",
+ "tracing-subscriber",
+ "uuid",
+]
+
[[package]]
name = "flate2"
version = "1.1.9"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index aa20db3e49f6..71d43f7179e3 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -2,52 +2,53 @@
resolver = "2"
members = [
- "property-defs-rs",
- "batch-import-worker",
- "capture",
- "capture-logs",
- "common/alloc",
- "common/assignment-coordination",
- "common/k8s-awareness",
- "common/cache",
- "common/cookieless",
- "common/database",
- "common/dns",
- "common/health",
- "common/kafka",
- "common/liveness",
- "common/lifecycle",
- "common/limiters",
- "common/metrics",
- "common/profiler",
- "common/continuous_profiling",
- "common/redis",
- "common/s3",
- "common/serve_metrics",
- "common/symbol_data",
- "common/types",
- "common/compression",
- "common/hypercache",
- "feature-flags",
- "hypercache-server",
- "cyclotron-core",
- "cyclotron-node",
- "cyclotron-janitor",
- "cymbal",
- "embedding-worker",
- "common/geoip",
- "common/hogvm",
- "kafka-assigner",
- "kafka-assigner-proto",
- "ingestion-consumer",
- "kafka-deduplicator",
- "personhog-common",
- "personhog-coordination",
- "personhog-leader",
- "personhog-writer",
- "personhog-proto",
- "personhog-replica",
- "personhog-router",
+ "property-defs-rs",
+ "batch-import-worker",
+ "capture",
+ "capture-logs",
+ "common/alloc",
+ "common/assignment-coordination",
+ "common/k8s-awareness",
+ "common/cache",
+ "common/cookieless",
+ "common/database",
+ "common/dns",
+ "common/health",
+ "common/kafka",
+ "common/liveness",
+ "common/lifecycle",
+ "common/limiters",
+ "common/metrics",
+ "common/profiler",
+ "common/continuous_profiling",
+ "common/redis",
+ "common/s3",
+ "common/serve_metrics",
+ "common/symbol_data",
+ "common/types",
+ "common/compression",
+ "common/hypercache",
+ "feature-flags",
+ "flags-consumer",
+ "hypercache-server",
+ "cyclotron-core",
+ "cyclotron-node",
+ "cyclotron-janitor",
+ "cymbal",
+ "embedding-worker",
+ "common/geoip",
+ "common/hogvm",
+ "kafka-assigner",
+ "kafka-assigner-proto",
+ "ingestion-consumer",
+ "kafka-deduplicator",
+ "personhog-common",
+ "personhog-coordination",
+ "personhog-leader",
+ "personhog-writer",
+ "personhog-proto",
+ "personhog-replica",
+ "personhog-router",
]
[workspace.lints.rust]
@@ -83,7 +84,13 @@ debug = "line-tables-only"
[workspace.dependencies]
anyhow = "1.0"
assert-json-diff = "2.0.2"
-async-compression = { version = "0.4", features = ["tokio", "gzip", "deflate", "brotli", "zstd"] }
+async-compression = { version = "0.4", features = [
+ "tokio",
+ "gzip",
+ "deflate",
+ "brotli",
+ "zstd",
+] }
async-trait = "0.1.74"
axum = { version = "0.7.5", features = ["http2", "macros", "matched-path"] }
axum-client-ip = "0.6.0"
@@ -124,19 +131,19 @@ serde_json = { version = "1.0" }
serde_urlencoded = "0.7.1"
siphasher = "1.0.1"
sqlx = { version = "0.8.6", features = [
- "chrono",
- "json",
- "migrate",
- "postgres",
- "runtime-tokio",
- "tls-native-tls",
- "uuid",
+ "chrono",
+ "json",
+ "migrate",
+ "postgres",
+ "runtime-tokio",
+ "tls-native-tls",
+ "uuid",
] }
time = { version = "0.3.36", features = [
- "formatting",
- "macros",
- "parsing",
- "serde",
+ "formatting",
+ "macros",
+ "parsing",
+ "serde",
] }
thiserror = { version = "2.0" }
tokio = { version = "1.51.1", features = ["full"] }
@@ -156,7 +163,14 @@ aws-sdk-s3 = "1.58.0"
mockall = "0.13.0"
moka = { version = "0.12.15", features = ["sync", "future"] }
posthog-rs = { version = "0.3.5", features = ["async-client"] }
-redis = { version = "0.32.7", features = ["tokio-comp", "cluster", "cluster-async", "tls-rustls", "tls-rustls-webpki-roots", "tokio-rustls-comp"] }
+redis = { version = "0.32.7", features = [
+ "tokio-comp",
+ "cluster",
+ "cluster-async",
+ "tls-rustls",
+ "tls-rustls-webpki-roots",
+ "tokio-rustls-comp",
+] }
regex = "1.11.1"
fancy-regex = "0.17"
lz-str = "0.2.1"
@@ -164,10 +178,10 @@ opentelemetry-proto = { version = "0.29.0", features = ["with-serde"] }
tonic = { version = "0.12.3", features = ["zstd"] }
tonic-build = "0.12"
clickhouse = { version = "0.13.2", features = [
- "uuid",
- "time",
- "inserter",
- "rustls-tls",
+ "uuid",
+ "time",
+ "inserter",
+ "rustls-tls",
] }
# Used for decrypting django encrypted fields
diff --git a/rust/bin/migrate-entry b/rust/bin/migrate-entry
index 134b5726bcdb..68f65f812566 100755
--- a/rust/bin/migrate-entry
+++ b/rust/bin/migrate-entry
@@ -23,12 +23,13 @@ parse_args() {
}
show_usage() {
- echo "Usage: $0 <all|persons|cyclotron|cyclotron-node|behavioral-cohorts> [--fresh]"
+ echo "Usage: $0 <all|persons|cyclotron|cyclotron-node|behavioral-cohorts|flags-read-store> [--fresh]"
echo " all - Run all migrations"
echo " persons - Run only persons migrations"
echo " cyclotron - Run only cyclotron migrations"
echo " cyclotron-node - Run only cyclotron node migrations"
echo " behavioral-cohorts - Run only behavioral cohorts migrations"
+ echo " flags-read-store - Run only flags read store migrations"
echo ""
echo "Options:"
echo " --fresh - Drop and recreate database before migrating (for test environments)"
@@ -163,6 +164,31 @@ run_behavioral_cohorts_migrations() {
fi
}
+run_flags_read_store_migrations() {
+ local db_type="flags-read-store"
+ FLAGS_READ_STORE_DATABASE_NAME=${FLAGS_READ_STORE_DATABASE_NAME:-flags_read_store}
+
+ # Use environment variables with defaults
+ DB_HOST="${POSTGRES_FLAGS_READ_STORE_HOST:-localhost}"
+ DB_USER="${POSTGRES_FLAGS_READ_STORE_USER:-posthog}"
+ DB_PASS="${POSTGRES_FLAGS_READ_STORE_PASSWORD:-posthog}"
+
+ FLAGS_READ_STORE_DATABASE_URL=${FLAGS_READ_STORE_DATABASE_URL:-postgres://${DB_USER}:${DB_PASS}@${DB_HOST}:5432/$FLAGS_READ_STORE_DATABASE_NAME}
+
+ log_json "info" "Starting migrations" "starting" "$db_type" "\"database_name\":\"$FLAGS_READ_STORE_DATABASE_NAME\",\"fresh_mode\":$FRESH_MODE"
+
+ if [ "$FRESH_MODE" = true ]; then
+ sqlx database reset -y -D "$FLAGS_READ_STORE_DATABASE_URL" --source "$MIGRATIONS_BASE/flags_read_store_migrations/"
+ log_json "info" "Database reset and migrations completed" "completed" "$db_type"
+ else
+ sqlx database create -D "$FLAGS_READ_STORE_DATABASE_URL"
+ log_json "info" "Database created or already exists" "running" "$db_type"
+
+ sqlx migrate run -D "$FLAGS_READ_STORE_DATABASE_URL" --source "$MIGRATIONS_BASE/flags_read_store_migrations/"
+ log_json "info" "Migrations completed successfully" "completed" "$db_type"
+ fi
+}
+
case "$MIGRATION_TYPE" in
persons)
run_persons_migrations
@@ -176,6 +202,9 @@ case "$MIGRATION_TYPE" in
behavioral-cohorts)
run_behavioral_cohorts_migrations
;;
+ flags-read-store)
+ run_flags_read_store_migrations
+ ;;
all)
run_persons_migrations
run_cyclotron_migrations
diff --git a/rust/bin/migrate-flags-read-store b/rust/bin/migrate-flags-read-store
new file mode 100755
index 000000000000..c1687606aa47
--- /dev/null
+++ b/rust/bin/migrate-flags-read-store
@@ -0,0 +1,4 @@
+#!/bin/sh
+SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
+
+exec "$SCRIPT_DIR/migrate-entry" flags-read-store
diff --git a/rust/common/kafka/src/kafka_consumer.rs b/rust/common/kafka/src/kafka_consumer.rs
index 07d2bd94b964..652ab9e18c99 100644
--- a/rust/common/kafka/src/kafka_consumer.rs
+++ b/rust/common/kafka/src/kafka_consumer.rs
@@ -210,6 +210,14 @@ impl Offset {
pub fn get_value(&self) -> i64 {
self.offset
}
+
+ pub fn partition(&self) -> i32 {
+ self.partition
+ }
+
+ pub fn topic(&self) -> &str {
+ &self.topic
+ }
}
impl fmt::Debug for Offset {
diff --git a/rust/flags-consumer/Cargo.toml b/rust/flags-consumer/Cargo.toml
new file mode 100644
index 000000000000..ef6510193c6f
--- /dev/null
+++ b/rust/flags-consumer/Cargo.toml
@@ -0,0 +1,36 @@
+[package]
+name = "flags-consumer"
+version = "0.1.0"
+edition = "2021"
+publish = false
+
+[dependencies]
+personhog-common = { path = "../personhog-common" }
+common-database = { path = "../common/database" }
+common-kafka = { path = "../common/kafka" }
+common-alloc = { path = "../common/alloc" }
+common-metrics = { path = "../common/metrics" }
+lifecycle = { path = "../common/lifecycle" }
+metrics = { workspace = true }
+metrics-exporter-prometheus = { workspace = true }
+
+axum = { workspace = true }
+chrono = { workspace = true }
+envconfig = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+sqlx = { workspace = true }
+anyhow = { workspace = true }
+clap = { version = "4", features = ["derive", "env"] }
+rand = { workspace = true }
+tokio = { workspace = true }
+tokio-util = { workspace = true }
+tracing = { workspace = true }
+tracing-subscriber = { workspace = true }
+uuid = { workspace = true }
+
+[dev-dependencies]
+tokio = { workspace = true, features = ["test-util"] }
+
+[lints]
+workspace = true
diff --git a/rust/flags-consumer/src/benchmark/data_gen.rs b/rust/flags-consumer/src/benchmark/data_gen.rs
new file mode 100644
index 000000000000..36081e436ad4
--- /dev/null
+++ b/rust/flags-consumer/src/benchmark/data_gen.rs
@@ -0,0 +1,178 @@
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use rand::Rng;
+use serde_json::Value;
+use uuid::Uuid;
+
+use super::BenchmarkArgs;
+
+pub struct PersonRegistry {
+ pub persons: Vec<(i32, Uuid)>,
+ pub distinct_ids: Vec<(i32, Uuid, String)>,
+}
+
+pub struct BenchmarkData {
+ pub persons: Arc<Vec<(i32, Uuid)>>,
+ pub distinct_ids: Arc<Vec<(i32, Uuid, String)>>,
+ /// team_id -> indices into `distinct_ids` for the first distinct_id per person.
+ pub team_person_indices: Arc<HashMap<i32, Vec<usize>>>,
+ /// Weighted CDF for team selection: (cumulative_probability, team_id).
+ pub team_cdf: Arc<Vec<(f64, i32)>>,
+}
+
+pub fn build_benchmark_data(registry: PersonRegistry) -> BenchmarkData {
+ let team_person_indices = build_team_person_indices(&registry.distinct_ids);
+ let team_cdf = build_team_cdf(&team_person_indices);
+
+ BenchmarkData {
+ persons: Arc::new(registry.persons),
+ distinct_ids: Arc::new(registry.distinct_ids),
+ team_person_indices: Arc::new(team_person_indices),
+ team_cdf: Arc::new(team_cdf),
+ }
+}
+
+fn build_team_person_indices(distinct_ids: &[(i32, Uuid, String)]) -> HashMap<i32, Vec<usize>> {
+ let mut seen_persons = std::collections::HashSet::new();
+ let mut map: HashMap<i32, Vec<usize>> = HashMap::new();
+
+ for (idx, (team_id, person_uuid, _)) in distinct_ids.iter().enumerate() {
+ if seen_persons.insert((*team_id, *person_uuid)) {
+ map.entry(*team_id).or_default().push(idx);
+ }
+ }
+
+ map
+}
+
+/// Only teams with >= 2 persons are included since merges require two distinct persons.
+fn build_team_cdf(team_person_indices: &HashMap<i32, Vec<usize>>) -> Vec<(f64, i32)> {
+ let mut entries: Vec<(i32, usize)> = team_person_indices
+ .iter()
+ .filter(|(_, v)| v.len() >= 2)
+ .map(|(&tid, v)| (tid, v.len()))
+ .collect();
+
+ entries.sort_by_key(|(tid, _)| *tid);
+
+ let eligible_total: f64 = entries.iter().map(|(_, count)| *count as f64).sum();
+ if eligible_total == 0.0 {
+ return Vec::new();
+ }
+
+ let mut cumulative = 0.0;
+ let mut cdf = Vec::with_capacity(entries.len());
+
+ for (tid, count) in &entries {
+ cumulative += *count as f64 / eligible_total;
+ cdf.push((cumulative, *tid));
+ }
+
+ if let Some(last) = cdf.last_mut() {
+ last.0 = 1.0;
+ }
+
+ cdf
+}
+
+pub fn select_team_weighted(cdf: &[(f64, i32)], rng: &mut impl Rng) -> Option<i32> {
+ if cdf.is_empty() {
+ return None;
+ }
+ let r: f64 = rng.gen();
+ let idx = cdf.partition_point(|(cum, _)| *cum < r);
+ Some(cdf[idx.min(cdf.len() - 1)].1)
+}
+
+/// Generate a JSONB properties object padded to approximately `target_bytes`.
+pub fn generate_properties(rng: &mut impl Rng, target_bytes: usize) -> Value {
+ const KEYS: &[&str] = &[
+ "$browser",
+ "$os",
+ "$initial_referrer",
+ "$initial_referring_domain",
+ "$geoip_city_name",
+ "$geoip_country_code",
+ "$geoip_time_zone",
+ "email",
+ "name",
+ "plan",
+ "company",
+ "role",
+ "signup_date",
+ "last_login",
+ ];
+
+ let mut obj = serde_json::Map::with_capacity(KEYS.len() + 1);
+
+ for &key in KEYS {
+ let val_len: usize = rng.gen_range(4..30);
+ let val: String = (0..val_len)
+ .map(|_| rng.gen_range(b'a'..=b'z') as char)
+ .collect();
+ obj.insert(key.to_string(), Value::String(val));
+ }
+
+ let current = serde_json::to_string(&Value::Object(obj.clone()))
+ .unwrap()
+ .len();
+ if current < target_bytes {
+ let padding_needed = target_bytes - current;
+ let pad_val_len = padding_needed.saturating_sub(12);
+ let pad: String = (0..pad_val_len)
+ .map(|_| rng.gen_range(b'a'..=b'z') as char)
+ .collect();
+ obj.insert("_pad".to_string(), Value::String(pad));
+ }
+
+ Value::Object(obj)
+}
+
+/// Zipf-weighted team sizes (weight = 1/rank^1.5) so a few teams dominate.
+/// 86% of persons get 1 distinct_id, 14% get 2 (matching the measured ~1.14 ratio).
+pub fn generate_person_registry(args: &BenchmarkArgs, rng: &mut impl Rng) -> PersonRegistry {
+ let scale = args.scale as usize;
+ let teams = args.teams;
+
+ let weights: Vec<f64> = (1..=teams).map(|i| 1.0 / (i as f64).powf(1.5)).collect();
+ let total_weight: f64 = weights.iter().sum();
+
+ let mut team_counts: Vec<usize> = weights
+ .iter()
+ .map(|w| ((w / total_weight) * scale as f64).round() as usize)
+ .collect();
+
+ let total: usize = team_counts.iter().sum();
+ match total.cmp(&scale) {
+ std::cmp::Ordering::Greater => team_counts[0] -= total - scale,
+ std::cmp::Ordering::Less => team_counts[0] += scale - total,
+ std::cmp::Ordering::Equal => {}
+ }
+
+ let mut persons = Vec::with_capacity(scale);
+ let mut distinct_ids = Vec::with_capacity((scale as f64 * 1.14) as usize);
+
+ for (team_idx, &count) in team_counts.iter().enumerate() {
+ let team_id = (team_idx as i32) + 1;
+ for _ in 0..count {
+ let person_uuid = Uuid::new_v4();
+ persons.push((team_id, person_uuid));
+
+ let mut bytes = [0u8; 16];
+ rng.fill(&mut bytes);
+ distinct_ids.push((team_id, person_uuid, Uuid::from_bytes(bytes).to_string()));
+
+ if rng.gen_ratio(14, 100) {
+ let mut bytes2 = [0u8; 16];
+ rng.fill(&mut bytes2);
+ distinct_ids.push((team_id, person_uuid, Uuid::from_bytes(bytes2).to_string()));
+ }
+ }
+ }
+
+ PersonRegistry {
+ persons,
+ distinct_ids,
+ }
+}
diff --git a/rust/flags-consumer/src/benchmark/metrics.rs b/rust/flags-consumer/src/benchmark/metrics.rs
new file mode 100644
index 000000000000..4134b2f2b6a5
--- /dev/null
+++ b/rust/flags-consumer/src/benchmark/metrics.rs
@@ -0,0 +1,160 @@
+use std::time::Duration;
+
+use sqlx::PgPool;
+
+#[derive(Debug, Clone)]
+pub struct PgSnapshot {
+ pub n_tup_upd: i64,
+ pub n_tup_hot_upd: i64,
+ pub n_dead_tup: i64,
+ pub table_bytes: i64,
+ pub index_bytes: i64,
+ pub wal_lsn: Option<String>,
+}
+
+pub struct PhaseDelta {
+ pub hot_pct: f64,
+ pub dead_tuples: i64,
+}
+
+#[derive(Debug)]
+pub struct LatencyStats {
+ pub count: usize,
+ pub p50: Duration,
+ pub p95: Duration,
+ pub p99: Duration,
+ pub max: Duration,
+}
+
+pub async fn capture_snapshot(pool: &PgPool) -> anyhow::Result<PgSnapshot> {
+ let stats: (i64, i64, i64) = sqlx::query_as(
+ "SELECT \
+ COALESCE(SUM(n_tup_upd), 0)::bigint, \
+ COALESCE(SUM(n_tup_hot_upd), 0)::bigint, \
+ COALESCE(SUM(n_dead_tup), 0)::bigint \
+ FROM pg_stat_user_tables \
+ WHERE relname LIKE 'flags_person_lookup_p%'",
+ )
+ .fetch_one(pool)
+ .await?;
+
+ let sizes: (i64, i64) = sqlx::query_as(
+ "SELECT \
+ COALESCE(SUM(pg_relation_size(oid)), 0)::bigint, \
+ COALESCE(SUM(pg_indexes_size(oid)), 0)::bigint \
+ FROM pg_class \
+ WHERE relname LIKE 'flags_person_lookup_p%'",
+ )
+ .fetch_one(pool)
+ .await?;
+
+ // Requires pg_monitor role; returns None on permission error.
+ let wal_lsn: Option<String> =
+ match sqlx::query_as::<_, (String,)>("SELECT pg_current_wal_lsn()::text")
+ .fetch_one(pool)
+ .await
+ {
+ Ok((lsn,)) => Some(lsn),
+ Err(e) => {
+ tracing::debug!("WAL LSN unavailable (need pg_monitor role): {e}");
+ None
+ }
+ };
+
+ Ok(PgSnapshot {
+ n_tup_upd: stats.0,
+ n_tup_hot_upd: stats.1,
+ n_dead_tup: stats.2,
+ table_bytes: sizes.0,
+ index_bytes: sizes.1,
+ wal_lsn,
+ })
+}
+
+pub fn compute_delta(before: &PgSnapshot, after: &PgSnapshot) -> PhaseDelta {
+ let updates = after.n_tup_upd - before.n_tup_upd;
+ let hot_updates = after.n_tup_hot_upd - before.n_tup_hot_upd;
+ let hot_pct = if updates > 0 {
+ (hot_updates as f64 / updates as f64) * 100.0
+ } else {
+ 0.0
+ };
+
+ PhaseDelta {
+ hot_pct,
+ dead_tuples: after.n_dead_tup - before.n_dead_tup,
+ }
+}
+
+pub async fn compute_wal_delta(
+ pool: &PgPool,
+ before: &PgSnapshot,
+ after: &PgSnapshot,
+) -> Option<i64> {
+ let (before_lsn, after_lsn) = match (&before.wal_lsn, &after.wal_lsn) {
+ (Some(b), Some(a)) => (b.clone(), a.clone()),
+ _ => return None,
+ };
+
+ match sqlx::query_as::<_, (i64,)>("SELECT pg_wal_lsn_diff($1::pg_lsn, $2::pg_lsn)::bigint")
+ .bind(&after_lsn)
+ .bind(&before_lsn)
+ .fetch_one(pool)
+ .await
+ {
+ Ok((diff,)) => Some(diff),
+ Err(e) => {
+ tracing::debug!("WAL diff query failed: {e}");
+ None
+ }
+ }
+}
+
+/// Requires pg_stat_scan_tables role. Logs a warning and returns early if unavailable.
+pub async fn reset_stats(pool: &PgPool) {
+ for i in 0..super::schema::PARTITION_COUNT {
+ let table = format!("flags_person_lookup_p{i}");
+ let result = sqlx::query(
+ "SELECT pg_stat_reset_single_table_counters(oid) FROM pg_class WHERE relname = $1",
+ )
+ .bind(&table)
+ .execute(pool)
+ .await;
+ if let Err(e) = result {
+ tracing::warn!(
+ "could not reset pg_stat counters for {table} (need pg_stat_scan_tables role): {e}"
+ );
+ return;
+ }
+ }
+ tracing::info!("pg_stat counters reset for all partitions");
+}
+
+/// Sorts the slice in place.
+pub fn compute_percentiles(latencies: &mut [Duration]) -> LatencyStats {
+ let count = latencies.len();
+ if count == 0 {
+ return LatencyStats {
+ count: 0,
+ p50: Duration::ZERO,
+ p95: Duration::ZERO,
+ p99: Duration::ZERO,
+ max: Duration::ZERO,
+ };
+ }
+
+ latencies.sort_unstable();
+
+ let p = |pct: f64| -> Duration {
+ let idx = ((count as f64 * pct) as usize).min(count - 1);
+ latencies[idx]
+ };
+
+ LatencyStats {
+ count,
+ p50: p(0.50),
+ p95: p(0.95),
+ p99: p(0.99),
+ max: latencies[count - 1],
+ }
+}
diff --git a/rust/flags-consumer/src/benchmark/mod.rs b/rust/flags-consumer/src/benchmark/mod.rs
new file mode 100644
index 000000000000..7f3b4aacb3c0
--- /dev/null
+++ b/rust/flags-consumer/src/benchmark/mod.rs
@@ -0,0 +1,168 @@
+pub mod data_gen;
+pub mod metrics;
+pub mod population;
+pub mod report;
+pub mod schema;
+pub mod workloads;
+
+use std::time::Instant;
+
+use common_database::{get_pool_with_config, PoolConfig};
+use rand::SeedableRng;
+
+use crate::storage::postgres::PostgresStorage;
+use data_gen::build_benchmark_data;
+
+#[derive(clap::Args)]
+pub struct BenchmarkArgs {
+ #[arg(long, default_value = "100000")]
+ pub scale: u64,
+
+ #[arg(long, default_value = "100")]
+ pub teams: i32,
+
+ #[arg(long, default_value = "60")]
+ pub duration_secs: u64,
+
+ #[arg(long, default_value = "4")]
+ pub concurrency: usize,
+
+ #[arg(long, default_value = "10")]
+ pub burst_factor: usize,
+
+ #[arg(long, default_value = "500")]
+ pub batch_size: usize,
+
+ #[arg(long)]
+ pub skip_populate: bool,
+}
+
+pub async fn run(args: BenchmarkArgs) -> anyhow::Result<()> {
+ let database_url = std::env::var("FLAGS_READ_STORE_DATABASE_URL")
+ .or_else(|_| std::env::var("DATABASE_URL"))
+ .map_err(|_| {
+ anyhow::anyhow!(
+ "FLAGS_READ_STORE_DATABASE_URL or DATABASE_URL must be set for benchmark mode"
+ )
+ })?;
+
+ tracing::info!(
+ scale = args.scale,
+ teams = args.teams,
+ concurrency = args.concurrency,
+ burst_factor = args.burst_factor,
+ duration_secs = args.duration_secs,
+ "starting GIN index benchmark"
+ );
+
+ // Burst phase needs concurrency * burst_factor + reader tasks + headroom.
+ let max_conns = (args.concurrency * args.burst_factor + args.concurrency + 4) as u32;
+ let max_conns = max_conns.max(64);
+
+ let pool = get_pool_with_config(
+ &database_url,
+ PoolConfig {
+ max_connections: max_conns,
+ min_connections: 2,
+ acquire_timeout: std::time::Duration::from_secs(30),
+ ..Default::default()
+ },
+ )?;
+
+ let storage = PostgresStorage::new(pool.clone());
+ storage.ping().await?;
+ tracing::info!("database connected");
+
+ let mut rng = rand::rngs::StdRng::seed_from_u64(42);
+ let registry = data_gen::generate_person_registry(&args, &mut rng);
+
+ if args.skip_populate {
+ if !schema::table_exists(&pool).await? {
+ anyhow::bail!("--skip-populate but flags_person_lookup table does not exist");
+ }
+ tracing::info!("skipping population");
+ } else {
+ schema::create_schema(&pool).await?;
+
+ let pop_start = Instant::now();
+ population::populate(&pool, &storage, &registry, args.batch_size).await?;
+ tracing::info!(
+ elapsed_secs = pop_start.elapsed().as_secs(),
+ "population complete"
+ );
+ }
+
+ let data = build_benchmark_data(registry);
+ tracing::info!(
+ teams_with_merges = data.team_cdf.len(),
+ "benchmark data ready"
+ );
+
+ metrics::reset_stats(&pool).await;
+
+ let mut results = Vec::new();
+
+ tracing::info!("=== Phase 1: Sustained property updates ===");
+ let r = workloads::phase_property_updates(&pool, &data, &args).await?;
+ tracing::info!(ops = r.latency.count, errors = r.errors, "phase 1 complete");
+ results.push(r);
+
+ metrics::reset_stats(&pool).await;
+
+ tracing::info!("=== Phase 2: Identification appends ===");
+ let r = workloads::phase_identification_appends(&pool, &data, &args).await?;
+ tracing::info!(ops = r.latency.count, errors = r.errors, "phase 2 complete");
+ results.push(r);
+
+ metrics::reset_stats(&pool).await;
+
+ tracing::info!("=== Phase 3: Merge workload ===");
+ let r = workloads::phase_merges(&pool, &data, &args, "Merges", None, None).await?;
+ tracing::info!(ops = r.latency.count, errors = r.errors, "phase 3 complete");
+ results.push(r);
+
+ metrics::reset_stats(&pool).await;
+
+ tracing::info!(
+ burst_concurrency = args.concurrency * args.burst_factor,
+ "=== Phase 4: Burst merge storm ==="
+ );
+ let burst_concurrency = args.concurrency * args.burst_factor;
+ let burst_duration = args.duration_secs / 4;
+ let burst_name = format!("Burst merges ({}x)", args.burst_factor);
+ let r = workloads::phase_merges(
+ &pool,
+ &data,
+ &args,
+ &burst_name,
+ Some(burst_concurrency),
+ Some(burst_duration),
+ )
+ .await?;
+ tracing::info!(ops = r.latency.count, errors = r.errors, "phase 4 complete");
+ results.push(r);
+
+ metrics::reset_stats(&pool).await;
+
+ tracing::info!("=== Phase 5: Concurrent reads + writes ===");
+ let (write_r, read_r, query_plan) =
+ workloads::phase_concurrent_reads_writes(&pool, &data, &args).await?;
+ tracing::info!(
+ write_ops = write_r.latency.count,
+ read_ops = read_r.latency.count,
+ "phase 5 complete"
+ );
+ results.push(write_r);
+ results.push(read_r);
+
+ metrics::reset_stats(&pool).await;
+
+ tracing::info!("=== Phase 6: Post-burst steady-state recovery ===");
+ let r = workloads::phase_merges(&pool, &data, &args, "Post-burst merges", None, None).await?;
+ tracing::info!(ops = r.latency.count, errors = r.errors, "phase 6 complete");
+ results.push(r);
+
+ report::print_report(&args, &results, &query_plan);
+
+ Ok(())
+}
diff --git a/rust/flags-consumer/src/benchmark/population.rs b/rust/flags-consumer/src/benchmark/population.rs
new file mode 100644
index 000000000000..7de4c0653324
--- /dev/null
+++ b/rust/flags-consumer/src/benchmark/population.rs
@@ -0,0 +1,121 @@
+use crate::storage::{postgres::PostgresStorage, types::PersonUpdateData};
+use rand::rngs::StdRng;
+use rand::SeedableRng;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use super::data_gen::{generate_properties, PersonRegistry};
+
+/// Uses a separate seeded RNG (seed 43) for properties so the structural
+/// distribution (persons, distinct_ids) is independent of property generation.
+pub async fn populate(
+ pool: &PgPool,
+ storage: &PostgresStorage,
+ registry: &PersonRegistry,
+ batch_size: usize,
+) -> anyhow::Result<()> {
+ let total = registry.persons.len();
+ tracing::info!(total, "populating person rows");
+
+ let mut prop_rng = StdRng::seed_from_u64(43);
+
+ for (batch_idx, chunk) in registry.persons.chunks(batch_size).enumerate() {
+ let updates: Vec<PersonUpdateData> = chunk
+ .iter()
+ .map(|(team_id, uuid)| PersonUpdateData {
+ team_id: *team_id,
+ person_uuid: *uuid,
+ properties: generate_properties(&mut prop_rng, 700),
+ version: 1,
+ })
+ .collect();
+
+ storage.batch_upsert_persons(&updates).await?;
+
+ let done = ((batch_idx + 1) * batch_size).min(total);
+ if done % (total / 10).max(1) < batch_size {
+ tracing::info!(done, total, "persons inserted");
+ }
+ }
+
+ assign_distinct_ids_bulk(pool, registry).await?;
+
+ tracing::info!(total, "population complete");
+ Ok(())
+}
+
+/// Bulk-assigns distinct_ids via UNNEST instead of the single-row transactional
+/// upsert_distinct_id, which would be too slow for initial population.
+async fn assign_distinct_ids_bulk(pool: &PgPool, registry: &PersonRegistry) -> anyhow::Result<()> {
+ let total = registry.distinct_ids.len();
+ tracing::info!(total, "assigning distinct_ids");
+
+ let mut person_dids: std::collections::HashMap<(i32, Uuid), Vec<String>> =
+ std::collections::HashMap::new();
+ for (team_id, person_uuid, did) in &registry.distinct_ids {
+ person_dids
+ .entry((*team_id, *person_uuid))
+ .or_default()
+ .push(did.clone());
+ }
+
+ let entries: Vec<((i32, Uuid), Vec<String>)> = person_dids.into_iter().collect();
+ let batch_size = 500;
+
+ for (batch_idx, chunk) in entries.chunks(batch_size).enumerate() {
+ let team_ids: Vec<i32> = chunk.iter().map(|((tid, _), _)| *tid).collect();
+ let person_uuids: Vec<Uuid> = chunk.iter().map(|((_, uuid), _)| *uuid).collect();
+ let primary_dids: Vec<String> = chunk.iter().map(|(_, dids)| dids[0].clone()).collect();
+
+ sqlx::query(
+ r#"
+ UPDATE flags_person_lookup AS f
+ SET distinct_ids = ARRAY[t.did]::text[],
+ distinct_id_version = 1
+ FROM UNNEST($1::int[], $2::uuid[], $3::text[]) AS t(team_id, person_uuid, did)
+ WHERE f.team_id = t.team_id AND f.person_uuid = t.person_uuid
+ "#,
+ )
+ .bind(&team_ids)
+ .bind(&person_uuids)
+ .bind(&primary_dids)
+ .execute(pool)
+ .await?;
+
+ let mut extra_team_ids = Vec::new();
+ let mut extra_uuids = Vec::new();
+ let mut extra_dids = Vec::new();
+ for ((tid, uuid), dids) in chunk {
+ if dids.len() > 1 {
+ for extra_did in &dids[1..] {
+ extra_team_ids.push(*tid);
+ extra_uuids.push(*uuid);
+ extra_dids.push(extra_did.clone());
+ }
+ }
+ }
+
+ if !extra_dids.is_empty() {
+ sqlx::query(
+ r#"
+ UPDATE flags_person_lookup AS f
+ SET distinct_ids = f.distinct_ids || t.did
+ FROM UNNEST($1::int[], $2::uuid[], $3::text[]) AS t(team_id, person_uuid, did)
+ WHERE f.team_id = t.team_id AND f.person_uuid = t.person_uuid
+ "#,
+ )
+ .bind(&extra_team_ids)
+ .bind(&extra_uuids)
+ .bind(&extra_dids)
+ .execute(pool)
+ .await?;
+ }
+
+ let done = ((batch_idx + 1) * batch_size).min(entries.len());
+ if done % (entries.len() / 10).max(1) < batch_size {
+ tracing::info!(done, total = entries.len(), "distinct_ids assigned");
+ }
+ }
+
+ Ok(())
+}
diff --git a/rust/flags-consumer/src/benchmark/report.rs b/rust/flags-consumer/src/benchmark/report.rs
new file mode 100644
index 000000000000..0320da254482
--- /dev/null
+++ b/rust/flags-consumer/src/benchmark/report.rs
@@ -0,0 +1,96 @@
+use super::metrics::compute_delta;
+use super::workloads::{PhaseResult, QueryPlanInfo};
+use super::BenchmarkArgs;
+
+fn fmt_duration_ms(d: std::time::Duration) -> String {
+ let ms = d.as_secs_f64() * 1000.0;
+ if ms < 1.0 {
+ format!("{:.2}ms", ms)
+ } else if ms < 100.0 {
+ format!("{:.1}ms", ms)
+ } else {
+ format!("{:.0}ms", ms)
+ }
+}
+
+fn fmt_bytes_mib(bytes: i64) -> String {
+ let mib = bytes as f64 / (1024.0 * 1024.0);
+ format!("{:.1}", mib)
+}
+
+fn print_phase_row(result: &PhaseResult, show_pg_metrics: bool) {
+ let delta = compute_delta(&result.before, &result.after);
+
+ let wal_mib = match result.wal_bytes {
+ Some(b) => fmt_bytes_mib(b),
+ None => "N/A".into(),
+ };
+
+ if show_pg_metrics {
+ println!(
+ " {:<24} | {:>6} | {:>7} | {:>7} | {:>7} | {:>7} | {:>6} | {:>6.1}% | {:>11} | {:>9} | {:>9} | {:>7}",
+ result.name,
+ result.latency.count,
+ fmt_duration_ms(result.latency.p50),
+ fmt_duration_ms(result.latency.p95),
+ fmt_duration_ms(result.latency.p99),
+ fmt_duration_ms(result.latency.max),
+ result.errors,
+ delta.hot_pct,
+ delta.dead_tuples,
+ fmt_bytes_mib(result.after.table_bytes),
+ fmt_bytes_mib(result.after.index_bytes),
+ wal_mib,
+ );
+ } else {
+ println!(
+ " {:<24} | {:>6} | {:>7} | {:>7} | {:>7} | {:>7} | {:>6} | {:>7} | {:>11} | {:>9} | {:>9} | {:>7}",
+ result.name,
+ result.latency.count,
+ fmt_duration_ms(result.latency.p50),
+ fmt_duration_ms(result.latency.p95),
+ fmt_duration_ms(result.latency.p99),
+ fmt_duration_ms(result.latency.max),
+ result.errors,
+ "",
+ "",
+ "",
+ "",
+ "",
+ );
+ }
+}
+
+pub fn print_report(args: &BenchmarkArgs, results: &[PhaseResult], query_plan: &QueryPlanInfo) {
+ println!();
+ println!("=== GIN Index Benchmark Report ===");
+ println!(
+ "Scale: {} rows | Teams: {} | Concurrency: {} | Burst: {}x | Duration: {}s/phase",
+ args.scale, args.teams, args.concurrency, args.burst_factor, args.duration_secs
+ );
+ println!(
+ "GIN index used for reads: {}",
+ if query_plan.gin_index_used {
+ "yes"
+ } else {
+ "NO (planner chose sequential scan)"
+ }
+ );
+ println!();
+
+ let header = format!(
+ " {:<24} | {:>6} | {:>7} | {:>7} | {:>7} | {:>7} | {:>6} | {:>7} | {:>11} | {:>9} | {:>9} | {:>7}",
+ "Phase", "Ops", "p50", "p95", "p99", "max", "Errors", "HOT%", "Dead Tuples", "Table MiB", "Index MiB", "WAL MiB"
+ );
+ let separator = "-".repeat(header.len());
+
+ println!("{header}");
+ println!("{separator}");
+
+ for result in results {
+ let is_read = result.name.contains("reads");
+ print_phase_row(result, !is_read);
+ }
+
+ println!();
+}
diff --git a/rust/flags-consumer/src/benchmark/schema.rs b/rust/flags-consumer/src/benchmark/schema.rs
new file mode 100644
index 000000000000..7302b21501b4
--- /dev/null
+++ b/rust/flags-consumer/src/benchmark/schema.rs
@@ -0,0 +1,65 @@
+use sqlx::PgPool;
+
+pub const PARTITION_COUNT: usize = 64;
+
+pub async fn create_schema(pool: &PgPool) -> anyhow::Result<()> {
+ tracing::info!("dropping existing schema (if any)");
+ sqlx::query("DROP TABLE IF EXISTS flags_person_lookup CASCADE")
+ .execute(pool)
+ .await?;
+
+ tracing::info!("creating btree_gin extension");
+ sqlx::query("CREATE EXTENSION IF NOT EXISTS btree_gin")
+ .execute(pool)
+ .await?;
+
+ tracing::info!("creating flags_person_lookup table (hash-partitioned, 64 partitions)");
+ sqlx::query(
+ r#"
+ CREATE TABLE IF NOT EXISTS flags_person_lookup (
+ team_id INTEGER NOT NULL,
+ person_uuid UUID NOT NULL,
+ distinct_ids TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[],
+ properties JSONB NOT NULL DEFAULT '{}'::jsonb,
+ person_version BIGINT NOT NULL DEFAULT 0,
+ distinct_id_version BIGINT NOT NULL DEFAULT 0,
+ deleted_at TIMESTAMPTZ,
+ PRIMARY KEY (team_id, person_uuid)
+ ) PARTITION BY HASH (team_id)
+ "#,
+ )
+ .execute(pool)
+ .await?;
+
+ for i in 0..PARTITION_COUNT {
+ let ddl = format!(
+ "CREATE TABLE IF NOT EXISTS flags_person_lookup_p{i} \
+ PARTITION OF flags_person_lookup \
+ FOR VALUES WITH (MODULUS {PARTITION_COUNT}, REMAINDER {i})"
+ );
+ sqlx::query(&ddl).execute(pool).await?;
+ }
+
+ tracing::info!("creating GIN index on (team_id, distinct_ids) WHERE deleted_at IS NULL");
+ sqlx::query(
+ "CREATE INDEX IF NOT EXISTS idx_flags_person_gin \
+ ON flags_person_lookup USING GIN (team_id, distinct_ids) \
+ WHERE deleted_at IS NULL",
+ )
+ .execute(pool)
+ .await?;
+
+ tracing::info!("schema created");
+ Ok(())
+}
+
+pub async fn table_exists(pool: &PgPool) -> anyhow::Result<bool> {
+ let row: (bool,) = sqlx::query_as(
+ "SELECT EXISTS (
+ SELECT 1 FROM pg_class WHERE relname = 'flags_person_lookup' AND relkind = 'p'
+ )",
+ )
+ .fetch_one(pool)
+ .await?;
+ Ok(row.0)
+}
diff --git a/rust/flags-consumer/src/benchmark/workloads.rs b/rust/flags-consumer/src/benchmark/workloads.rs
new file mode 100644
index 000000000000..61df301d1291
--- /dev/null
+++ b/rust/flags-consumer/src/benchmark/workloads.rs
@@ -0,0 +1,439 @@
+use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use crate::storage::{
+ postgres::PostgresStorage,
+ types::{DistinctIdAssignmentData, PersonUpdateData},
+};
+use rand::rngs::StdRng;
+use rand::{Rng, SeedableRng};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use super::data_gen::{generate_properties, select_team_weighted, BenchmarkData};
+use super::metrics::{self, LatencyStats, PgSnapshot};
+use super::BenchmarkArgs;
+
+pub struct PhaseResult {
+ pub name: String,
+ pub latency: LatencyStats,
+ pub before: PgSnapshot,
+ pub after: PgSnapshot,
+ pub wal_bytes: Option<i64>,
+ pub errors: u64,
+}
+
+fn spawn_merge_writers(
+ pool: &PgPool,
+ data: &BenchmarkData,
+ concurrency: usize,
+ deadline: Instant,
+ seed_offset: u64,
+ version_counter: Arc<AtomicI64>,
+ error_counter: Arc<AtomicU64>,
+) -> Vec<tokio::task::JoinHandle<Vec<Duration>>> {
+ let mut handles = Vec::with_capacity(concurrency);
+
+ for task_id in 0..concurrency {
+ let storage = PostgresStorage::new(pool.clone());
+ let distinct_ids = data.distinct_ids.clone();
+ let team_indices = data.team_person_indices.clone();
+ let team_cdf = data.team_cdf.clone();
+ let version_counter = version_counter.clone();
+ let error_counter = error_counter.clone();
+
+ handles.push(tokio::spawn(async move {
+ let mut latencies = Vec::with_capacity(10_000);
+ let mut rng = StdRng::seed_from_u64(seed_offset + task_id as u64);
+
+ while Instant::now() < deadline {
+ let team_id = match select_team_weighted(&team_cdf, &mut rng) {
+ Some(tid) => tid,
+ None => continue,
+ };
+
+ let indices = match team_indices.get(&team_id) {
+ Some(idx) if idx.len() >= 2 => idx,
+ _ => continue,
+ };
+
+ let src_local = rng.gen_range(0..indices.len());
+ let mut tgt_local = rng.gen_range(0..indices.len());
+ while tgt_local == src_local {
+ tgt_local = rng.gen_range(0..indices.len());
+ }
+
+ let (_, _, src_did) = &distinct_ids[indices[src_local]];
+ let (_, tgt_uuid, _) = &distinct_ids[indices[tgt_local]];
+
+ let assignment = DistinctIdAssignmentData {
+ team_id,
+ person_uuid: *tgt_uuid,
+ distinct_id: src_did.clone().into_boxed_str(),
+ version: version_counter.fetch_add(1, Ordering::Relaxed),
+ };
+
+ let start = Instant::now();
+ match storage.upsert_distinct_id(&assignment).await {
+ Ok(_) => latencies.push(start.elapsed()),
+ Err(_) => {
+ error_counter.fetch_add(1, Ordering::Relaxed);
+ }
+ }
+ }
+ latencies
+ }));
+ }
+
+ handles
+}
+
+/// Property-only updates. Does not mutate distinct_ids, so the GIN index is untouched
+/// and updates should be HOT-eligible.
+pub async fn phase_property_updates(
+ pool: &PgPool,
+ data: &BenchmarkData,
+ args: &BenchmarkArgs,
+) -> anyhow::Result<PhaseResult> {
+ let before = metrics::capture_snapshot(pool).await?;
+ let deadline = Instant::now() + Duration::from_secs(args.duration_secs);
+ let version_counter = Arc::new(AtomicI64::new(100));
+ let error_counter = Arc::new(AtomicU64::new(0));
+
+ let mut handles = Vec::with_capacity(args.concurrency);
+
+ for task_id in 0..args.concurrency {
+ let storage = PostgresStorage::new(pool.clone());
+ let persons = data.persons.clone();
+ let batch_size = args.batch_size;
+ let version_counter = version_counter.clone();
+ let error_counter = error_counter.clone();
+
+ handles.push(tokio::spawn(async move {
+ let mut latencies = Vec::with_capacity(10_000);
+ let mut rng = StdRng::seed_from_u64(task_id as u64);
+
+ while Instant::now() < deadline {
+ // Unique persons per batch to avoid "ON CONFLICT DO UPDATE cannot affect
+ // row a second time". Sorted by (team_id, person_uuid) to prevent deadlocks.
+ let actual_batch = batch_size.min(persons.len());
+ let mut seen = std::collections::HashSet::with_capacity(actual_batch);
+ let mut batch = Vec::with_capacity(actual_batch);
+ while batch.len() < actual_batch {
+ let idx = rng.gen_range(0..persons.len());
+ if seen.insert(idx) {
+ let (team_id, person_uuid) = &persons[idx];
+ batch.push(PersonUpdateData {
+ team_id: *team_id,
+ person_uuid: *person_uuid,
+ properties: generate_properties(&mut rng, 700),
+ version: version_counter.fetch_add(1, Ordering::Relaxed),
+ });
+ }
+ }
+ batch.sort_by(|a, b| {
+ a.team_id
+ .cmp(&b.team_id)
+ .then(a.person_uuid.cmp(&b.person_uuid))
+ });
+
+ let start = Instant::now();
+ match storage.batch_upsert_persons(&batch).await {
+ Ok(_) => latencies.push(start.elapsed()),
+ Err(e) => {
+ tracing::warn!("batch_upsert_persons error: {e}");
+ error_counter.fetch_add(1, Ordering::Relaxed);
+ }
+ }
+ }
+ latencies
+ }));
+ }
+
+ let mut all_latencies = Vec::new();
+ for handle in handles {
+ all_latencies.extend(handle.await?);
+ }
+
+ let after = metrics::capture_snapshot(pool).await?;
+ let wal_bytes = metrics::compute_wal_delta(pool, &before, &after).await;
+
+ Ok(PhaseResult {
+ name: "Property updates".into(),
+ latency: metrics::compute_percentiles(&mut all_latencies),
+ before,
+ after,
+ wal_bytes,
+ errors: error_counter.load(Ordering::Relaxed),
+ })
+}
+
+/// Assign new distinct_ids to existing persons. Each operation appends to the
+/// distinct_ids array and forces a GIN index update.
+pub async fn phase_identification_appends(
+ pool: &PgPool,
+ data: &BenchmarkData,
+ args: &BenchmarkArgs,
+) -> anyhow::Result<PhaseResult> {
+ let before = metrics::capture_snapshot(pool).await?;
+ let deadline = Instant::now() + Duration::from_secs(args.duration_secs);
+ let version_counter = Arc::new(AtomicI64::new(1_000_000));
+ let error_counter = Arc::new(AtomicU64::new(0));
+
+ let mut handles = Vec::with_capacity(args.concurrency);
+
+ for task_id in 0..args.concurrency {
+ let storage = PostgresStorage::new(pool.clone());
+ let persons = data.persons.clone();
+ let version_counter = version_counter.clone();
+ let error_counter = error_counter.clone();
+
+ handles.push(tokio::spawn(async move {
+ let mut latencies = Vec::with_capacity(10_000);
+ let mut rng = StdRng::seed_from_u64(1000 + task_id as u64);
+
+ while Instant::now() < deadline {
+ let idx = rng.gen_range(0..persons.len());
+ let (team_id, person_uuid) = &persons[idx];
+
+ let mut did_bytes = [0u8; 16];
+ rng.fill(&mut did_bytes);
+
+ let assignment = DistinctIdAssignmentData {
+ team_id: *team_id,
+ person_uuid: *person_uuid,
+ distinct_id: Uuid::from_bytes(did_bytes).to_string().into_boxed_str(),
+ version: version_counter.fetch_add(1, Ordering::Relaxed),
+ };
+
+ let start = Instant::now();
+ match storage.upsert_distinct_id(&assignment).await {
+ Ok(_) => latencies.push(start.elapsed()),
+ Err(_) => {
+ error_counter.fetch_add(1, Ordering::Relaxed);
+ }
+ }
+ }
+ latencies
+ }));
+ }
+
+ let mut all_latencies = Vec::new();
+ for handle in handles {
+ all_latencies.extend(handle.await?);
+ }
+
+ let after = metrics::capture_snapshot(pool).await?;
+ let wal_bytes = metrics::compute_wal_delta(pool, &before, &after).await;
+
+ Ok(PhaseResult {
+ name: "ID appends".into(),
+ latency: metrics::compute_percentiles(&mut all_latencies),
+ before,
+ after,
+ wal_bytes,
+ errors: error_counter.load(Ordering::Relaxed),
+ })
+}
+
+/// Reassign a distinct_id from one person to another within the same team.
+/// Each merge triggers array_remove on the source and array_append on the target,
+/// causing two GIN index updates per operation.
+pub async fn phase_merges(
+ pool: &PgPool,
+ data: &BenchmarkData,
+ args: &BenchmarkArgs,
+ name: &str,
+ concurrency_override: Option<usize>,
+ duration_override: Option<u64>,
+) -> anyhow::Result<PhaseResult> {
+ let before = metrics::capture_snapshot(pool).await?;
+ let concurrency = concurrency_override.unwrap_or(args.concurrency);
+ let duration = duration_override.unwrap_or(args.duration_secs);
+ let deadline = Instant::now() + Duration::from_secs(duration);
+ let version_counter = Arc::new(AtomicI64::new(10_000_000));
+ let error_counter = Arc::new(AtomicU64::new(0));
+
+ let handles = spawn_merge_writers(
+ pool,
+ data,
+ concurrency,
+ deadline,
+ 2000,
+ version_counter,
+ error_counter.clone(),
+ );
+
+ let mut all_latencies = Vec::new();
+ for handle in handles {
+ all_latencies.extend(handle.await?);
+ }
+
+ let after = metrics::capture_snapshot(pool).await?;
+ let wal_bytes = metrics::compute_wal_delta(pool, &before, &after).await;
+
+ Ok(PhaseResult {
+ name: name.into(),
+ latency: metrics::compute_percentiles(&mut all_latencies),
+ before,
+ after,
+ wal_bytes,
+ errors: error_counter.load(Ordering::Relaxed),
+ })
+}
+
+pub struct QueryPlanInfo {
+ pub gin_index_used: bool,
+ pub plan_text: String,
+}
+
+/// Merge writers alongside GIN-indexed read queries to measure whether
+/// GIN maintenance degrades read latency.
+pub async fn phase_concurrent_reads_writes(
+ pool: &PgPool,
+ data: &BenchmarkData,
+ args: &BenchmarkArgs,
+) -> anyhow::Result<(PhaseResult, PhaseResult, QueryPlanInfo)> {
+ let plan_info = check_read_query_plan(pool, data).await;
+
+ let before = metrics::capture_snapshot(pool).await?;
+ let deadline = Instant::now() + Duration::from_secs(args.duration_secs);
+ let version_counter = Arc::new(AtomicI64::new(100_000_000));
+ let write_errors = Arc::new(AtomicU64::new(0));
+ let read_errors = Arc::new(AtomicU64::new(0));
+
+ let write_handles = spawn_merge_writers(
+ pool,
+ data,
+ args.concurrency,
+ deadline,
+ 5000,
+ version_counter,
+ write_errors.clone(),
+ );
+
+ let mut read_handles = Vec::with_capacity(args.concurrency);
+
+ for task_id in 0..args.concurrency {
+ let pool = pool.clone();
+ let distinct_ids = data.distinct_ids.clone();
+ let read_errors = read_errors.clone();
+
+ read_handles.push(tokio::spawn(async move {
+ let mut latencies = Vec::with_capacity(50_000);
+ let mut rng = StdRng::seed_from_u64(6000 + task_id as u64);
+
+ while Instant::now() < deadline {
+ let idx = rng.gen_range(0..distinct_ids.len());
+ let (team_id, _, did) = &distinct_ids[idx];
+
+ let start = Instant::now();
+ let result = sqlx::query(
+ "SELECT person_uuid, distinct_ids, properties \
+ FROM flags_person_lookup \
+ WHERE team_id = $1 AND distinct_ids @> ARRAY[$2]::text[] \
+ AND deleted_at IS NULL \
+ LIMIT 1",
+ )
+ .bind(team_id)
+ .bind(did)
+ .fetch_optional(&pool)
+ .await;
+
+ match result {
+ Ok(_) => latencies.push(start.elapsed()),
+ Err(_) => {
+ read_errors.fetch_add(1, Ordering::Relaxed);
+ }
+ }
+ }
+ latencies
+ }));
+ }
+
+ let mut write_latencies = Vec::new();
+ for handle in write_handles {
+ write_latencies.extend(handle.await?);
+ }
+ let mut read_latencies = Vec::new();
+ for handle in read_handles {
+ read_latencies.extend(handle.await?);
+ }
+
+ let after = metrics::capture_snapshot(pool).await?;
+ let wal_bytes = metrics::compute_wal_delta(pool, &before, &after).await;
+
+ let write_result = PhaseResult {
+ name: "Reads+Writes (writes)".into(),
+ latency: metrics::compute_percentiles(&mut write_latencies),
+ before: before.clone(),
+ after: after.clone(),
+ wal_bytes,
+ errors: write_errors.load(Ordering::Relaxed),
+ };
+
+ let read_result = PhaseResult {
+ name: "Reads+Writes (reads)".into(),
+ latency: metrics::compute_percentiles(&mut read_latencies),
+ before,
+ after,
+ wal_bytes: None,
+ errors: read_errors.load(Ordering::Relaxed),
+ };
+
+ Ok((write_result, read_result, plan_info))
+}
+
+/// Run EXPLAIN on the read query and check whether the GIN index is used.
+/// After heavy mutations the planner might fall back to sequential scans.
+async fn check_read_query_plan(pool: &PgPool, data: &BenchmarkData) -> QueryPlanInfo {
+ if data.distinct_ids.is_empty() {
+ return QueryPlanInfo {
+ gin_index_used: false,
+ plan_text: "no data".into(),
+ };
+ }
+
+ let (team_id, _, did) = &data.distinct_ids[0];
+
+ let plan: Result<Vec<(String,)>, _> = sqlx::query_as(
+ "EXPLAIN (ANALYZE, BUFFERS) \
+ SELECT person_uuid, distinct_ids, properties \
+ FROM flags_person_lookup \
+ WHERE team_id = $1 AND distinct_ids @> ARRAY[$2]::text[] \
+ AND deleted_at IS NULL \
+ LIMIT 1",
+ )
+ .bind(team_id)
+ .bind(did)
+ .fetch_all(pool)
+ .await;
+
+ match plan {
+ Ok(rows) => {
+ let plan_text = rows
+ .into_iter()
+ .map(|(line,)| line)
+ .collect::<Vec<_>>()
+ .join("\n");
+ // The migration names the parent GIN index `idx_flags_person_gin`,
+ // but Postgres auto-names partition-local indexes as
+ // `<partition>_team_id_distinct_ids_idx`, so we match either form.
+ let gin_index_used = plan_text.contains("idx_flags_person_gin")
+ || plan_text.contains("team_id_distinct_ids_idx");
+ tracing::info!(gin_index_used, "Phase 5 read query plan:\n{plan_text}");
+ QueryPlanInfo {
+ gin_index_used,
+ plan_text,
+ }
+ }
+ Err(e) => {
+ tracing::warn!("could not run EXPLAIN for read query: {e}");
+ QueryPlanInfo {
+ gin_index_used: false,
+ plan_text: format!("EXPLAIN failed: {e}"),
+ }
+ }
+ }
+}
diff --git a/rust/flags-consumer/src/config.rs b/rust/flags-consumer/src/config.rs
new file mode 100644
index 000000000000..0c4cf57f922f
--- /dev/null
+++ b/rust/flags-consumer/src/config.rs
@@ -0,0 +1,271 @@
+use std::collections::HashSet;
+use std::time::Duration;
+
+use common_kafka::config::{ConsumerConfig, KafkaConfig};
+use envconfig::Envconfig;
+
+/// Configuration for the `flags-consumer` CDC service.
+#[derive(Envconfig, Clone, Debug)]
+pub struct Config {
+ // ── Database ──────────────────────────────────────────────────────────
+ #[envconfig(default = "postgres://posthog:posthog@localhost:5432/flags_read_store")]
+ pub flags_read_store_database_url: String,
+
+ #[envconfig(default = "20")]
+ pub max_pg_connections: u32,
+
+ #[envconfig(default = "5")]
+ pub min_pg_connections: u32,
+
+ #[envconfig(default = "10")]
+ pub acquire_timeout_secs: u64,
+
+ #[envconfig(default = "300")]
+ pub idle_timeout_secs: u64,
+
+ /// Statement timeout for CDC writes (ms).
+ #[envconfig(default = "5000")]
+ pub write_statement_timeout_ms: u64,
+
+ #[envconfig(default = "10")]
+ pub pool_monitor_interval_secs: u64,
+
+ // ── Kafka ─────────────────────────────────────────────────────────────
+ #[envconfig(default = "localhost:9092")]
+ pub kafka_hosts: String,
+
+ #[envconfig(default = "false")]
+ pub kafka_tls: bool,
+
+ #[envconfig(default = "")]
+ pub kafka_client_rack: String,
+
+ #[envconfig(default = "")]
+ pub kafka_client_id: String,
+
+ #[envconfig(default = "flags-cdc-consumer")]
+ pub kafka_consumer_group: String,
+
+ #[envconfig(default = "latest")]
+ pub kafka_consumer_offset_reset: String,
+
+ #[envconfig(default = "clickhouse_person")]
+ pub kafka_person_topic: String,
+
+ #[envconfig(default = "clickhouse_person_distinct_id")]
+ pub kafka_person_distinct_id_topic: String,
+
+ // ── Batching ──────────────────────────────────────────────────────────
+ /// Max messages per batch write.
+ #[envconfig(default = "500")]
+ pub batch_size: usize,
+
+ /// Max wait (ms) before flushing a partial batch.
+ #[envconfig(default = "100")]
+ pub batch_timeout_ms: u64,
+
+ // ── Team filtering (POC scoping) ──────────────────────────────────────
+ /// Comma-separated team IDs to process. Empty means "all teams".
+ #[envconfig(default = "")]
+ pub filtered_team_ids: String,
+
+ // ── Retry / resilience ────────────────────────────────────────────────
+ #[envconfig(default = "3")]
+ pub max_retries: u32,
+
+ /// Base backoff between retries (doubles each attempt).
+ #[envconfig(default = "50")]
+ pub retry_backoff_base_ms: u64,
+
+ // ── Heartbeat ─────────────────────────────────────────────────────────
+ #[envconfig(default = "10")]
+ pub heartbeat_interval_secs: u64,
+
+ // ── Observability ─────────────────────────────────────────────────────
+ #[envconfig(default = "9105")]
+ pub metrics_port: u16,
+}
+
+impl Config {
+ pub fn acquire_timeout(&self) -> Duration {
+ Duration::from_secs(self.acquire_timeout_secs)
+ }
+
+ pub fn idle_timeout(&self) -> Option<Duration> {
+ if self.idle_timeout_secs == 0 {
+ None
+ } else {
+ Some(Duration::from_secs(self.idle_timeout_secs))
+ }
+ }
+
+ pub fn statement_timeout(&self) -> Option<u64> {
+ if self.write_statement_timeout_ms == 0 {
+ None
+ } else {
+ Some(self.write_statement_timeout_ms)
+ }
+ }
+
+ pub fn batch_timeout(&self) -> Duration {
+ Duration::from_millis(self.batch_timeout_ms)
+ }
+
+ /// Parse the comma-separated team filter into a `HashSet`.
+ /// Returns `None` if empty (meaning "all teams").
+ pub fn parsed_team_filter(&self) -> Option<HashSet<i32>> {
+ if self.filtered_team_ids.is_empty() {
+ return None;
+ }
+ Some(
+ self.filtered_team_ids
+ .split(',')
+ .filter_map(|s| s.trim().parse::<i32>().ok())
+ .collect(),
+ )
+ }
+
+ /// Build the common Kafka connection config.
+ pub fn build_kafka_config(&self) -> KafkaConfig {
+ KafkaConfig {
+ kafka_hosts: self.kafka_hosts.clone(),
+ kafka_tls: self.kafka_tls,
+ kafka_client_rack: self.kafka_client_rack.clone(),
+ kafka_client_id: self.kafka_client_id.clone(),
+ // Producer settings — unused by consumers but required by KafkaConfig.
+ kafka_producer_linger_ms: 20,
+ kafka_producer_queue_mib: 400,
+ kafka_producer_queue_messages: 10_000_000,
+ kafka_message_timeout_ms: 20_000,
+ kafka_compression_codec: "none".to_string(),
+ kafka_producer_batch_size: None,
+ kafka_producer_batch_num_messages: None,
+ kafka_producer_enable_idempotence: None,
+ kafka_producer_max_in_flight_requests_per_connection: None,
+ kafka_producer_topic_metadata_refresh_interval_ms: None,
+ kafka_producer_message_max_bytes: None,
+ kafka_producer_sticky_partitioning_linger_ms: None,
+ }
+ }
+
+ /// Build the consumer config for the `clickhouse_person` topic.
+ pub fn build_person_consumer_config(&self) -> ConsumerConfig {
+ ConsumerConfig {
+ kafka_consumer_group: self.kafka_consumer_group.clone(),
+ kafka_consumer_topic: self.kafka_person_topic.clone(),
+ kafka_consumer_offset_reset: self.kafka_consumer_offset_reset.clone(),
+ kafka_consumer_auto_commit: true,
+ kafka_consumer_auto_commit_interval_ms: 5000,
+ kafka_consumer_fetch_wait_max_ms: None,
+ kafka_consumer_fetch_min_bytes: None,
+ kafka_consumer_fetch_max_bytes: None,
+ kafka_consumer_max_partition_fetch_bytes: None,
+ kafka_consumer_group_instance_id: None,
+ kafka_consumer_partition_strategy: None,
+ kafka_consumer_socket_send_buffer_bytes: None,
+ kafka_consumer_socket_receive_buffer_bytes: None,
+ kafka_consumer_metadata_refresh_interval_ms: None,
+ }
+ }
+
+ /// Build the consumer config for the `clickhouse_person_distinct_id` topic.
+ pub fn build_distinct_id_consumer_config(&self) -> ConsumerConfig {
+ ConsumerConfig {
+ kafka_consumer_group: self.kafka_consumer_group.clone(),
+ kafka_consumer_topic: self.kafka_person_distinct_id_topic.clone(),
+ kafka_consumer_offset_reset: self.kafka_consumer_offset_reset.clone(),
+ kafka_consumer_auto_commit: true,
+ kafka_consumer_auto_commit_interval_ms: 5000,
+ kafka_consumer_fetch_wait_max_ms: None,
+ kafka_consumer_fetch_min_bytes: None,
+ kafka_consumer_fetch_max_bytes: None,
+ kafka_consumer_max_partition_fetch_bytes: None,
+ kafka_consumer_group_instance_id: None,
+ kafka_consumer_partition_strategy: None,
+ kafka_consumer_socket_send_buffer_bytes: None,
+ kafka_consumer_socket_receive_buffer_bytes: None,
+ kafka_consumer_metadata_refresh_interval_ms: None,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn test_config() -> Config {
+ Config {
+ flags_read_store_database_url: "postgres://localhost/test".to_string(),
+ max_pg_connections: 5,
+ min_pg_connections: 1,
+ acquire_timeout_secs: 10,
+ idle_timeout_secs: 300,
+ write_statement_timeout_ms: 5000,
+ pool_monitor_interval_secs: 10,
+ kafka_hosts: "localhost:9092".to_string(),
+ kafka_tls: false,
+ kafka_client_rack: String::new(),
+ kafka_client_id: String::new(),
+ kafka_consumer_group: "test-group".to_string(),
+ kafka_consumer_offset_reset: "latest".to_string(),
+ kafka_person_topic: "clickhouse_person".to_string(),
+ kafka_person_distinct_id_topic: "clickhouse_person_distinct_id".to_string(),
+ batch_size: 500,
+ batch_timeout_ms: 100,
+ filtered_team_ids: String::new(),
+ max_retries: 3,
+ retry_backoff_base_ms: 50,
+ heartbeat_interval_secs: 10,
+ metrics_port: 9105,
+ }
+ }
+
+ #[test]
+ fn test_parsed_team_filter_empty() {
+ let config = test_config();
+ assert!(config.parsed_team_filter().is_none());
+ }
+
+ #[test]
+ fn test_parsed_team_filter_single() {
+ let mut config = test_config();
+ config.filtered_team_ids = "42".to_string();
+ let filter = config.parsed_team_filter().unwrap();
+ assert_eq!(filter.len(), 1);
+ assert!(filter.contains(&42));
+ }
+
+ #[test]
+ fn test_parsed_team_filter_multiple() {
+ let mut config = test_config();
+ config.filtered_team_ids = "1, 2, 3".to_string();
+ let filter = config.parsed_team_filter().unwrap();
+ assert_eq!(filter.len(), 3);
+ assert!(filter.contains(&1));
+ assert!(filter.contains(&2));
+ assert!(filter.contains(&3));
+ }
+
+ #[test]
+ fn test_parsed_team_filter_invalid_entries() {
+ let mut config = test_config();
+ config.filtered_team_ids = "1, abc, 3".to_string();
+ let filter = config.parsed_team_filter().unwrap();
+ assert_eq!(filter.len(), 2);
+ assert!(filter.contains(&1));
+ assert!(filter.contains(&3));
+ }
+
+ #[test]
+ fn test_batch_timeout() {
+ let config = test_config();
+ assert_eq!(config.batch_timeout(), Duration::from_millis(100));
+ }
+
+ #[test]
+ fn test_statement_timeout_zero_means_none() {
+ let mut config = test_config();
+ config.write_statement_timeout_ms = 0;
+ assert!(config.statement_timeout().is_none());
+ }
+}
diff --git a/rust/flags-consumer/src/kafka/consumer.rs b/rust/flags-consumer/src/kafka/consumer.rs
new file mode 100644
index 000000000000..b80bcd2e2a94
--- /dev/null
+++ b/rust/flags-consumer/src/kafka/consumer.rs
@@ -0,0 +1,67 @@
+use std::collections::HashSet;
+use std::time::Duration;
+
+use common_kafka::kafka_consumer::{RecvErr, SingleTopicConsumer};
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use crate::kafka::messages::KafkaMessage;
+use crate::metric_consts;
+use crate::pipeline::batch::EventWithOffset;
+
+/// Single-topic consumer loop, generic over the message type `M`.
+pub async fn consume_loop<M: KafkaMessage>(
+ consumer: SingleTopicConsumer,
+ tx: mpsc::Sender<EventWithOffset>,
+ team_filter: Option<HashSet<i32>>,
+ shutdown: CancellationToken,
+) {
+ loop {
+ tokio::select! {
+ biased;
+ _ = shutdown.cancelled() => {
+ tracing::info!("{} consumer shutting down", M::SOURCE);
+ break;
+ }
+ result = consumer.json_recv::<M>() => {
+ match result {
+ Ok((msg, offset)) => {
+ metrics::counter!(metric_consts::MESSAGES_RECEIVED, "source" => M::SOURCE)
+ .increment(1);
+
+ if let Some(ref filter) = team_filter {
+ if !filter.contains(&msg.team_id()) {
+ if let Err(e) = offset.store() {
+ tracing::warn!(error = %e, "{} failed to store filtered offset", M::SOURCE);
+ }
+ metrics::counter!(metric_consts::MESSAGES_FILTERED, "source" => M::SOURCE)
+ .increment(1);
+ continue;
+ }
+ }
+
+ let event = msg.classify();
+ if tx.send(EventWithOffset { event, offset }).await.is_err() {
+ tracing::info!("{} channel closed, exiting", M::SOURCE);
+ break;
+ }
+ }
+ Err(RecvErr::Serde(e)) => {
+ tracing::warn!("{} serde error (poison pill skipped): {e}", M::SOURCE);
+ metrics::counter!(metric_consts::MESSAGES_SKIPPED, "source" => M::SOURCE, "reason" => "serde")
+ .increment(1);
+ }
+ Err(RecvErr::Empty) => {
+ metrics::counter!(metric_consts::MESSAGES_SKIPPED, "source" => M::SOURCE, "reason" => "empty")
+ .increment(1);
+ }
+ Err(RecvErr::Kafka(e)) => {
+ tracing::error!("{} kafka error: {e}", M::SOURCE);
+ metrics::counter!(metric_consts::KAFKA_ERRORS, "source" => M::SOURCE).increment(1);
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/rust/flags-consumer/src/kafka/messages.rs b/rust/flags-consumer/src/kafka/messages.rs
new file mode 100644
index 000000000000..d9d402c942b9
--- /dev/null
+++ b/rust/flags-consumer/src/kafka/messages.rs
@@ -0,0 +1,261 @@
+use serde::de::DeserializeOwned;
+use serde::Deserialize;
+use uuid::Uuid;
+
+use crate::types::CdcEvent;
+use crate::utils::mock::Mock;
+
+/// A Kafka message that can be deserialized, filtered, and classified into a [`CdcEvent`].
+///
+/// Adding a new topic requires a new struct + impl of this trait.
+pub trait KafkaMessage: DeserializeOwned + Send {
+ /// Prometheus metrics label for this topic.
+ const SOURCE: &'static str;
+
+ fn team_id(&self) -> i32;
+
+ /// Classify into a [`CdcEvent`], consuming the raw message.
+ fn classify(self) -> CdcEvent;
+}
+
+/// Raw message from the `clickhouse_person` Kafka topic.
+///
+/// `properties` is a JSON-encoded string (the Plugin Server stringifies it).
+/// Parsed into `serde_json::Value` in `classify()`, only for non-deletion messages.
+#[derive(Debug, Clone, Deserialize)]
+pub struct PersonMessage {
+ pub id: Uuid,
+ pub team_id: i32,
+ pub properties: String,
+ pub version: i64,
+ #[serde(default)]
+ pub is_deleted: i32,
+}
+
+impl KafkaMessage for PersonMessage {
+ const SOURCE: &'static str = "person";
+
+ fn team_id(&self) -> i32 {
+ self.team_id
+ }
+
+ fn classify(self) -> CdcEvent {
+ if self.is_deleted != 0 {
+ CdcEvent::PersonDeletion {
+ team_id: self.team_id,
+ person_uuid: self.id,
+ version: self.version,
+ }
+ } else {
+ let properties = serde_json::from_str(&self.properties).unwrap_or_default();
+ CdcEvent::PersonUpdate {
+ team_id: self.team_id,
+ person_uuid: self.id,
+ properties,
+ version: self.version,
+ }
+ }
+ }
+}
+
+/// Raw message from the `clickhouse_person_distinct_id` Kafka topic.
+#[derive(Debug, Clone, Deserialize)]
+pub struct DistinctIdMessage {
+ pub person_id: Uuid,
+ pub team_id: i32,
+ pub distinct_id: String,
+ pub version: i64,
+ #[serde(default)]
+ pub is_deleted: i32,
+}
+
+impl KafkaMessage for DistinctIdMessage {
+ const SOURCE: &'static str = "distinct_id";
+
+ fn team_id(&self) -> i32 {
+ self.team_id
+ }
+
+ fn classify(self) -> CdcEvent {
+ let distinct_id = self.distinct_id.into_boxed_str();
+ if self.is_deleted != 0 {
+ CdcEvent::DistinctIdDeletion {
+ team_id: self.team_id,
+ person_uuid: self.person_id,
+ distinct_id,
+ version: self.version,
+ }
+ } else {
+ CdcEvent::DistinctIdAssignment {
+ team_id: self.team_id,
+ person_uuid: self.person_id,
+ distinct_id,
+ version: self.version,
+ }
+ }
+ }
+}
+
+// Mock implementations
+impl Mock for PersonMessage {
+ fn mock() -> Self {
+ Self {
+ id: Uuid::nil(),
+ team_id: 1,
+ properties: r#"{"email":"[email protected]"}"#.to_string(),
+ version: 1,
+ is_deleted: 0,
+ }
+ }
+}
+
+impl Mock for DistinctIdMessage {
+ fn mock() -> Self {
+ Self {
+ person_id: Uuid::nil(),
+ team_id: 1,
+ distinct_id: "test_distinct_id".to_string(),
+ version: 1,
+ is_deleted: 0,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::mock;
+
+ #[test]
+ fn test_person_message_deserialize() {
+ let json = r#"{
+ "id": "00000000-0000-0000-0000-000000000001",
+ "team_id": 42,
+ "properties": "{\"email\":\"[email protected]\"}",
+ "version": 5,
+ "is_deleted": 0
+ }"#;
+ let msg: PersonMessage = serde_json::from_str(json).unwrap();
+ assert_eq!(msg.team_id, 42);
+ assert_eq!(msg.version, 5);
+ assert_eq!(msg.is_deleted, 0);
+ }
+
+ #[test]
+ fn test_person_message_deserialize_missing_is_deleted() {
+ let json = r#"{
+ "id": "00000000-0000-0000-0000-000000000001",
+ "team_id": 42,
+ "properties": "{}",
+ "version": 5
+ }"#;
+ let msg: PersonMessage = serde_json::from_str(json).unwrap();
+ assert_eq!(msg.is_deleted, 0);
+ }
+
+ #[test]
+ fn test_distinct_id_message_deserialize() {
+ let json = r#"{
+ "person_id": "00000000-0000-0000-0000-000000000002",
+ "team_id": 42,
+ "distinct_id": "user-abc",
+ "version": 3,
+ "is_deleted": 0
+ }"#;
+ let msg: DistinctIdMessage = serde_json::from_str(json).unwrap();
+ assert_eq!(msg.distinct_id, "user-abc");
+ assert_eq!(msg.version, 3);
+ }
+
+ #[test]
+ fn test_classify_person_update() {
+ let msg = mock!(PersonMessage, team_id: 42, version: 5);
+ let event = msg.classify();
+ match event {
+ CdcEvent::PersonUpdate {
+ team_id, version, ..
+ } => {
+ assert_eq!(team_id, 42);
+ assert_eq!(version, 5);
+ }
+ _ => panic!("expected PersonUpdate"),
+ }
+ }
+
+ #[test]
+ fn test_classify_person_deletion() {
+ let msg = mock!(PersonMessage, is_deleted: 1, version: 105);
+ let event = msg.classify();
+ match event {
+ CdcEvent::PersonDeletion { version, .. } => {
+ assert_eq!(version, 105);
+ }
+ _ => panic!("expected PersonDeletion"),
+ }
+ }
+
+ #[test]
+ fn test_classify_person_malformed_properties() {
+ let msg = mock!(PersonMessage, properties: "not valid json".to_string());
+ let event = msg.classify();
+ match event {
+ CdcEvent::PersonUpdate { properties, .. } => {
+ assert_eq!(properties, serde_json::Value::Null);
+ }
+ _ => panic!("expected PersonUpdate"),
+ }
+ }
+
+ #[test]
+ fn test_classify_distinct_id_assignment() {
+ let msg = mock!(DistinctIdMessage, distinct_id: "user-xyz".to_string(), version: 7);
+ let event = msg.classify();
+ match event {
+ CdcEvent::DistinctIdAssignment {
+ distinct_id,
+ version,
+ ..
+ } => {
+ assert_eq!(&*distinct_id, "user-xyz");
+ assert_eq!(version, 7);
+ }
+ _ => panic!("expected DistinctIdAssignment"),
+ }
+ }
+
+ #[test]
+ fn test_classify_distinct_id_deletion() {
+ let msg = mock!(DistinctIdMessage, is_deleted: 1, version: 3);
+ let event = msg.classify();
+ match event {
+ CdcEvent::DistinctIdDeletion { version, .. } => {
+ assert_eq!(version, 3);
+ }
+ _ => panic!("expected DistinctIdDeletion"),
+ }
+ }
+
+ #[test]
+ fn test_mock_person_message_defaults() {
+ let msg = mock!(PersonMessage);
+ assert_eq!(msg.team_id, 1);
+ assert_eq!(msg.version, 1);
+ assert_eq!(msg.is_deleted, 0);
+ assert_eq!(msg.id, Uuid::nil());
+ }
+
+ #[test]
+ fn test_mock_person_message_overrides() {
+ let msg = mock!(PersonMessage, team_id: 99, version: 42);
+ assert_eq!(msg.team_id, 99);
+ assert_eq!(msg.version, 42);
+ assert_eq!(msg.is_deleted, 0);
+ }
+
+ #[test]
+ fn test_mock_distinct_id_message_defaults() {
+ let msg = mock!(DistinctIdMessage);
+ assert_eq!(msg.team_id, 1);
+ assert_eq!(msg.distinct_id, "test_distinct_id");
+ }
+}
diff --git a/rust/flags-consumer/src/kafka/mod.rs b/rust/flags-consumer/src/kafka/mod.rs
new file mode 100644
index 000000000000..6812b82d3ca5
--- /dev/null
+++ b/rust/flags-consumer/src/kafka/mod.rs
@@ -0,0 +1,2 @@
+pub mod consumer;
+pub mod messages;
diff --git a/rust/flags-consumer/src/lib.rs b/rust/flags-consumer/src/lib.rs
new file mode 100644
index 000000000000..7601eb49a68d
--- /dev/null
+++ b/rust/flags-consumer/src/lib.rs
@@ -0,0 +1,9 @@
+pub mod benchmark;
+pub mod config;
+pub mod kafka;
+pub mod metric_consts;
+pub mod pipeline;
+pub mod storage;
+pub mod types;
+
+pub mod utils;
diff --git a/rust/flags-consumer/src/main.rs b/rust/flags-consumer/src/main.rs
new file mode 100644
index 000000000000..26ba82c2f168
--- /dev/null
+++ b/rust/flags-consumer/src/main.rs
@@ -0,0 +1,246 @@
+use std::sync::Arc;
+use std::time::Duration;
+
+use axum::{routing::get, Router};
+use clap::{Parser, Subcommand};
+use common_database::{get_pool_with_config, PoolConfig};
+use common_kafka::kafka_consumer::SingleTopicConsumer;
+use envconfig::Envconfig;
+use lifecycle::{ComponentOptions, Manager};
+use metrics_exporter_prometheus::PrometheusBuilder;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+use tracing::level_filters::LevelFilter;
+use tracing_subscriber::fmt;
+use tracing_subscriber::layer::SubscriberExt;
+use tracing_subscriber::util::SubscriberInitExt;
+use tracing_subscriber::EnvFilter;
+
+use personhog_common::{spawn_pool_monitor, MonitoredPool};
+
+use flags_consumer::benchmark::BenchmarkArgs;
+use flags_consumer::config::Config;
+use flags_consumer::kafka::consumer::consume_loop;
+use flags_consumer::kafka::messages::{DistinctIdMessage, PersonMessage};
+use flags_consumer::pipeline::batch::batch_processor_loop;
+use flags_consumer::storage::postgres::PostgresStorage;
+
+common_alloc::used!();
+
+const POOL_NAME: &str = "flags_read_store";
+const SERVICE_NAME: &str = "flags-consumer";
+
+#[derive(Parser)]
+#[command(name = "flags-consumer")]
+struct Cli {
+ #[command(subcommand)]
+ command: Option<Command>,
+}
+
+#[derive(Subcommand)]
+enum Command {
+ /// Run the GIN index benchmark against the configured database
+ Benchmark(BenchmarkArgs),
+}
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ let cli = Cli::parse();
+
+ match cli.command {
+ Some(Command::Benchmark(args)) => {
+ tracing_subscriber::fmt::init();
+ flags_consumer::benchmark::run(args).await
+ }
+ None => {
+ let config = Config::init_from_env().expect("Invalid configuration");
+ init_tracing();
+ log_startup_config(&config);
+ run_consumer(config).await
+ }
+ }
+}
+
+async fn run_consumer(config: Config) -> anyhow::Result<()> {
+ let mut manager = Manager::builder(SERVICE_NAME).build();
+ let metrics_handle = manager.register(
+ "metrics_server",
+ ComponentOptions::new().is_observability(true),
+ );
+ let main_handle = manager.register(
+ "main",
+ ComponentOptions::new()
+ .with_graceful_shutdown(Duration::from_secs(15))
+ .with_liveness_deadline(Duration::from_secs(30)),
+ );
+ let readiness = manager.readiness_handler();
+ let liveness = manager.liveness_handler();
+ let monitor = manager.monitor_background();
+
+ spawn_metrics_server(metrics_handle, readiness, liveness, config.metrics_port);
+
+ let storage = create_storage(&config).await;
+ storage
+ .ping()
+ .await
+ .expect("Startup SELECT 1 against flags_read_store failed");
+ tracing::info!("Startup SELECT 1 check succeeded");
+
+ spawn_pool_monitor(
+ vec![MonitoredPool {
+ pool: storage.pool.clone(),
+ label: POOL_NAME.to_string(),
+ max_connections: config.max_pg_connections,
+ }],
+ Duration::from_secs(config.pool_monitor_interval_secs),
+ );
+
+ // Build Kafka consumers
+ let kafka_config = config.build_kafka_config();
+ let person_consumer =
+ SingleTopicConsumer::new(kafka_config.clone(), config.build_person_consumer_config())
+ .expect("Failed to create person Kafka consumer");
+ let did_consumer =
+ SingleTopicConsumer::new(kafka_config, config.build_distinct_id_consumer_config())
+ .expect("Failed to create distinct_id Kafka consumer");
+
+ let team_filter = config.parsed_team_filter();
+ let config = Arc::new(config);
+ let (tx, rx) = mpsc::channel(config.batch_size * 4);
+ let shutdown = CancellationToken::new();
+
+ // Spawn consumer tasks
+ let person_tx = tx.clone();
+ let person_shutdown = shutdown.clone();
+ let person_filter = team_filter.clone();
+ tokio::spawn(async move {
+ consume_loop::<PersonMessage>(person_consumer, person_tx, person_filter, person_shutdown)
+ .await;
+ });
+
+ let did_shutdown = shutdown.clone();
+ let did_filter = team_filter;
+ tokio::spawn(async move {
+ consume_loop::<DistinctIdMessage>(did_consumer, tx, did_filter, did_shutdown).await;
+ });
+
+ // Spawn batch processor
+ let processor_storage = storage.clone();
+ let processor_config = config.clone();
+ let processor_shutdown = shutdown.clone();
+ tokio::spawn(async move {
+ let _guard = main_handle.process_scope();
+ batch_processor_loop(
+ rx,
+ processor_storage,
+ processor_config,
+ processor_shutdown,
+ main_handle.clone(),
+ )
+ .await;
+ });
+
+ monitor.wait().await?;
+ shutdown.cancel();
+
+ Ok(())
+}
+
+fn init_tracing() {
+ let log_layer = fmt::layer()
+ .with_target(true)
+ .with_thread_ids(true)
+ .with_level(true);
+
+ tracing_subscriber::registry()
+ .with(log_layer)
+ .with(
+ EnvFilter::builder()
+ .with_default_directive(LevelFilter::INFO.into())
+ .from_env_lossy(),
+ )
+ .init();
+}
+
+fn log_startup_config(config: &Config) {
+ tracing::info!("Starting {SERVICE_NAME} service");
+ tracing::info!(
+ person_topic = config.kafka_person_topic,
+ did_topic = config.kafka_person_distinct_id_topic,
+ consumer_group = config.kafka_consumer_group,
+ batch_size = config.batch_size,
+ metrics_port = config.metrics_port,
+ "CDC consumer configuration"
+ );
+
+ if !config.filtered_team_ids.is_empty() {
+ tracing::info!(
+ teams = config.filtered_team_ids,
+ "Team filter active (only processing listed teams)"
+ );
+ }
+}
+
+async fn create_storage(config: &Config) -> Arc<PostgresStorage> {
+ let pool_config = PoolConfig {
+ min_connections: config.min_pg_connections,
+ max_connections: config.max_pg_connections,
+ acquire_timeout: config.acquire_timeout(),
+ idle_timeout: config.idle_timeout(),
+ test_before_acquire: true,
+ statement_timeout_ms: config.statement_timeout(),
+ pool_name: Some(POOL_NAME.to_string()),
+ };
+
+ let pool = get_pool_with_config(&config.flags_read_store_database_url, pool_config)
+ .expect("Failed to create flags_read_store database pool");
+ tracing::info!("Created flags_read_store database pool");
+
+ Arc::new(PostgresStorage::new(pool))
+}
+
+fn spawn_metrics_server(
+ handle: lifecycle::Handle,
+ readiness: lifecycle::ReadinessHandler,
+ liveness: lifecycle::LivenessHandler,
+ port: u16,
+) {
+ tokio::spawn(async move {
+ let _guard = handle.process_scope();
+
+ let health_router = Router::new()
+ .route(
+ "/_readiness",
+ get(move || {
+ let r = readiness.clone();
+ async move { r.check().await }
+ }),
+ )
+ .route("/_liveness", get(move || async move { liveness.check() }));
+
+ const BUCKETS: &[f64] = &[
+ 1.0, 5.0, 10.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0,
+ ];
+ let recorder_handle = PrometheusBuilder::new()
+ .add_global_label("service", SERVICE_NAME)
+ .set_buckets(BUCKETS)
+ .unwrap()
+ .install_recorder()
+ .expect("Failed to install metrics recorder");
+
+ let router = health_router.route(
+ "/metrics",
+ get(move || std::future::ready(recorder_handle.render())),
+ );
+
+ let bind = format!("0.0.0.0:{port}");
+ let listener = tokio::net::TcpListener::bind(&bind)
+ .await
+ .expect("Failed to bind metrics port");
+ tracing::info!("Metrics server listening on {}", bind);
+ axum::serve(listener, router)
+ .with_graceful_shutdown(handle.shutdown_signal())
+ .await
+ .expect("Metrics server error");
+ });
+}
diff --git a/rust/flags-consumer/src/metric_consts.rs b/rust/flags-consumer/src/metric_consts.rs
new file mode 100644
index 000000000000..b26c122fd9de
--- /dev/null
+++ b/rust/flags-consumer/src/metric_consts.rs
@@ -0,0 +1,14 @@
+pub const MESSAGES_RECEIVED: &str = "flags_consumer_messages_received_total";
+pub const MESSAGES_PROCESSED: &str = "flags_consumer_messages_processed_total";
+pub const MESSAGES_FILTERED: &str = "flags_consumer_messages_filtered_total";
+pub const MESSAGES_SKIPPED: &str = "flags_consumer_messages_skipped_total";
+
+pub const BATCH_SIZE: &str = "flags_consumer_batch_size";
+pub const BATCH_PROCESS_DURATION_MS: &str = "flags_consumer_batch_process_duration_ms";
+
+pub const DB_QUERY_DURATION_MS: &str = "flags_consumer_db_query_duration_ms";
+pub const DB_RETRIES: &str = "flags_consumer_db_retries_total";
+pub const DB_ERRORS: &str = "flags_consumer_db_errors_total";
+
+pub const KAFKA_ERRORS: &str = "flags_consumer_kafka_errors_total";
+pub const HEARTBEAT_WRITES: &str = "flags_consumer_heartbeat_writes_total";
diff --git a/rust/flags-consumer/src/pipeline/batch.rs b/rust/flags-consumer/src/pipeline/batch.rs
new file mode 100644
index 000000000000..a057da0e05b2
--- /dev/null
+++ b/rust/flags-consumer/src/pipeline/batch.rs
@@ -0,0 +1,175 @@
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::Duration;
+
+use common_kafka::kafka_consumer::Offset;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use crate::config::Config;
+use crate::metric_consts;
+use crate::pipeline::processor;
+use crate::storage::postgres::PostgresStorage;
+use crate::types::CdcEvent;
+
+/// Interns topic name strings so `HeartbeatState` key lookups don't
+/// allocate on every message.
+struct TopicInterns(HashMap<Box<str>, Arc<str>>);
+
+impl TopicInterns {
+ fn new() -> Self {
+ Self(HashMap::new())
+ }
+
+ fn get(&mut self, topic: &str) -> Arc<str> {
+ if let Some(arc) = self.0.get(topic) {
+ return Arc::clone(arc);
+ }
+ let arc: Arc<str> = Arc::from(topic);
+ self.0.insert(Box::from(topic), Arc::clone(&arc));
+ arc
+ }
+}
+
+pub struct EventWithOffset {
+ pub event: CdcEvent,
+ pub offset: Offset,
+}
+
+/// Highest offset seen per (topic, partition). Used for periodic heartbeat writes.
+type HeartbeatState = HashMap<(Arc<str>, i32), i64>;
+
+/// Accumulates events into batches, flushing on size or timeout.
+/// Also writes periodic heartbeat records for lag monitoring.
+pub async fn batch_processor_loop(
+ mut rx: mpsc::Receiver<EventWithOffset>,
+ storage: Arc<PostgresStorage>,
+ config: Arc<Config>,
+ shutdown: CancellationToken,
+ liveness_handle: lifecycle::Handle,
+) {
+ let mut batch: Vec<EventWithOffset> = Vec::with_capacity(config.batch_size);
+ let mut batch_timer = tokio::time::interval(config.batch_timeout());
+ let mut heartbeat_timer =
+ tokio::time::interval(Duration::from_secs(config.heartbeat_interval_secs));
+ let mut heartbeat_state: HeartbeatState = HashMap::new();
+ let mut topic_interns = TopicInterns::new();
+
+ batch_timer.tick().await;
+ heartbeat_timer.tick().await;
+
+ loop {
+ tokio::select! {
+ biased;
+
+ _ = shutdown.cancelled() => {
+ tracing::info!("batch processor shutting down, flushing final batch");
+ if !batch.is_empty() {
+ flush_batch(&mut batch, &storage, &config, &mut heartbeat_state, &mut topic_interns).await;
+ }
+ flush_heartbeats(&storage, &heartbeat_state).await;
+ break;
+ }
+
+ _ = batch_timer.tick() => {
+ if !batch.is_empty() {
+ flush_batch(&mut batch, &storage, &config, &mut heartbeat_state, &mut topic_interns).await;
+ }
+ liveness_handle.report_healthy();
+ }
+
+ _ = heartbeat_timer.tick() => {
+ flush_heartbeats(&storage, &heartbeat_state).await;
+ }
+
+ msg = rx.recv() => {
+ match msg {
+ Some(item) => {
+ track_heartbeat(&item.offset, &mut heartbeat_state, &mut topic_interns);
+
+ batch.push(item);
+ if batch.len() >= config.batch_size {
+ flush_batch(&mut batch, &storage, &config, &mut heartbeat_state, &mut topic_interns).await;
+ liveness_handle.report_healthy();
+ }
+ }
+ None => {
+ tracing::info!("channel closed, flushing remaining batch");
+ if !batch.is_empty() {
+ flush_batch(&mut batch, &storage, &config, &mut heartbeat_state, &mut topic_interns).await;
+ }
+ flush_heartbeats(&storage, &heartbeat_state).await;
+ break;
+ }
+ }
+ }
+ }
+ }
+}
+
+/// Update the heartbeat high-watermark for the given offset's (topic, partition).
+fn track_heartbeat(offset: &Offset, state: &mut HeartbeatState, interns: &mut TopicInterns) {
+ let topic = interns.get(offset.topic());
+ let partition = offset.partition();
+ let value = offset.get_value();
+ state
+ .entry((topic, partition))
+ .and_modify(|stored| {
+ if value > *stored {
+ *stored = value;
+ }
+ })
+ .or_insert(value);
+}
+
+/// Flush the batch: drain events into the processor, then store offsets.
+/// `drain(..)` preserves the vec's allocation for the next batch.
+///
+/// Offsets are only stored when the batch writes succeed. On failure the
+/// offsets are dropped, so Kafka will redeliver those messages on restart.
+async fn flush_batch(
+ batch: &mut Vec<EventWithOffset>,
+ storage: &PostgresStorage,
+ config: &Config,
+ heartbeat_state: &mut HeartbeatState,
+ topic_interns: &mut TopicInterns,
+) {
+ let batch_len = batch.len();
+ metrics::histogram!(metric_consts::BATCH_SIZE).record(batch_len as f64);
+
+ match processor::process_batch(batch.drain(..), batch_len, storage, config).await {
+ Ok(offsets) => {
+ for offset in offsets {
+ track_heartbeat(&offset, heartbeat_state, topic_interns);
+
+ if let Err(e) = offset.store() {
+ tracing::warn!(error = %e, "failed to store offset");
+ }
+ }
+ }
+ Err(e) => {
+ tracing::error!(
+ batch_size = batch_len,
+ error = %e,
+ "batch write failed, offsets not committed — will reprocess on restart"
+ );
+ }
+ }
+}
+
+/// Write heartbeat records for all tracked (source, partition) pairs.
+async fn flush_heartbeats(storage: &PostgresStorage, state: &HeartbeatState) {
+ for ((source, partition), offset) in state {
+ if let Err(e) = storage
+ .write_heartbeat(source, *partition, *offset, None)
+ .await
+ {
+ tracing::warn!(
+ source = &**source,
+ partition,
+ error = %e,
+ "failed to write heartbeat"
+ );
+ }
+ }
+}
diff --git a/rust/flags-consumer/src/pipeline/mod.rs b/rust/flags-consumer/src/pipeline/mod.rs
new file mode 100644
index 000000000000..28a05a459b4c
--- /dev/null
+++ b/rust/flags-consumer/src/pipeline/mod.rs
@@ -0,0 +1,2 @@
+pub mod batch;
+pub mod processor;
diff --git a/rust/flags-consumer/src/pipeline/processor.rs b/rust/flags-consumer/src/pipeline/processor.rs
new file mode 100644
index 000000000000..016c1762baf3
--- /dev/null
+++ b/rust/flags-consumer/src/pipeline/processor.rs
@@ -0,0 +1,205 @@
+use std::future::Future;
+use std::time::Duration;
+
+use anyhow::Context;
+use common_database::is_transient_error;
+use common_kafka::kafka_consumer::Offset;
+
+use crate::config::Config;
+use crate::metric_consts;
+use crate::pipeline::batch::EventWithOffset;
+use crate::storage::postgres::PostgresStorage;
+use crate::storage::types::{
+ DistinctIdAssignmentData, DistinctIdDeletionData, PersonDeletionData, PersonUpdateData,
+};
+use crate::types::CdcEvent;
+
+/// Classify events into operation types, execute DB writes, return offsets.
+///
+/// Returns offsets only on success — the caller stores them to advance
+/// the consumer group. On failure, offsets are dropped so Kafka redelivers
+/// the batch on restart.
+pub async fn process_batch(
+ items: impl Iterator<Item = EventWithOffset>,
+ size_hint: usize,
+ storage: &PostgresStorage,
+ config: &Config,
+) -> anyhow::Result<Vec<Offset>> {
+ let start = std::time::Instant::now();
+
+ let mut offsets = Vec::with_capacity(size_hint);
+ let mut person_updates: Vec<PersonUpdateData> = Vec::new();
+ let mut person_deletions: Vec<PersonDeletionData> = Vec::new();
+ let mut did_assignments: Vec<DistinctIdAssignmentData> = Vec::new();
+ let mut did_deletions: Vec<DistinctIdDeletionData> = Vec::new();
+
+ for item in items {
+ offsets.push(item.offset);
+ match item.event {
+ CdcEvent::PersonUpdate {
+ team_id,
+ person_uuid,
+ properties,
+ version,
+ } => {
+ person_updates.push(PersonUpdateData {
+ team_id,
+ person_uuid,
+ properties,
+ version,
+ });
+ }
+ CdcEvent::PersonDeletion {
+ team_id,
+ person_uuid,
+ version,
+ } => {
+ person_deletions.push(PersonDeletionData {
+ team_id,
+ person_uuid,
+ version,
+ });
+ }
+ CdcEvent::DistinctIdAssignment {
+ team_id,
+ person_uuid,
+ distinct_id,
+ version,
+ } => {
+ did_assignments.push(DistinctIdAssignmentData {
+ team_id,
+ person_uuid,
+ distinct_id,
+ version,
+ });
+ }
+ CdcEvent::DistinctIdDeletion {
+ team_id,
+ person_uuid,
+ distinct_id,
+ version,
+ } => {
+ did_deletions.push(DistinctIdDeletionData {
+ team_id,
+ person_uuid,
+ distinct_id,
+ version,
+ });
+ }
+ }
+ }
+
+ let result = execute_writes(
+ storage,
+ config,
+ &person_updates,
+ &person_deletions,
+ &did_assignments,
+ &did_deletions,
+ )
+ .await;
+
+ let elapsed_ms = start.elapsed().as_millis() as f64;
+ metrics::histogram!(metric_consts::BATCH_PROCESS_DURATION_MS).record(elapsed_ms);
+
+ result?;
+
+ tracing::debug!(batch_size = offsets.len(), "batch processed successfully");
+ Ok(offsets)
+}
+
+/// Execute storage writes: person upserts/deletes (batched via UNNEST),
+/// then distinct-ID assignments/deletes (individual transactions).
+async fn execute_writes(
+ storage: &PostgresStorage,
+ config: &Config,
+ person_updates: &[PersonUpdateData],
+ person_deletions: &[PersonDeletionData],
+ did_assignments: &[DistinctIdAssignmentData],
+ did_deletions: &[DistinctIdDeletionData],
+) -> anyhow::Result<()> {
+ if !person_updates.is_empty() {
+ with_retry(config, || storage.batch_upsert_persons(person_updates)).await?;
+ metrics::counter!(
+ metric_consts::MESSAGES_PROCESSED,
+ "operation" => "person_upsert"
+ )
+ .increment(person_updates.len() as u64);
+ }
+
+ if !person_deletions.is_empty() {
+ with_retry(config, || storage.batch_delete_persons(person_deletions)).await?;
+ metrics::counter!(
+ metric_consts::MESSAGES_PROCESSED,
+ "operation" => "person_delete"
+ )
+ .increment(person_deletions.len() as u64);
+ }
+
+ for assignment in did_assignments {
+ with_retry(config, || storage.upsert_distinct_id(assignment)).await?;
+ }
+ if !did_assignments.is_empty() {
+ metrics::counter!(
+ metric_consts::MESSAGES_PROCESSED,
+ "operation" => "did_assign"
+ )
+ .increment(did_assignments.len() as u64);
+ }
+
+ for deletion in did_deletions {
+ with_retry(config, || storage.delete_distinct_id(deletion)).await?;
+ }
+ if !did_deletions.is_empty() {
+ metrics::counter!(
+ metric_consts::MESSAGES_PROCESSED,
+ "operation" => "did_delete"
+ )
+ .increment(did_deletions.len() as u64);
+ }
+
+ Ok(())
+}
+
+/// Retry with exponential backoff on transient DB errors (SQLSTATE-classified).
+async fn with_retry<F, Fut, T>(config: &Config, f: F) -> anyhow::Result<T>
+where
+ F: Fn() -> Fut,
+ Fut: Future<Output = Result<T, sqlx::Error>>,
+{
+ let mut attempt = 0u32;
+ loop {
+ match f().await {
+ Ok(v) => return Ok(v),
+ Err(e) if is_transient_error(&e) && attempt < config.max_retries => {
+ attempt += 1;
+ let backoff =
+ Duration::from_millis(config.retry_backoff_base_ms * 2u64.pow(attempt - 1));
+ tracing::warn!(
+ attempt,
+ max = config.max_retries,
+ backoff_ms = backoff.as_millis() as u64,
+ error = %e,
+ "transient DB error, retrying"
+ );
+ metrics::counter!(metric_consts::DB_RETRIES).increment(1);
+ tokio::time::sleep(backoff).await;
+ }
+ Err(e) => {
+ let transient = is_transient_error(&e);
+ metrics::counter!(
+ metric_consts::DB_ERRORS,
+ "transient" => if transient { "true" } else { "false" }
+ )
+ .increment(1);
+
+ if transient {
+ return Err(e).with_context(|| {
+ format!("retries exhausted after {} attempts", attempt + 1)
+ });
+ }
+ return Err(e.into());
+ }
+ }
+ }
+}
diff --git a/rust/flags-consumer/src/storage/mod.rs b/rust/flags-consumer/src/storage/mod.rs
new file mode 100644
index 000000000000..f3098ed3c64e
--- /dev/null
+++ b/rust/flags-consumer/src/storage/mod.rs
@@ -0,0 +1,2 @@
+pub mod postgres;
+pub mod types;
diff --git a/rust/flags-consumer/src/storage/postgres.rs b/rust/flags-consumer/src/storage/postgres.rs
new file mode 100644
index 000000000000..70aeec0f035e
--- /dev/null
+++ b/rust/flags-consumer/src/storage/postgres.rs
@@ -0,0 +1,240 @@
+use std::sync::LazyLock;
+
+use chrono::{DateTime, Utc};
+use sqlx::postgres::PgPool;
+use uuid::Uuid;
+
+use crate::metric_consts;
+use crate::storage::types::{
+ DistinctIdAssignmentData, DistinctIdDeletionData, PersonDeletionData, PersonUpdateData,
+};
+
+static LABELS_PERSON_UPSERT: LazyLock<[(String, String); 1]> =
+ LazyLock::new(|| [("operation".to_string(), "person_upsert".to_string())]);
+static LABELS_PERSON_DELETE: LazyLock<[(String, String); 1]> =
+ LazyLock::new(|| [("operation".to_string(), "person_delete".to_string())]);
+static LABELS_DID_ASSIGN: LazyLock<[(String, String); 1]> =
+ LazyLock::new(|| [("operation".to_string(), "did_assign".to_string())]);
+static LABELS_DID_DELETE: LazyLock<[(String, String); 1]> =
+ LazyLock::new(|| [("operation".to_string(), "did_delete".to_string())]);
+static LABELS_HEARTBEAT: LazyLock<[(String, String); 1]> =
+ LazyLock::new(|| [("operation".to_string(), "heartbeat".to_string())]);
+
+/// PostgreSQL handle for the dedicated `flags_read_store` database.
+pub struct PostgresStorage {
+ pub pool: PgPool,
+}
+
+impl PostgresStorage {
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+
+ /// Startup connectivity check.
+ pub async fn ping(&self) -> Result<(), sqlx::Error> {
+ sqlx::query_scalar::<_, i32>("SELECT 1")
+ .fetch_one(&self.pool)
+ .await
+ .map(|_| ())
+ }
+
+ /// Batch-upsert person properties via UNNEST.
+ /// Version guard: only newer versions overwrite existing rows.
+ pub async fn batch_upsert_persons(
+ &self,
+ updates: &[PersonUpdateData],
+ ) -> Result<u64, sqlx::Error> {
+ if updates.is_empty() {
+ return Ok(0);
+ }
+
+ let _timer = common_metrics::timing_guard(
+ metric_consts::DB_QUERY_DURATION_MS,
+ &*LABELS_PERSON_UPSERT,
+ );
+
+ let team_ids: Vec<i32> = updates.iter().map(|u| u.team_id).collect();
+ let person_uuids: Vec<Uuid> = updates.iter().map(|u| u.person_uuid).collect();
+ let properties: Vec<serde_json::Value> =
+ updates.iter().map(|u| u.properties.clone()).collect();
+ let versions: Vec<i64> = updates.iter().map(|u| u.version).collect();
+
+ let result = sqlx::query(
+ r#"
+ INSERT INTO flags_person_lookup (team_id, person_uuid, properties, person_version)
+ SELECT * FROM UNNEST($1::int[], $2::uuid[], $3::jsonb[], $4::bigint[])
+ ON CONFLICT (team_id, person_uuid) DO UPDATE SET
+ properties = EXCLUDED.properties,
+ person_version = EXCLUDED.person_version,
+ deleted_at = NULL
+ WHERE flags_person_lookup.person_version < EXCLUDED.person_version
+ "#,
+ )
+ .bind(&team_ids)
+ .bind(&person_uuids)
+ .bind(&properties)
+ .bind(&versions)
+ .execute(&self.pool)
+ .await?;
+
+ Ok(result.rows_affected())
+ }
+
+ /// Soft-delete: keep the row so the upsert's version guard can still
+ /// reject stale `PersonUpdate` messages arriving after the delete.
+ /// The incoming version includes a +100 bump from the producer for deletions.
+ /// `distinct_ids` is cleared so the GIN index can't surface tombstoned rows.
+ pub async fn batch_delete_persons(
+ &self,
+ deletions: &[PersonDeletionData],
+ ) -> Result<u64, sqlx::Error> {
+ if deletions.is_empty() {
+ return Ok(0);
+ }
+
+ let _timer = common_metrics::timing_guard(
+ metric_consts::DB_QUERY_DURATION_MS,
+ &*LABELS_PERSON_DELETE,
+ );
+
+ let team_ids: Vec<i32> = deletions.iter().map(|d| d.team_id).collect();
+ let person_uuids: Vec<Uuid> = deletions.iter().map(|d| d.person_uuid).collect();
+ let versions: Vec<i64> = deletions.iter().map(|d| d.version).collect();
+
+ let result = sqlx::query(
+ r#"
+ INSERT INTO flags_person_lookup
+ (team_id, person_uuid, distinct_ids, properties, person_version, deleted_at)
+ SELECT team_id, person_uuid, ARRAY[]::text[], '{}'::jsonb, version, NOW()
+ FROM UNNEST($1::int[], $2::uuid[], $3::bigint[])
+ AS t(team_id, person_uuid, version)
+ ON CONFLICT (team_id, person_uuid) DO UPDATE SET
+ distinct_ids = ARRAY[]::text[],
+ properties = '{}'::jsonb,
+ person_version = EXCLUDED.person_version,
+ deleted_at = NOW()
+ WHERE flags_person_lookup.person_version < EXCLUDED.person_version
+ "#,
+ )
+ .bind(&team_ids)
+ .bind(&person_uuids)
+ .bind(&versions)
+ .execute(&self.pool)
+ .await?;
+
+ Ok(result.rows_affected())
+ }
+
+ /// Assign a distinct_id to a person within a transaction.
+ /// Removes it from any previous owner first (handles person merges).
+ pub async fn upsert_distinct_id(
+ &self,
+ assignment: &DistinctIdAssignmentData,
+ ) -> Result<(), sqlx::Error> {
+ let _timer =
+ common_metrics::timing_guard(metric_consts::DB_QUERY_DURATION_MS, &*LABELS_DID_ASSIGN);
+
+ let mut tx = self.pool.begin().await?;
+
+ sqlx::query(
+ r#"
+ UPDATE flags_person_lookup
+ SET distinct_ids = array_remove(distinct_ids, $1)
+ WHERE team_id = $2
+ AND distinct_ids @> ARRAY[$1]::text[]
+ AND person_uuid != $3
+ "#,
+ )
+ .bind(&*assignment.distinct_id)
+ .bind(assignment.team_id)
+ .bind(assignment.person_uuid)
+ .execute(&mut *tx)
+ .await?;
+
+ sqlx::query(
+ r#"
+ INSERT INTO flags_person_lookup (team_id, person_uuid, distinct_ids, distinct_id_version)
+ VALUES ($1, $2, ARRAY[$3]::text[], $4)
+ ON CONFLICT (team_id, person_uuid) DO UPDATE SET
+ distinct_ids = CASE
+ WHEN $3 = ANY(flags_person_lookup.distinct_ids)
+ THEN flags_person_lookup.distinct_ids
+ ELSE flags_person_lookup.distinct_ids || $3
+ END,
+ distinct_id_version = GREATEST(flags_person_lookup.distinct_id_version, $4)
+ WHERE flags_person_lookup.deleted_at IS NULL
+ AND (flags_person_lookup.distinct_id_version < $4
+ OR NOT ($3 = ANY(flags_person_lookup.distinct_ids)))
+ "#,
+ )
+ .bind(assignment.team_id)
+ .bind(assignment.person_uuid)
+ .bind(&*assignment.distinct_id)
+ .bind(assignment.version)
+ .execute(&mut *tx)
+ .await?;
+
+ tx.commit().await?;
+ Ok(())
+ }
+
+ /// Remove a distinct_id from its owner's array.
+ pub async fn delete_distinct_id(
+ &self,
+ deletion: &DistinctIdDeletionData,
+ ) -> Result<(), sqlx::Error> {
+ let _timer =
+ common_metrics::timing_guard(metric_consts::DB_QUERY_DURATION_MS, &*LABELS_DID_DELETE);
+
+ sqlx::query(
+ r#"
+ UPDATE flags_person_lookup
+ SET distinct_ids = array_remove(distinct_ids, $1),
+ distinct_id_version = GREATEST(distinct_id_version, $3)
+ WHERE team_id = $2
+ AND person_uuid = $4
+ AND $1 = ANY(distinct_ids)
+ "#,
+ )
+ .bind(&*deletion.distinct_id)
+ .bind(deletion.team_id)
+ .bind(deletion.version)
+ .bind(deletion.person_uuid)
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+
+ /// Write a heartbeat record for lag monitoring.
+ pub async fn write_heartbeat(
+ &self,
+ source: &str,
+ partition: i32,
+ offset: i64,
+ event_ts: Option<DateTime<Utc>>,
+ ) -> Result<(), sqlx::Error> {
+ let _timer =
+ common_metrics::timing_guard(metric_consts::DB_QUERY_DURATION_MS, &*LABELS_HEARTBEAT);
+
+ sqlx::query(
+ r#"
+ INSERT INTO flags_read_store_heartbeat (source, partition, last_offset, last_event_ts, updated_at)
+ VALUES ($1, $2, $3, $4, NOW())
+ ON CONFLICT (source, partition) DO UPDATE SET
+ last_offset = GREATEST(flags_read_store_heartbeat.last_offset, EXCLUDED.last_offset),
+ last_event_ts = EXCLUDED.last_event_ts,
+ updated_at = NOW()
+ "#,
+ )
+ .bind(source)
+ .bind(partition)
+ .bind(offset)
+ .bind(event_ts)
+ .execute(&self.pool)
+ .await?;
+
+ metrics::counter!(metric_consts::HEARTBEAT_WRITES).increment(1);
+ Ok(())
+ }
+}
diff --git a/rust/flags-consumer/src/storage/types.rs b/rust/flags-consumer/src/storage/types.rs
new file mode 100644
index 000000000000..2d97068aa5fb
--- /dev/null
+++ b/rust/flags-consumer/src/storage/types.rs
@@ -0,0 +1,28 @@
+use uuid::Uuid;
+
+pub struct PersonUpdateData {
+ pub team_id: i32,
+ pub person_uuid: Uuid,
+ pub properties: serde_json::Value,
+ pub version: i64,
+}
+
+pub struct PersonDeletionData {
+ pub team_id: i32,
+ pub person_uuid: Uuid,
+ pub version: i64,
+}
+
+pub struct DistinctIdAssignmentData {
+ pub team_id: i32,
+ pub person_uuid: Uuid,
+ pub distinct_id: Box<str>,
+ pub version: i64,
+}
+
+pub struct DistinctIdDeletionData {
+ pub team_id: i32,
+ pub person_uuid: Uuid,
+ pub distinct_id: Box<str>,
+ pub version: i64,
+}
diff --git a/rust/flags-consumer/src/types.rs b/rust/flags-consumer/src/types.rs
new file mode 100644
index 000000000000..d510981d73ab
--- /dev/null
+++ b/rust/flags-consumer/src/types.rs
@@ -0,0 +1,52 @@
+use uuid::Uuid;
+
+/// Internal CDC event produced by classifying a Kafka message.
+///
+/// Intentionally not `Clone` — events move through the pipeline without
+/// copying. Immutable string fields use `Box<str>`.
+#[derive(Debug)]
+pub enum CdcEvent {
+ PersonUpdate {
+ team_id: i32,
+ person_uuid: Uuid,
+ properties: serde_json::Value,
+ version: i64,
+ },
+ PersonDeletion {
+ team_id: i32,
+ person_uuid: Uuid,
+ version: i64,
+ },
+ DistinctIdAssignment {
+ team_id: i32,
+ person_uuid: Uuid,
+ distinct_id: Box<str>,
+ version: i64,
+ },
+ DistinctIdDeletion {
+ team_id: i32,
+ person_uuid: Uuid,
+ distinct_id: Box<str>,
+ version: i64,
+ },
+}
+
+impl CdcEvent {
+ pub fn team_id(&self) -> i32 {
+ match self {
+ CdcEvent::PersonUpdate { team_id, .. }
+ | CdcEvent::PersonDeletion { team_id, .. }
+ | CdcEvent::DistinctIdAssignment { team_id, .. }
+ | CdcEvent::DistinctIdDeletion { team_id, .. } => *team_id,
+ }
+ }
+
+ pub fn operation_label(&self) -> &'static str {
+ match self {
+ CdcEvent::PersonUpdate { .. } => "person_upsert",
+ CdcEvent::PersonDeletion { .. } => "person_delete",
+ CdcEvent::DistinctIdAssignment { .. } => "did_assign",
+ CdcEvent::DistinctIdDeletion { .. } => "did_delete",
+ }
+ }
+}
diff --git a/rust/flags-consumer/src/utils/mock.rs b/rust/flags-consumer/src/utils/mock.rs
new file mode 100644
index 000000000000..672a94016ef8
--- /dev/null
+++ b/rust/flags-consumer/src/utils/mock.rs
@@ -0,0 +1,96 @@
+/// Like `Default`, but for test contexts. Provides sensible test defaults
+/// (non-zero IDs, descriptive names, 100% rollout, etc.).
+///
+/// Unlike `Default`, `Mock` values are designed to be "obviously test data" --
+/// for instance, `FeatureFlag::mock()` returns a flag with `key: "test_flag"`
+/// and `active: true` rather than zero values.
+pub trait Mock {
+ fn mock() -> Self;
+}
+
+/// Create a mock of `Self` seeded from a value of type `T`.
+///
+/// Useful for converting between related types (e.g., building a
+/// `FeatureFlagRow` from a `FeatureFlag` for database insertion tests)
+/// or for ergonomic type coercions (e.g., `&str` → `Option<String>`).
+pub trait MockFrom<T> {
+ fn mock_from(value: T) -> Self;
+}
+
+/// The reciprocal of [`MockFrom`].
+pub trait MockInto<T> {
+ fn mock_into(self) -> T;
+}
+
+impl<T, U: MockFrom<T>> MockInto<U> for T {
+ fn mock_into(self) -> U {
+ U::mock_from(self)
+ }
+}
+
+impl<T> MockFrom<T> for T {
+ fn mock_from(value: T) -> Self {
+ value
+ }
+}
+
+// Primitive / standard-library conversions
+
+impl MockFrom<&str> for String {
+ fn mock_from(value: &str) -> Self {
+ value.to_owned()
+ }
+}
+
+impl<X> MockFrom<X> for Option<String>
+where
+ String: MockFrom<X>,
+{
+ fn mock_from(value: X) -> Self {
+ Some(String::mock_from(value))
+ }
+}
+
+/// Creates a mock instance of a type implementing [`Mock`], with optional field overrides.
+///
+/// # Usage
+///
+/// ```rust,ignore
+/// // No overrides -- pure defaults
+/// let flag = mock!(FeatureFlag);
+///
+/// // With field overrides
+/// let flag = mock!(FeatureFlag, team_id: 42, key: "my_flag".mock_into());
+///
+/// // Nested mocks via MockInto
+/// let flag = mock!(FeatureFlag,
+/// filters: mock!(PropertyFilter, key: "country".mock_into()).mock_into()
+/// );
+///
+/// // MockFrom -- create from another type
+/// let row = mock!(FeatureFlagRow, from: flag.clone());
+///
+/// // MockFrom with additional overrides
+/// let row = mock!(FeatureFlagRow, from: flag, key: "override".mock_into());
+/// ```
+#[macro_export]
+macro_rules! mock {
+ // No overrides
+ ($T:path) => {
+ <$T as $crate::utils::mock::Mock>::mock()
+ };
+ // MockFrom, no extra overrides (must precede the generic field-override arm)
+ ($T:path, from: $source:expr) => {
+ <$T as $crate::utils::mock::MockFrom<_>>::mock_from($source)
+ };
+ // MockFrom with field overrides
+ ($T:path, from: $source:expr, $($field:ident : $value:expr),+ $(,)?) => {{
+ let base = <$T as $crate::utils::mock::MockFrom<_>>::mock_from($source);
+ $T { $($field: $value),+, ..base }
+ }};
+ // With field overrides via struct update syntax
+ ($T:path, $($field:ident : $value:expr),+ $(,)?) => {{
+ let base = <$T as $crate::utils::mock::Mock>::mock();
+ $T { $($field: $value),+, ..base }
+ }};
+}
diff --git a/rust/flags-consumer/src/utils/mod.rs b/rust/flags-consumer/src/utils/mod.rs
new file mode 100644
index 000000000000..9afc1d5e9f71
--- /dev/null
+++ b/rust/flags-consumer/src/utils/mod.rs
@@ -0,0 +1 @@
+pub mod mock;
diff --git a/rust/flags_read_store_migrations/20260411000001_create_flags_person_lookup.sql b/rust/flags_read_store_migrations/20260411000001_create_flags_person_lookup.sql
new file mode 100644
index 000000000000..3280918bfbaf
--- /dev/null
+++ b/rust/flags_read_store_migrations/20260411000001_create_flags_person_lookup.sql
@@ -0,0 +1,60 @@
+-- One row per person, keyed on (team_id, person_uuid), with a distinct_ids TEXT[]
+-- column indexed by GIN so the flags service can replace its two-table JOIN with a
+-- single PK / GIN read. HASH-partitioned by team_id (64 partitions) to mirror the
+-- posthog_person table in the shared persons database.
+
+-- btree_gin is required so the GIN index can include the scalar team_id column
+-- alongside the distinct_ids array. A single hash partition can hold rows from
+-- multiple teams, so keeping team_id in the GIN index is necessary for selective
+-- lookups within a partition.
+CREATE EXTENSION IF NOT EXISTS btree_gin;
+
+-- `deleted_at` keeps tombstoned rows around so the upsert's version guard
+-- still has a row to compare against and can reject stale PersonUpdate
+-- messages arriving after a delete. Reads must filter `deleted_at IS NULL`.
+CREATE TABLE IF NOT EXISTS flags_person_lookup (
+ team_id INTEGER NOT NULL,
+ person_uuid UUID NOT NULL,
+ distinct_ids TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[],
+ properties JSONB NOT NULL DEFAULT '{}'::jsonb,
+ person_version BIGINT NOT NULL DEFAULT 0,
+ distinct_id_version BIGINT NOT NULL DEFAULT 0,
+ deleted_at TIMESTAMPTZ,
+ PRIMARY KEY (team_id, person_uuid)
+) PARTITION BY HASH (team_id);
+
+-- Create 64 hash partitions. This matches posthog_person's partition count so the
+-- two tables stay aligned for future bootstrap / hash key override work.
+DO $$
+DECLARE
+ num_partitions INTEGER := 64;
+ i INTEGER;
+BEGIN
+ FOR i IN 0..(num_partitions - 1) LOOP
+ EXECUTE format(
+ 'CREATE TABLE IF NOT EXISTS flags_person_lookup_p%s PARTITION OF flags_person_lookup FOR VALUES WITH (MODULUS %s, REMAINDER %s)',
+ i, num_partitions, i
+ );
+ END LOOP;
+END $$;
+
+-- GIN index on (team_id, distinct_ids), partial on live rows. Postgres propagates
+-- the index definition to every hash partition automatically. The partial predicate
+-- mirrors the read-path filter so tombstoned rows never produce GIN entries, which
+-- shrinks the index and avoids write amplification as deletions accumulate.
+CREATE INDEX IF NOT EXISTS idx_flags_person_gin
+ ON flags_person_lookup
+ USING GIN (team_id, distinct_ids)
+ WHERE deleted_at IS NULL;
+
+-- Heartbeat / lag-monitoring table. The CDC consumer will write one row per (source, partition) with
+-- the last Kafka offset / event timestamp it processed; the shadow read path will
+-- join against this for staleness checks. Table-only in Step 1; no writes yet.
+CREATE TABLE IF NOT EXISTS flags_read_store_heartbeat (
+ source TEXT NOT NULL,
+ partition INTEGER NOT NULL,
+ last_offset BIGINT NOT NULL DEFAULT 0,
+ last_event_ts TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ PRIMARY KEY (source, partition)
+);