Giter VIP home page Giter VIP logo

httprate's Introduction

httprate

net/http request rate limiter based on the Sliding Window Counter pattern inspired by CloudFlare https://blog.cloudflare.com/counting-things-a-lot-of-different-things/.

The sliding window counter pattern is accurate, smooths traffic and offers a simple counter design to share a rate-limit among a cluster of servers. For example, if you'd like to use redis to coordinate a rate-limit across a group of microservices you just need to implement the httprate.LimitCounter interface to support an atomic increment and get.

Example

package main

import (
  "net/http"

  "github.com/go-chi/chi/v5"
  "github.com/go-chi/chi/v5/middleware"
  "github.com/go-chi/httprate"
)

func main() {
  r := chi.NewRouter()
  r.Use(middleware.Logger)

  // Enable httprate request limiter of 100 requests per minute.
  //
  // In the code example below, rate-limiting is bound to the request IP address
  // via the LimitByIP middleware handler.
  //
  // To have a single rate-limiter for all requests, use httprate.LimitAll(..).
  //
  // Please see _example/main.go for other more, or read the library code.
  r.Use(httprate.LimitByIP(100, 1*time.Minute))

  r.Get("/", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("."))
  })

  http.ListenAndServe(":3333", r)
}

Common use cases

Rate limit by IP and URL path (aka endpoint)

  r.Use(httprate.Limit(
  	10,             // requests
  	10*time.Second, // per duration
  	httprate.WithKeyFuncs(httprate.KeyByIP, httprate.KeyByEndpoint),
  ))

Rate limit by arbitrary keys

  r.Use(httprate.Limit(
    100,           // requests
    1*time.Minute, // per duration
    // an oversimplified example of rate limiting by a custom header
    httprate.WithKeyFuncs(func(r *http.Request) (string, error) {
    	return r.Header.Get("X-Access-Token"), nil
    }),
  ))

Send specific response for rate limited requests

  r.Use(httprate.Limit(
    10,            // requests
    1*time.Second, // per duration
    httprate.WithLimitHandler(func(w http.ResponseWriter, r *http.Request) {
      http.Error(w, "some specific response here", http.StatusTooManyRequests)
    }),
  ))

Related packages

Redis backend for httprate: https://github.com/go-chi/httprate-redis

LICENSE

MIT

httprate's People

Contributors

pkieltyka avatar yaronius avatar adam-p avatar creack avatar nickspring avatar missinglink avatar coraxster avatar

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.