Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
fix(scheduler): reuse redis consumer across polls (#13690)
Abhinav Sharmaba71bc66abfa
diff --git a/crates/redis_interface/src/test.rs b/crates/redis_interface/src/test.rsindex 2c8621f684..67e08c3eeb 100644--- a/crates/redis_interface/src/test.rs+++ b/crates/redis_interface/src/test.rs@@ -1754,6 +1754,99 @@ async fn test_consumer_group_set_last_id() {assert!(is_success);}+/// Characterises the `XREADGROUP` behaviour that the scheduler consumer fix+/// (juspay/hyperswitch#13628) relies on: `XREADGROUP` registers its consumer in the group+/// as a side effect of the read, even when there are no new entries to deliver, and Redis+/// never expires these registrations on its own. A caller that generates a fresh consumer+/// name on every poll therefore grows the consumer group without bound, while one that+/// reuses a stable name does not.+///+/// This pins Redis' behaviour, not the scheduler change itself — it passes with or without+/// the `crates/scheduler` fix. Both halves are asserted so it cannot go vacuous: were a+/// future Redis to stop registering consumers on an empty read, the rotating-name case+/// would drop to 0 and fail here rather than silently making the stable case trivial.+#[tokio::test]+async fn test_xreadgroup_consumer_registration_tracks_consumer_name() {+ let (stable_consumers, rotating_consumers) = tokio::task::spawn_blocking(move || {+ futures::executor::block_on(async {+ let pool = test_connection(&RedisSettings::default())+ .await+ .expect("failed to create redis connection pool");+ let uid = unique_test_id();+ let stream_name = format!("test_consumer_registration_{uid}");+ let stream: RedisKey = stream_name.clone().into();+ let stable_group = format!("test_stable_group_{uid}");+ let rotating_group = format!("test_rotating_group_{uid}");++ // `xgroup_create_mkstream` underneath creates the stream, so it need not exist yet.+ for group in [&stable_group, &rotating_group] {+ pool.consumer_group_create(+ &stream,+ group,+ &RedisEntryId::UserSpecifiedID {+ milliseconds: "0".to_string(),+ sequence_number: "0".to_string(),+ },+ )+ .await+ .expect("failed to create group");+ }++ // Five reads under one stable consumer name, as the scheduler now does.+ let stable_consumer = format!("test_stable_consumer_name_{uid}");+ for _ in 0..5 {+ let _ = pool+ .stream_read_with_options(+ std::slice::from_ref(&stream),+ vec![RedisEntryId::UndeliveredEntryID.to_stream_id()],+ Some(10),+ None,+ Some((stable_group.as_str(), stable_consumer.as_str())),+ )+ .await;+ }++ // Five reads under a fresh consumer name each time, as it did before the fix.+ for i in 0..5 {+ let rotating_consumer = format!("test_rotating_consumer_name_{uid}_{i}");+ let _ = pool+ .stream_read_with_options(+ std::slice::from_ref(&stream),+ vec![RedisEntryId::UndeliveredEntryID.to_stream_id()],+ Some(10),+ None,+ Some((rotating_group.as_str(), rotating_consumer.as_str())),+ )+ .await;+ }++ const COUNT_CONSUMERS: &str =+ r#"return #redis.call("XINFO", "CONSUMERS", KEYS[1], ARGV[1])"#;+ let stable: i64 = pool+ .evaluate_redis_script(COUNT_CONSUMERS, vec![stream_name.clone()], stable_group)+ .await+ .expect("failed to inspect consumer group via XINFO CONSUMERS");+ let rotating: i64 = pool+ .evaluate_redis_script(COUNT_CONSUMERS, vec![stream_name], rotating_group)+ .await+ .expect("failed to inspect consumer group via XINFO CONSUMERS");++ (stable, rotating)+ })+ })+ .await+ .expect("Spawn block failure");++ assert_eq!(+ stable_consumers, 1,+ "reusing one consumer name across five reads must register exactly one consumer"+ );+ assert_eq!(+ rotating_consumers, 5,+ "a fresh consumer name per read must register one consumer per read — this is the leak"+ );+}+// ─── List Commands ────────────────────────────────────────────────────────────#[tokio::test]diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex bc7b3779f1..012309e1ab 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -1674,6 +1674,17 @@ impl QueueInterface for KafkaStore {.await}+ async fn consumer_group_remove_consumer(+ &self,+ stream: &str,+ group: &str,+ consumer: &str,+ ) -> CustomResult<(), RedisError> {+ self.diesel_store+ .consumer_group_remove_consumer(stream, group, consumer)+ .await+ }+async fn acquire_pt_lock(&self,tag: &str,diff --git a/crates/scheduler/src/consumer.rs b/crates/scheduler/src/consumer.rsindex 1df96dce95..e26361c942 100644--- a/crates/scheduler/src/consumer.rs+++ b/crates/scheduler/src/consumer.rs@@ -55,6 +55,11 @@ wherelet mut shutdown_interval =tokio::time::interval(Duration::from_millis(settings.graceful_shutdown_interval));+ // Generated once per process rather than per poll iteration, so that the Redis consumer+ // group registers a single, stable consumer for the lifetime of this process instead of+ // accumulating a new entry on every poll (entries are never expired by Redis).+ let consumer_name = format!("consumer_{}", common_utils::generate_uuid_v4());+let consumer_operation_counter = sync::Arc::new(atomic::AtomicU64::new(0));let signal = get_allowed_signals().map_err(|error| {@@ -87,6 +92,7 @@ wherelogger::error!(?error, "Failed to perform consumer operation");},workflow_selector,+ &consumer_name,).await;}@@ -109,6 +115,40 @@ wherematch active_tasks {0 => {logger::info!("Terminating consumer");+ for tenant in state.get_tenants() {+ let session_state = match app_state_to_session_state(state, &tenant)+ {+ Ok(session_state) => session_state,+ Err(error) => {+ logger::error!(+ ?error,+ ?tenant,+ "Failed to build session state, skipping consumer removal for tenant"+ );+ continue;+ }+ };+ let stream_name = match session_state.get_application_source() {+ enums::ApplicationSource::Main => settings.stream.clone(),+ enums::ApplicationSource::Cug => settings.cug_stream.clone(),+ };+ let group_name = settings.consumer.consumer_group.clone();+ if let Err(error) = session_state+ .get_db()+ .consumer_group_remove_consumer(+ &stream_name,+ &group_name,+ &consumer_name,+ )+ .await+ {+ logger::error!(+ ?error,+ ?tenant,+ "Failed to remove consumer from consumer group during graceful shutdown"+ );+ }+ }break 'consumer;}_ => continue,@@ -130,13 +170,13 @@ pub async fn consumer_operations<T: SchedulerSessionState + 'static>(state: &T,settings: &SchedulerSettings,workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + Copy + std::fmt::Debug,+ consumer_name: &str,) -> CustomResult<(), errors::ProcessTrackerError> {let stream_name = match state.get_application_source() {enums::ApplicationSource::Main => settings.stream.clone(),enums::ApplicationSource::Cug => settings.cug_stream.clone(),};let group_name = settings.consumer.consumer_group.clone();- let consumer_name = format!("consumer_{}", common_utils::generate_uuid_v4());let _group_created = &mut state.get_db()@@ -146,7 +186,7 @@ pub async fn consumer_operations<T: SchedulerSessionState + 'static>(let mut tasks = state.get_db().as_scheduler()- .fetch_consumer_tasks(&stream_name, &group_name, &consumer_name)+ .fetch_consumer_tasks(&stream_name, &group_name, consumer_name).await?;if !tasks.is_empty() {diff --git a/crates/scheduler/src/db/queue.rs b/crates/scheduler/src/db/queue.rsindex 80f2b8b4c9..b4012a4fd4 100644--- a/crates/scheduler/src/db/queue.rs+++ b/crates/scheduler/src/db/queue.rs@@ -22,6 +22,13 @@ pub trait QueueInterface {id: &RedisEntryId,) -> CustomResult<(), RedisError>;+ async fn consumer_group_remove_consumer(+ &self,+ stream: &str,+ group: &str,+ consumer: &str,+ ) -> CustomResult<(), RedisError>;+async fn acquire_pt_lock(&self,tag: &str,@@ -74,6 +81,18 @@ impl QueueInterface for Store {.await}+ async fn consumer_group_remove_consumer(+ &self,+ stream: &str,+ group: &str,+ consumer: &str,+ ) -> CustomResult<(), RedisError> {+ self.get_redis_conn()?+ .consumer_group_delete_consumer(&stream.into(), group, consumer)+ .await+ .map(|_pending_messages| ())+ }+async fn acquire_pt_lock(&self,tag: &str,@@ -158,6 +177,16 @@ impl QueueInterface for MockDb {Err(RedisError::ConsumerGroupCreateFailed)?}+ async fn consumer_group_remove_consumer(+ &self,+ _stream: &str,+ _group: &str,+ _consumer: &str,+ ) -> CustomResult<(), RedisError> {+ // [#172]: Implement function for `MockDb`+ Err(RedisError::ConsumerGroupRemoveConsumerFailed)?+ }+async fn acquire_pt_lock(&self,_tag: &str,diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rsindex a6244c48fa..fd65ddab4f 100644--- a/crates/scheduler/src/utils.rs+++ b/crates/scheduler/src/utils.rs@@ -303,12 +303,13 @@ pub async fn consumer_operation_handler<E, T>(settings: sync::Arc<SchedulerSettings>,error_handler_fun: E,workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + Copy + std::fmt::Debug,+ consumer_name: &str,) where// Error handler functionE: FnOnce(error_stack::Report<errors::ProcessTrackerError>),T: SchedulerSessionState + Send + Sync + 'static,{- match consumer::consumer_operations(&state, &settings, workflow_selector).await {+ match consumer::consumer_operations(&state, &settings, workflow_selector, consumer_name).await {Ok(_) => (),Err(err) => error_handler_fun(err),}