: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cymbal): eject overloaded resolution endpoints (#61073)
Hugues Pouillotb5d9f726f88e
diff --git a/rust/cymbal-resolution/src/service/resolve.rs b/rust/cymbal-resolution/src/service/resolve.rsindex 2c81f7484ec7..febf4358aba4 100644--- a/rust/cymbal-resolution/src/service/resolve.rs+++ b/rust/cymbal-resolution/src/service/resolve.rs@@ -19,6 +19,8 @@ use crate::load_monitor::LoadMonitor;const RESOLVE_REQUEST_DURATION_MS: &str = "cymbal_remote_resolution_server_request_duration_ms";const SERVER_ERROR_KINDS: &str = "cymbal_remote_resolution_server_error_kinds_total";+const SERVER_ITEM_DURATION_MS: &str = "cymbal_remote_resolution_server_item_duration_ms";+const SERVER_ITEMS_TOTAL: &str = "cymbal_remote_resolution_server_items_total";pub(super) async fn run_resolve(mut input: Streaming<ResolveItem>,@@ -47,7 +49,10 @@ pub(super) async fn run_resolve(}};+ let item_started_at = Instant::now();+if item.deadline_ms == 0 {+ record_item_metrics(item_started_at, "error", "timeout");if !send_overloaded(&tx, item.id, "item deadline expired", 0).await {record_resolve_duration(started_at, "cancelled");return;@@ -56,6 +61,7 @@ pub(super) async fn run_resolve(}if !load_monitor.try_admit() {+ record_item_metrics(item_started_at, "error", "overloaded");if !send_overloaded(&tx, item.id, "server overloaded", 0).await {record_resolve_duration(started_at, "cancelled");return;@@ -120,39 +126,62 @@ async fn process_item(item: ResolveItem,in_flight_guard: InFlightGuard,) -> ProcessedItem {+ let started_at = Instant::now();let id = item.id;let deadline = Duration::from_millis(item.deadline_ms as u64);let _in_flight_guard = in_flight_guard;- let result = match tokio::time::timeout(deadline, resolve_item(&stage, &item)).await {- Ok(Ok(resolved)) => resolve_outcome::Result::Done(Done {- resolved_exception_json: resolved,- }),- Ok(Err(ItemFailure::InvalidPayload(msg))) => {- debug!(- id,- error = %msg,- "rejecting item with invalid payload",- );- error_result(codes::ErrorKind::InvalidPayload, msg)- }- Ok(Err(ItemFailure::Overloaded(msg))) => {- warn!(id, "limiter closed mid-request, asking caller to retry");- error_result(codes::ErrorKind::Overloaded, msg)- }- Ok(Err(ItemFailure::Unhandled(err))) => {- warn!(- id,- error = %err,- "unhandled error during resolution",- );- error_result(codes::ErrorKind::Unhandled, err)- }- Err(_) => error_result(- codes::ErrorKind::Overloaded,- "item deadline expired".to_string(),- ),- };+ let (result, outcome, kind) =+ match tokio::time::timeout(deadline, resolve_item(&stage, &item)).await {+ Ok(Ok(resolved)) => (+ resolve_outcome::Result::Done(Done {+ resolved_exception_json: resolved,+ }),+ "done",+ "ok",+ ),+ Ok(Err(ItemFailure::InvalidPayload(msg))) => {+ debug!(+ id,+ error = %msg,+ "rejecting item with invalid payload",+ );+ (+ error_result(codes::ErrorKind::InvalidPayload, msg),+ "error",+ "invalid_payload",+ )+ }+ Ok(Err(ItemFailure::Overloaded(msg))) => {+ warn!(id, "limiter closed mid-request, asking caller to retry");+ (+ error_result(codes::ErrorKind::Overloaded, msg),+ "error",+ "overloaded",+ )+ }+ Ok(Err(ItemFailure::Unhandled(err))) => {+ warn!(+ id,+ error = %err,+ "unhandled error during resolution",+ );+ (+ error_result(codes::ErrorKind::Unhandled, err),+ "error",+ "unhandled",+ )+ }+ Err(_) => (+ error_result(+ codes::ErrorKind::Overloaded,+ "item deadline expired".to_string(),+ ),+ "error",+ "timeout",+ ),+ };+ record_item_metrics(started_at, outcome, kind);ProcessedItem { id, result }}@@ -181,6 +210,12 @@ fn record_resolve_duration(started_at: Instant, outcome: &'static str) {.record(started_at.elapsed().as_secs_f64() * 1000.0);}+fn record_item_metrics(started_at: Instant, outcome: &'static str, kind: &'static str) {+ metrics::counter!(SERVER_ITEMS_TOTAL, "outcome" => outcome, "kind" => kind).increment(1);+ metrics::histogram!(SERVER_ITEM_DURATION_MS, "outcome" => outcome, "kind" => kind)+ .record(started_at.elapsed().as_secs_f64() * 1000.0);+}+enum ItemFailure {InvalidPayload(String),Overloaded(String),diff --git a/rust/cymbal/README.md b/rust/cymbal/README.mdindex c08e0501321b..bbac0d91f154 100644--- a/rust/cymbal/README.md+++ b/rust/cymbal/README.md@@ -32,9 +32,16 @@ resolvers and then rejoin the same properties/grouping/linking pipeline.Backpressure is result-only on the `Resolve` stream: overload is surfaced as`ResolveOutcome.Error { kind: ERROR_KIND_OVERLOADED }`, which the cymbal client-reroutes with overload-specific backoff. `LoadEvent` is only a-freshness/draining signal for endpoint routing, not an overload or dynamic-batch-size control plane.+reroutes with overload-specific backoff. When+`CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_MS` is non-zero, the overloaded+endpoint is also excluded from new routing in that cymbal process. Repeated+overloads double the endpoint cooldown up to+`CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_MAX_MS`, and a quiet+`CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_DECAY_MS` window resets it.+`LoadEvent` is only a freshness/draining signal for endpoint routing, not an+overload or dynamic batch-size control plane. `CYMBAL_REMOTE_RESOLUTION_ROUTING_JITTER`+can probabilistically blend strict sticky routing (`0.0`) with fully random routing (`1.0`)+when hot-key distribution needs extra spread.See [`docs/compatibility.md`](docs/compatibility.md) for the Node consumercompatibility checklist and [`../cymbal-resolution/README.md`](../cymbal-resolution/README.md)diff --git a/rust/cymbal/docs/compatibility.md b/rust/cymbal/docs/compatibility.mdindex a868ec93c372..c73e7fe28d81 100644--- a/rust/cymbal/docs/compatibility.md+++ b/rust/cymbal/docs/compatibility.md@@ -29,6 +29,6 @@ No generated type changes are needed:- Unsampled events use the local exception and frame resolvers.- Sampled remote exceptions are grouped per team, flattened into `ResolveItem`s, and submitted over per-endpoint bidirectional `Resolve` streams.- Resolver-specific context is carried in `ResolveItem.metadata` as JSON bytes. The current Apple symbolication convention uses an `apple_debug_images_json` key.-- Per-item `ResolveOutcome.Error.kind` is the control-flow surface. `ERROR_KIND_OVERLOADED` is result-only backpressure and triggers item reroute; `LoadEvent` is only endpoint freshness/draining state.+- Per-item `ResolveOutcome.Error.kind` is the control-flow surface. `ERROR_KIND_OVERLOADED` is result-only backpressure and triggers item reroute. If `CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_MS` is non-zero, the overloaded endpoint is also temporarily excluded from new routing in that cymbal process. Repeated overloads double that cooldown up to `CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_MAX_MS`, and a quiet `CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_DECAY_MS` window resets it. `CYMBAL_REMOTE_RESOLUTION_ROUTING_JITTER` controls how often routing ignores the sticky rendezvous endpoint in favor of a random endpoint (`0.0` strict sticky, `1.0` fully random). `LoadEvent` is only endpoint freshness/draining state.This means Node request chunking limits protect cymbal's public HTTP body size, while cymbal's private gRPC path owns exception-level routing, reroute depth, and overload handling.diff --git a/rust/cymbal/src/config.rs b/rust/cymbal/src/config.rsindex f3c70dc8e6d0..454389f36553 100644--- a/rust/cymbal/src/config.rs+++ b/rust/cymbal/src/config.rs@@ -236,6 +236,30 @@ pub struct Config {)]pub remote_resolution_retry_max_backoff_ms: u64,+ /// Initial duration to temporarily remove an endpoint from routing after it+ /// returns a per-item overload outcome. `0` keeps the legacy per-item-only+ /// reroute behavior.+ #[envconfig(+ from = "CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_MS",+ default = "100"+ )]+ pub remote_resolution_overload_ejection_ms: u64,++ /// Maximum endpoint ejection duration after repeated overloads.+ #[envconfig(+ from = "CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_MAX_MS",+ default = "5000"+ )]+ pub remote_resolution_overload_ejection_max_ms: u64,++ /// Quiet window after which an endpoint's overload ejection duration resets+ /// to the initial value.+ #[envconfig(+ from = "CYMBAL_REMOTE_RESOLUTION_OVERLOAD_EJECTION_DECAY_MS",+ default = "30000"+ )]+ pub remote_resolution_overload_ejection_decay_ms: u64,+/// Deterministic event-level rollout sample for remote resolution./// Defaults to `0.0` so flipping `CYMBAL_REMOTE_RESOLUTION_ENABLED=true`/// alone does not start sending traffic — the rollout has to be ramped@@ -245,6 +269,12 @@ pub struct Config {#[envconfig(from = "CYMBAL_REMOTE_RESOLUTION_SAMPLE_RATE", default = "0.0")]pub remote_resolution_sample_rate: f64,+ /// Probability of routing a remote resolution item randomly instead of+ /// using sticky rendezvous routing. `0.0` is fully sticky, `1.0` is fully+ /// random, and intermediate values probabilistically blend both modes.+ #[envconfig(from = "CYMBAL_REMOTE_RESOLUTION_ROUTING_JITTER", default = "0.0")]+ pub remote_resolution_routing_jitter: f64,+/// Tick cadence hint sent on `SubscribeRequest.tick_hint_ms` to the/// cymbal-resolution freshness/draining stream. The server clamps to its own bounds/// (see cymbal-resolution `SUBSCRIBE_MIN_TICK_MS`/`SUBSCRIBE_MAX_TICK_MS`),diff --git a/rust/cymbal/src/metric_consts.rs b/rust/cymbal/src/metric_consts.rsindex 66ab6af93db4..6c92b232ae3e 100644--- a/rust/cymbal/src/metric_consts.rs+++ b/rust/cymbal/src/metric_consts.rs@@ -134,6 +134,8 @@ pub const REMOTE_RESOLUTION_REQUESTS: &str = "cymbal_remote_resolution_requests_pub const REMOTE_RESOLUTION_LATENCY: &str = "cymbal_remote_resolution_latency_ms";pub const REMOTE_RESOLUTION_SAMPLING: &str = "cymbal_remote_resolution_sampling_total";pub const REMOTE_RESOLUTION_POOL_SIZE: &str = "cymbal_remote_resolution_pool_size";+pub const REMOTE_RESOLUTION_ENDPOINTS_BY_STATE: &str =+ "cymbal_remote_resolution_endpoints_by_state";pub const REMOTE_RESOLUTION_ENDPOINT_IN_FLIGHT: &str ="cymbal_remote_resolution_endpoint_in_flight";pub const REMOTE_RESOLUTION_ENDPOINT_MUX_IN_FLIGHT: &str =diff --git a/rust/cymbal/src/stages/resolution/remote/config.rs b/rust/cymbal/src/stages/resolution/remote/config.rsindex 094d463ee0c8..bc206a37a3f1 100644--- a/rust/cymbal/src/stages/resolution/remote/config.rs+++ b/rust/cymbal/src/stages/resolution/remote/config.rs@@ -21,10 +21,19 @@ pub struct RemoteResolutionConfig {pub retry_backoff: Duration,/// Ceiling for the exponential retry backoff window.pub retry_max_backoff: Duration,+ /// Initial process-local endpoint ejection window after a per-item overload outcome.+ pub overload_ejection_initial: Duration,+ /// Maximum process-local endpoint ejection window after repeated overload outcomes.+ pub overload_ejection_max: Duration,+ /// Quiet window after which endpoint ejection backs off to the initial duration.+ pub overload_ejection_decay: Duration,/// Event-level deterministic sample rate for sending eligible events to/// cymbal-resolution. Defaults to 0.0 in [`Config`] so enabling remote mode/// alone does not start sending traffic until rollout is ramped explicitly.pub sample_rate: f64,+ /// Probability of selecting a random endpoint instead of the sticky+ /// rendezvous endpoint for a routing key.+ pub routing_jitter: f64,/// Cadence hint sent on `SubscribeRequest.tick_hint_ms`. The server may/// clamp this; the caller relies on whatever cadence the server settles on./// Doubles as the freshness window: snapshots older than `2 *@@ -66,7 +75,19 @@ impl RemoteResolutionConfig {.remote_resolution_retry_max_backoff_ms.max(config.remote_resolution_retry_backoff_ms.max(1)),),- sample_rate: normalized_sample_rate(config.remote_resolution_sample_rate),+ overload_ejection_initial: Duration::from_millis(+ config.remote_resolution_overload_ejection_ms,+ ),+ overload_ejection_max: Duration::from_millis(+ config+ .remote_resolution_overload_ejection_max_ms+ .max(config.remote_resolution_overload_ejection_ms),+ ),+ overload_ejection_decay: Duration::from_millis(+ config.remote_resolution_overload_ejection_decay_ms,+ ),+ sample_rate: normalized_probability(config.remote_resolution_sample_rate),+ routing_jitter: normalized_probability(config.remote_resolution_routing_jitter),subscribe_tick_hint: Duration::from_millis(config.remote_resolution_subscribe_tick_hint_ms.max(1),),@@ -79,22 +100,22 @@ impl RemoteResolutionConfig {}}-fn normalized_sample_rate(sample_rate: f64) -> f64 {- if !sample_rate.is_finite() {+fn normalized_probability(value: f64) -> f64 {+ if !value.is_finite() {return 1.0;}- sample_rate.clamp(0.0, 1.0)+ value.clamp(0.0, 1.0)}#[cfg(test)]mod tests {- use super::normalized_sample_rate;+ use super::normalized_probability;#[test]- fn sample_rate_is_clamped_to_valid_range() {- assert_eq!(normalized_sample_rate(-0.5), 0.0);- assert_eq!(normalized_sample_rate(0.25), 0.25);- assert_eq!(normalized_sample_rate(1.5), 1.0);- assert_eq!(normalized_sample_rate(f64::NAN), 1.0);+ fn probability_is_clamped_to_valid_range() {+ assert_eq!(normalized_probability(-0.5), 0.0);+ assert_eq!(normalized_probability(0.25), 0.25);+ assert_eq!(normalized_probability(1.5), 1.0);+ assert_eq!(normalized_probability(f64::NAN), 1.0);}}diff --git a/rust/cymbal/src/stages/resolution/remote/pool.rs b/rust/cymbal/src/stages/resolution/remote/pool.rsindex e09288fcac89..309ffa019f1f 100644--- a/rust/cymbal/src/stages/resolution/remote/pool.rs+++ b/rust/cymbal/src/stages/resolution/remote/pool.rs@@ -5,7 +5,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::{Arc, Mutex as StdMutex};use std::time::{Duration, Instant};-use rand::seq::SliceRandom;+use rand::{seq::SliceRandom, Rng};use sha2::{Digest, Sha256};use thiserror::Error;use tokio::sync::{Mutex, Notify};@@ -16,7 +16,10 @@ use super::config::RemoteResolutionConfig;use super::dns::DnsResolver;use super::mux::ResolveMux;use super::subscription::{spawn_subscription, LoadCell, LoadSnapshot, SubscriptionHandle};-use crate::metric_consts::{REMOTE_RESOLUTION_ENDPOINT_IN_FLIGHT, REMOTE_RESOLUTION_POOL_SIZE};+use crate::metric_consts::{+ REMOTE_RESOLUTION_ENDPOINTS_BY_STATE, REMOTE_RESOLUTION_ENDPOINT_IN_FLIGHT,+ REMOTE_RESOLUTION_POOL_SIZE,+};const RESOLVE_MUX_QUEUE_CAPACITY: usize = 64;@@ -25,6 +28,7 @@ pub enum EndpointPoolEmptyReason {NoEndpoints,NoFreshLoadSnapshots,AllEndpointsDraining,+ AllEndpointsEjected,}impl EndpointPoolEmptyReason {@@ -33,6 +37,7 @@ impl EndpointPoolEmptyReason {Self::NoEndpoints => "no_endpoints",Self::NoFreshLoadSnapshots => "no_fresh_load_snapshots",Self::AllEndpointsDraining => "all_endpoints_draining",+ Self::AllEndpointsEjected => "all_endpoints_ejected",}}}@@ -43,6 +48,7 @@ impl fmt::Display for EndpointPoolEmptyReason {Self::NoEndpoints => "no DNS endpoints",Self::NoFreshLoadSnapshots => "no fresh load snapshots",Self::AllEndpointsDraining => "all endpoints draining",+ Self::AllEndpointsEjected => "all endpoints ejected after overload",})}}@@ -78,6 +84,14 @@ struct EndpointState {/// Latest server-reported load snapshot. Updated by the subscription task/// when one is attached; reads on the routing path are cheap.load: LoadCell,+ /// Deadline until which this endpoint is temporarily excluded after an+ /// overload outcome. This is local to this cymbal process.+ overload_ejected_until: Option<Instant>,+ /// Current adaptive ejection duration. Repeated overloads double this up to+ /// config.overload_ejection_max; a quiet window resets it to the initial duration.+ overload_ejection_cooldown: Duration,+ /// Last time this endpoint reported overload in this cymbal process.+ overload_last_seen: Option<Instant>,/// Background task subscribing to this endpoint's freshness/draining stream. `None`/// when subscriptions are disabled (test pools constructed via/// [`EndpointPool::from_addrs_without_subscriptions`]).@@ -212,6 +226,11 @@ impl EndpointPool {inner.endpoints.insert(*addr, state);}metrics::gauge!(REMOTE_RESOLUTION_POOL_SIZE).set(inner.endpoints.len() as f64);+ record_endpoint_states(+ &inner,+ Instant::now(),+ config.subscribe_tick_hint.saturating_mul(2),+ );drop(inner);Ok(pool)}@@ -312,6 +331,11 @@ impl EndpointPool {.filter(|state| !state.draining).count();metrics::gauge!(REMOTE_RESOLUTION_POOL_SIZE).set(healthy_count as f64);+ record_endpoint_states(+ &inner,+ Instant::now(),+ self.config.subscribe_tick_hint.saturating_mul(2),+ );Ok(())}@@ -330,6 +354,46 @@ impl EndpointPool {self.select_inner(SelectionStrategy::Random, exclude).await}+ /// Temporarily remove an endpoint from routing after it returned a+ /// per-item overload outcome. The ejection is process-local, doubles on+ /// repeated overloads up to the configured max, and expires automatically+ /// on the selection path.+ pub async fn eject_overloaded(&self, addr: SocketAddr) {+ if self.config.overload_ejection_initial.is_zero() {+ return;+ }+ let now = Instant::now();+ let mut inner = self.inner.lock().await;+ if let Some(state) = inner.endpoints.get_mut(&addr) {+ let quiet = state+ .overload_last_seen+ .and_then(|last_seen| now.checked_duration_since(last_seen))+ .is_none_or(|elapsed| elapsed >= self.config.overload_ejection_decay);+ let cooldown = if quiet || state.overload_ejection_cooldown.is_zero() {+ self.config.overload_ejection_initial+ } else {+ state+ .overload_ejection_cooldown+ .saturating_mul(2)+ .min(self.config.overload_ejection_max)+ };+ let until = now + cooldown;+ state.overload_last_seen = Some(now);+ state.overload_ejection_cooldown = cooldown;+ state.overload_ejected_until = Some(until);+ warn!(+ endpoint = %addr,+ ejection_ms = cooldown.as_millis() as u64,+ "temporarily ejected overloaded remote resolution endpoint"+ );+ record_endpoint_states(+ &inner,+ now,+ self.config.subscribe_tick_hint.saturating_mul(2),+ );+ }+ }+/// Select an endpoint using rendezvous hashing for the supplied routing/// key. This keeps events that need the same symbol set sticky to one/// cymbal-resolution pod, improving warm-cache locality while still@@ -345,6 +409,9 @@ impl EndpointPool {if routing_key.is_empty() {return self.select(exclude).await;}+ if should_jitter_route(self.config.routing_jitter) {+ return self.select(exclude).await;+ }self.select_inner(SelectionStrategy::ByKey { routing_key }, exclude).await}@@ -354,7 +421,7 @@ impl EndpointPool {strategy: SelectionStrategy<'_>,exclude: &[SocketAddr],) -> Result<EndpointPoolHandle, EndpointPoolError> {- let inner = self.inner.lock().await;+ let mut inner = self.inner.lock().await;if inner.endpoints.is_empty() {return Err(EndpointPoolError::Empty(EndpointPoolEmptyReason::NoEndpoints,@@ -379,12 +446,21 @@ impl EndpointPool {// begins.let mut candidates: Vec<Candidate> = Vec::with_capacity(inner.endpoints.len());let mut active_endpoint_count = 0usize;+ let mut ejected_endpoint_count = 0usize;let mut saw_missing_or_stale_snapshot = false;- for (addr, state) in inner.endpoints.iter() {+ for (addr, state) in inner.endpoints.iter_mut() {if state.draining {continue;}active_endpoint_count += 1;+ if state+ .overload_ejected_until+ .is_some_and(|ejected_until| ejected_until > now)+ {+ ejected_endpoint_count += 1;+ continue;+ }+ state.overload_ejected_until = None;let Some(snapshot) = state.load.lock().ok().and_then(|guard| guard.clone()) else {saw_missing_or_stale_snapshot = true;continue;@@ -404,9 +480,12 @@ impl EndpointPool {});}+ record_endpoint_states(&inner, now, stale_after);+if candidates.is_empty() {return Err(EndpointPoolError::Empty(classify_empty_reason(active_endpoint_count,+ ejected_endpoint_count,saw_missing_or_stale_snapshot,)));}@@ -481,6 +560,7 @@ impl EndpointPool {return Err(EndpointPoolEmptyReason::NoEndpoints);}let mut active_endpoint_count = 0usize;+ let mut ejected_endpoint_count = 0usize;let mut saw_missing_or_stale_snapshot = false;let now = Instant::now();let stale_after = self.config.subscribe_tick_hint.saturating_mul(2);@@ -489,6 +569,13 @@ impl EndpointPool {continue;}active_endpoint_count += 1;+ if state+ .overload_ejected_until+ .is_some_and(|ejected_until| ejected_until > now)+ {+ ejected_endpoint_count += 1;+ continue;+ }let Some(snapshot) = state.load.lock().ok().and_then(|guard| guard.clone()) else {saw_missing_or_stale_snapshot = true;continue;@@ -503,6 +590,7 @@ impl EndpointPool {}Err(classify_empty_reason(active_endpoint_count,+ ejected_endpoint_count,saw_missing_or_stale_snapshot,))}@@ -543,6 +631,25 @@ impl EndpointPool {}false}++ #[cfg(test)]+ async fn expire_overload_ejection_for_test(&self, addr: SocketAddr) -> bool {+ let mut inner = self.inner.lock().await;+ let Some(state) = inner.endpoints.get_mut(&addr) else {+ return false;+ };+ state.overload_ejected_until = Some(Instant::now() - Duration::from_millis(1));+ true+ }++ #[cfg(test)]+ async fn overload_ejection_cooldown_for_test(&self, addr: SocketAddr) -> Option<Duration> {+ let inner = self.inner.lock().await;+ inner+ .endpoints+ .get(&addr)+ .map(|state| state.overload_ejection_cooldown)+ }}#[derive(Clone)]@@ -560,10 +667,13 @@ enum SelectionStrategy<'a> {fn classify_empty_reason(active_endpoint_count: usize,+ ejected_endpoint_count: usize,saw_missing_or_stale_snapshot: bool,) -> EndpointPoolEmptyReason {if active_endpoint_count == 0 {EndpointPoolEmptyReason::AllEndpointsDraining+ } else if ejected_endpoint_count == active_endpoint_count {+ EndpointPoolEmptyReason::AllEndpointsEjected} else if saw_missing_or_stale_snapshot {EndpointPoolEmptyReason::NoFreshLoadSnapshots} else {@@ -580,6 +690,92 @@ fn rendezvous_score(routing_key: &str, addr: SocketAddr) -> u64 {u64::from_be_bytes(digest[0..8].try_into().expect("sha256 digest has 8 bytes"))}+#[derive(Clone, Copy)]+enum EndpointRoutingState {+ Routable,+ Ejected,+ Draining,+ Stale,+ MissingSnapshot,+}++impl EndpointRoutingState {+ const ALL: [Self; 5] = [+ Self::Routable,+ Self::Ejected,+ Self::Draining,+ Self::Stale,+ Self::MissingSnapshot,+ ];++ fn as_metric_tag(self) -> &'static str {+ match self {+ Self::Routable => "routable",+ Self::Ejected => "ejected",+ Self::Draining => "draining",+ Self::Stale => "stale",+ Self::MissingSnapshot => "missing_snapshot",+ }+ }++ fn index(self) -> usize {+ match self {+ Self::Routable => 0,+ Self::Ejected => 1,+ Self::Draining => 2,+ Self::Stale => 3,+ Self::MissingSnapshot => 4,+ }+ }+}++fn endpoint_routing_state(+ state: &EndpointState,+ now: Instant,+ stale_after: Duration,+) -> EndpointRoutingState {+ if state.draining {+ return EndpointRoutingState::Draining;+ }+ if state+ .overload_ejected_until+ .is_some_and(|ejected_until| ejected_until > now)+ {+ return EndpointRoutingState::Ejected;+ }+ let Some(snapshot) = state.load.lock().ok().and_then(|guard| guard.clone()) else {+ return EndpointRoutingState::MissingSnapshot;+ };+ if !snapshot.is_fresh(now, stale_after) {+ return EndpointRoutingState::Stale;+ }+ if snapshot.draining {+ return EndpointRoutingState::Draining;+ }+ EndpointRoutingState::Routable+}++fn record_endpoint_states(inner: &PoolInner, now: Instant, stale_after: Duration) {+ let mut counts = [0usize; EndpointRoutingState::ALL.len()];+ for state in inner.endpoints.values() {+ counts[endpoint_routing_state(state, now, stale_after).index()] += 1;+ }+ for state in EndpointRoutingState::ALL {+ metrics::gauge!(REMOTE_RESOLUTION_ENDPOINTS_BY_STATE, "state" => state.as_metric_tag())+ .set(counts[state.index()] as f64);+ }+}++fn should_jitter_route(routing_jitter: f64) -> bool {+ if routing_jitter <= 0.0 {+ return false;+ }+ if routing_jitter >= 1.0 {+ return true;+ }+ rand::thread_rng().gen_bool(routing_jitter)+}+/// Start a background task that periodically calls [`EndpointPool::refresh`]./// Returns the join handle so callers can shut it down when needed.pub fn spawn_refresh_task(pool: Arc<EndpointPool>) -> tokio::task::JoinHandle<()> {@@ -623,6 +819,9 @@ fn build_endpoint_state(in_flight: Arc::new(AtomicUsize::new(0)),draining: false,load: Arc::new(StdMutex::new(None)),+ overload_ejected_until: None,+ overload_ejection_cooldown: Duration::ZERO,+ overload_last_seen: None,subscription: None,})}@@ -648,6 +847,10 @@ mod test {retry_backoff: Duration::from_millis(1),retry_max_backoff: Duration::from_millis(2),sample_rate: 1.0,+ routing_jitter: 0.0,+ overload_ejection_initial: Duration::ZERO,+ overload_ejection_max: Duration::ZERO,+ overload_ejection_decay: Duration::from_secs(30),subscribe_tick_hint: Duration::from_millis(50),subscribe_reconnect_backoff: Duration::from_millis(50),}@@ -862,6 +1065,34 @@ mod test {}}+ #[tokio::test]+ async fn select_for_key_uses_random_routing_when_jitter_is_full() {+ let addrs = [+ addr("10.0.0.1:50061"),+ addr("10.0.0.2:50061"),+ addr("10.0.0.3:50061"),+ ];+ let mut config = mock_config();+ config.routing_jitter = 1.0;+ let pool = EndpointPool::from_addrs_without_subscriptions(config, &addrs).unwrap();+ inject_uniform_fresh_snapshots(&pool, &addrs).await;++ let mut picks = std::collections::HashSet::new();+ for _ in 0..200 {+ picks.insert(+ pool.select_for_key("team:1:symbol:bundle-a", &[])+ .await+ .unwrap()+ .addr,+ );+ }++ assert!(+ picks.len() > 1,+ "full routing jitter should not stay sticky to one endpoint"+ );+ }+#[tokio::test]async fn select_for_key_spreads_distinct_keys_across_endpoints() {let addrs = [@@ -921,6 +1152,87 @@ mod test {assert_ne!(third, retry);}+ #[tokio::test]+ async fn overload_ejection_excludes_endpoint_across_requests_until_expiry() {+ let addrs = [+ addr("10.0.0.1:50061"),+ addr("10.0.0.2:50061"),+ addr("10.0.0.3:50061"),+ ];+ let mut config = mock_config();+ config.overload_ejection_initial = Duration::from_millis(25);+ config.overload_ejection_max = Duration::from_millis(100);+ let pool = EndpointPool::from_addrs_without_subscriptions(config, &addrs).unwrap();+ inject_uniform_fresh_snapshots(&pool, &addrs).await;++ let first = pool+ .select_for_key("team:1:symbol:bundle-a", &[])+ .await+ .unwrap()+ .addr;+ pool.eject_overloaded(first).await;++ let while_ejected = pool+ .select_for_key("team:1:symbol:bundle-a", &[])+ .await+ .unwrap()+ .addr;+ assert_ne!(while_ejected, first);++ assert_eq!(+ pool.overload_ejection_cooldown_for_test(first).await,+ Some(Duration::from_millis(25))+ );+ assert!(pool.expire_overload_ejection_for_test(first).await);+ let after_expiry = pool+ .select_for_key("team:1:symbol:bundle-a", &[])+ .await+ .unwrap()+ .addr;+ assert_eq!(after_expiry, first);++ pool.eject_overloaded(first).await;+ assert_eq!(+ pool.overload_ejection_cooldown_for_test(first).await,+ Some(Duration::from_millis(50))+ );+ let after_initial_duration = pool+ .select_for_key("team:1:symbol:bundle-a", &[])+ .await+ .unwrap()+ .addr;+ assert_ne!(after_initial_duration, first);++ assert!(pool.expire_overload_ejection_for_test(first).await);+ let after_doubled_duration = pool+ .select_for_key("team:1:symbol:bundle-a", &[])+ .await+ .unwrap()+ .addr;+ assert_eq!(after_doubled_duration, first);+ }++ #[tokio::test]+ async fn select_reports_all_ejected_when_every_endpoint_is_in_cooldown() {+ let addrs = [addr("10.0.0.1:50061"), addr("10.0.0.2:50061")];+ let mut config = mock_config();+ config.overload_ejection_initial = Duration::from_secs(1);+ config.overload_ejection_max = Duration::from_secs(1);+ let pool = EndpointPool::from_addrs_without_subscriptions(config, &addrs).unwrap();+ inject_uniform_fresh_snapshots(&pool, &addrs).await;++ for addr in addrs {+ pool.eject_overloaded(addr).await;+ }++ assert!(matches!(+ pool.select(&[]).await,+ Err(EndpointPoolError::Empty(+ EndpointPoolEmptyReason::AllEndpointsEjected+ ))+ ));+ }+#[tokio::test]async fn select_for_key_excludes_draining_endpoints() {let addrs = [addr("10.0.0.1:50061"), addr("10.0.0.2:50061")];diff --git a/rust/cymbal/src/stages/resolution/remote/resolver/retry.rs b/rust/cymbal/src/stages/resolution/remote/resolver/retry.rsindex 2940ffe1502b..881a46b46fa9 100644--- a/rust/cymbal/src/stages/resolution/remote/resolver/retry.rs+++ b/rust/cymbal/src/stages/resolution/remote/resolver/retry.rs@@ -153,6 +153,7 @@ pub(super) async fn resolve_work_item(attempt,"remote resolution returned item overload; rerouting with overload policy");+ ctx.pool.eject_overloaded(endpoint).await;excluded_endpoints.push(endpoint);last_error = Some(format!("per-item Overloaded outcome from {endpoint}: {message}"diff --git a/rust/cymbal/tests/common/mod.rs b/rust/cymbal/tests/common/mod.rsindex c4fe6051312f..988b2eb8bdd2 100644--- a/rust/cymbal/tests/common/mod.rs+++ b/rust/cymbal/tests/common/mod.rs@@ -321,6 +321,10 @@ pub fn make_config_with_sample_rate(retry_backoff: Duration::from_millis(1),retry_max_backoff: Duration::from_millis(2),sample_rate,+ routing_jitter: 0.0,+ overload_ejection_initial: Duration::ZERO,+ overload_ejection_max: Duration::ZERO,+ overload_ejection_decay: Duration::from_secs(30),// Subscription cadence is irrelevant for tests that don't wire the// subscription client — kept short so tests that do consume it run// quickly when they opt in via a dedicated pool builder.diff --git a/rust/cymbal/tests/remote_resolution_subscribe.rs b/rust/cymbal/tests/remote_resolution_subscribe.rsindex df9aaa319916..99515d71b95a 100644--- a/rust/cymbal/tests/remote_resolution_subscribe.rs+++ b/rust/cymbal/tests/remote_resolution_subscribe.rs@@ -120,6 +120,10 @@ fn pool_config(host: &str, tick_hint: Duration) -> RemoteResolutionConfig {retry_backoff: Duration::from_millis(1),retry_max_backoff: Duration::from_millis(2),sample_rate: 1.0,+ routing_jitter: 0.0,+ overload_ejection_initial: Duration::ZERO,+ overload_ejection_max: Duration::ZERO,+ overload_ejection_decay: Duration::from_secs(30),subscribe_tick_hint: tick_hint,subscribe_reconnect_backoff: Duration::from_millis(20),}