RepositoryGoCNChina
Yiming1997

Yiming1997/agilePool

A golang goroutine pool with high-performance and elegance

324stars
50forks
1issues
2views

Featured achievements

The project's latest awards

1
TINIX TRENDING·Topic: worker-pool

#1 Repository of the week

1
TINIX TRENDING·Topic: pool

#1 Repository of the week

1
TINIX TRENDING·Topic: goroutine-pool

#1 Repository of the week

agilePool

agilePool logo

CI Go Version Tag Go Reference Go Report Card License

简体中文

agilePool is a high-performance goroutine pool for Go. It features adaptive worker scaling driven by sliding-window rate statistics, bounded concurrency, idle worker reuse, unbounded task buffering with backpressure, retryable tasks, and graceful shutdown — ideal for applications submitting millions of small asynchronous jobs without unbounded goroutine growth.

Features

  • Adaptive scaler — histogram-based median rate tracking automatically adjusts the worker count to match submission load, with configurable backlog decay for burst handling.
  • Bounded workers with configurable capacity (WithWorkerNumCapacity).
  • Unbounded task buffering — small internal handoff channel + chunked linked-list buffer with backpressure (maxChunkLen).
  • Blocking & non-blocking submit modes.
  • Automatic idle worker cleanup — background cleaner purges idle workers that exceed the idle timeout.
  • Pluggable idle containers — LinkedList (FIFO), MinHeap (LRU), Slice (FIFO), RingQueue (circular buffer, O(1) Pop).
  • Retryable tasks with exponential backoff (default) or custom backoff strategy.
  • Context-aware submission — SubmitCtx supports cancellation before and after queueing.
  • Time-bounded submission — SubmitBefore with a deadline window.
  • Graceful shutdown — Wait blocks until all in-flight tasks complete; Close stops new submissions.
  • Custom logger — plug any Printf/Println implementation (e.g. zap.SugaredLogger).

Installation

go get github.com/Yiming1997/agilePool

Quick Start

package main

import (
	"time"

	agilepool "github.com/Yiming1997/agilePool"
)

func main() {
	pool := agilepool.NewPool(agilepool.NewConfig())
	defer pool.Close()

	for i := 0; i < 1000; i++ {
		pool.Submit(agilepool.TaskFunc(func() error {
			time.Sleep(10 * time.Millisecond)
			return nil
		}))
	}

	pool.Wait()
}

Configuration

Create a pool with NewConfig and functional options:

pool := agilepool.NewPool(agilepool.NewConfig(
	agilepool.WithWorkerNumCapacity(20000),
	agilepool.WithCleanPeriod(500*time.Millisecond),
	agilepool.WithBlockMode(agilepool.BLOCK),
	agilepool.WithIdleContainerType(agilepool.LinkedListType),
	agilepool.WithScalerPeriod(10*time.Millisecond),
	agilepool.WithBacklogDecayFactor(0.3),
))
defer pool.Close()

Available options

OptionDefaultDescription
WithCleanPeriod500msHow often the background cleaner purges expired idle workers.
WithWorkerNumCapacitymath.MaxInt64Maximum number of running workers.
WithBlockModeBLOCKBLOCK queues tasks; NONBLOCK drops submissions when full.
WithIdleContainerTypeLinkedListTypeData structure for idle workers (see Idle Worker Containers).
WithStatsSamplePeriod100msRate-statistics sampling interval.
WithStatsWindowSize10Number of sliding windows for median calculation.
WithScalerPeriod10msHow often the scaler evaluates whether to spawn workers.
WithBacklogDecayFactor0.3Weight (0–1) for backlog in the scaler target formula. Higher values make the scaler more aggressive at draining queues.

Note: WithTaskQueueSize is retained for API compatibility but has no effect — the internal handoff channel capacity is fixed at 10,000 slots and the primary buffer grows dynamically.

Submitting Tasks

Basic submission

pool.Submit(agilepool.TaskFunc(func() error {
	// Do work here.
	return nil
}))

TaskFunc returns error for compatibility with retry patterns; plain Submit does not inspect the returned error.

Context-aware submission

SubmitCtx supports cooperative cancellation:

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

pool.SubmitCtx(ctx, agilepool.TaskFunc(func() error {
	select {
	case <-ctx.Done():
		return ctx.Err()
	default:
		// Do work here.
		return nil
	}
}))

Cancellation semantics:

  • If ctx is already canceled before submission → task is dropped.
  • In BLOCK mode, waiting for queue space is interruptible by ctx cancellation.
  • If the task is queued but not yet started → worker skips execution when ctx is canceled.
  • If the task has already started → the pool does not forcibly stop the goroutine; the task must check ctx.Done() or pass ctx to downstream calls.

Deadline-bound submission

SubmitBefore schedules a task with a timeout window. If the deadline expires before the worker picks up the task, it is skipped.

pool.SubmitBefore(
	agilepool.TaskFunc(func() error {
		time.Sleep(10 * time.Millisecond)
		return nil
	}),
	10*time.Second,
)

