Giter VIP home page Giter VIP logo

limiters's Introduction

Distributed rate limiters for Golang

Build Status codecov Go Report Card GoDoc

Rate limiters for distributed applications in Golang with configurable back-ends and distributed locks.
Any types of back-ends and locks can be used that implement certain minimalistic interfaces. Most common implementations are already provided.

  • Token bucket

    • in-memory (local)
    • redis
    • memcached
    • etcd
    • dynamodb

    Allows requests at a certain input rate with possible bursts configured by the capacity parameter.
    The output rate equals to the input rate.
    Precise (no over or under-limiting), but requires a lock (provided).

  • Leaky bucket

    • in-memory (local)
    • redis
    • memcached
    • etcd
    • dynamodb

    Puts requests in a FIFO queue to be processed at a constant rate.
    There are no restrictions on the input rate except for the capacity of the queue.
    Requires a lock (provided).

  • Fixed window counter

    • in-memory (local)
    • redis
    • memcached
    • dynamodb

    Simple and resources efficient algorithm that does not need a lock.
    Precision may be adjusted by the size of the window.
    May be lenient when there are many requests around the boundary between 2 adjacent windows.

  • Sliding window counter

    • in-memory (local)
    • redis
    • memcached
    • dynamodb

    Smoothes out the bursts around the boundary between 2 adjacent windows.
    Needs as twice more memory as the Fixed Window algorithm (2 windows instead of 1 at a time).
    It will disallow all the requests in case when a client is flooding the service with requests. It's the client's responsibility to handle a disallowed request properly: wait before making a new one again.

  • Concurrent buffer

    • in-memory (local)
    • redis
    • memcached

    Allows concurrent requests up to the given capacity.
    Requires a lock (provided).

gRPC example

Global token bucket rate limiter for a gRPC service example:

// examples/example_grpc_simple_limiter_test.go
rate := time.Second * 3
limiter := limiters.NewTokenBucket(
    2,
    rate,
    limiters.NewLockerEtcd(etcdClient, "/ratelimiter_lock/simple/", limiters.NewStdLogger()),
    limiters.NewTokenBucketRedis(
        redisClient,
        "ratelimiter/simple",
        rate, false),
    limiters.NewSystemClock(), limiters.NewStdLogger(),
)

// Add a unary interceptor middleware to rate limit all requests.
s := grpc.NewServer(grpc.UnaryInterceptor(
    func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
        w, err := limiter.Limit(ctx)
        if err == limiters.ErrLimitExhausted {
            return nil, status.Errorf(codes.ResourceExhausted, "try again later in %s", w)
        } else if err != nil {
            // The limiter failed. This error should be logged and examined.
            log.Println(err)
            return nil, status.Error(codes.Internal, "internal error")
        }
        return handler(ctx, req)
    }))

For something close to a real world example see the IP address based gRPC global rate limiter in the examples directory.

DynamoDB

The use of DynamoDB requires the creation of a DynamoDB Table prior to use. An existing table can be used or a new one can be created. Depending on the limiter backend:

  • Partion Key
    • String
    • Required for all Backends
  • Sort Key
    • String
    • Backends:
      • FixedWindow
      • SlidingWindow
  • TTL
    • Number
    • Backends:
      • FixedWindow
      • SlidingWindow
      • LeakyBucket
      • TokenBucket

All DynamoDB backends accept a DynamoDBTableProperties struct as a paramater. This can be manually created or use the LoadDynamoDBTableProperties with the table name. When using LoadDynamoDBTableProperties, the table description is fetched from AWS and verified that the table can be used for Limiter backends. Results of LoadDynamoDBTableProperties are cached.

Distributed locks

Some algorithms require a distributed lock to guarantee consistency during concurrent requests.
In case there is only 1 running application instance then no distributed lock is needed as all the algorithms are thread-safe (use LockNoop).

Supported backends:

Memcached

It's important to understand that memcached is not ideal for implementing reliable locks or data persistence due to its inherent limitations:

  • No guaranteed data retention: Memcached can evict data at any point due to memory pressure, even if it appears to have space available. This can lead to unexpected lock releases or data loss.
  • Lack of distributed locking features: Memcached doesn't offer functionalities like distributed coordination required for consistent locking across multiple servers.

If memcached exists already and it is okay to handle burst traffic caused by unexpected evicted data, Memcached-based implementations are convenient, otherwise Redis-based implementations will be better choices.

Testing

Run tests locally:

make

limiters's People

Contributors

bernata avatar brianleishman avatar dependabot[bot] avatar grbit avatar guyguy333 avatar kavehjamshidi avatar kishaningithub avatar lamebear avatar leeym avatar mennanov avatar oskarwojciski avatar ri-char avatar slunak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

limiters's Issues

Redis backend with race check bug

This is a corner case for the issue addressed here: #29.
This occurs when the version fetched by State() is deleted before SetState() is executed. That will cause an error: got [1 1 OK OK] from redis, expected [<version_before_remove>+1 1 OK OK] raised by checkResponseFromRedis.

Potential solution is to always expect version to be in initial state: #42

epsilon in slidingWindow

Hi,
Could you please explain what should be ideal value of epsilon in slidingWindow.
Here is my current configuration

