From ffc10f88dc19b2d0640c20f8aee09d59ed8a117a Mon Sep 17 00:00:00 2001 From: simonredfern Date: Sat, 27 Dec 2025 07:30:57 +0100 Subject: [PATCH] RateLimitingUtil single point of entry to Redis part 2 --- .../code/api/util/RateLimitingUtil.scala | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/obp-api/src/main/scala/code/api/util/RateLimitingUtil.scala b/obp-api/src/main/scala/code/api/util/RateLimitingUtil.scala index 370a145c5..98bc75f0b 100644 --- a/obp-api/src/main/scala/code/api/util/RateLimitingUtil.scala +++ b/obp-api/src/main/scala/code/api/util/RateLimitingUtil.scala @@ -256,16 +256,21 @@ object RateLimitingUtil extends MdcLoggable { (-1, -1) } } - + /** + * Get remaining TTL (time to live) for a rate limit counter. + * Used to populate X-Rate-Limit-Reset header when rate limit is exceeded. + * + * NOTE: This function could be further optimized by eliminating it entirely. + * We already call getCounterState() in underConsumerLimits(), so we could + * cache/reuse that TTL value instead of making another Redis call here. + * + * @param consumerKey The consumer ID or IP address + * @param period The time period + * @return Seconds until counter resets, or 0 if no counter exists + */ private def ttl(consumerKey: String, period: LimitCallPeriod): Long = { - val key = createUniqueKey(consumerKey, period) - val ttl = Redis.use(JedisMethod.TTL, key).get.toInt - ttl match { - case -2 => // if the Key does not exists, -2 is returned - 0 - case _ => // otherwise increment the counter - ttl - } + val state = getCounterState(consumerKey, period) + state.ttl.getOrElse(0L) }