Retryable Tasks

TaskWithRetry retries a task when it returns an error. Uses exponential backoff by default; provide BackOffStrategy for custom behaviour.

pool.Submit(&agilepool.TaskWithRetry{
	MinBackOff: 1 * time.Second,
	MaxBackOff: 30 * time.Second,
	RetryNum:   3,
	Task: func() error {
		return errors.New("temporary failure")
	},
})

Idle Worker Containers

The pool reuses idle workers. Choose the container that fits your workload:

ContainerOrderingPopCleanupBest for
LinkedListTypeInsertion order (FIFO)O(1)O(n) full scanGeneral-purpose, simple FIFO reuse.
MinHeapTypelastActiveAt (LRU)O(log n)O(k log n) early-stopMany workers, efficient expiry scan.
SliceTypeInsertion order (FIFO)O(1)O(log n + k) binary-searchModerate idle counts, cache-friendly.
RingQueueTypeInsertion order (FIFO)O(1)O(n) scan with wrapFixed-capacity idle pool, O(1) Pop.
pool := agilepool.NewPool(agilepool.NewConfig(
	agilepool.WithIdleContainerType(agilepool.RingQueueType),
	agilepool.WithWorkerNumCapacity(20000),
))

Adaptive Scaler

The scaler is the core mechanism that keeps the worker count aligned with the submission rate. It runs every scalerPeriod (default 10 ms) and uses a three-step pipeline:

1. Rate sampling — Every statsSamplePeriod (100 ms), the statsSampler atomically swaps and resets three counters — submitCount, consumeCount, and exitCount — and records them into sliding-window histograms.

2. Median extraction — Each histogram retains the last statsWindowSize (10) samples in a fixed-bucket ring buffer. getMedianRates() returns the approximate median submit / consume / exit rate, which is far more resilient to short spikes than an average.

3. Scaling decision — scaleIfNeeded() computes the target worker count:

target = submitMed × running / consumeMed          (Little's Law)

When a backlog exists (tasks in the channel + chunked buffer), the scaler becomes more aggressive using a dynamic decay factor:

bufPressure  = min(1.0, bufDepth / consumeMed × 0.15)
dynamicDecay = backlogDecayFactor + (1 - backlogDecayFactor) × bufPressure
effectiveSubmit = submitMed + totalBacklog × dynamicDecay

This means:

  • Shallow backlog → decay stays near backlogDecayFactor (0.3) → conservative scaling.
  • Deep backlog → bufPressure pushes decay toward 1.0 → aggressive scaling to drain quickly.

The scaler also compensates for expected worker exits (exitMed) and re-checks under lock for thread safety before spawning.

Tuning the scaler

ScenarioRecommended tweak
Bursty, short-lived trafficIncrease backlogDecayFactor (e.g. 0.6) for faster ramp-up.
Steady, predictable loadDecrease scalerPeriod to 5 ms for tighter tracking.
Memory-constrainedLower WithWorkerNumCapacity to cap peak workers.

Lifecycle

Wait — blocks until all submitted tasks complete:

pool.Wait()

Close — stops accepting new tasks. Already submitted tasks continue to run. Idempotent and safe from any goroutine.

pool.Close()

Typical shutdown pattern:

pool.Close()
pool.Wait()

Custom Logger

Replace the default log.Default() logger with any implementation of Printf/Println:

pool.SetLogger(log.Default())       // stdlib
pool.SetLogger(zapLogger.Sugar())   // zap

Benchmark

A comprehensive benchmark suite comparing agilePool against other popular Go goroutine pools is available at agilePool-benchmark.

Acknowledgments

The adaptive scaler design draws inspiration from Little's Law — special thanks to @knowledge404 for the insightful suggestion of applying queuing theory to worker pool auto-scaling.

License

MIT

Similar Projects

Discover other similar projects and AI models.

RepositoryGo
panjf2000/ants

🐜🐜🐜 ants is the most powerful and reliable pooling solution for Go.

14.5k
Sep 19, 2026
RepositoryGo
neilotoole/errgroup

errgroup with goroutine worker limits

163
Jan 10, 2023
RepositoryGo
alphadose/itogami

Fastest and most efficient goroutine pool (experimental)

141
Oct 16, 2022
RepositoryGo
alitto/pond

🔘 Minimalistic and High-performance goroutine worker pool written in Go

2.2k
Oct 24, 2026
RepositoryGo
ivpusic/grpool

Lightweight Goroutine pool

731
Jan 27, 2019
RepositoryGo
goptics/varmq

A Simplest in-memory and Distributed Storage-Agnostic Message Queue for Your Concurrent Go Program

210
Dec 1, 2026
RepositoryGo
avelino/awesome-go

A curated list of awesome Go frameworks, libraries and software

197.2k
Dec 2, 2026
RepositoryGo
ollama/ollama

Get up and running with Inkling, Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

188.9k
Dec 2, 2026
RepositoryGo
golang/go

The Go programming language

140.0k
Dec 1, 2026