slidingLimiter := registry.GetOrCreate(ip, func() interface{} {
		return limiters.NewSlidingWindow(100, window, limiters.NewSlidingWindowRedis(redisClient, ip), clock, 60)
	}, 0*time.Second, clock.Now())

	t, err := slidingLimiter.(*limiters.SlidingWindow).Limit(req.Context())
	fmt.Println("timeDuration: ", t)
	if err == limiters.ErrLimitExhausted {
		wrt.WriteHeader(http.StatusTooManyRequests)
		return
	} else if err != nil {
		// The limiter failed. This error should be logged and examined.
		wrt.WriteHeader(http.StatusInternalServerError)
		return
	}

	serveWebSocket(wrt, req)

When i run a load test,
Sometimes i get this panic
image

And other times, server breaks, but gives no error, only go routine ids

Please help

Reset or Clear a Limit

Hello,

It does not appear that this package allows for the reset of a limit, is that correct? I have come across a use case where rate limits need to be reset. A user forgets their password, gets rate limited logging into their account. They successfully reset their password, the previous limit should be cleared so they are allowed to attempt to login again.

Would you consider a PR for this feature?

Lock vs Unlock context aware

Hello. Is there any particular reason why locker's Lock is context aware but Unlock is not?

type DistLocker interface {

I am implementing redis locker which needs to be context aware during Lock and Unlock.

TokenBucket not accounting for all time when adding tokens

Given the following:

  1. TokenBucket created with refill rate of 100ms
  2. Request 1 occurs at t = 0ms
  3. Request 2 occurs at t = 90ms
  4. Request 3 occurs at t = 140ms
  5. Request 4 occurs at t = 210ms

The TokenBucket limiter should have added 2 tokens to the bucket, but only one token is added.

Relevent Code

now := t.clock.Now().UnixNano()
// Refill the bucket.
tokensToAdd := (now - state.Last) / int64(t.refillRate)
if tokensToAdd > 0 {
	state.Last = now
	if tokensToAdd+state.Available <= t.capacity {
		state.Available += tokensToAdd
	} else {
		state.Available = t.capacity
	}
}

The way this currently works is:

  1. state.Last is set to 0ms on the first request, consuming a token.
  2. state.Last is left at 0ms for request 2, consuming a token.
  3. state.Last is set to 140ms for request 3, adding and consuming a token.
  4. since the time between request 3 and 4 is < 100 ms, no token is added to the bucket

A simple fix would be to modify the logic to truncate state.Last to t.refillRate:

now := t.clock.Now().UnixNano()
// Refill the bucket.
tokensToAdd := (now - state.Last) / int64(t.refillRate)
modTime := (now - state.Last) % int64(t.refillRate)
if tokensToAdd > 0 {
	if tokensToAdd+state.Available < t.capacity {
		state.Available += tokensToAdd
		state.Last = now - modTime
	} else {
		state.Available = t.capacity
		state.Last = now
	}
}

With that change, a token is correctly added to the bucket for request 3:

  1. state.Last is set to 0ms on Request 1
  2. state.Last is left at 0ms on Request 2
  3. state.Last is set to 100ms on Request 3, adding a token to the bucket: 140ms - (140ms % 100ms) = 100ms
  4. state.Last is set to 200ms on Request 4, adding a token to the bucket: 210ms - (210ms % 100ms) = 200ms

Alternatively, the Available member of the TokenBucketState struct can be changed from an int64 to a float64 to account for partial tokens, but that would be a more involved change.

Redis backend with race check bug

After the fix from #22 I found a bug:
With a small amount of Takes from the bucket, where Backend is a Redis with raceCheck=true then sometimes the expected version is higher than the actual one.

To replicate the issue I created a simple test:

func (s *LimitersTestSuite) TestTokenBucketRealClockRaceCheckRedisProblem() {
	ttl := time.Second
	limit := int64(2)
	refillEvery := time.Duration(int64(ttl) / limit)
	locker := l.NewLockNoop()
	backend := l.NewTokenBucketRedis(s.redisClient, uuid.New().String(), ttl, true)

	clk := l.NewSystemClock()
	ctx := context.Background()

	bucket := l.NewTokenBucket(
		limit,
		refillEvery,
		locker,
		backend,
		clk,
		nil,
	)

	for i := 0; i < 4; i++ {
		wait, err := bucket.Limit(ctx)
		if err != nil {
			assert.ErrorIs(s.T(), err, l.ErrLimitExhausted)
		}
		if wait.Seconds() > 0 {
			clk.Sleep(time.Second) // after a second all keys expired and the initial state was returned, but lastVersion is not cleared
		}
	}
}

checkResponseFromRedis returns error:

got [1 1 OK OK] from redis, expected [3 1 OK OK]

Can't clone V2

$> go get github.com/mennanov/[email protected]
go: github.com/mennanov/[email protected]: invalid version: module contains a go.mod file, so module path must match major version ("github.com/mennanov/limiters/v2")

$> go get github.com/mennanov/limiters/v2
go: module github.com/mennanov/limiters@upgrade found (v1.1.0), but does not contain package github.com/mennanov/limiters/v2

question/clarification about fixed window counter lock

README.md states that:

Fixed window counter
Simple and resources efficient algorithm that does not need a lock.

But the implementation uses a lock link

limiters/fixedwindow.go

Lines 46 to 50 in 0b557ff

// Limit returns the time duration to wait before the request can be processed.
// It returns ErrLimitExhausted if the request overflows the window's capacity.
func (f *FixedWindow) Limit(ctx context.Context) (time.Duration, error) {
f.mu.Lock()
defer f.mu.Unlock()

I'm confused.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.