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(core): Cache business_profile (#13351)

Anurag Thakur12011bd47f65
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index 2a00f67b11..8dd6dbbfb1 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -18,8 +18,16 @@ use crate::schema_v2::business_profile;
/// If two adjacent columns have the same type, then the compiler will not throw any error, but the
/// fields read / written will be interchanged
#[cfg(feature = "v1")]
-#[derive(Clone, Debug, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay)]
-#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]
+#[derive(
+ Clone,
+ Debug,
+ Identifiable,
+ Queryable,
+ Selectable,
+ router_derive::DebugAsDisplay,
+ serde::Serialize,
+ serde::Deserialize,
+)]
#[diesel(table_name = business_profile, primary_key(profile_id), check_for_backend(diesel::pg::Pg))]
pub struct Profile {
pub profile_id: common_utils::id_type::ProfileId,
@@ -233,8 +241,16 @@ pub struct ProfileUpdateInternal {
/// If two adjacent columns have the same type, then the compiler will not throw any error, but the
/// fields read / written will be interchanged
#[cfg(feature = "v2")]
-#[derive(Clone, Debug, Identifiable, Queryable, Selectable, router_derive::DebugAsDisplay)]
-#[cfg_attr(feature = "deja", derive(serde::Serialize, serde::Deserialize))]
+#[derive(
+ Clone,
+ Debug,
+ Identifiable,
+ Queryable,
+ Selectable,
+ router_derive::DebugAsDisplay,
+ serde::Serialize,
+ serde::Deserialize,
+)]
#[diesel(table_name = business_profile, primary_key(id), check_for_backend(diesel::pg::Pg))]
pub struct Profile {
pub merchant_id: common_utils::id_type::MerchantId,
diff --git a/crates/storage_impl/src/business_profile.rs b/crates/storage_impl/src/business_profile.rs
index a3ae9bdad3..5e7432dfb5 100644
--- a/crates/storage_impl/src/business_profile.rs
+++ b/crates/storage_impl/src/business_profile.rs
@@ -7,14 +7,67 @@ use hyperswitch_domain_models::{
},
merchant_key_store::MerchantKeyStore,
};
+#[cfg(feature = "accounts_cache")]
+use router_env::logger;
use router_env::{instrument, tracing};
+#[cfg(feature = "accounts_cache")]
+use crate::redis::{
+ cache,
+ cache::{CacheKind, ACCOUNTS_CACHE},
+};
use crate::{
behaviour::{Conversion, ForeignFrom, ReverseConversion},
kv_router_store,
utils::{pg_accounts_connection_read, pg_accounts_connection_write},
CustomResult, DatabaseStore, MockDb, RouterStore, StorageError,
};
+#[cfg(feature = "accounts_cache")]
+use crate::{metrics, RedisConnInterface};
+
+/// Time to live for the redis copy of a profile, in seconds.
+///
+/// Tuned independently of the in-memory cache's TTL, and deliberately longer than it, so that an
+/// expired in-memory entry can be refilled from redis instead of the database.
+#[cfg(feature = "accounts_cache")]
+const PROFILE_REDIS_CACHE_TTL: i64 = 60 * 60;
+
+/// Cache key for a profile, shared by both the profile-scoped and merchant-scoped lookups.
+#[cfg(feature = "accounts_cache")]
+fn profile_cache_key(profile_id: &common_utils::id_type::ProfileId) -> String {
+ format!("business_profile_{}", profile_id.get_string_repr())
+}
+
+/// Invalidates the cached profile on a best-effort basis.
+///
+/// Callers invoke this only after their database write has committed, so a redis failure must not
+/// fail their request: the write did succeed, and returning an error would both misreport that and
+/// 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),
+ profile_id: &common_utils::id_type::ProfileId,
+) {
+ let redaction_result = cache::redact_from_redis_and_publish(
+ store,
+ [CacheKind::Accounts(profile_cache_key(profile_id).into())],
+ )
+ .await;
+
+ if let Err(error) = redaction_result {
+ metrics::CACHE_REDACTION_FAILURE_COUNT.add(
+ 1,
+ router_env::metric_attributes!(("entity", "business_profile")),
+ );
+ logger::error!(
+ ?error,
+ profile_id = profile_id.get_string_repr(),
+ "Failed to invalidate business profile cache after a committed database write, \
+ cached entries may be stale until they expire"
+ );
+ }
+}
#[async_trait::async_trait]
impl<T: DatabaseStore> ProfileInterface for kv_router_store::KVRouterStore<T> {
@@ -142,12 +195,53 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {
merchant_key_store: &MerchantKeyStore,
profile_id: &common_utils::id_type::ProfileId,
) -> CustomResult<domain::Profile, StorageError> {
- let conn = pg_accounts_connection_read(self).await?;
- self.call_database_new(
- merchant_key_store,
- diesel::Profile::find_by_profile_id(&conn, profile_id),
- )
- .await
+ let fetch_func = || async {
+ let conn = pg_accounts_connection_read(self).await?;
+ diesel::Profile::find_by_profile_id(&conn, profile_id)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))
+ };
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ let state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
+ fetch_func()
+ .await?
+ .convert(
+ state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ }
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ let state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?
+ .clone();
+
+ let identifier = merchant_key_store.merchant_id.clone().into();
+
+ cache::get_or_populate_in_memory_with_transform(
+ self,
+ &profile_cache_key(profile_id),
+ Some(PROFILE_REDIS_CACHE_TTL),
+ fetch_func,
+ |diesel_profile| async move {
+ diesel_profile
+ .convert(&state, &merchant_key_store.key, identifier)
+ .await
+ .change_context(StorageError::DecryptionError)
+ },
+ &ACCOUNTS_CACHE,
+ )
+ .await
+ }
}
async fn find_business_profile_by_merchant_id_profile_id(
@@ -156,12 +250,53 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {
merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
) -> CustomResult<domain::Profile, StorageError> {
- let conn = pg_accounts_connection_read(self).await?;
- self.call_database_new(
- merchant_key_store,
- diesel::Profile::find_by_merchant_id_profile_id(&conn, merchant_id, profile_id),
- )
- .await
+ let fetch_func = || async {
+ let conn = pg_accounts_connection_read(self).await?;
+ diesel::Profile::find_by_merchant_id_profile_id(&conn, merchant_id, profile_id)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))
+ };
+
+ #[cfg(not(feature = "accounts_cache"))]
+ {
+ let state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?;
+ fetch_func()
+ .await?
+ .convert(
+ state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
+ }
+
+ #[cfg(feature = "accounts_cache")]
+ {
+ let state = self
+ .get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?
+ .clone();
+
+ let identifier = merchant_key_store.merchant_id.clone().into();
+
+ cache::get_or_populate_in_memory_with_transform(
+ self,
+ &profile_cache_key(profile_id),
+ Some(PROFILE_REDIS_CACHE_TTL),
+ fetch_func,
+ |diesel_profile| async move {
+ diesel_profile
+ .convert(&state, &merchant_key_store.key, identifier)
+ .await
+ .change_context(StorageError::DecryptionError)
+ },
+ &ACCOUNTS_CACHE,
+ )
+ .await
+ }
}
#[instrument(skip_all)]
@@ -187,22 +322,27 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {
profile_update: domain::ProfileUpdate,
) -> CustomResult<domain::Profile, StorageError> {
let conn = pg_accounts_connection_write(self).await?;
- Box::pin(
+ let updated_profile = Box::pin(
Conversion::convert(current_state)
.await
.change_context(StorageError::EncryptionError)?
.update_by_profile_id(&conn, ProfileUpdateInternal::foreign_from(profile_update)),
)
.await
- .map_err(|error| report!(StorageError::from(error)))?
- .convert(
- self.get_keymanager_state()
- .attach_printable("Missing KeyManagerState")?,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone().into(),
- )
- .await
- .change_context(StorageError::DecryptionError)
+ .map_err(|error| report!(StorageError::from(error)))?;
+
+ #[cfg(feature = "accounts_cache")]
+ publish_and_redact_business_profile_cache(self, updated_profile.get_id()).await;
+
+ updated_profile
+ .convert(
+ self.get_keymanager_state()
+ .attach_printable("Missing KeyManagerState")?,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(StorageError::DecryptionError)
}
#[instrument(skip_all)]
@@ -212,9 +352,15 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, StorageError> {
let conn = pg_accounts_connection_write(self).await?;
- diesel::Profile::delete_by_profile_id_merchant_id(&conn, profile_id, merchant_id)
- .await
- .map_err(|error| report!(StorageError::from(error)))
+ let is_deleted =
+ diesel::Profile::delete_by_profile_id_merchant_id(&conn, profile_id, merchant_id)
+ .await
+ .map_err(|error| report!(StorageError::from(error)))?;
+
+ #[cfg(feature = "accounts_cache")]
+ publish_and_redact_business_profile_cache(self, profile_id).await;
+
+ Ok(is_deleted)
}
#[instrument(skip_all)]
diff --git a/crates/storage_impl/src/metrics.rs b/crates/storage_impl/src/metrics.rs
index b0c0c70af0..303259f659 100644
--- a/crates/storage_impl/src/metrics.rs
+++ b/crates/storage_impl/src/metrics.rs
@@ -16,3 +16,6 @@ gauge_metric!(IN_MEMORY_CACHE_ENTRY_COUNT, 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);
+
+// Metrics for cache invalidation
+counter_metric!(CACHE_REDACTION_FAILURE_COUNT, GLOBAL_METER);
diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs
index 1d951742f3..70eaae5ec4 100644
--- a/crates/storage_impl/src/redis/cache.rs
+++ b/crates/storage_impl/src/redis/cache.rs
@@ -210,6 +210,29 @@ impl From<CacheKey> for String {
}
}
+/// The physical moka key for a logical [`CacheKey`].
+///
+/// During replay the in-memory cache is a process-global structure shared across correlations, so
+/// its keys are namespaced by correlation id — the same isolation
+/// `RedisConnectionPool::add_prefix` applies to physical redis keys. This keeps a replayed
+/// correlation from observing entries another one populated: the first lookup per correlation
+/// misses and falls through to the redis and database boundaries, which are instrumented and
+/// therefore deterministic.
+///
+/// Deliberately not folded into `From<CacheKey> for String`: that conversion also builds the
+/// recorded args for the `in_memory_get` boundary, which must stay un-namespaced so the args a
+/// replay computes still match the ones the recording captured.
+fn in_memory_cache_key(key: CacheKey) -> String {
+ let physical = String::from(key);
+
+ #[cfg(feature = "deja")]
+ if let Some(correlation_id) = deja::replay_key_namespace() {
+ return format!("{correlation_id}:{physical}");
+ }
+
+ physical
+}
+
impl Cache {
/// With given `time_to_live` and `time_to_idle` creates a moka cache.
///
@@ -249,11 +272,13 @@ impl Cache {
}
pub async fn push<T: Cacheable>(&self, key: CacheKey, val: T) {
- self.inner.insert(key.into(), Arc::new(val)).await;
+ self.inner
+ .insert(in_memory_cache_key(key), Arc::new(val))
+ .await;
}
pub async fn get_val<T: Clone + Cacheable>(&self, key: CacheKey) -> Option<T> {
- let val = self.inner.get::<String>(&key.into()).await;
+ let val = self.inner.get::<String>(&in_memory_cache_key(key)).await;
// Add cache hit and cache miss metrics
if val.is_some() {
@@ -271,11 +296,13 @@ impl Cache {
/// Check if a key exists in cache
pub async fn exists(&self, key: CacheKey) -> bool {
- self.inner.contains_key::<String>(&key.into())
+ self.inner.contains_key::<String>(&in_memory_cache_key(key))
}
pub async fn remove(&self, key: CacheKey) {
- self.inner.invalidate::<String>(&key.into()).await;
+ self.inner
+ .invalidate::<String>(&in_memory_cache_key(key))
+ .await;
}
/// Performs any pending maintenance operations needed by the cache.
@@ -306,6 +333,7 @@ impl Cache {
pub async fn get_or_populate_redis<T, F, Fut>(
redis: &RedisConnectionWithContext,
key: impl AsRef<str>,
+ ttl: Option<i64>,
fun: F,
) -> CustomResult<T, StorageError>
where
@@ -320,10 +348,15 @@ where
.await;
let get_data_set_redis = || async {
let data = fun().await?;
- redis
- .serialize_and_set_key(&key.into(), &data)
- .await
- .change_context(StorageError::KVError)?;
+ match ttl {
+ Some(ttl) => {
+ redis
+ .serialize_and_set_key_with_expiry(&key.into(), &data, ttl)
+ .await
+ }
+ None => redis.serialize_and_set_key(&key.into(), &data).await,
+ }
+ .change_context(StorageError::KVError)?;
Ok::<_, Report<StorageError>>(data)
};
match redis_val {
@@ -407,7 +440,7 @@ where
if let Some(val) = cache_val {
Ok(val)
} else {
- let val = get_or_populate_redis(redis, key, fun).await?;
+ let val = get_or_populate_redis(redis, key, None, fun).await?;
cache
.push(
CacheKey {
@@ -421,6 +454,67 @@ where
}
}
+/// Two-tier cache where redis (L2) holds type `R` — typically the encrypted diesel model — and
+/// the in-memory cache (L1) holds type `T` — typically the decrypted domain model.
+/// `transform_func` converts the redis representation into the in-memory one, so that the
+/// (potentially expensive) decryption is paid once per in-memory population rather than once per
+/// read.
+///
+/// `redis_ttl` is the time to live for the redis entry in seconds; `None` stores it without an
+/// expiry. It is deliberately independent of the in-memory cache's TTL so the two tiers can be
+/// tuned separately — set it longer than the in-memory TTL to let an expired in-memory entry be
+/// refilled from redis instead of the database.
+#[instrument(skip_all)]
+pub async fn get_or_populate_in_memory_with_transform<T, R, F, Fut, TransF, TransFut>(
+ store: &(dyn RedisConnInterface + Send + Sync),
+ key: &str,
+ redis_ttl: Option<i64>,
+ fetch_func: F,
+ transform_func: TransF,
+ cache: &Cache,
+) -> CustomResult<T, StorageError>
+where
+ T: Cacheable + Debug + Clone,
+ R: serde::Serialize + serde::de::DeserializeOwned + Debug + Send,
+ F: FnOnce() -> Fut + Send,
+ Fut: futures::Future<Output = CustomResult<R, StorageError>> + Send,
+ TransF: FnOnce(R) -> TransFut + Send,
+ TransFut: futures::Future<Output = CustomResult<T, StorageError>> + Send,
+{
+ let redis = &store
+ .get_redis_conn()
+ .change_context(StorageError::RedisError(
+ RedisError::RedisConnectionError.into(),
+ ))
+ .attach_printable("Failed to get redis connection")?;
+
+ let cache_val = cache
+ .get_val::<T>(CacheKey {
+ key: key.to_string(),
+ prefix: redis.redis_conn.key_prefix.clone(),
+ })
+ .await;
+ if let Some(val) = cache_val {
+ return Ok(val);
+ }
+
+ let redis_model = get_or_populate_redis(redis, key, redis_ttl, fetch_func).await?;
+
+ let domain_model = transform_func(redis_model).await?;
+
+ cache
+ .push(
+ CacheKey {
+ key: key.to_string(),
+ prefix: redis.redis_conn.key_prefix.clone(),
+ },
+ domain_model.clone(),
+ )
+ .await;
+
+ Ok(domain_model)
+}
+
#[instrument(skip_all)]
pub async fn redact_from_redis_and_publish<
'a,