steady

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 8 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

http-keystone Steady Middleware

A high-performance concurrency limiter for Echo v5.

→ View Full API Documentation

steady ensures your server remains stable under heavy load by limiting the number of requests processed simultaneously. Instead of immediately rejecting excess traffic, it allows requests to wait in a queue for a configurable amount of time before returning a "Service Unavailable" response.

Features

  • Concurrency Control: Strictly limit the number of active goroutines handling requests.
  • Smart Queueing: Requests wait for a slot instead of being dropped immediately.
  • Configurable Timeouts: Define how long a request should wait before giving up.
  • Custom Error Handling: Fully customize the response sent when the limit is exceeded.
  • Context Awareness: Automatically stops waiting if the client cancels the request.
  • Echo v5 Ready: Designed specifically for the latest Echo pointer-based context.

Installation

go get github.com/its-ernest/http-keystone@latest

Then import github.com/its-ernest/http-keystone/steady.


Basic Usage

package main

import (
	"net/http"
	"time"

	"github.com/its-ernest/http-keystone/steady"
	"github.com/labstack/echo/v5"
)

func main() {
	e := echo.New()

	// Apply steady middleware with custom limits
	e.Use(steady.New(steady.Config{
		MaxConcurrent: 50,               // Allow 50 simultaneous requests
		WaitTimeout:   10 * time.Second, // Wait up to 10s for a slot
	}))

	e.GET("/", func(c *echo.Context) error {
		return c.String(http.StatusOK, "Stable and Steady!")
	})

	e.Start(":8080")
}

Configuration Options

Field Type Default Description
MaxConcurrent int 100 Maximum number of requests to process at once.
MaxWaiting int 100 Maximum number of requests that may queue. 0 uses the default; a negative value means unlimited.
WaitTimeout time.Duration 10s How long a request will wait in the queue for a slot.
Skipper middleware.Skipper DefaultSkipper Function to skip this middleware for certain routes.
ErrorHandler func(*echo.Context) error Internal Called when a request times out in the queue (503 + Retry-After).
QueueFullHandler func(*echo.Context) error Internal Called when MaxWaiting is already reached. Default is 503 + Retry-After, wrapping ErrQueueFull.
Stats *Stats nil Optional live counters: InFlight, Waiting, Rejected.

How it Works

  1. Slot Acquisition: When a request arrives, the middleware tries to acquire a "slot" from an internal semaphore.
  2. Immediate Execution: If a slot is available, the request proceeds immediately.
  3. Bounded Queueing: If the server is at MaxConcurrent capacity, the request joins the waiting queue — but only if fewer than MaxWaiting requests are already queued. The queue is bounded, so a burst cannot accumulate an unlimited number of goroutines, connections and request bodies.
  4. Queue Full: Requests beyond MaxWaiting are rejected immediately by QueueFullHandler (default 503 Service Unavailable with Retry-After), wrapping steady.ErrQueueFull. No goroutine is parked.
  5. Waiting: A queued request waits until:
    • A slot becomes free (as another request finishes).
    • The WaitTimeout is reached.
    • The client closes the connection (context cancellation), which frees its queue slot immediately.
  6. Timeout: If WaitTimeout is reached before a slot is freed, ErrorHandler is triggered (default 503 Service Unavailable with a Retry-After header).
stats := &steady.Stats{}

e.Use(steady.New(steady.Config{
	MaxConcurrent: 100,
	MaxWaiting:    200, // at most 200 requests queue; the rest get 503
	Stats:         stats,
}))

// Later, from a metrics handler:
// stats.InFlight.Load(), stats.Waiting.Load(), stats.Rejected.Load()

Queue rejections wrap steady.ErrQueueFull, so a custom handler can label them, and callers/tests can distinguish them from a WaitTimeout rejection:

QueueFullHandler: func(c *echo.Context) error {
	c.Response().Header().Set("Retry-After", "2")
	return echo.NewHTTPError(http.StatusServiceUnavailable, "queue is full").
		Wrap(steady.ErrQueueFull)
},

// errors.Is(err, steady.ErrQueueFull) == true for queue-full rejections

Why use Steady?

Standard rate limiters often focus on requests-per-second (RPS). However, some requests are "heavier" than others (e.g., intensive DB queries or image processing). steady focuses on concurrency, ensuring that no matter how slow your handlers are, you never exceed the resource limits (CPU/Memory) of your server.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultConfig = Config{
	Skipper:       middleware.DefaultSkipper,
	MaxConcurrent: 100,
	MaxWaiting:    100,
	WaitTimeout:   10 * time.Second,
}

DefaultConfig is the default configuration for the steady middleware.

View Source
var ErrQueueFull = errors.New("steady: waiting queue is full")

ErrQueueFull is wrapped by the default QueueFullHandler when MaxWaiting is exceeded. Use errors.Is(err, steady.ErrQueueFull) to distinguish an immediate queue rejection from a WaitTimeout error in a custom handler.

Functions

func New

func New(config Config) echo.MiddlewareFunc

New returns a steady middleware that limits concurrent requests.

Example
package main

import (
	"net/http"
	"time"

	"github.com/its-ernest/http-keystone/steady"
	"github.com/labstack/echo/v5"
)

func main() {
	e := echo.New()

	// Configure the steady middleware with a maximum of 10 concurrent requests
	// and a 5-second wait timeout for a slot.
	config := steady.Config{
		MaxConcurrent: 10,
		WaitTimeout:   5 * time.Second,
	}

	// Add the middleware to the Echo instance
	e.Use(steady.New(config))

	e.GET("/", func(c *echo.Context) error {
		return c.String(http.StatusOK, "Hello, World!")
	})

	e.Start(":8080")
}

Types

type Config

type Config struct {
	// Skipper defines a function to skip middleware.
	Skipper middleware.Skipper

	// MaxConcurrent is the maximum number of concurrent requests allowed.
	// Default is 100.
	MaxConcurrent int

	// MaxWaiting is the maximum number of requests that may queue for a slot.
	// Requests arriving when the queue is full are rejected immediately with
	// QueueFullHandler instead of parking another goroutine.
	// Default is 100. A negative value means unlimited.
	MaxWaiting int

	// WaitTimeout is the maximum time a request will wait for a processing slot.
	// Default is 10 seconds.
	WaitTimeout time.Duration

	// ErrorHandler is called when a request times out waiting for a slot.
	// Default returns 503 Service Unavailable with Retry-After header.
	ErrorHandler func(c *echo.Context) error

	// QueueFullHandler is called when MaxWaiting is already reached.
	// Default returns 503 Service Unavailable with Retry-After and wraps
	// ErrQueueFull. If nil, ErrorHandler is used.
	QueueFullHandler func(c *echo.Context) error

	// Stats optionally receives live counters for this middleware instance.
	Stats *Stats
}

Config defines the configuration for the steady middleware.

type Stats added in v0.2.0

type Stats struct {
	// InFlight is the number of requests currently holding a slot.
	InFlight atomic.Int64
	// Waiting is the number of requests queued for a slot.
	Waiting atomic.Int64
	// Rejected counts queue-full and wait-timeout rejections.
	Rejected atomic.Int64
}

Stats exposes live counters for one middleware instance. All fields are safe for concurrent use. Pass a value in Config.Stats to observe a running middleware; a zero value is ready to use.

Jump to

Keyboard shortcuts

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