throttle

package module
v0.0.0-...-b35b60c Latest Latest
Warning

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

Go to latest
Published: May 6, 2025 License: MIT Imports: 1 Imported by: 0

README

Throttle - Precise Request Rate Controller for Go

Go Reference

A lightweight, zero-dependency Go library designed for precise request-per-second (RPS) control. Perfect for load testing, API clients, and rate-limited workloads.

Features

  • 🚀 Microsecond Precision: Leverages monotonic clock for accurate scheduling
  • Dynamic Rate Recovery: Auto-switches to accelerated mode when falling behind
  • 🧩 Minimalist API: Single struct with one core method
  • 🛡️ Concurrency-Ready: Lock-free design for goroutine-local usage
  • 📦 Zero Dependencies: Pure Go standard library implementation

Installation

go get github.com/cocotyty/throttle

Quick Start

package main

import (
	"time"
	"github.com/cocotyty/throttle"
)

func main() {
	controller := throttle.New(1000) // Target: 1000 requests/sec
	
	for {
		wait := controller.NextWait()
		time.Sleep(wait)
		
		// Execute your rate-limited operation
		performTask()
	}
}

Core API

throttle.New(targetRPS float64) *Throttler

Creates a rate controller instance:
targetRPS: Desired requests per second

NextWait() time.Duration

Returns the duration to wait before next request. Updates internal state atomically.

Design Principles

Base Timeline:
  Expected(n) = StartTime + n*(1s/targetRPS)

Recovery Mode (when behind schedule):
  Expected(m) = RecoveryStart + m*(1s/catchupRPS)

Contributing

Contributions are welcome! Please follow standard workflow:

  1. Fork the repository
  2. Create a feature branch
  3. Commit changes
  4. Push to the branch
  5. Open a Pull Request

License

Distributed under MIT License. See LICENSE for full text.

Documentation

Overview

Package throttle provides precise throughput control

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Throttler

type Throttler struct {
	// contains filtered or unexported fields
}

func New

func New(targetRPS float64) *Throttler

New creates a throughput controller targetRPS: requests per second

func NewWithCatchup

func NewWithCatchup(targetRPS, catchupRPS float64) *Throttler

NewWithCatchup creates a throughput controller with catch-up RPS targetRPS: requests per second catchupRPS: catch-up requests per second

func (*Throttler) NextWait

func (t *Throttler) NextWait() time.Duration

NextWait calculates and updates the time to wait for the next request

Jump to

Keyboard shortcuts

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