limit

package module
v0.0.0-...-2cc5cbc Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 9, 2015 License: MIT Imports: 5 Imported by: 0

README

Why?

If you:

  • Have several distributed workers that are dependent on a rate limited service
  • Need to control how fast a group of workers and how quickly they hit an API/Service

Then this is the package for you.

Installation

go get github.com/joshrendek/redis-rate-limit

Guarantees

  • Global lock deadlock prevention with a TTL
  • Individual worker lock deadlock prevention with TTLs

Usage

See examples/main.go

Importing:

import(
	"github.com/joshrendek/redis-rate-limit"
)

Using with a regular WG - we can have other parts of a job run at one concurrency (lets say this is CPU intensive) and then sending to an API.

We want to run N workers but also limit the amount of workers that can concurrently access the limited resource:

package main

import (
	"fmt"
	"github.com/joshrendek/redis-rate-limit"
	"math/rand"
	"sync"
	"time"
)

var (
	wg    sync.WaitGroup
	tasks = make(chan bool, 40)
)

func startWorkers() {
	opts := limit.Options{
		Address:          "localhost:6379",
		LockName:         "wg",
		MaxRate:          15,
		LockWaitDuration: 100 * time.Millisecond,
		WorkerTimeout:    5 * time.Second,
	}
	limiter := limit.NewRateLimit(opts)
	for i := 0; i < 40; i++ {
		wg.Add(1)
		go func() {
			for data := range tasks {
				uid := limiter.Add(1)
				fmt.Printf("Working .... %+v\n", data)
				time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
				// do some work on data
				limiter.Done(uid)
			}
			wg.Done()
		}()
	}
}

func main() {
	go startWorkers()

	for i := 0; i < 5000; i++ {
		tasks <- true
		time.Sleep(100 * time.Millisecond)
	}

	close(tasks)
	wg.Wait()
}

License


The MIT License (MIT)

Copyright (c) 2015 Josh Rendek

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Options

type Options struct {
	Address          string
	MaxRate          int64
	LockWaitDuration time.Duration
	WorkerTimeout    time.Duration
	LockName         string
}

Options is used to contain config options for the limiter Address is the address of the redis server MaxRate is the concurrency limit LockWaitDuration is used as a duration for busy waiting on the lock key WorkerTimeout is used as the TTL for the worker key, this should be set longer than you expect your workers to take.

type RateLimit

type RateLimit struct {
	Redis *redis.Client
	Opts  Options
}

RateLimit is the limiter object exposed to control concurrency

func NewRateLimit

func NewRateLimit(opts Options) RateLimit

NewRateLimit is for setting up a new rate limiter with options

func (*RateLimit) Add

func (l *RateLimit) Add(i int) string

Add is for telling wait group something is starting A lock using SetNX is created in redis based on the l.Opts.LockName The lock busy waits until its free and then acquires it LockWaitDuration should be set to something reasonable so the CPU isn't wasting cycles. Add handles generating the UUID for the lock set and also the lock keys that are given a TTL The return value should be stored so you can pass the uid to Done()

func (*RateLimit) Done

func (l *RateLimit) Done(uid string)

Done Instructs the limiter to remove the lock key and uuid from the lock set

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL