Skip to content

Commit

Permalink
added rate limiter
Browse files Browse the repository at this point in the history
  • Loading branch information
harshil-goel committed Dec 25, 2024
1 parent a881a3e commit c692ff0
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ type Cache[K Key, V any] struct {
// Metrics contains a running log of important statistics like hits, misses,
// and dropped items.
Metrics *Metrics
// Rate limiter for asynchronus set.
rateLimiter int64
// Max buffer items for asynchronus set.
maxItems int64
}

// Config is passed to NewCache for creating new Cache instances.
Expand Down Expand Up @@ -233,6 +237,8 @@ func NewCache[K Key, V any](config *Config[K, V]) (*Cache[K, V], error) {
cost: config.Cost,
ignoreInternalCost: config.IgnoreInternalCost,
cleanupTicker: time.NewTicker(time.Duration(config.TtlTickerDurationInSec) * time.Second / 2),
maxItems: config.BufferItems,
rateLimiter: 0,
}
cache.onExit = func(val V) {
if config.OnExit != nil {
Expand Down Expand Up @@ -489,6 +495,13 @@ func (c *Cache[K, V]) UpdateMaxCost(maxCost int64) {
}

func (c *Cache[K, V]) AsyncSet(key K, value V, cost int64) bool {
if atomic.AddInt64(&c.rateLimiter, 1) > c.maxItems {
atomic.AddInt64(&c.rateLimiter, -1) // Decrement on failure
return false
}

defer atomic.AddInt64(&c.rateLimiter, -1)

if c == nil || c.isClosed.Load() {
return false
}
Expand Down

0 comments on commit c692ff0

Please sign in to comment.