Skip to content

Commit

Permalink
localCounter: Use RWMutex to speed up lookups
Browse files Browse the repository at this point in the history
  • Loading branch information
VojtechVitek committed Jul 24, 2024
1 parent 7228fd5 commit c661580
Showing 1 changed file with 4 additions and 3 deletions.
7 changes: 4 additions & 3 deletions local_counter.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ type localCounter struct {
counters map[uint64]*count
windowLength time.Duration
lastEvict time.Time
mu sync.Mutex
mu sync.RWMutex
}

type count struct {
Expand All @@ -25,6 +25,7 @@ type count struct {
func (c *localCounter) Config(requestLimit int, windowLength time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()

c.windowLength = windowLength
}

Expand Down Expand Up @@ -52,8 +53,8 @@ func (c *localCounter) IncrementBy(key string, currentWindow time.Time, amount i
}

func (c *localCounter) Get(key string, currentWindow, previousWindow time.Time) (int, int, error) {
c.mu.Lock()
defer c.mu.Unlock()
c.mu.RLock()
defer c.mu.RUnlock()

curr, ok := c.counters[LimitCounterKey(key, currentWindow)]
if !ok {
Expand Down

0 comments on commit c661580

Please sign in to comment.