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

refactor(cache): make in-memory caches runtime-configurable and store-owned (#14509)

Hrithikesh0fd3020ba7c9
diff --git a/config/config.example.toml b/config/config.example.toml
index f7a4167846..d5984833d9 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -126,6 +126,46 @@ unresponsive_check_interval = 2 # The frequency at which the client checks for
max_failure_threshold_seconds = 5 # Max seconds Redis can be unreachable before server shutdown (min 5s)
max_feed_count = 200 # The maximum number of frames that will be fed to a socket before flushing.
+# In-memory (moka) cache tuning, with per-cache granularity.
+#
+# Every key below is optional, and each default is the value the corresponding cache is built
+# with when this section is absent — so uncomment only what you want to change.
+#
+# [cache]
+# invalidation_channel = "hyperswitch_invalidate" # Redis pub/sub channel used to invalidate in-memory cache entries across instances; must be identical on every instance of a deployment
+#
+# Each of the caches below accepts the same keys:
+# ttl_in_secs # Seconds an entry is retained after it was inserted (default: 1800)
+# tti_in_secs # Seconds an entry is retained after it was last read or written (default: 600)
+# max_entries # Maximum number of entries the cache may hold. `0` makes it unbounded.
+# #
+# # Default for every cache except `config`: 31457280. That is the ceiling these
+# # caches have always had — a `30` that was documented as megabytes but reached moka
+# # as an entry count, because no weigher was ever configured — kept so that enabling
+# # this section changes no eviction behaviour. It binds nothing in practice; pick a
+# # real ceiling per cache once you know the numbers involved. `config` defaults to
+# # unbounded, as before.
+# #
+# # As an environment variable:
+# # ROUTER__CACHE__ACCOUNTS__MAX_ENTRIES=500000
+#
+# Note that `time_to_idle` is what bounds the resident set in normal operation — these caches are
+# keyed per merchant and profile, so an entry unread for its window is dropped. `max_entries` is a
+# backstop against runaway growth, and an eviction attributable to it shows up on
+# IN_MEMORY_CACHE_EVICTION_COUNT with removal_cause=Size.
+#
+# [cache.config] # CONFIG_CACHE, unbounded by default
+# [cache.accounts] # ACCOUNTS_CACHE
+# [cache.mca_list] # MCA_LIST_CACHE
+# [cache.routing] # ROUTING_CACHE
+# [cache.decision_manager] # DECISION_MANAGER_CACHE
+# [cache.surcharge] # SURCHARGE_CACHE
+# [cache.cgraph] # CGRAPH_CACHE
+# [cache.pm_filters_cgraph] # PM_FILTERS_CGRAPH_CACHE
+# [cache.success_based_dynamic_algorithm] # SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
+# [cache.elimination_based_dynamic_algorithm] # ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE
+# [cache.contract_based_dynamic_algorithm] # CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE
+
# This section provides configs for currency conversion api
[forex_api]
api_key = "" # Api key for making request to foreign exchange Api
diff --git a/config/development.toml b/config/development.toml
index 4cb4c1df74..ce54dfe624 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -135,6 +135,46 @@ default_command_timeout = 30
unresponsive_timeout = 10
unresponsive_check_interval = 2
max_feed_count = 200
+
+# In-memory (moka) cache tuning, with per-cache granularity.
+#
+# Every key below is optional, and each default is the value the corresponding cache is built
+# with when this section is absent — so uncomment only what you want to change.
+#
+# [cache]
+# invalidation_channel = "hyperswitch_invalidate" # Redis pub/sub channel used to invalidate in-memory cache entries across instances; must be identical on every instance of a deployment
+#
+# Each of the caches below accepts the same keys:
+# ttl_in_secs # Seconds an entry is retained after it was inserted (default: 1800)
+# tti_in_secs # Seconds an entry is retained after it was last read or written (default: 600)
+# max_entries # Maximum number of entries the cache may hold. `0` makes it unbounded.
+# #
+# # Default for every cache except `config`: 31457280. That is the ceiling these
+# # caches have always had — a `30` that was documented as megabytes but reached moka
+# # as an entry count, because no weigher was ever configured — kept so that enabling
+# # this section changes no eviction behaviour. It binds nothing in practice; pick a
+# # real ceiling per cache once you know the numbers involved. `config` defaults to
+# # unbounded, as before.
+# #
+# # As an environment variable:
+# # ROUTER__CACHE__ACCOUNTS__MAX_ENTRIES=500000
+#
+# Note that `time_to_idle` is what bounds the resident set in normal operation — these caches are
+# keyed per merchant and profile, so an entry unread for its window is dropped. `max_entries` is a
+# backstop against runaway growth, and an eviction attributable to it shows up on
+# IN_MEMORY_CACHE_EVICTION_COUNT with removal_cause=Size.
+#
+# [cache.config] # CONFIG_CACHE, unbounded by default
+# [cache.accounts] # ACCOUNTS_CACHE
+# [cache.mca_list] # MCA_LIST_CACHE
+# [cache.routing] # ROUTING_CACHE
+# [cache.decision_manager] # DECISION_MANAGER_CACHE
+# [cache.surcharge] # SURCHARGE_CACHE
+# [cache.cgraph] # CGRAPH_CACHE
+# [cache.pm_filters_cgraph] # PM_FILTERS_CGRAPH_CACHE
+# [cache.success_based_dynamic_algorithm] # SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
+# [cache.elimination_based_dynamic_algorithm] # ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE
+# [cache.contract_based_dynamic_algorithm] # CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE
max_failure_threshold_seconds = 5
[trace_header]
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 9852c6fa3b..3aa5144332 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -178,6 +178,46 @@ unresponsive_timeout = 10
unresponsive_check_interval = 2 # The frequency at which the client checks for unresponsive connections. In seconds. This value should usually be less than half of `unresponsive_timeout` and always more than 1 ms.
max_feed_count = 200
+# In-memory (moka) cache tuning, with per-cache granularity.
+#
+# Every key below is optional, and each default is the value the corresponding cache is built
+# with when this section is absent — so uncomment only what you want to change.
+#
+# [cache]
+# invalidation_channel = "hyperswitch_invalidate" # Redis pub/sub channel used to invalidate in-memory cache entries across instances; must be identical on every instance of a deployment
+#
+# Each of the caches below accepts the same keys:
+# ttl_in_secs # Seconds an entry is retained after it was inserted (default: 1800)
+# tti_in_secs # Seconds an entry is retained after it was last read or written (default: 600)
+# max_entries # Maximum number of entries the cache may hold. `0` makes it unbounded.
+# #
+# # Default for every cache except `config`: 31457280. That is the ceiling these
+# # caches have always had — a `30` that was documented as megabytes but reached moka
+# # as an entry count, because no weigher was ever configured — kept so that enabling
+# # this section changes no eviction behaviour. It binds nothing in practice; pick a
+# # real ceiling per cache once you know the numbers involved. `config` defaults to
+# # unbounded, as before.
+# #
+# # As an environment variable:
+# # ROUTER__CACHE__ACCOUNTS__MAX_ENTRIES=500000
+#
+# Note that `time_to_idle` is what bounds the resident set in normal operation — these caches are
+# keyed per merchant and profile, so an entry unread for its window is dropped. `max_entries` is a
+# backstop against runaway growth, and an eviction attributable to it shows up on
+# IN_MEMORY_CACHE_EVICTION_COUNT with removal_cause=Size.
+#
+# [cache.config] # CONFIG_CACHE, unbounded by default
+# [cache.accounts] # ACCOUNTS_CACHE
+# [cache.mca_list] # MCA_LIST_CACHE
+# [cache.routing] # ROUTING_CACHE
+# [cache.decision_manager] # DECISION_MANAGER_CACHE
+# [cache.surcharge] # SURCHARGE_CACHE
+# [cache.cgraph] # CGRAPH_CACHE
+# [cache.pm_filters_cgraph] # PM_FILTERS_CGRAPH_CACHE
+# [cache.success_based_dynamic_algorithm] # SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
+# [cache.elimination_based_dynamic_algorithm] # ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE
+# [cache.contract_based_dynamic_algorithm] # CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE
+
[key_manager]
url = "http://localhost:5000"
use_legacy_key_store_decryption = false
diff --git a/crates/redis_interface/src/module/fred/commands.rs b/crates/redis_interface/src/module/fred/commands.rs
index fc6844a386..787b2505d6 100644
--- a/crates/redis_interface/src/module/fred/commands.rs
+++ b/crates/redis_interface/src/module/fred/commands.rs
@@ -552,7 +552,6 @@ impl super::RedisConnectionWithContext {
T: serde::de::DeserializeOwned,
{
let value_bytes = self.get_key::<Vec<u8>>(key).await?;
-
fp_utils::when(value_bytes.is_empty(), || Err(errors::RedisError::NotFound))?;
value_bytes
diff --git a/crates/redis_interface/src/module/redis_rs/commands.rs b/crates/redis_interface/src/module/redis_rs/commands.rs
index 3e05a03bc2..771aae7933 100644
--- a/crates/redis_interface/src/module/redis_rs/commands.rs
+++ b/crates/redis_interface/src/module/redis_rs/commands.rs
@@ -513,6 +513,7 @@ impl super::RedisConnectionWithContext {
{
let value_bytes = self.get_key::<Vec<u8>>(key).await?;
fp_utils::when(value_bytes.is_empty(), || Err(errors::RedisError::NotFound))?;
+
value_bytes
.parse_struct(type_name)
.change_context(errors::RedisError::JsonDeserializationFailed)
diff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rs
index 893d503c31..5c5b0c56a6 100644
--- a/crates/router/src/bin/router.rs
+++ b/crates/router/src/bin/router.rs
@@ -3,7 +3,6 @@ use router::{
configs::settings::{CmdLineConf, Settings},
core::errors::{ApplicationError, ApplicationResult},
logger,
- routes::metrics,
};
#[tokio::main]
@@ -83,11 +82,6 @@ async fn main() -> ApplicationResult<()> {
);
}
- // Spawn a thread for collecting metrics at fixed intervals
- metrics::bg_metrics_collector::spawn_metrics_collector(
- conf.log.telemetry.bg_metrics_collection_interval_in_secs,
- );
-
#[allow(clippy::expect_used)]
let server = Box::pin(router::start_server(conf, router_env::service_name!()))
.await
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 911078934f..57d52ded39 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -696,6 +696,7 @@ pub(crate) async fn fetch_raw_secrets(
accounts_database,
global_database,
redis: conf.redis,
+ cache: conf.cache,
log: conf.log,
#[cfg(feature = "deja")]
deja: conf.deja,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index a9aafbd835..5aff4c24d8 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -48,7 +48,7 @@ pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry};
use rust_decimal::Decimal;
use scheduler::SchedulerSettings;
use serde::Deserialize;
-use storage_impl::config::QueueStrategy;
+use storage_impl::{config::QueueStrategy, redis::cache::CacheConfig};
#[cfg(feature = "olap")]
use crate::analytics::{AnalyticsConfig, AnalyticsProvider};
@@ -90,6 +90,9 @@ pub struct Settings<S: SecretState> {
#[cfg(feature = "olap")]
pub replica_database: SecretStateContainer<Database, S>,
pub redis: RedisSettings,
+ /// Per-cache tuning for the in-memory caches. Anything left unset keeps the compiled-in
+ /// default for that cache.
+ pub cache: CacheConfig,
pub log: Log,
#[cfg(feature = "deja")]
#[serde(default)]
@@ -505,6 +508,7 @@ impl TenantConfig {
storage_impl: &app::StorageImpl,
conf: &configs::Settings,
cache_store: Arc<storage_impl::redis::RedisStore>,
+ caches: Arc<storage_impl::redis::cache::Caches>,
testable: bool,
) -> (StorageInterfaceMap, AccountsStorageInterfaceMap) {
#[allow(clippy::expect_used)]
@@ -523,6 +527,7 @@ impl TenantConfig {
conf.master_database.clone().into_inner(),
conf.accounts_database_config(),
cache_store.clone(),
+ caches.clone(),
testable,
))
.await;
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 07d39630a0..c3217a2a34 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -4607,13 +4607,10 @@ impl ProfileWrapper {
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref in business profile")?;
- storage_impl::redis::cache::redact_from_redis_and_publish(
- db.get_cache_store().as_ref(),
- [routing_cache_key],
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to invalidate routing cache")?;
+ storage_impl::redis::cache::redact_from_redis_and_publish(db, [routing_cache_key])
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to invalidate routing cache")?;
Ok(())
}
diff --git a/crates/router/src/core/cache.rs b/crates/router/src/core/cache.rs
index fbe75f3c9c..70903bb02e 100644
--- a/crates/router/src/core/cache.rs
+++ b/crates/router/src/core/cache.rs
@@ -10,12 +10,9 @@ pub async fn invalidate(
key: &str,
) -> CustomResult<services::api::ApplicationResponse<serde_json::Value>, errors::ApiErrorResponse> {
let store = state.store.as_ref();
- let result = redact_from_redis_and_publish(
- store.get_cache_store().as_ref(),
- [CacheKind::All(key.into())],
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let result = redact_from_redis_and_publish(store, [CacheKind::All(key.into())])
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
// If the message was published to atleast one channel
// then return status Ok
diff --git a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
index 661be4a4cf..7f547a96aa 100644
--- a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
+++ b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
@@ -17,7 +17,7 @@ use euclid::{
};
use router_env::{instrument, logger, tracing};
use serde::{Deserialize, Serialize};
-use storage_impl::redis::cache::{self, SURCHARGE_CACHE};
+use storage_impl::redis::cache;
use crate::{
core::{
@@ -510,15 +510,11 @@ pub async fn ensure_algorithm_cached(
.change_context(errors::StorageError::ValueNotFound("Program".to_string()))
.attach_printable("Error initializing DSL interpreter backend")
};
- let interpreter = cache::get_or_populate_in_memory(
- store.get_cache_store().as_ref(),
- &key,
- value_to_cache,
- &SURCHARGE_CACHE,
- )
- .await
- .change_context(ConfigError::CacheMiss)
- .attach_printable("Unable to retrieve cached routing algorithm even after refresh")?;
+ let interpreter =
+ cache::get_or_populate_in_memory(store, &key, value_to_cache, cache::CacheId::Surcharge)
+ .await
+ .change_context(ConfigError::CacheMiss)
+ .attach_printable("Unable to retrieve cached routing algorithm even after refresh")?;
Ok(interpreter)
}
diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rs
index 00bbf4ea92..93c83363fb 100644
--- a/crates/router/src/core/payment_methods/utils.rs
+++ b/crates/router/src/core/payment_methods/utils.rs
@@ -17,7 +17,7 @@ use hyperswitch_masking::ExposeInterface;
use kgraph_utils::{error::KgraphError, transformers::IntoDirValue};
#[cfg(feature = "v1")]
use router_env::logger;
-use storage_impl::redis::cache::{CacheKey, PM_FILTERS_CGRAPH_CACHE};
+use storage_impl::redis::cache::CacheKey;
use crate::{
configs::settings, core::configs::dimension_state, routes::SessionState,
@@ -64,7 +64,10 @@ pub async fn get_merchant_pm_filter_graph(
state: &SessionState,
key: &str,
) -> Option<Arc<hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue>>> {
- PM_FILTERS_CGRAPH_CACHE
+ state
+ .store
+ .caches()
+ .pm_filters_cgraph
.get_val::<Arc<hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue>>>(CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
@@ -78,7 +81,10 @@ pub async fn refresh_pm_filters_cache(
graph: cgraph::ConstraintGraph<dir::DirValue>,
) -> Arc<hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue>> {
let pm_filter_graph = Arc::new(graph);
- PM_FILTERS_CGRAPH_CACHE
+ state
+ .store
+ .caches()
+ .pm_filters_cgraph
.push(
CacheKey {
key: key.to_string(),
diff --git a/crates/router/src/core/payments/conditional_configs.rs b/crates/router/src/core/payments/conditional_configs.rs
index cbec1635de..73744780e5 100644
--- a/crates/router/src/core/payments/conditional_configs.rs
+++ b/crates/router/src/core/payments/conditional_configs.rs
@@ -3,7 +3,7 @@ use common_utils::ext_traits::StringExt;
use error_stack::ResultExt;
use euclid::backend::{self, inputs as dsl_inputs, EuclidBackend};
use router_env::{instrument, tracing};
-use storage_impl::redis::cache::{self, DECISION_MANAGER_CACHE};
+use storage_impl::redis::cache;
use super::routing::make_dsl_input;
#[cfg(feature = "v2")]
@@ -49,10 +49,10 @@ pub async fn perform_decision_management(
};
let interpreter = cache::get_or_populate_in_memory(
- db.get_cache_store().as_ref(),
+ db,
&key,
find_key_from_db,
- &DECISION_MANAGER_CACHE,
+ cache::CacheId::DecisionManager,
)
.await
.change_context(ConfigError::DslCachePoisoned)?;
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 76f0aa8893..e016f8d6a0 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -57,7 +57,7 @@ use rand::SeedableRng;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use router_env::{instrument, tracing};
use rustc_hash::FxHashMap;
-use storage_impl::redis::cache::{CacheKey, CGRAPH_CACHE, ROUTING_CACHE};
+use storage_impl::redis::cache::CacheKey;
#[cfg(feature = "v2")]
use crate::core::admin;
@@ -2055,7 +2055,10 @@ pub async fn ensure_algorithm_cached_v1(
}
};
- let cached_algorithm = ROUTING_CACHE
+ let cached_algorithm = state
+ .store
+ .caches()
+ .routing
.get_val::<Arc<CachedAlgorithm>>(CacheKey {
key: key.clone(),
prefix: state.tenant.redis_key_prefix.clone(),
@@ -2202,7 +2205,10 @@ pub async fn refresh_routing_cache_v1(
let arc_cached_algorithm = Arc::new(cached_algorithm);
- ROUTING_CACHE
+ state
+ .store
+ .caches()
+ .routing
.push(
CacheKey {
key,
@@ -2322,7 +2328,10 @@ pub async fn get_merchant_cgraph(
}
};
- let cached_cgraph = CGRAPH_CACHE
+ let cached_cgraph = state
+ .store
+ .caches()
+ .cgraph
.get_val::<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>>(
CacheKey {
key: key.clone(),
@@ -2433,7 +2442,10 @@ pub async fn refresh_cgraph_cache(
.attach_printable("when construction cgraph")?,
);
- CGRAPH_CACHE
+ state
+ .store
+ .caches()
+ .cgraph
.push(
CacheKey {
key,
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index 797364a93e..e463730a07 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -2759,7 +2759,7 @@ pub async fn success_based_routing_update_configs(
cache_key.into(),
)];
let _ = cache::redact_from_redis_and_publish(
- state.store.get_cache_store().as_ref(),
+ &*state.store,
cache_entries_to_redact,
)
.await
@@ -2865,7 +2865,7 @@ pub async fn elimination_routing_update_configs(
)];
cache::redact_from_redis_and_publish(
- state.store.get_cache_store().as_ref(),
+ &*state.store,
cache_entries_to_redact,
)
.await
@@ -3137,7 +3137,7 @@ pub async fn contract_based_routing_update_configs(
cache_key.into(),
)];
let _ = cache::redact_from_redis_and_publish(
- state.store.get_cache_store().as_ref(),
+ &*state.store,
cache_entries_to_redact,
)
.await
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 2120b1e112..ec2803af98 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -219,7 +219,7 @@ pub async fn update_merchant_active_algorithm_ref(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref in merchant account")?;
- cache::redact_from_redis_and_publish(db.get_cache_store().as_ref(), [config_key])
+ cache::redact_from_redis_and_publish(db, [config_key])
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate the config cache")?;
@@ -278,7 +278,7 @@ pub async fn update_profile_active_algorithm_ref(
.into(),
);
- cache::redact_from_redis_and_publish(db.get_cache_store().as_ref(), [routing_cache_key])
+ cache::redact_from_redis_and_publish(db, [routing_cache_key])
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate routing cache")?;
@@ -680,7 +680,10 @@ impl DynamicRoutingCache for routing_types::SuccessBasedRoutingConfig {
state: &SessionState,
key: &str,
) -> Option<Arc<Self>> {
- cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
+ state
+ .store
+ .caches()
+ .success_based_dynamic_algorithm
.get_val::<Arc<Self>>(cache::CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
@@ -699,10 +702,10 @@ impl DynamicRoutingCache for routing_types::SuccessBasedRoutingConfig {
Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send,
{
cache::get_or_populate_in_memory(
- state.store.get_cache_store().as_ref(),
+ &*state.store,
key,
func,
- &cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE,
+ cache::CacheId::SuccessBasedDynamicAlgorithm,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -717,7 +720,10 @@ impl DynamicRoutingCache for routing_types::ContractBasedRoutingConfig {
state: &SessionState,
key: &str,
) -> Option<Arc<Self>> {
- cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE
+ state
+ .store
+ .caches()
+ .contract_based_dynamic_algorithm
.get_val::<Arc<Self>>(cache::CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
@@ -736,10 +742,10 @@ impl DynamicRoutingCache for routing_types::ContractBasedRoutingConfig {
Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send,
{
cache::get_or_populate_in_memory(
- state.store.get_cache_store().as_ref(),
+ &*state.store,
key,
func,
- &cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE,
+ cache::CacheId::ContractBasedDynamicAlgorithm,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -754,7 +760,10 @@ impl DynamicRoutingCache for routing_types::EliminationRoutingConfig {
state: &SessionState,
key: &str,
) -> Option<Arc<Self>> {
- cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE
+ state
+ .store
+ .caches()
+ .elimination_based_dynamic_algorithm
.get_val::<Arc<Self>>(cache::CacheKey {
key: key.to_string(),
prefix: state.tenant.redis_key_prefix.clone(),
@@ -773,10 +782,10 @@ impl DynamicRoutingCache for routing_types::EliminationRoutingConfig {
Fut: futures::Future<Output = errors::CustomResult<T, errors::StorageError>> + Send,
{
cache::get_or_populate_in_memory(
- state.store.get_cache_store().as_ref(),
+ &*state.store,
key,
func,
- &cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE,
+ cache::CacheId::EliminationBasedDynamicAlgorithm,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -1987,7 +1996,7 @@ pub async fn disable_dynamic_routing_algorithm(
// redact cache for dynamic routing config
let _ = cache::redact_from_redis_and_publish(
- state.store.get_cache_store().as_ref(),
+ &*state.store,
cache_entries_to_redact,
)
.await
@@ -2916,13 +2925,10 @@ pub async fn redact_cgraph_cache(
let config_payouts_key = cache::CacheKind::CGraph(cgraph_payouts_key.clone().into());
let config_payments_key = cache::CacheKind::CGraph(cgraph_payments_key.clone().into());
- cache::redact_from_redis_and_publish(
- state.store.get_cache_store().as_ref(),
- [config_payouts_key, config_payments_key],
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to invalidate the cgraph cache")?;
+ cache::redact_from_redis_and_publish(&*state.store, [config_payouts_key, config_payments_key])
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to invalidate the cgraph cache")?;
Ok(())
}
@@ -2948,7 +2954,7 @@ pub async fn redact_routing_cache(
// this key lives in ROUTING_CACHE. (Redis deletion is by key, so only other pods were affected.)
let routing_payments_cache_key = cache::CacheKind::Routing(routing_payments_key.clone().into());
cache::redact_from_redis_and_publish(
- state.store.get_cache_store().as_ref(),
+ &*state.store,
[routing_payouts_cache_key, routing_payments_cache_key],
)
.await
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 8cc0ebabed..6833897a6a 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -69,7 +69,9 @@ use router_env::logger;
#[cfg(feature = "v2")]
use storage_impl::revenue_recovery_retry_stats;
use storage_impl::{
- errors::StorageError, redis::kv_store::RedisConnInterface, tokenization, MockDb,
+ errors::StorageError,
+ redis::{cache::CacheInterface, kv_store::RedisConnInterface},
+ tokenization, MockDb,
};
pub use self::kafka_store::KafkaStore;
@@ -137,6 +139,7 @@ pub trait StorageInterface:
+ MasterKeyInterface
+ payment_link::PaymentLinkInterface
+ RedisConnInterface
+ + CacheInterface
+ RequestIdStore
+ business_profile::ProfileInterface<Error = StorageError>
+ routing_algorithm::RoutingAlgorithmInterface
@@ -182,6 +185,7 @@ pub trait GlobalStorageInterface:
+ user_key_store::UserKeyStoreInterface
+ role::RoleInterface
+ RedisConnInterface
+ + CacheInterface
+ RequestIdStore
+ 'static
{
@@ -199,6 +203,7 @@ pub trait GlobalStorageInterface:
+ user_key_store::UserKeyStoreInterface
+ role::RoleInterface
+ RedisConnInterface
+ + CacheInterface
+ RequestIdStore
+ 'static
{
diff --git a/crates/router/src/db/api_keys.rs b/crates/router/src/db/api_keys.rs
index c6c2346790..8c4ad159df 100644
--- a/crates/router/src/db/api_keys.rs
+++ b/crates/router/src/db/api_keys.rs
@@ -1,7 +1,7 @@
use error_stack::report;
use router_env::{instrument, tracing};
#[cfg(feature = "accounts_cache")]
-use storage_impl::redis::cache::{self, CacheKind, ACCOUNTS_CACHE};
+use storage_impl::redis::cache::{self, CacheKind};
use super::{MockDb, Store};
use crate::{
@@ -191,7 +191,7 @@ impl ApiKeyInterface for Store {
self,
&_hashed_api_key.into_inner(),
find_call,
- &ACCOUNTS_CACHE,
+ cache::CacheId::Accounts,
)
.await
}
@@ -374,11 +374,11 @@ impl ApiKeyInterface for MockDb {
#[cfg(test)]
mod tests {
- use std::borrow::Cow;
+ use std::{borrow::Cow, sync::Arc};
use common_utils::types::keymanager::KeyManagerState;
use storage_impl::redis::{
- cache::{self, CacheKey, CacheKind, ACCOUNTS_CACHE},
+ cache::{self, CacheInterface, CacheKey, CacheKind},
kv_store::RedisConnInterface,
pub_sub::PubSubInterface,
};
@@ -501,7 +501,7 @@ mod tests {
let redis_conn = db.get_redis_conn().unwrap();
redis_conn
- .subscribe("hyperswitch_invalidate")
+ .subscribe(&db.caches().invalidation_channel, Arc::clone(&db.caches))
.await
.unwrap();
@@ -534,7 +534,7 @@ mod tests {
hashed_api_key.clone().into_inner()
),
find_call,
- &ACCOUNTS_CACHE,
+ cache::CacheId::Accounts,
)
.await
.unwrap();
@@ -556,7 +556,9 @@ mod tests {
.await
.unwrap();
- assert!(ACCOUNTS_CACHE
+ assert!(db
+ .caches()
+ .accounts
.get_val::<storage::ApiKey>(CacheKey {
key: format!(
"{}_{}",
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 054e765d0c..5bf1454809 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -46,7 +46,7 @@ use scheduler::{
SchedulerInterface,
};
use serde::Serialize;
-use storage_impl::redis::kv_store::RedisConnInterface;
+use storage_impl::redis::{cache::CacheInterface, kv_store::RedisConnInterface};
#[cfg(feature = "v2")]
use storage_impl::revenue_recovery_retry_stats;
use time::PrimitiveDateTime;
@@ -3949,6 +3949,16 @@ impl RedisConnInterface for KafkaStore {
}
}
+impl CacheInterface for KafkaStore {
+ fn caches(&self) -> &storage_impl::redis::cache::Caches {
+ self.diesel_store.caches()
+ }
+
+ fn cache_key_prefix(&self) -> &str {
+ self.diesel_store.cache_key_prefix()
+ }
+}
+
#[async_trait::async_trait]
impl UserRoleInterface for KafkaStore {
async fn insert_user_role(
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index cc38cc586e..4b31a117ca 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -104,7 +104,7 @@ mod merchant_connector_account_cache_tests {
use storage_impl::{
behaviour::Conversion,
redis::{
- cache::{self, CacheKey, CacheKind, ACCOUNTS_CACHE},
+ cache::{self, CacheInterface, CacheKey, CacheKind},
kv_store::RedisConnInterface,
pub_sub::PubSubInterface,
},
@@ -161,7 +161,7 @@ mod merchant_connector_account_cache_tests {
let redis_conn = db.get_redis_conn().unwrap();
let master_key = db.get_master_key();
redis_conn
- .subscribe("hyperswitch_invalidate")
+ .subscribe(&db.caches().invalidation_channel, Arc::clone(&db.caches))
.await
.unwrap();
@@ -280,7 +280,7 @@ mod merchant_connector_account_cache_tests {
profile_id.get_string_repr(),
),
find_call,
- &ACCOUNTS_CACHE,
+ cache::CacheId::Accounts,
)
.await
.unwrap();
@@ -306,7 +306,9 @@ mod merchant_connector_account_cache_tests {
.await
.unwrap();
- assert!(ACCOUNTS_CACHE
+ assert!(db
+ .caches()
+ .accounts
.get_val::<domain::MerchantConnectorAccount>(CacheKey {
key: format!("{}_{}", merchant_id.get_string_repr(), connector_label),
prefix: String::default(),
@@ -346,7 +348,7 @@ mod merchant_connector_account_cache_tests {
let redis_conn = db.get_redis_conn().unwrap();
let master_key = db.get_master_key();
redis_conn
- .subscribe("hyperswitch_invalidate")
+ .subscribe(&db.caches().invalidation_channel, Arc::clone(&db.caches))
.await
.unwrap();
@@ -459,7 +461,7 @@ mod merchant_connector_account_cache_tests {
profile_id.get_string_repr()
),
find_call,
- &ACCOUNTS_CACHE,
+ cache::CacheId::Accounts,
)
.await
.unwrap();
@@ -476,7 +478,9 @@ mod merchant_connector_account_cache_tests {
.await
.unwrap();
- assert!(ACCOUNTS_CACHE
+ assert!(db
+ .caches()
+ .accounts
.get_val::<domain::MerchantConnectorAccount>(CacheKey {
key: format!("{}_{}", merchant_id.get_string_repr(), connector_label),
prefix: String::default(),
diff --git a/crates/router/src/db/organization.rs b/crates/router/src/db/organization.rs
index 7e606a5831..47b1cc024d 100644
--- a/crates/router/src/db/organization.rs
+++ b/crates/router/src/db/organization.rs
@@ -3,7 +3,7 @@ use diesel_models::{organization as storage, organization::OrganizationBridge};
use error_stack::report;
use router_env::{instrument, tracing};
#[cfg(feature = "accounts_cache")]
-use storage_impl::redis::cache::{self, CacheKind, ACCOUNTS_CACHE};
+use storage_impl::redis::cache::{self, CacheKind};
use crate::{connection, core::errors, services::Store};
@@ -63,7 +63,7 @@ impl OrganizationInterface for Store {
self,
org_id.get_string_repr(),
find_call,
- &ACCOUNTS_CACHE,
+ cache::CacheId::Accounts,
)
.await
}
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index b39757279b..091cbb34a9 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -409,6 +409,18 @@ pub async fn start_server(
errors::ApplicationError::ApiClientError(error.current_context().clone())
})?);
let state = Box::pin(AppState::new(conf, tx, api_client, service_name)).await;
+
+ // Spawn a thread for collecting metrics at fixed intervals. It has to run against the
+ // caches the state built, not a set of its own.
+ routes::metrics::bg_metrics_collector::spawn_metrics_collector(
+ state
+ .conf
+ .log
+ .telemetry
+ .bg_metrics_collection_interval_in_secs,
+ std::sync::Arc::clone(&state.caches),
+ );
+
let request_body_limit = server.request_body_limit;
let server_builder =
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index a483badd0f..638d7d7ec9 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -32,7 +32,10 @@ use hyperswitch_interfaces::{
};
use router_env::RequestId;
use scheduler::SchedulerInterface;
-use storage_impl::{redis::RedisStore, MockDb};
+use storage_impl::{
+ redis::{cache::Caches, RedisStore},
+ MockDb,
+};
use tokio::sync::oneshot;
use self::settings::Tenant;
@@ -362,6 +365,9 @@ pub struct AppState {
pub infra_components: Option<serde_json::Value>,
pub enhancement: Option<HashMap<String, String>>,
pub superposition_service: Arc<SuperpositionClient>,
+ /// In-memory caches, shared with every tenant's store and with the redis subscriber
+ /// that invalidates them.
+ pub caches: Arc<Caches>,
}
impl scheduler::SchedulerAppState for AppState {
fn get_tenants(&self) -> Vec<id_type::TenantId> {
@@ -499,6 +505,9 @@ impl AppState {
)
.await
.expect("Failed to create store");
+ // One set for the whole process: every tenant store and the single redis
+ // subscriber that invalidates entries must point at the same caches.
+ let caches = Arc::new(Caches::new(&conf.cache));
let global_store: Box<dyn GlobalStorageInterface> =
Box::pin(Self::get_store_interface(
&storage_impl,
@@ -508,6 +517,7 @@ impl AppState {
conf.global_database_config(),
conf.global_database_config(),
Arc::clone(&cache_store),
+ Arc::clone(&caches),
testable,
))
.await
@@ -521,7 +531,13 @@ impl AppState {
let (stores, accounts_store) = conf
.multitenancy
.tenants
- .get_store_interface_maps(&storage_impl, &conf, Arc::clone(&cache_store), testable)
+ .get_store_interface_maps(
+ &storage_impl,
+ &conf,
+ Arc::clone(&cache_store),
+ Arc::clone(&caches),
+ testable,
+ )
.await;
#[cfg(feature = "email")]
@@ -564,6 +580,7 @@ impl AppState {
infra_components: infra_component_values,
enhancement,
superposition_service,
+ caches,
}
})
.await
@@ -581,6 +598,7 @@ impl AppState {
master_config: settings::Database,
accounts_config: settings::Database,
cache_store: Arc<RedisStore>,
+ caches: Arc<Caches>,
testable: bool,
) -> Box<dyn CommonStorageInterface> {
let km_conf = conf.key_manager.get_inner();
@@ -615,6 +633,7 @@ impl AppState {
master_config.clone(),
accounts_config.clone(),
Arc::clone(&cache_store),
+ Arc::clone(&caches),
testable,
key_manager_state,
)
@@ -634,6 +653,7 @@ impl AppState {
master_config,
accounts_config,
Arc::clone(&cache_store),
+ caches,
testable,
key_manager_state,
)
diff --git a/crates/router/src/routes/metrics/bg_metrics_collector.rs b/crates/router/src/routes/metrics/bg_metrics_collector.rs
index 2cdeb698ac..dfe4f65b6f 100644
--- a/crates/router/src/routes/metrics/bg_metrics_collector.rs
+++ b/crates/router/src/routes/metrics/bg_metrics_collector.rs
@@ -1,29 +1,20 @@
-use storage_impl::redis::cache;
+use std::sync::Arc;
+
+use storage_impl::redis::cache::Caches;
const DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS: u16 = 15;
-pub fn spawn_metrics_collector(metrics_collection_interval_in_secs: Option<u16>) {
+pub fn spawn_metrics_collector(
+ metrics_collection_interval_in_secs: Option<u16>,
+ caches: Arc<Caches>,
+) {
let metrics_collection_interval = metrics_collection_interval_in_secs
.unwrap_or(DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS);
- let cache_instances = [
- &cache::CONFIG_CACHE,
- &cache::ACCOUNTS_CACHE,
- &cache::MCA_LIST_CACHE,
- &cache::ROUTING_CACHE,
- &cache::CGRAPH_CACHE,
- &cache::PM_FILTERS_CGRAPH_CACHE,
- &cache::DECISION_MANAGER_CACHE,
- &cache::SURCHARGE_CACHE,
- &cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE,
- &cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE,
- &cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE,
- ];
-
tokio::spawn(async move {
loop {
- for instance in cache_instances {
- instance.record_entry_count_metric().await
+ for instance in caches.all() {
+ instance.record_size_metrics().await
}
tokio::time::sleep(std::time::Duration::from_secs(
diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs
index 94ddc20069..f2780bff5d 100644
--- a/crates/router/src/services.rs
+++ b/crates/router/src/services.rs
@@ -27,7 +27,11 @@ pub use hyperswitch_interfaces::connector_integration_v2::{
use hyperswitch_masking::{ExposeInterface, StrongSecret};
#[cfg(feature = "kv_store")]
use storage_impl::kv_router_store::KVRouterStore;
-use storage_impl::{errors::StorageResult, redis::RedisStore, RouterStore};
+use storage_impl::{
+ errors::StorageResult,
+ redis::{cache::Caches, RedisStore},
+ RouterStore,
+};
use tokio::sync::oneshot;
pub use self::{api::*, encryption::*};
@@ -49,13 +53,14 @@ pub type Store = KVRouterStore<StoreType>;
/// # Panics
///
/// Will panic if hex decode of master key fails
-#[allow(clippy::expect_used)]
+#[allow(clippy::expect_used, clippy::too_many_arguments)]
pub async fn get_store(
config: &Settings,
tenant: &dyn TenantConfig,
master_config: Database,
accounts_config: Database,
cache_store: Arc<RedisStore>,
+ caches: Arc<Caches>,
test_transaction: bool,
key_manager_state: keymanager::KeyManagerState,
) -> StorageResult<Store> {
@@ -89,6 +94,7 @@ pub async fn get_store(
tenant,
&config.redis,
master_enc_key,
+ caches,
Some(key_manager_state.clone()),
Arc::clone(&database_event_emitter),
)
@@ -99,7 +105,7 @@ pub async fn get_store(
tenant,
master_enc_key,
cache_store,
- storage_impl::redis::cache::IMC_INVALIDATION_CHANNEL,
+ caches,
Some(key_manager_state.clone()),
database_event_emitter,
)
diff --git a/crates/router/tests/cache.rs b/crates/router/tests/cache.rs
index 85f917adc9..535b4e1cc4 100644
--- a/crates/router/tests/cache.rs
+++ b/crates/router/tests/cache.rs
@@ -1,7 +1,7 @@
use std::sync::Arc;
use router::{configs::settings::Settings, routes, services};
-use storage_impl::redis::cache::{self, CacheKey};
+use storage_impl::redis::cache::CacheKey;
mod utils;
@@ -36,7 +36,10 @@ async fn invalidate_existing_cache_success() {
let api_key = ("api-key", "test_admin");
let client = awc::Client::default();
- cache::CONFIG_CACHE
+ state
+ .store
+ .caches()
+ .config
.push(
CacheKey {
key: cache_key.clone(),
@@ -46,7 +49,10 @@ async fn invalidate_existing_cache_success() {
)
.await;
- cache::ACCOUNTS_CACHE
+ state
+ .store
+ .caches()
+ .accounts
.push(
CacheKey {
key: cache_key.clone(),
@@ -70,14 +76,20 @@ async fn invalidate_existing_cache_success() {
let response_body = response.body().await;
println!("invalidate Cache: {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
- assert!(cache::CONFIG_CACHE
+ assert!(state
+ .store
+ .caches()
+ .config
.get_val::<String>(CacheKey {
key: cache_key.clone(),
prefix: String::default()
})
.await
.is_none());
- assert!(cache::ACCOUNTS_CACHE
+ assert!(state
+ .store
+ .caches()
+ .accounts
.get_val::<String>(CacheKey {
key: cache_key,
prefix: String::default()
diff --git a/crates/storage_impl/src/business_profile.rs b/crates/storage_impl/src/business_profile.rs
index 6dc4201067..502b33e7b0 100644
--- a/crates/storage_impl/src/business_profile.rs
+++ b/crates/storage_impl/src/business_profile.rs
@@ -11,10 +11,13 @@ use hyperswitch_domain_models::{
use router_env::logger;
use router_env::{instrument, tracing};
+#[cfg(feature = "accounts_cache")]
+use crate::metrics;
#[cfg(feature = "accounts_cache")]
use crate::redis::{
cache,
- cache::{CacheKind, ACCOUNTS_CACHE},
+ cache::{CacheId, CacheInterface, CacheKind},
+ kv_store::RedisConnInterface,
};
use crate::{
behaviour::{Conversion, ForeignFrom, ReverseConversion},
@@ -22,8 +25,6 @@ use crate::{
utils::{pg_accounts_connection_read, pg_accounts_connection_write},
CustomResult, DatabaseStore, MockDb, RouterStore, StorageError,
};
-#[cfg(feature = "accounts_cache")]
-use crate::{metrics, RedisConnInterface};
/// Cache key for a profile, shared by both the profile-scoped and merchant-scoped lookups.
#[cfg(feature = "accounts_cache")]
@@ -38,10 +39,12 @@ fn profile_cache_key(profile_id: &common_utils::id_type::ProfileId) -> String {
/// invite a retry, without clearing the stale entry either way. The staleness is instead bounded by
/// the cache TTLs, and the failure is logged and counted so it stays visible.
#[cfg(feature = "accounts_cache")]
-async fn publish_and_redact_business_profile_cache(
- store: &(dyn RedisConnInterface + Send + Sync),
+async fn publish_and_redact_business_profile_cache<S>(
+ store: &S,
profile_id: &common_utils::id_type::ProfileId,
-) {
+) where
+ S: RedisConnInterface + CacheInterface + Send + Sync + ?Sized,
+{
let redaction_result = cache::redact_from_redis_and_publish(
store,
[CacheKind::Accounts(profile_cache_key(profile_id).into())],
@@ -217,7 +220,7 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {
self,
&profile_cache_key(profile_id),
fetch_func,
- &ACCOUNTS_CACHE,
+ CacheId::Accounts,
))
.await?
.convert(
@@ -265,7 +268,7 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {
self,
&profile_cache_key(profile_id),
fetch_func,
- &ACCOUNTS_CACHE,
+ CacheId::Accounts,
))
.await?
.convert(
diff --git a/crates/storage_impl/src/card_issuer.rs b/crates/storage_impl/src/card_issuer.rs
index 8f3a7fb5a2..e2db70836a 100644
--- a/crates/storage_impl/src/card_issuer.rs
+++ b/crates/storage_impl/src/card_issuer.rs
@@ -9,7 +9,7 @@ use router_env::{instrument, tracing};
use crate::{
errors::StorageError,
kv_router_store::KVRouterStore,
- redis::cache::{self, CacheKind, CONFIG_CACHE},
+ redis::cache::{self, CacheKind},
utils::{pg_connection_read, pg_connection_write},
CustomResult, DatabaseStore, MockDb, RouterStore,
};
@@ -93,7 +93,7 @@ impl<T: DatabaseStore> CardIssuersInterface for RouterStore<T> {
self,
CARD_ISSUERS_LIST_CACHE_KEY,
fetch_func,
- &CONFIG_CACHE,
+ cache::CacheId::Config,
)
.await
}
diff --git a/crates/storage_impl/src/configs.rs b/crates/storage_impl/src/configs.rs
index 6759d22df2..4cad28a16c 100644
--- a/crates/storage_impl/src/configs.rs
+++ b/crates/storage_impl/src/configs.rs
@@ -9,7 +9,7 @@ use crate::{
kv_router_store,
redis::{
cache,
- cache::{CacheKind, CONFIG_CACHE},
+ cache::{CacheId, CacheKind},
},
store::ConfigUpdateInternal,
CustomResult, DatabaseStore, MockDb, RouterStore,
@@ -124,7 +124,8 @@ impl<T: DatabaseStore> ConfigInterface for RouterStore<T> {
}
}
};
- cache::get_or_populate_in_memory(self, key, find_config_by_key_from_db, &CONFIG_CACHE).await
+ cache::get_or_populate_in_memory(self, key, find_config_by_key_from_db, CacheId::Config)
+ .await
}
#[instrument(skip_all)]
diff --git a/crates/storage_impl/src/kv_router_store.rs b/crates/storage_impl/src/kv_router_store.rs
index 86b1e42ee6..489095205a 100644
--- a/crates/storage_impl/src/kv_router_store.rs
+++ b/crates/storage_impl/src/kv_router_store.rs
@@ -24,9 +24,12 @@ use crate::{
errors::{self, RedisErrorExt, StorageResult},
lookup::ReverseLookupInterface,
metrics,
- redis::kv_store::{
- decide_storage_scheme, kv_wrapper, KvOperation, KvStorePartition, Op, PartitionKey,
- RedisConnInterface,
+ redis::{
+ cache::{CacheInterface, Caches},
+ kv_store::{
+ decide_storage_scheme, kv_wrapper, KvOperation, KvStorePartition, Op, PartitionKey,
+ RedisConnInterface,
+ },
},
utils::{find_all_combined_kv_database, try_redis_get_else_try_database_get},
RouterStore, TenantConfig, UniqueConstraints,
@@ -185,6 +188,16 @@ impl<T: DatabaseStore> RedisConnInterface for KVRouterStore<T> {
}
}
+impl<T: DatabaseStore> CacheInterface for KVRouterStore<T> {
+ fn caches(&self) -> &Caches {
+ self.router_store.caches()
+ }
+
+ fn cache_key_prefix(&self) -> &str {
+ self.router_store.cache_key_prefix()
+ }
+}
+
impl<T: DatabaseStore> KVRouterStore<T> {
pub fn from_store(
store: RouterStore<T>,
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs
index a603885d84..2ea47e4270 100644
--- a/crates/storage_impl/src/lib.rs
+++ b/crates/storage_impl/src/lib.rs
@@ -61,13 +61,19 @@ use redis_interface::{errors::RedisError, RedisConnectionWithContext, SaddReply}
#[cfg(not(feature = "payouts"))]
pub use crate::database::store::Store;
-use crate::redis::kv_store;
+use crate::redis::{
+ cache::{CacheInterface, Caches},
+ kv_store,
+};
pub use crate::{database::store::DatabaseStore, errors::StorageError};
#[derive(Debug, Clone)]
pub struct RouterStore<T: DatabaseStore> {
db_store: T,
cache_store: Arc<RedisStore>,
+ /// The process-wide in-memory caches. Shared with every other tenant's store and with
+ /// the redis subscriber that invalidates them; see [`Caches`].
+ caches: Arc<Caches>,
master_encryption_key: StrongSecret<Vec<u8>>,
pub request_id: Option<String>,
key_manager_state: Option<KeyManagerState>,
@@ -82,6 +88,16 @@ impl<T: DatabaseStore> RedisConnInterface for RouterStore<T> {
}
}
+impl<T: DatabaseStore> CacheInterface for RouterStore<T> {
+ fn caches(&self) -> &Caches {
+ &self.caches
+ }
+
+ fn cache_key_prefix(&self) -> &str {
+ self.cache_store.key_prefix()
+ }
+}
+
impl<T: DatabaseStore> RouterStore<T> {
pub fn set_key_manager_state(&mut self, state: KeyManagerState) {
self.key_manager_state = Some(state);
@@ -108,7 +124,7 @@ where
redis_interface::RedisSettings,
StrongSecret<Vec<u8>>,
tokio::sync::oneshot::Sender<()>,
- &'static str,
+ Arc<Caches>,
);
async fn new(
config: Self::Config,
@@ -117,14 +133,14 @@ where
key_manager_state: Option<KeyManagerState>,
event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> error_stack::Result<Self, StorageError> {
- let (db_conf, cache_conf, encryption_key, cache_error_signal, inmemory_cache_stream) =
- config;
+ let (db_conf, cache_conf, encryption_key, cache_error_signal, caches) = config;
if test_transaction {
Self::test_store(
db_conf,
tenant_config,
&cache_conf,
encryption_key,
+ caches,
key_manager_state,
event_emitter,
)
@@ -137,7 +153,7 @@ where
encryption_key,
Self::cache_store(&cache_conf, cache_error_signal, Arc::new(NoOpEventEmitter))
.await?,
- inmemory_cache_stream,
+ caches,
key_manager_state,
event_emitter,
)
@@ -179,7 +195,7 @@ impl<T: DatabaseStore> RouterStore<T> {
tenant_config: &dyn TenantConfig,
encryption_key: StrongSecret<Vec<u8>>,
cache_store: Arc<RedisStore>,
- inmemory_cache_stream: &str,
+ caches: Arc<Caches>,
key_manager_state: Option<KeyManagerState>,
event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> error_stack::Result<Self, StorageError> {
@@ -199,7 +215,7 @@ impl<T: DatabaseStore> RouterStore<T> {
cache_store
.get_redis_pool()
.change_context(StorageError::InitializationError)?
- .subscribe(inmemory_cache_stream)
+ .subscribe(&caches.invalidation_channel, Arc::clone(&caches))
.await
.change_context(StorageError::InitializationError)
.attach_printable("Failed to subscribe to inmemory cache stream")?;
@@ -207,6 +223,7 @@ impl<T: DatabaseStore> RouterStore<T> {
Ok(Self {
db_store,
cache_store,
+ caches,
master_encryption_key: encryption_key,
request_id: None,
key_manager_state,
@@ -432,6 +449,7 @@ impl<T: DatabaseStore> RouterStore<T> {
tenant_config: &dyn TenantConfig,
cache_conf: &redis_interface::RedisSettings,
encryption_key: StrongSecret<Vec<u8>>,
+ caches: Arc<Caches>,
key_manager_state: Option<KeyManagerState>,
event_emitter: Arc<dyn ExternalServiceEventEmitter>,
) -> error_stack::Result<Self, StorageError> {
@@ -451,6 +469,7 @@ impl<T: DatabaseStore> RouterStore<T> {
Ok(Self {
db_store,
cache_store: Arc::new(cache_store),
+ caches,
master_encryption_key: encryption_key,
request_id: None,
key_manager_state,
diff --git a/crates/storage_impl/src/merchant_account.rs b/crates/storage_impl/src/merchant_account.rs
index f2a4bfe65d..2e28543495 100644
--- a/crates/storage_impl/src/merchant_account.rs
+++ b/crates/storage_impl/src/merchant_account.rs
@@ -15,10 +15,10 @@ use router_env::{instrument, tracing};
#[cfg(feature = "accounts_cache")]
use crate::redis::{
cache,
- cache::{CacheKind, ACCOUNTS_CACHE},
+ cache::{CacheId, CacheInterface, CacheKind},
+ kv_store::RedisConnInterface,
};
#[cfg(feature = "accounts_cache")]
-use crate::RedisConnInterface;
use crate::{
behaviour::{Conversion, ForeignFrom, ForeignInto, ReverseConversion},
kv_router_store,
@@ -208,7 +208,7 @@ impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> {
self,
merchant_id.get_string_repr(),
fetch_func,
- &ACCOUNTS_CACHE,
+ CacheId::Accounts,
)
.await?
.convert(
@@ -308,7 +308,7 @@ impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> {
self,
publishable_key,
fetch_by_pub_key_func,
- &ACCOUNTS_CACHE,
+ CacheId::Accounts,
)
.await?;
}
@@ -806,10 +806,13 @@ impl MerchantAccountInterface for MockDb {
}
#[cfg(feature = "accounts_cache")]
-async fn publish_and_redact_merchant_account_cache(
- store: &(dyn RedisConnInterface + Send + Sync),
+async fn publish_and_redact_merchant_account_cache<S>(
+ store: &S,
merchant_account: &storage::MerchantAccount,
-) -> CustomResult<(), StorageError> {
+) -> CustomResult<(), StorageError>
+where
+ S: RedisConnInterface + CacheInterface + Send + Sync + ?Sized,
+{
let publishable_key = merchant_account
.publishable_key
.as_ref()
@@ -843,10 +846,13 @@ async fn publish_and_redact_merchant_account_cache(
}
#[cfg(feature = "accounts_cache")]
-async fn publish_and_redact_all_merchant_account_cache(
- cache: &(dyn RedisConnInterface + Send + Sync),
+async fn publish_and_redact_all_merchant_account_cache<S>(
+ cache: &S,
merchant_accounts: &[storage::MerchantAccount],
-) -> CustomResult<(), StorageError> {
+) -> CustomResult<(), StorageError>
+where
+ S: RedisConnInterface + CacheInterface + Send + Sync + ?Sized,
+{
let merchant_ids = merchant_accounts
.iter()
.map(|merchant_account| merchant_account.get_id().get_string_repr().to_string());
diff --git a/crates/storage_impl/src/merchant_connector_account.rs b/crates/storage_impl/src/merchant_connector_account.rs
index d4d6f20897..6597de734d 100644
--- a/crates/storage_impl/src/merchant_connector_account.rs
+++ b/crates/storage_impl/src/merchant_connector_account.rs
@@ -102,7 +102,7 @@ async fn list_all_by_merchant_id<T: DatabaseStore>(
store,
&list_cache::merchant_scope_key(merchant_id),
find_call,
- &cache::MCA_LIST_CACHE,
+ cache::CacheId::McaList,
)
.await
}
@@ -140,7 +140,7 @@ async fn list_all_by_merchant_id_profile_id<T: DatabaseStore>(
store,
&list_cache::merchant_profile_scope_key(merchant_id, profile_id),
find_call,
- &cache::MCA_LIST_CACHE,
+ cache::CacheId::McaList,
)
.await
}
@@ -457,7 +457,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {
self,
&format!("{}_{}", merchant_id.get_string_repr(), connector_label),
find_call,
- &cache::ACCOUNTS_CACHE,
+ cache::CacheId::Accounts,
)
.await
.async_and_then(|item| async {
@@ -513,7 +513,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {
self,
&format!("{}_{}", profile_id.get_string_repr(), connector_name),
find_call,
- &cache::ACCOUNTS_CACHE,
+ cache::CacheId::Accounts,
)
.await
.async_and_then(|item| async {
@@ -590,7 +590,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {
merchant_connector_id.get_string_repr()
),
find_call,
- &cache::ACCOUNTS_CACHE,
+ cache::CacheId::Accounts,
)
.await?
.convert(
@@ -638,7 +638,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {
self,
id.get_string_repr(),
find_call,
- &cache::ACCOUNTS_CACHE,
+ cache::CacheId::Accounts,
)
.await?
.convert(
diff --git a/crates/storage_impl/src/merchant_key_store.rs b/crates/storage_impl/src/merchant_key_store.rs
index 5793509c2c..2f9bb3c54d 100644
--- a/crates/storage_impl/src/merchant_key_store.rs
+++ b/crates/storage_impl/src/merchant_key_store.rs
@@ -10,7 +10,7 @@ use router_env::{instrument, tracing};
#[cfg(feature = "accounts_cache")]
use crate::redis::{
cache,
- cache::{CacheKind, ACCOUNTS_CACHE},
+ cache::{CacheId, CacheKind},
};
use crate::{
kv_router_store,
@@ -140,7 +140,7 @@ impl<T: DatabaseStore> MerchantKeyStoreInterface for RouterStore<T> {
self,
&key_store_cache_key,
fetch_func,
- &ACCOUNTS_CACHE,
+ CacheId::Accounts,
)
.await?
.convert(state, key, merchant_id.clone().into())
diff --git a/crates/storage_impl/src/metrics.rs b/crates/storage_impl/src/metrics.rs
index 303259f659..2d9cfc3af3 100644
--- a/crates/storage_impl/src/metrics.rs
+++ b/crates/storage_impl/src/metrics.rs
@@ -13,6 +13,10 @@ counter_metric!(KV_SOFT_KILL_ACTIVE_UPDATE, GLOBAL_METER);
// Metrics for In-memory cache
gauge_metric!(IN_MEMORY_CACHE_ENTRY_COUNT, GLOBAL_METER);
+// The configured entry ceiling, recorded alongside the count above so that utilisation is
+// computable from the metrics rather than from configuration. moka's other runtime figure,
+// `weighted_size`, is not recorded: with no weigher configured it equals the entry count.
+gauge_metric!(IN_MEMORY_CACHE_MAX_CAPACITY, GLOBAL_METER);
counter_metric!(IN_MEMORY_CACHE_HIT, GLOBAL_METER);
counter_metric!(IN_MEMORY_CACHE_MISS, GLOBAL_METER);
counter_metric!(IN_MEMORY_CACHE_EVICTION_COUNT, GLOBAL_METER);
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
index 196c2e9f70..464a527de8 100644
--- a/crates/storage_impl/src/mock_db.rs
+++ b/crates/storage_impl/src/mock_db.rs
@@ -11,7 +11,10 @@ use hyperswitch_domain_models::{
};
use redis_interface::RedisSettings;
-use crate::{errors::StorageError, redis::RedisStore};
+use crate::{
+ errors::StorageError,
+ redis::{cache::Caches, RedisStore},
+};
pub mod payment_attempt;
pub mod payment_intent;
@@ -36,6 +39,9 @@ pub struct MockDb {
pub refunds: Arc<Mutex<Vec<store::Refund>>>,
pub processes: Arc<Mutex<Vec<store::ProcessTracker>>>,
pub redis: Arc<RedisStore>,
+ /// In-memory caches, built with the defaults — a mock store has no configuration to
+ /// take them from.
+ pub caches: Arc<Caches>,
pub api_keys: Arc<Mutex<Vec<store::ApiKey>>>,
pub ephemeral_keys: Arc<Mutex<Vec<store::EphemeralKey>>>,
pub cards_info: Arc<Mutex<Vec<store::CardInfo>>>,
@@ -98,6 +104,7 @@ impl MockDb {
.await
.change_context(StorageError::InitializationError)?,
),
+ caches: Arc::new(Caches::default()),
api_keys: Default::default(),
ephemeral_keys: Default::default(),
cards_info: Default::default(),
diff --git a/crates/storage_impl/src/mock_db/redis_conn.rs b/crates/storage_impl/src/mock_db/redis_conn.rs
index e78e525489..20fe82b058 100644
--- a/crates/storage_impl/src/mock_db/redis_conn.rs
+++ b/crates/storage_impl/src/mock_db/redis_conn.rs
@@ -1,7 +1,10 @@
use redis_interface::errors::RedisError;
use super::MockDb;
-use crate::redis::kv_store::RedisConnInterface;
+use crate::redis::{
+ cache::{CacheInterface, Caches},
+ kv_store::RedisConnInterface,
+};
impl RedisConnInterface for MockDb {
fn get_redis_conn(
@@ -12,3 +15,13 @@ impl RedisConnInterface for MockDb {
Ok(redis_interface::RedisConnectionWithContext::new_without_context(pool))
}
}
+
+impl CacheInterface for MockDb {
+ fn caches(&self) -> &Caches {
+ &self.caches
+ }
+
+ fn cache_key_prefix(&self) -> &str {
+ self.redis.key_prefix()
+ }
+}
diff --git a/crates/storage_impl/src/redis.rs b/crates/storage_impl/src/redis.rs
index 541e114d50..ec6222e769 100644
--- a/crates/storage_impl/src/redis.rs
+++ b/crates/storage_impl/src/redis.rs
@@ -65,6 +65,15 @@ impl RedisStore {
}
}
+ /// The key prefix this store's keys are namespaced by.
+ ///
+ /// Deliberately not routed through [`Self::get_redis_pool`]: the prefix is a plain
+ /// string that is known whether or not redis is reachable, and callers need it on paths
+ /// that must not fail when redis is down.
+ pub fn key_prefix(&self) -> &str {
+ &self.redis_conn.key_prefix
+ }
+
pub fn clone_pool_with_prefix(&self, key_prefix: &str) -> Self {
Self {
redis_conn: Arc::new(redis_interface::RedisConnectionPool::clone(
diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs
index 28146e6bf8..a8d04fab0b 100644
--- a/crates/storage_impl/src/redis/cache.rs
+++ b/crates/storage_impl/src/redis/cache.rs
@@ -1,9 +1,4 @@
-use std::{
- any::Any,
- borrow::Cow,
- fmt::Debug,
- sync::{Arc, LazyLock},
-};
+use std::{any::Any, borrow::Cow, fmt::Debug, sync::Arc};
use common_utils::{
errors::{self, CustomResult},
@@ -24,97 +19,308 @@ use crate::{
redis::{kv_store::RedisConnInterface, pub_sub::PubSubInterface},
};
-/// Redis channel name used for publishing invalidation messages
-pub const IMC_INVALIDATION_CHANNEL: &str = "hyperswitch_invalidate";
+/// Default redis channel name used for publishing invalidation messages
+pub const DEFAULT_IMC_INVALIDATION_CHANNEL: &str = "hyperswitch_invalidate";
+
+/// Default time to live 30 mins
+pub const DEFAULT_CACHE_TTL: u64 = 30 * 60;
-/// Time to live 30 mins
-const CACHE_TTL: u64 = 30 * 60;
+/// Default time to idle 10 mins
+pub const DEFAULT_CACHE_TTI: u64 = 10 * 60;
-/// Time to idle 10 mins
-const CACHE_TTI: u64 = 10 * 60;
+/// Default entry ceiling, deliberately the number the caches have always been built with.
+///
+/// It was written as `30` and documented as megabytes, then multiplied by `1024 * 1024` on the
+/// way into moka — which, with no weigher configured, read it as a number of entries. So the
+/// effective ceiling has always been 31,457,280 entries, and these caches have never come
+/// close to it.
+///
+/// Kept verbatim rather than replaced with a tighter or byte-based default: at this size it
+/// binds nothing, which is exactly the point — the ceiling that ships must not start evicting
+/// where nothing evicted before. What bounds the resident set in normal operation is
+/// `time_to_idle`, since these caches are keyed per merchant and profile and an entry unread
+/// for its window is dropped.
+///
+/// Choosing a ceiling that actually binds is an operational decision rather than a default:
+/// set `max_capacity` per cache, in either unit, once the sizes involved are known.
+pub const DEFAULT_MAX_ENTRIES: u64 = 30 * 1024 * 1024;
-/// Max Capacity of Cache in MB
-const MAX_CAPACITY: u64 = 30;
+/// Runtime overrides for a single in-memory cache.
+///
+/// Every field is optional: whatever is left unset falls back to that cache's compiled-in
+/// default, so an absent (or partial) configuration reproduces the values the caches were
+/// previously hardcoded with.
+#[derive(Debug, Clone, Copy, Default, serde::Deserialize)]
+#[serde(default)]
+pub struct CacheSettings {
+ /// Time in seconds an entry is retained after it was inserted
+ pub ttl_in_secs: Option<u64>,
+ /// Time in seconds an entry is retained after it was last read or written
+ pub tti_in_secs: Option<u64>,
+ /// Maximum number of entries the cache may hold. `0` makes it unbounded, and leaving it
+ /// unset keeps the cache's own default.
+ pub max_entries: Option<u64>,
+}
-/// Config Cache with time_to_live as 30 mins and time_to_idle as 10 mins.
-pub static CONFIG_CACHE: LazyLock<Cache> =
- LazyLock::new(|| Cache::new("CONFIG_CACHE", CACHE_TTL, CACHE_TTI, None));
+impl CacheSettings {
+ fn time_to_live(&self) -> u64 {
+ self.ttl_in_secs.unwrap_or(DEFAULT_CACHE_TTL)
+ }
-/// Accounts cache with time_to_live as 30 mins and size limit
-pub static ACCOUNTS_CACHE: LazyLock<Cache> =
- LazyLock::new(|| Cache::new("ACCOUNTS_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
+ fn time_to_idle(&self) -> u64 {
+ self.tti_in_secs.unwrap_or(DEFAULT_CACHE_TTI)
+ }
-/// Merchant connector account list cache.
+ /// Resolves the entry ceiling against the cache's own default.
+ ///
+ /// `None` means unbounded, and an explicitly configured `0` is how a bounded cache is made
+ /// unbounded, since the key's absence already means "use the default".
+ fn max_entries(&self, default: Option<u64>) -> Option<u64> {
+ match self.max_entries {
+ Some(0) => None,
+ Some(entries) => Some(entries),
+ None => default,
+ }
+ }
+
+ /// Builds the cache this configuration describes.
+ ///
+ /// `default` is the cache's own ceiling when the configuration names none, `None` meaning
+ /// unbounded.
+ fn build(&self, name: &'static str, default: Option<u64>) -> Cache {
+ Cache::new(
+ name,
+ self.time_to_live(),
+ self.time_to_idle(),
+ self.max_entries(default),
+ )
+ }
+}
+
+/// Runtime configuration of the in-memory caches, with per-cache granularity.
+#[derive(Debug, Clone, Default, serde::Deserialize)]
+#[serde(default)]
+pub struct CacheConfig {
+ /// Redis channel the invalidation messages are published on and subscribed to.
+ /// All instances of a deployment must agree on this value.
+ pub invalidation_channel: Option<String>,
+ pub config: CacheSettings,
+ pub accounts: CacheSettings,
+ pub mca_list: CacheSettings,
+ pub routing: CacheSettings,
+ pub decision_manager: CacheSettings,
+ pub surcharge: CacheSettings,
+ pub cgraph: CacheSettings,
+ pub pm_filters_cgraph: CacheSettings,
+ pub success_based_dynamic_algorithm: CacheSettings,
+ pub elimination_based_dynamic_algorithm: CacheSettings,
+ pub contract_based_dynamic_algorithm: CacheSettings,
+}
+
+/// The in-memory caches, together with the redis channel their invalidations travel on.
///
-/// Holds whole-scope supersets of merchant connector account rows (every account of a
-/// merchant, or of a profile) which the individual list queries project from. Kept
-/// separate from [`ACCOUNTS_CACHE`] so that list hit rates and entry counts are
-/// observable on their own, and so the two can be sized independently.
-pub static MCA_LIST_CACHE: LazyLock<Cache> =
- LazyLock::new(|| Cache::new("MCA_LIST_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
-
-/// Routing Cache
-pub static ROUTING_CACHE: LazyLock<Cache> =
- LazyLock::new(|| Cache::new("ROUTING_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
-
-/// 3DS Decision Manager Cache
-pub static DECISION_MANAGER_CACHE: LazyLock<Cache> = LazyLock::new(|| {
- Cache::new(
- "DECISION_MANAGER_CACHE",
- CACHE_TTL,
- CACHE_TTI,
- Some(MAX_CAPACITY),
- )
-});
-
-/// Surcharge Cache
-pub static SURCHARGE_CACHE: LazyLock<Cache> =
- LazyLock::new(|| Cache::new("SURCHARGE_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
-
-/// CGraph Cache
-pub static CGRAPH_CACHE: LazyLock<Cache> =
- LazyLock::new(|| Cache::new("CGRAPH_CACHE", CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
-
-/// PM Filter CGraph Cache
-pub static PM_FILTERS_CGRAPH_CACHE: LazyLock<Cache> = LazyLock::new(|| {
- Cache::new(
- "PM_FILTERS_CGRAPH_CACHE",
- CACHE_TTL,
- CACHE_TTI,
- Some(MAX_CAPACITY),
- )
-});
-
-/// Success based Dynamic Algorithm Cache
-pub static SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE: LazyLock<Cache> = LazyLock::new(|| {
- Cache::new(
- "SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE",
- CACHE_TTL,
- CACHE_TTI,
- Some(MAX_CAPACITY),
- )
-});
-
-/// Elimination based Dynamic Algorithm Cache
-pub static ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE: LazyLock<Cache> = LazyLock::new(|| {
- Cache::new(
- "ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE",
- CACHE_TTL,
- CACHE_TTI,
- Some(MAX_CAPACITY),
- )
-});
-
-/// Contract Routing based Dynamic Algorithm Cache
-pub static CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE: LazyLock<Cache> = LazyLock::new(|| {
- Cache::new(
- "CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE",
- CACHE_TTL,
- CACHE_TTI,
- Some(MAX_CAPACITY),
- )
-});
+/// Built once per process and shared by every tenant's store through an [`Arc`]: entries are
+/// isolated by the tenant prefix carried in [`CacheKey`], and the single redis subscriber that
+/// applies invalidations has to reach the very same instances the stores read from. Handing a
+/// tenant its own set would both multiply the memory budget and strand every tenant but one
+/// with stale entries.
+#[derive(Debug)]
+pub struct Caches {
+ /// Redis channel invalidation messages are published on and subscribed to
+ pub invalidation_channel: String,
+ /// Config cache, unbounded by default
+ pub config: Cache,
+ /// Accounts cache
+ pub accounts: Cache,
+ /// Merchant connector account list cache.
+ ///
+ /// Holds whole-scope supersets of merchant connector account rows (every account of a
+ /// merchant, or of a profile) which the individual list queries project from. Kept
+ /// separate from [`Caches::accounts`] so that list hit rates and entry counts are
+ /// observable on their own, and so the two can be sized independently.
+ pub mca_list: Cache,
+ /// Routing cache
+ pub routing: Cache,
+ /// 3DS decision manager cache
+ pub decision_manager: Cache,
+ /// Surcharge cache
+ pub surcharge: Cache,
+ /// CGraph cache
+ pub cgraph: Cache,
+ /// PM filter CGraph cache
+ pub pm_filters_cgraph: Cache,
+ /// Success based dynamic algorithm cache
+ pub success_based_dynamic_algorithm: Cache,
+ /// Elimination based dynamic algorithm cache
+ pub elimination_based_dynamic_algorithm: Cache,
+ /// Contract routing based dynamic algorithm cache
+ pub contract_based_dynamic_algorithm: Cache,
+}
+impl Caches {
+ /// Builds every cache from `config`, falling back to the per-cache defaults for anything
+ /// left unset.
+ pub fn new(config: &CacheConfig) -> Self {
+ // Every cache defaults to the ceiling it has always had, so shipping this changes no
+ // eviction behaviour anywhere.
+ const DEFAULT: Option<u64> = Some(DEFAULT_MAX_ENTRIES);
+ // As before, the config cache is the one built with no ceiling at all.
+ const UNBOUNDED: Option<u64> = None;
+
+ Self {
+ invalidation_channel: config
+ .invalidation_channel
+ .clone()
+ .unwrap_or_else(|| DEFAULT_IMC_INVALIDATION_CHANNEL.to_string()),
+ config: config.config.build("CONFIG_CACHE", UNBOUNDED),
+ accounts: config.accounts.build("ACCOUNTS_CACHE", DEFAULT),
+ mca_list: config.mca_list.build("MCA_LIST_CACHE", DEFAULT),
+ routing: config.routing.build("ROUTING_CACHE", DEFAULT),
+ decision_manager: config
+ .decision_manager
+ .build("DECISION_MANAGER_CACHE", DEFAULT),
+ surcharge: config.surcharge.build("SURCHARGE_CACHE", DEFAULT),
+ cgraph: config.cgraph.build("CGRAPH_CACHE", DEFAULT),
+ pm_filters_cgraph: config
+ .pm_filters_cgraph
+ .build("PM_FILTERS_CGRAPH_CACHE", DEFAULT),
+ success_based_dynamic_algorithm: config
+ .success_based_dynamic_algorithm
+ .build("SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE", DEFAULT),
+ elimination_based_dynamic_algorithm: config
+ .elimination_based_dynamic_algorithm
+ .build("ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE", DEFAULT),
+ contract_based_dynamic_algorithm: config
+ .contract_based_dynamic_algorithm
+ .build("CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE", DEFAULT),
+ }
+ }
+
+ /// The caches an invalidation of `kind` has to be applied to.
+ pub fn for_kind(&self, kind: &CacheKind<'_>) -> Vec<&Cache> {
+ match kind {
+ CacheKind::Config(_) => vec![&self.config],
+ CacheKind::Accounts(_) => vec![&self.accounts],
+ CacheKind::MerchantConnectorAccountList(_) => vec![&self.mca_list],
+ CacheKind::Routing(_) => vec![&self.routing],
+ CacheKind::DecisionManager(_) => vec![&self.decision_manager],
+ CacheKind::Surcharge(_) => vec![&self.surcharge],
+ CacheKind::CGraph(_) => vec![&self.cgraph],
+ CacheKind::PmFiltersCGraph(_) => vec![&self.pm_filters_cgraph],
+ CacheKind::SuccessBasedDynamicRoutingCache(_) => {
+ vec![&self.success_based_dynamic_algorithm]
+ }
+ CacheKind::EliminationBasedDynamicRoutingCache(_) => {
+ vec![&self.elimination_based_dynamic_algorithm]
+ }
+ CacheKind::ContractBasedDynamicRoutingCache(_) => {
+ vec![&self.contract_based_dynamic_algorithm]
+ }
+ CacheKind::All(_) => self.all().to_vec(),
+ }
+ }
+
+ /// The cache `id` names.
+ pub fn get(&self, id: CacheId) -> &Cache {
+ let Self {
+ config,
+ accounts,
+ mca_list,
+ routing,
+ decision_manager,
+ surcharge,
+ cgraph,
+ pm_filters_cgraph,
+ success_based_dynamic_algorithm,
+ elimination_based_dynamic_algorithm,
+ contract_based_dynamic_algorithm,
+ invalidation_channel: _,
+ } = self;
+ match id {
+ CacheId::Config => config,
+ CacheId::Accounts => accounts,
+ CacheId::McaList => mca_list,
+ CacheId::Routing => routing,
+ CacheId::DecisionManager => decision_manager,
+ CacheId::Surcharge => surcharge,
+ CacheId::CGraph => cgraph,
+ CacheId::PmFiltersCGraph => pm_filters_cgraph,
+ CacheId::SuccessBasedDynamicAlgorithm => success_based_dynamic_algorithm,
+ CacheId::EliminationBasedDynamicAlgorithm => elimination_based_dynamic_algorithm,
+ CacheId::ContractBasedDynamicAlgorithm => contract_based_dynamic_algorithm,
+ }
+ }
+
+ /// Every cache in the set, so that callers iterating over all of them — metrics
+ /// collection, say — cannot silently fall behind a newly added cache.
+ pub fn all(&self) -> [&Cache; 11] {
+ let Self {
+ config,
+ accounts,
+ mca_list,
+ routing,
+ decision_manager,
+ surcharge,
+ cgraph,
+ pm_filters_cgraph,
+ success_based_dynamic_algorithm,
+ elimination_based_dynamic_algorithm,
+ contract_based_dynamic_algorithm,
+ invalidation_channel: _,
+ } = self;
+ [
+ config,
+ accounts,
+ mca_list,
+ routing,
+ decision_manager,
+ surcharge,
+ cgraph,
+ pm_filters_cgraph,
+ success_based_dynamic_algorithm,
+ elimination_based_dynamic_algorithm,
+ contract_based_dynamic_algorithm,
+ ]
+ }
+}
+
+impl Default for Caches {
+ fn default() -> Self {
+ Self::new(&CacheConfig::default())
+ }
+}
+
+/// A store that owns a set of in-memory caches, the way [`RedisConnInterface`] gives one a
+/// redis connection. Deliberately independent of it: holding caches and holding a redis
+/// connection are separate capabilities, and the helpers below ask for both where they need
+/// both.
+pub trait CacheInterface {
+ fn caches(&self) -> &Caches;
+
+ /// The tenant prefix in-memory cache keys are namespaced by.
+ ///
+ /// Available without a redis connection, so an in-memory hit never has to acquire one.
+ fn cache_key_prefix(&self) -> &str;
+}
+
+/// Names one of the [`Caches`].
+///
+/// Lookups name the cache they want rather than passing an instance, so the cache they read
+/// is necessarily the one belonging to the store they are given.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CacheId {
+ Config,
+ Accounts,
+ McaList,
+ Routing,
+ DecisionManager,
+ Surcharge,
+ CGraph,
+ PmFiltersCGraph,
+ SuccessBasedDynamicAlgorithm,
+ EliminationBasedDynamicAlgorithm,
+ ContractBasedDynamicAlgorithm,
+}
/// Trait which defines the behaviour of types that's gonna be stored in Cache
pub trait Cacheable: Any + Send + Sync + DynClone {
fn as_any(&self) -> &dyn Any;
@@ -204,6 +410,14 @@ pub struct Cache {
inner: MokaCache<String, Arc<dyn Cacheable>>,
}
+impl Debug for Cache {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Cache")
+ .field("name", &self.name)
+ .finish_non_exhaustive()
+ }
+}
+
#[derive(Debug, Clone)]
pub struct CacheKey {
pub key: String,
@@ -250,12 +464,12 @@ impl Cache {
/// `name` : Cache type name to be used as an attribute in metrics
/// `time_to_live`: Time in seconds before an object is stored in a caching system before it’s deleted
/// `time_to_idle`: Time in seconds before a `get` or `insert` operation an object is stored in a caching system before it's deleted
- /// `max_capacity`: Max size in MB's that the cache can hold
+ /// `max_entries` : Maximum number of entries the cache can hold, `None` for unbounded
pub fn new(
name: &'static str,
time_to_live: u64,
time_to_idle: u64,
- max_capacity: Option<u64>,
+ max_entries: Option<u64>,
) -> Self {
// Record the metrics of manual invalidation of cache entry by the application
let eviction_listener = move |_, _, cause| {
@@ -272,8 +486,10 @@ impl Cache {
.time_to_idle(std::time::Duration::from_secs(time_to_idle))
.eviction_listener(eviction_listener);
- if let Some(capacity) = max_capacity {
- cache_builder = cache_builder.max_capacity(capacity * 1024 * 1024);
+ // No weigher is configured, so moka counts entries — which is what this number has
+ // always meant, and now says.
+ if let Some(entries) = max_entries {
+ cache_builder = cache_builder.max_capacity(entries);
}
Self {
@@ -333,9 +549,11 @@ impl Cache {
.add(1, router_env::metric_attributes!(("cache_type", self.name)));
}
- let val = (*val?).as_any().downcast_ref::<T>().cloned();
-
- val
+ // The explicit deref is load-bearing. `Arc<dyn Cacheable>` satisfies the blanket
+ // `Cacheable` impl itself, so `val?.as_any()` would resolve to the `Arc`'s own impl and
+ // hand back a `&dyn Any` describing the `Arc` — downcasting which silently turns every
+ // read into a miss. Deref first so `as_any` comes from the value inside.
+ (*val?).as_any().downcast_ref::<T>().cloned()
}
/// Check if a key exists in cache
@@ -389,13 +607,26 @@ impl Cache {
self.name
}
- pub async fn record_entry_count_metric(&self) {
+ /// Records everything moka exposes about this cache's occupancy.
+ ///
+ /// `entry_count` and `weighted_size` are the only runtime figures it publishes — there are
+ /// no built-in hit or miss statistics, which is why those are counted by hand in
+ /// [`Self::get_val`]. The configured ceiling is recorded alongside so that utilisation is
+ /// derivable from the metrics rather than from configuration.
+ pub async fn record_size_metrics(&self) {
self.run_pending_tasks().await;
- metrics::IN_MEMORY_CACHE_ENTRY_COUNT.record(
- self.get_entry_count(),
- router_env::metric_attributes!(("cache_type", self.name)),
- );
+ let attributes = router_env::metric_attributes!(("cache_type", self.name));
+
+ metrics::IN_MEMORY_CACHE_ENTRY_COUNT.record(self.get_entry_count(), attributes);
+
+ // `weighted_size` is deliberately not recorded: with no weigher configured it is the
+ // entry count again, so it would be a second name for the gauge above.
+ //
+ // Absent for an unbounded cache, where there is no ceiling to be a fraction of.
+ if let Some(max_capacity) = self.inner.policy().max_capacity() {
+ metrics::IN_MEMORY_CACHE_MAX_CAPACITY.record(max_capacity, attributes);
+ }
}
}
@@ -450,53 +681,53 @@ fn deja_in_memory_args(cache_name: &str, key: &CacheKey) -> serde_json::Value {
}
#[instrument(skip_all)]
-pub async fn get_or_populate_in_memory<T, F, Fut>(
- store: &(dyn RedisConnInterface + Send + Sync),
+pub async fn get_or_populate_in_memory<T, F, Fut, S>(
+ store: &S,
key: &str,
fun: F,
- cache: &Cache,
+ cache: CacheId,
) -> CustomResult<T, StorageError>
where
T: Cacheable + serde::Serialize + serde::de::DeserializeOwned + Debug + Clone,
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
+ S: RedisConnInterface + CacheInterface + Send + Sync + ?Sized,
{
+ let cache = store.caches().get(cache);
+ let cache_key = CacheKey {
+ key: key.to_string(),
+ prefix: store.cache_key_prefix().to_string(),
+ };
+
+ // An in-memory hit answers on its own. The redis connection is acquired only on a miss,
+ // so a redis outage degrades this to a cold cache rather than an error.
+ if let Some(val) = cache.get_val::<T>(cache_key.clone()).await {
+ return Ok(val);
+ }
+
let redis = &store
.get_redis_conn()
.change_context(StorageError::RedisError(
RedisError::RedisConnectionError.into(),
))
.attach_printable("Failed to get redis connection")?;
- let cache_key = CacheKey {
- key: key.to_string(),
- prefix: redis.redis_conn.key_prefix.clone(),
- };
- let cache_val = cache.get_val::<T>(cache_key).await;
- if let Some(val) = cache_val {
- Ok(val)
- } else {
- let val = get_or_populate_redis(redis, key, None, fun).await?;
- cache
- .push(
- CacheKey {
- key: key.to_string(),
- prefix: redis.redis_conn.key_prefix.clone(),
- },
- val.clone(),
- )
- .await;
- Ok(val)
- }
+ // The redis round trip already materialized the payload, so its size is free here and
+ // does not have to be recomputed to bound the cache.
+ let val = get_or_populate_redis(redis, key, None, fun).await?;
+ cache.push(cache_key, val.clone()).await;
+
+ Ok(val)
}
#[instrument(skip_all)]
-pub async fn redact_from_redis_and_publish<
- 'a,
- K: IntoIterator<Item = CacheKind<'a>> + Send + Clone,
->(
- store: &(dyn RedisConnInterface + Send + Sync),
+pub async fn redact_from_redis_and_publish<'a, K, S>(
+ store: &S,
keys: K,
-) -> CustomResult<usize, StorageError> {
+) -> CustomResult<usize, StorageError>
+where
+ K: IntoIterator<Item = CacheKind<'a>> + Send + Clone,
+ S: RedisConnInterface + CacheInterface + Send + Sync + ?Sized,
+{
let redis_conn = store
.get_redis_conn()
.change_context(StorageError::RedisError(
@@ -525,7 +756,7 @@ pub async fn redact_from_redis_and_publish<
let redis_conn = &redis_conn;
let futures = keys.into_iter().map(move |key| async move {
redis_conn
- .publish(IMC_INVALIDATION_CHANNEL, key)
+ .publish(&store.caches().invalidation_channel, key)
.await
.change_context(StorageError::KVError)
});
@@ -537,14 +768,15 @@ pub async fn redact_from_redis_and_publish<
}
#[instrument(skip_all)]
-pub async fn publish_and_redact<'a, T, F, Fut>(
- store: &(dyn RedisConnInterface + Send + Sync),
+pub async fn publish_and_redact<'a, T, F, Fut, S>(
+ store: &S,
key: CacheKind<'a>,
fun: F,
) -> CustomResult<T, StorageError>
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
+ S: RedisConnInterface + CacheInterface + Send + Sync + ?Sized,
{
let data = fun().await?;
redact_from_redis_and_publish(store, [key]).await?;
@@ -552,8 +784,8 @@ where
}
#[instrument(skip_all)]
-pub async fn publish_and_redact_multiple<'a, T, F, Fut, K>(
- store: &(dyn RedisConnInterface + Send + Sync),
+pub async fn publish_and_redact_multiple<'a, T, F, Fut, K, S>(
+ store: &S,
keys: K,
fun: F,
) -> CustomResult<T, StorageError>
@@ -561,6 +793,7 @@ where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
K: IntoIterator<Item = CacheKind<'a>> + Send + Clone,
+ S: RedisConnInterface + CacheInterface + Send + Sync + ?Sized,
{
let data = fun().await?;
redact_from_redis_and_publish(store, keys).await?;
@@ -571,6 +804,81 @@ where
mod cache_tests {
use super::*;
+ /// The `[cache]` documentation in `config/*.toml` promises this syntax.
+ #[test]
+ fn the_documented_toml_syntax_deserializes() {
+ let config: CacheConfig = config::Config::builder()
+ .add_source(config::File::from_str(
+ r#"
+ invalidation_channel = "channel_from_toml"
+
+ [accounts]
+ ttl_in_secs = 120
+ max_entries = 500000
+
+ [config]
+ max_entries = 0
+ "#,
+ config::FileFormat::Toml,
+ ))
+ .build()
+ .expect("failed to build cache configuration")
+ .try_deserialize()
+ .expect("failed to deserialize cache configuration from TOML");
+
+ assert_eq!(
+ config.invalidation_channel.as_deref(),
+ Some("channel_from_toml")
+ );
+ assert_eq!(config.accounts.time_to_live(), 120);
+ assert_eq!(config.accounts.max_entries, Some(500_000));
+ assert_eq!(config.config.max_entries, Some(0));
+ // Untouched caches keep their own defaults.
+ assert_eq!(config.routing.max_entries, None);
+ assert_eq!(config.routing.time_to_live(), DEFAULT_CACHE_TTL);
+ }
+
+ /// Pinned against the same `Environment` source `Settings::with_config_path` builds.
+ ///
+ /// The registered list-parse keys are load-bearing: without any of them `list_separator`
+ /// applies to every key and silently turns plain string values into single-element arrays,
+ /// which no string field will accept.
+ #[test]
+ fn the_documented_env_vars_deserialize() {
+ let source: std::collections::HashMap<String, String> = [
+ ("ROUTER__ACCOUNTS__MAX_ENTRIES", "500000"),
+ ("ROUTER__CONFIG__MAX_ENTRIES", "0"),
+ ("ROUTER__CGRAPH__TTL_IN_SECS", "120"),
+ ("ROUTER__INVALIDATION_CHANNEL", "channel_from_env"),
+ ]
+ .into_iter()
+ .map(|(key, value)| (key.to_string(), value.to_string()))
+ .collect();
+
+ let config: CacheConfig = config::Config::builder()
+ .add_source(
+ config::Environment::with_prefix("ROUTER")
+ .try_parsing(true)
+ .separator("__")
+ .list_separator(",")
+ .with_list_parse_key("log.telemetry.route_to_trace")
+ .with_list_parse_key("redis.cluster_urls")
+ .source(Some(source)),
+ )
+ .build()
+ .expect("failed to build cache configuration")
+ .try_deserialize()
+ .expect("failed to deserialize cache configuration from the environment");
+
+ assert_eq!(config.accounts.max_entries, Some(500_000));
+ assert_eq!(config.config.max_entries, Some(0));
+ assert_eq!(config.cgraph.time_to_live(), 120);
+ assert_eq!(
+ config.invalidation_channel.as_deref(),
+ Some("channel_from_env")
+ );
+ }
+
#[tokio::test]
async fn construct_and_get_cache() {
let cache = Cache::new("test", 1800, 1800, None);
diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs
index 965ec17306..98909d1bea 100644
--- a/crates/storage_impl/src/redis/pub_sub.rs
+++ b/crates/storage_impl/src/redis/pub_sub.rs
@@ -1,19 +1,20 @@
-use std::sync::atomic;
+use std::sync::{atomic, Arc};
use error_stack::ResultExt;
use redis_interface::{errors as redis_errors, RedisValue};
use router_env::{logger, tracing::Instrument};
-use crate::redis::cache::{
- CacheKey, CacheKind, CacheRedact, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE,
- CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE, DECISION_MANAGER_CACHE,
- ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE, MCA_LIST_CACHE, PM_FILTERS_CGRAPH_CACHE,
- ROUTING_CACHE, SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, SURCHARGE_CACHE,
-};
+use crate::redis::cache::{CacheKey, CacheKind, CacheRedact, Caches};
#[async_trait::async_trait]
pub trait PubSubInterface {
- async fn subscribe(&self, channel: &str) -> error_stack::Result<(), redis_errors::RedisError>;
+ /// Subscribes to `channel`, spawning the handler that applies incoming invalidations to
+ /// `caches` if it is not already running.
+ async fn subscribe(
+ &self,
+ channel: &str,
+ caches: Arc<Caches>,
+ ) -> error_stack::Result<(), redis_errors::RedisError>;
async fn publish<'a>(
&self,
@@ -21,16 +22,27 @@ pub trait PubSubInterface {
key: CacheKind<'a>,
) -> error_stack::Result<usize, redis_errors::RedisError>;
- async fn on_message(&self) -> error_stack::Result<(), redis_errors::RedisError>;
+ async fn on_message(
+ &self,
+ caches: Arc<Caches>,
+ ) -> error_stack::Result<(), redis_errors::RedisError>;
}
#[async_trait::async_trait]
-impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
+impl PubSubInterface for Arc<redis_interface::RedisConnectionPool> {
#[inline]
- async fn subscribe(&self, channel: &str) -> error_stack::Result<(), redis_errors::RedisError> {
+ async fn subscribe(
+ &self,
+ channel: &str,
+ caches: Arc<Caches>,
+ ) -> error_stack::Result<(), redis_errors::RedisError> {
self.subscriber.subscribe(channel).await?;
- // Spawn only one thread handling all the published messages to different channels
+ // Spawn only one thread handling all the published messages to different channels.
+ //
+ // The handler is process-wide while stores are per tenant, so the caches it is given
+ // must be the same set every tenant's store reads from — otherwise whichever tenant
+ // subscribed first would be the only one whose entries ever get invalidated.
if self
.subscriber
.is_subscriber_handler_spawned
@@ -45,7 +57,7 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
let redis_clone = self.clone();
let _task_handle = tokio::spawn(
async move {
- if let Err(pubsub_error) = redis_clone.on_message().await {
+ if let Err(pubsub_error) = redis_clone.on_message(caches).await {
logger::error!(?pubsub_error);
}
}
@@ -77,207 +89,45 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
}
#[inline]
- async fn on_message(&self) -> error_stack::Result<(), redis_errors::RedisError> {
+ async fn on_message(
+ &self,
+ caches: Arc<Caches>,
+ ) -> error_stack::Result<(), redis_errors::RedisError> {
logger::debug!("Started on message");
let mut rx = self.subscriber.message_rx();
while let Ok(message) = rx.recv().await {
let channel_name = message.channel.to_string();
logger::debug!("Received message on channel: {channel_name}");
- match channel_name.as_str() {
- super::cache::IMC_INVALIDATION_CHANNEL => {
- let message = match CacheRedact::try_from(message.value)
- .change_context(redis_errors::RedisError::OnMessageError)
- {
- Ok(value) => value,
- Err(err) => {
- logger::error!(value_conversion_err=?err);
- continue;
- }
- };
-
- let key = match message.kind {
- CacheKind::Config(key) => {
- CONFIG_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- key
- }
- CacheKind::Accounts(key) => {
- ACCOUNTS_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- key
- }
- CacheKind::MerchantConnectorAccountList(key) => {
- MCA_LIST_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- key
- }
- CacheKind::CGraph(key) => {
- CGRAPH_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- key
- }
- CacheKind::PmFiltersCGraph(key) => {
- PM_FILTERS_CGRAPH_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- key
- }
- CacheKind::EliminationBasedDynamicRoutingCache(key) => {
- ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- key
- }
- CacheKind::ContractBasedDynamicRoutingCache(key) => {
- CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- key
- }
- CacheKind::SuccessBasedDynamicRoutingCache(key) => {
- SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- key
- }
- CacheKind::Routing(key) => {
- ROUTING_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- key
- }
- CacheKind::DecisionManager(key) => {
- DECISION_MANAGER_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- key
- }
- CacheKind::Surcharge(key) => {
- SURCHARGE_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- key
- }
- CacheKind::All(key) => {
- CONFIG_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- ACCOUNTS_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- MCA_LIST_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- CGRAPH_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- PM_FILTERS_CGRAPH_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- ROUTING_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- DECISION_MANAGER_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
- SURCHARGE_CACHE
- .remove(CacheKey {
- key: key.to_string(),
- prefix: message.tenant.clone(),
- })
- .await;
-
- key
- }
- };
+ if channel_name != caches.invalidation_channel {
+ logger::debug!("Received message from unknown channel: {channel_name}");
+ continue;
+ }
- logger::debug!(
- key_prefix=?message.tenant.clone(),
- channel_name=?channel_name,
- "Done invalidating {key}"
- );
- }
- _ => {
- logger::debug!("Received message from unknown channel: {channel_name}");
+ let message = match CacheRedact::try_from(message.value)
+ .change_context(redis_errors::RedisError::OnMessageError)
+ {
+ Ok(value) => value,
+ Err(err) => {
+ logger::error!(value_conversion_err=?err);
+ continue;
}
+ };
+
+ let key = CacheKey {
+ key: message.kind.get_key_without_prefix().to_owned(),
+ prefix: message.tenant.clone(),
+ };
+ for cache in caches.for_kind(&message.kind) {
+ cache.remove(key.clone()).await;
}
+
+ logger::debug!(
+ key_prefix=?message.tenant,
+ channel_name=?channel_name,
+ "Done invalidating {}",
+ key.key
+ );
}
Ok(())
}
@@ -285,8 +135,12 @@ impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
#[async_trait::async_trait]
impl PubSubInterface for redis_interface::RedisConnectionWithContext {
- async fn subscribe(&self, channel: &str) -> error_stack::Result<(), redis_errors::RedisError> {
- self.redis_conn.subscribe(channel).await
+ async fn subscribe(
+ &self,
+ channel: &str,
+ caches: Arc<Caches>,
+ ) -> error_stack::Result<(), redis_errors::RedisError> {
+ self.redis_conn.subscribe(channel, caches).await
}
async fn publish<'a>(
@@ -297,7 +151,10 @@ impl PubSubInterface for redis_interface::RedisConnectionWithContext {
self.redis_conn.publish(channel, key).await
}
- async fn on_message(&self) -> error_stack::Result<(), redis_errors::RedisError> {
- self.redis_conn.on_message().await
+ async fn on_message(
+ &self,
+ caches: Arc<Caches>,
+ ) -> error_stack::Result<(), redis_errors::RedisError> {
+ self.redis_conn.on_message(caches).await
}
}