Skip to content

A simple implementation of the Sliding Window Algorithm for Rate Limiting in Golang

Notifications You must be signed in to change notification settings

abishz17/ratelimit

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Go Sliding Window RateLimiter

A simple rate limiting library for Go using the Sliding Window algorithm. Control the number of requests a user can make within a specified time window.

Installation

go get github.com/abishz17/ratelimit

Usage

package main

import (
	"fmt"
	"time"

	"github.com/abishz17/ratelimit"
)

func main() {
	// Create a new rate limiter with a limit of 10 requests per 10 minutes
	limiter := ratelimit.NewRateLimiter(
		ratelimit.WithLimit(10),
		ratelimit.WithTimeWindow(10*time.Minute),
	)

	userID := "user1"

	// Simulate 20 requests
	for i := 0; i < 20; i++ {
		if limiter.Allow(userID) {
			fmt.Println("Request Allowed")
		} else {
			fmt.Println("Request Denied")
		}
	}
}

API

NewRateLimiter(opts ...Options) Limiter
Creates a new rate limiter with optional configurations.

Allow(key string) bool
Checks if a request is allowed for the given key. Returns true if allowed, false otherwise.

GetCurrentCount(key string) uint64
Retrieves the current count of requests for the given key.

Options
WithLimit(limit uint64): Sets the maximum number of requests allowed.
WithTimeWindow(timeWindow time.Duration): Sets the time window for rate limiting.

About

A simple implementation of the Sliding Window Algorithm for Rate Limiting in Golang

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages