Skip to content

Commit

Permalink
bug fix in redis and used sync.Map in the in memory rate limiter
Browse files Browse the repository at this point in the history
  • Loading branch information
Nebulizer1213 committed Jul 17, 2022
1 parent e0340f5 commit d0b827d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 20 deletions.
34 changes: 15 additions & 19 deletions GinRateLimit.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,34 +11,31 @@ type user struct {
tokens int
}

func clearInBackground(data map[string]*user, rate int64, mutex *sync.Mutex) {
func clearInBackground(data *sync.Map, rate int64) {
for {
mutex.Lock()
for k, v := range data {
if v.ts+rate <= time.Now().Unix() {
delete(data, k)
data.Range(func(k, v any) bool {
if v.(user).ts+rate <= time.Now().Unix() {
data.Delete(k)
}
}
mutex.Unlock()
return true
})
time.Sleep(time.Minute)
}
}

type InMemoryStoreType struct {
rate int64
limit int
data map[string]*user
mutex *sync.Mutex
data *sync.Map
}

func (s *InMemoryStoreType) Limit(key string) (bool, time.Duration) {
s.mutex.Lock()
defer s.mutex.Unlock()
_, ok := s.data[key]
_, ok := s.data.Load(key)
if !ok {
s.data[key] = &user{time.Now().Unix(), s.limit}
s.data.Store(key, user{time.Now().Unix(), s.limit})
}
u := s.data[key]
m, _ := s.data.Load(key)
u := m.(user)
if u.ts+s.rate <= time.Now().Unix() {
u.tokens = s.limit
}
Expand All @@ -48,7 +45,7 @@ func (s *InMemoryStoreType) Limit(key string) (bool, time.Duration) {
}
u.tokens--
u.ts = time.Now().Unix()
s.data[key] = u
s.data.Store(key, u)
return false, time.Duration(0)
}

Expand All @@ -57,10 +54,9 @@ type store interface {
}

func InMemoryStore(rate time.Duration, limit int) *InMemoryStoreType {
mutex := &sync.Mutex{}
data := map[string]*user{}
store := InMemoryStoreType{int64(rate.Seconds()), limit, data, mutex}
go clearInBackground(data, store.rate, mutex)
data := &sync.Map{}
store := InMemoryStoreType{int64(rate.Seconds()), limit, data}
go clearInBackground(data, store.rate)
return &store
}

Expand Down
3 changes: 2 additions & 1 deletion redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ func (s *RedisStoreType) Limit(key string) (bool, time.Duration) {
hits = 0
}
if ts+s.rate <= time.Now().Unix() {
p.Set(s.ctx, key+"hits", 0, time.Duration(0))
hits = 0
p.Set(s.ctx, key+"hits", hits, time.Duration(0))
}
remaining := time.Duration((s.rate - (time.Now().Unix() - ts)) * time.Second.Nanoseconds())
if hits >= int64(s.limit) {
Expand Down

0 comments on commit d0b827d

Please sign in to comment.