Skip to content

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

perf(routing): Reduce redundant MCA DB fetches (#13374)

Anurag Thakur3ef8e1e540a9
diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
index 8000f2ef95..cbaee72045 100644
--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs
@@ -1177,6 +1177,9 @@ common_utils::create_list_wrapper!(
.filter(|mca| mca.connector_type == connector_type)
.collect()
}
+ pub fn get_ids(&self) -> std::collections::HashSet<id_type::MerchantConnectorAccountId> {
+ self.iter().map(|mca| mca.get_id()).collect()
+ }
pub fn is_merchant_connector_account_id_in_connector_mandate_details(
&self,
connector_mandate_details: &CommonMandateReference,
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index f33cccc5d2..cbae365895 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -301,6 +301,8 @@ pub enum RoutingError {
KgraphCacheFailure,
#[error("failed to refresh the kgraph cache")]
KgraphCacheRefreshFailed,
+ #[error("failed to fetch merchant connector accounts")]
+ MerchantConnectorAccountsFetchFailed,
#[error("there was an error during the kgraph analysis phase")]
KgraphAnalysisError,
#[error("'profile_id' was not provided")]
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 6a50a38c1f..384b43b476 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -12630,12 +12630,16 @@ where
{
let chosen = connectors.apply_filter_for_session_routing();
- let active_mca_ids =
- routing::get_active_mca_ids(&state, processor.get_key_store(), business_profile.get_id())
- .await
- .change_context(errors::ApiErrorResponse::GenericNotFoundError {
- message: "Active mca_ids not found".to_string(),
- })?;
+ // Degrade to an empty active set on a transient MCA fetch error, with an explicit
+ // log, instead of returning a client-facing error for an infra failure. Note the
+ // empty set filters out every MCA-carrying choice, so a warm-cache request yields no
+ // session tokens and a cold-cache refresh can still hard-error.
+ let active_mca_ids = routing::get_active_mca_ids_for_session(
+ &state,
+ processor.get_key_store(),
+ business_profile.get_id(),
+ )
+ .await;
let session_input = routing::SessionRoutingInput {
state: &state,
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index b3b0789ba3..10b027bb41 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -2078,6 +2078,9 @@ pub async fn refresh_cgraph_cache(
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {
+ // Fetch the MCA list from the DB here (only reached on a cache miss) rather than
+ // reusing a caller-supplied snapshot, so the cached graph is always built from
+ // live data and cannot be poisoned by a stale pre-eviction snapshot.
let mut merchant_connector_accounts = state
.store
.list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(
@@ -2330,6 +2333,7 @@ pub async fn perform_eligibility_analysis(
transaction_data: &routing::TransactionData<'_>,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
profile_id: &common_utils::id_type::ProfileId,
+ active_mca_ids: &std::collections::HashSet<common_utils::id_type::MerchantConnectorAccountId>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
let backend_input = match transaction_data {
routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
@@ -2337,7 +2341,6 @@ pub async fn perform_eligibility_analysis(
routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?,
};
- let active_mca_ids = get_active_mca_ids(state, key_store, profile_id).await?;
perform_cgraph_filtering(
state,
key_store,
@@ -2346,48 +2349,67 @@ pub async fn perform_eligibility_analysis(
eligible_connectors,
profile_id,
&api_enums::TransactionType::from(transaction_data),
- &active_mca_ids,
+ active_mca_ids,
)
.await
}
+/// Fetches the merchant's default (fallback) list of routable connectors.
+///
+/// This is the ultimate degrade target for routing: it never applies cgraph/MCA
+/// filtering, so it can be returned as-is when the active MCA list is unavailable.
+#[cfg_attr(feature = "v2", allow(clippy::unused_async))]
+async fn get_fallback_config(
+ state: &SessionState,
+ transaction_data: &routing::TransactionData<'_>,
+ #[cfg(feature = "v1")] _business_profile: &domain::Profile,
+ #[cfg(feature = "v2")] business_profile: &domain::Profile,
+) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
+ #[cfg(feature = "v1")]
+ {
+ routing::helpers::get_merchant_default_config(
+ &*state.store,
+ match transaction_data {
+ routing::TransactionData::Payment(payment_data) => payment_data
+ .payment_intent
+ .profile_id
+ .as_ref()
+ .get_required_value("profile_id")
+ .change_context(errors::RoutingError::ProfileIdMissing)?
+ .get_string_repr(),
+ #[cfg(feature = "payouts")]
+ routing::TransactionData::Payout(payout_data) => {
+ payout_data.payout_attempt.profile_id.get_string_repr()
+ }
+ },
+ &api_enums::TransactionType::from(transaction_data),
+ )
+ .await
+ .change_context(errors::RoutingError::FallbackConfigFetchFailed)
+ }
+ #[cfg(feature = "v2")]
+ {
+ let _ = (state, transaction_data);
+ admin::ProfileWrapper::new(business_profile.clone())
+ .get_default_fallback_list_of_connector_under_profile()
+ .change_context(errors::RoutingError::FallbackConfigFetchFailed)
+ }
+}
+
pub async fn perform_fallback_routing(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
transaction_data: &routing::TransactionData<'_>,
eligible_connectors: Option<&Vec<api_enums::RoutableConnectors>>,
business_profile: &domain::Profile,
+ active_mca_ids: &std::collections::HashSet<common_utils::id_type::MerchantConnectorAccountId>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
- #[cfg(feature = "v1")]
- let fallback_config = routing::helpers::get_merchant_default_config(
- &*state.store,
- match transaction_data {
- routing::TransactionData::Payment(payment_data) => payment_data
- .payment_intent
- .profile_id
- .as_ref()
- .get_required_value("profile_id")
- .change_context(errors::RoutingError::ProfileIdMissing)?
- .get_string_repr(),
- #[cfg(feature = "payouts")]
- routing::TransactionData::Payout(payout_data) => {
- payout_data.payout_attempt.profile_id.get_string_repr()
- }
- },
- &api_enums::TransactionType::from(transaction_data),
- )
- .await
- .change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
- #[cfg(feature = "v2")]
- let fallback_config = admin::ProfileWrapper::new(business_profile.clone())
- .get_default_fallback_list_of_connector_under_profile()
- .change_context(errors::RoutingError::FallbackConfigFetchFailed)?;
+ let fallback_config = get_fallback_config(state, transaction_data, business_profile).await?;
let backend_input = match transaction_data {
routing::TransactionData::Payment(payment_data) => make_dsl_input(payment_data)?,
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(payout_data) => make_dsl_input_for_payouts(payout_data)?,
};
- let active_mca_ids = get_active_mca_ids(state, key_store, business_profile.get_id()).await?;
perform_cgraph_filtering(
state,
key_store,
@@ -2396,7 +2418,7 @@ pub async fn perform_fallback_routing(
eligible_connectors,
business_profile.get_id(),
&api_enums::TransactionType::from(transaction_data),
- &active_mca_ids,
+ active_mca_ids,
)
.await
}
@@ -2415,6 +2437,35 @@ pub async fn perform_eligibility_analysis_with_fallback(
let eligible_connectors =
update_eligible_connectors_for_installments(state, transaction_data, eligible_connectors);
+ // If the active-MCA fetch fails (e.g. a transient DB error), degrade to the
+ // merchant's fallback config instead of aborting the payment — log and return the
+ // fallback config, still restricted to the caller-specified eligible connectors
+ // (already intersected for installments) so a requested connector is never silently
+ // swapped for an arbitrary default. Hard failure can still occur downstream (e.g. a
+ // cold-cache refresh errors after this fetch succeeded); only the MCA-fetch failure
+ // is degraded here. Never populate the cgraph cache from a failed fetch.
+ let active_mca_ids =
+ match get_active_merchant_connector_accounts(state, key_store, business_profile.get_id())
+ .await
+ {
+ Ok(merchant_connector_accounts) => merchant_connector_accounts.get_ids(),
+ Err(err) => {
+ logger::error!(
+ error = ?err,
+ "euclid_routing: failed to fetch active merchant connector accounts; \
+ degrading to eligibility-filtered fallback config"
+ );
+ return get_fallback_config(state, transaction_data, business_profile)
+ .await
+ .map(|mut fallback_config| {
+ if let Some(eligible) = eligible_connectors {
+ fallback_config.retain(|choice| eligible.contains(&choice.connector));
+ }
+ fallback_config
+ });
+ }
+ };
+
let mut final_selection = perform_eligibility_analysis(
state,
key_store,
@@ -2422,6 +2473,7 @@ pub async fn perform_eligibility_analysis_with_fallback(
transaction_data,
eligible_connectors.as_ref(),
business_profile.get_id(),
+ &active_mca_ids,
)
.await?;
@@ -2431,6 +2483,7 @@ pub async fn perform_eligibility_analysis_with_fallback(
transaction_data,
eligible_connectors.as_ref(),
business_profile,
+ &active_mca_ids,
)
.await;
@@ -2539,7 +2592,7 @@ pub async fn perform_session_flow_routing<'a>(
api_enums::PaymentMethodType,
Vec<routing_types::SessionRoutingChoice>,
> = FxHashMap::default();
- let active_mca_ids = get_active_mca_ids(state, key_store, &profile_id).await?;
+ let active_mca_ids = get_active_mca_ids_for_session(state, key_store, &profile_id).await;
for (pm_type, allowed_connectors) in pm_type_map {
let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;
@@ -2704,7 +2757,8 @@ pub async fn perform_session_flow_routing(
> = FxHashMap::default();
let mut final_routing_approach = None;
let active_mca_ids =
- get_active_mca_ids(session_input.state, session_input.key_store, &profile_id).await?;
+ get_active_mca_ids_for_session(session_input.state, session_input.key_store, &profile_id)
+ .await;
for (pm_type, allowed_connectors) in pm_type_map {
let euclid_pmt: euclid_enums::PaymentMethodType = pm_type;
@@ -4085,25 +4139,40 @@ where
}
}
-pub async fn get_active_mca_ids(
+pub async fn get_active_merchant_connector_accounts(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
profile_id: &common_utils::id_type::ProfileId,
-) -> RoutingResult<std::collections::HashSet<common_utils::id_type::MerchantConnectorAccountId>> {
- let db_mcas = state
+) -> RoutingResult<domain::MerchantConnectorAccountsWithoutEncrypted> {
+ state
.store
.list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(
&key_store.merchant_id,
profile_id,
)
.await
- .unwrap_or_else(|_| {
- hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccountsWithoutEncrypted::new(
- vec![],
- )
- });
+ .change_context(errors::RoutingError::MerchantConnectorAccountsFetchFailed)
+}
- let active_mca_ids: std::collections::HashSet<_> =
- db_mcas.iter().map(|mca| mca.get_id().clone()).collect();
- Ok(active_mca_ids)
+/// Fetches the set of active MCA ids for session routing, degrading to an empty set on
+/// failure, with an explicit log. Note the empty set does not yield fallback-config
+/// tokens: with a warm cgraph cache every MCA-carrying choice is filtered out (no
+/// session tokens), and with a cold cache the refresh's own DB fetch can still
+/// hard-error.
+pub async fn get_active_mca_ids_for_session(
+ state: &SessionState,
+ key_store: &domain::MerchantKeyStore,
+ profile_id: &common_utils::id_type::ProfileId,
+) -> std::collections::HashSet<common_utils::id_type::MerchantConnectorAccountId> {
+ match get_active_merchant_connector_accounts(state, key_store, profile_id).await {
+ Ok(merchant_connector_accounts) => merchant_connector_accounts.get_ids(),
+ Err(err) => {
+ logger::error!(
+ error = ?err,
+ "euclid_routing: failed to fetch active merchant connector accounts for \
+ session routing; continuing with empty active set"
+ );
+ std::collections::HashSet::new()
+ }
+ }
}
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index f790f553fb..448ef5132b 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -2219,52 +2219,14 @@ pub async fn contract_based_dynamic_routing_setup(
};
// validate the contained mca_ids
- let mut contained_mca = Vec::new();
if let Some(info_vec) = &config.label_info {
- for info in info_vec {
- utils::when(
- contained_mca.iter().any(|mca_id| mca_id == &info.mca_id),
- || {
- Err(error_stack::Report::new(
- errors::ApiErrorResponse::InvalidRequestData {
- message: "Duplicate mca configuration received".to_string(),
- },
- ))
- },
- )?;
-
- contained_mca.push(info.mca_id.to_owned());
- }
-
- let validation_futures: Vec<_> = info_vec
- .iter()
- .map(|info| async {
- let mca_id = info.mca_id.clone();
- let label = info.label.clone();
- let mca = db
- .find_by_merchant_connector_account_merchant_id_merchant_connector_id(
- processor.get_account().get_id(),
- &mca_id,
- processor.get_key_store(),
- )
- .await
- .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
- id: mca_id.get_string_repr().to_owned(),
- })?;
-
- utils::when(mca.connector_name != label, || {
- Err(error_stack::Report::new(
- errors::ApiErrorResponse::InvalidRequestData {
- message: "Incorrect mca configuration received".to_string(),
- },
- ))
- })?;
-
- Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(())
- })
- .collect();
-
- futures::future::try_join_all(validation_futures).await?;
+ helpers::validate_contract_based_label_info(
+ db,
+ processor.get_account().get_id(),
+ &profile_id,
+ info_vec,
+ )
+ .await?;
}
let record = db
@@ -2322,39 +2284,14 @@ pub async fn contract_based_routing_update_configs(
.attach_printable("unable to deserialize algorithm data from routing table into ContractBasedRoutingConfig")?;
// validate the contained mca_ids
- let mut contained_mca = Vec::new();
if let Some(info_vec) = &request.label_info {
- for info in info_vec {
- let mca = db
- .find_by_merchant_connector_account_merchant_id_merchant_connector_id(
- processor.get_account().get_id(),
- &info.mca_id,
- processor.get_key_store(),
- )
- .await
- .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
- id: info.mca_id.get_string_repr().to_owned(),
- })?;
-
- utils::when(mca.connector_name != info.label, || {
- Err(errors::ApiErrorResponse::InvalidRequestData {
- message: "Incorrect mca configuration received".to_string(),
- })
- })?;
-
- utils::when(
- contained_mca.iter().any(|mca_id| mca_id == &info.mca_id),
- || {
- Err(error_stack::Report::new(
- errors::ApiErrorResponse::InvalidRequestData {
- message: "Duplicate mca configuration received".to_string(),
- },
- ))
- },
- )?;
-
- contained_mca.push(info.mca_id.to_owned());
- }
+ helpers::validate_contract_based_label_info(
+ db,
+ processor.get_account().get_id(),
+ &profile_id,
+ info_vec,
+ )
+ .await?;
}
config_to_update.update(request);
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index def27431ca..2399c08256 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -464,6 +464,72 @@ impl RoutingAlgorithmHelpers<'_> {
}
}
+/// Validates the `label_info` entries of a contract-based routing config against the
+/// merchant's connector accounts, in a single list fetch.
+///
+/// Shared by the contract-based setup and update endpoints so both apply the same
+/// checks in the same order:
+/// 1. duplicate `mca_id` in the request -> `InvalidRequestData` ("Duplicate ...")
+/// 2. `mca_id` not present for the profile -> `MerchantConnectorAccountNotFound`
+/// 3. label not matching the connector name -> `InvalidRequestData` ("Incorrect ...")
+///
+/// A failure of the list fetch itself is an infra error (an empty result is `Ok(vec![])`,
+/// not an error), so it maps to `InternalServerError` rather than a 404.
+#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
+pub async fn validate_contract_based_label_info(
+ db: &dyn StorageInterface,
+ merchant_id: &id_type::MerchantId,
+ profile_id: &id_type::ProfileId,
+ label_info: &[routing_types::LabelInformation],
+) -> RouterResult<()> {
+ // Fetching disabled MCAs too: a contract config may reference a temporarily disabled
+ // MCA — validation checks connector existence and label, not activity.
+ let all_mcas = db
+ .list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(
+ merchant_id,
+ profile_id,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(
+ "Failed to list merchant connector accounts for contract based routing validation",
+ )?;
+
+ let mca_map: std::collections::HashMap<_, _> = all_mcas
+ .iter()
+ .map(|mca| (mca.get_id(), mca.connector_name.clone()))
+ .collect();
+
+ let mut contained_mca = Vec::new();
+ for info in label_info {
+ if contained_mca.contains(&info.mca_id) {
+ return Err(error_stack::Report::new(
+ errors::ApiErrorResponse::InvalidRequestData {
+ message: "Duplicate mca configuration received".to_string(),
+ },
+ ));
+ }
+
+ let mca_connector_name = mca_map.get(&info.mca_id).ok_or_else(|| {
+ error_stack::Report::new(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: info.mca_id.get_string_repr().to_owned(),
+ })
+ })?;
+
+ if mca_connector_name != &info.label {
+ return Err(error_stack::Report::new(
+ errors::ApiErrorResponse::InvalidRequestData {
+ message: "Incorrect mca configuration received".to_string(),
+ },
+ ));
+ }
+
+ contained_mca.push(info.mca_id.clone());
+ }
+
+ Ok(())
+}
+
#[cfg(feature = "v1")]
pub async fn validate_connectors_in_routing_config(
state: &SessionState,