Skip to content

A golang library based on go-redis connection pool that can be used to implement rate limit function

Notifications You must be signed in to change notification settings

rueian/redlimiter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

redlimiter

CircleCI codecov

A golang library based on go-redis connection pool that can be used to implement rate limit function.

Counter

The counter package provides 2 Incrementer implementations that both INCR a key in redis and set expiration atomically when the key created without race condition.

package main

import (
	"github.com/go-redis/redis"
	"github.com/rueian/redlimiter/counter"
)

func main() {
	client := redis.NewUniversalClient(&redis.UniversalOptions{Addrs: []string{"redis:6379"}})
	
	incrementer := counter.NewLuaIncrementer(client) // or counter.NewTxIncrementer(client)
	count, err := incrementer.Incr("client_ip", 1) // expire in 1 sec
	if err != nil {
		rejectWithErr(err)
	}
	if count > 50 {
		rejectWithLimitExceeded()
	}
}

LuaIncrementer

Executing a lua script which issues a INCR command and a conditional EXPIRE command on a key atomically on redis.

TxIncrementer

Issuing MULTI SET EX NX INCR EXEC commands on a key atomically on redis.

Benchmark

▶ docker-compose run --rm bench
Starting redlimiter_redis_1 ... done
goos: linux
goarch: amd64
pkg: github.com/rueian/redlimiter/counter
BenchmarkLuaIncrementer-6   	    5000	    279119 ns/op
BenchmarkTxIncrementer-6    	    5000	    307964 ns/op
PASS
ok  	github.com/rueian/redlimiter/counter	5.138s

About

A golang library based on go-redis connection pool that can be used to implement rate limit function

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages