concurrency

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 7 Imported by: ? 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

concurrency

concurrency is a small Go library of typed building blocks for in-process concurrent work: futures, bounded structured groups, ordered parallel maps, reusable worker pools, token-bucket rate limiting and adaptive (AIMD) concurrency limits. It is for Go developers who fan work out across goroutines and want precise, tested semantics for errors, cancellation and shutdown without pulling in dependencies: it uses only the standard library.

Features

  • Futures: Go starts one function and returns a typed *Future[T]; Await, Try and Done read it. Completed and Failed build resolved futures.
  • Bounded groups: NewGroup runs related callbacks with a concurrency limit, cancels peers on the first error and joins all errors in submission order.
  • Ordered parallel map: ParallelMap applies one function to a slice with bounded concurrency and returns results in input order.
  • Worker pools: NewPool processes typed inputs with one worker function, separate worker and queue limits, and a future per submission.
  • Rate limiting: NewLimiter is a token bucket with FIFO waiters and a rate that can change at runtime (including paused and unlimited).
  • Adaptive concurrency: NewAdaptive admits permits up to a limit that grows on Success and shrinks on Overload.
  • Context-aware everywhere, safe for concurrent use, no goroutine leaks, no logging.

Installation

go get github.com/justusschock/concurrency@latest

Requires Go 1.25 or newer. Import it as:

import concurrency "github.com/justusschock/concurrency"

Quick start

Square numbers with at most two concurrent calls; the results keep input order. This is the package Example, so it is compiled and checked by go test:

package main

import (
	"context"
	"fmt"

	concurrency "github.com/justusschock/concurrency"
)

func main() {
	ctx := context.Background()

	squares, err := concurrency.ParallelMap(ctx, []int{1, 2, 3, 4}, 2, func(ctx context.Context, n int) (int, error) {
		if err := context.Cause(ctx); err != nil {
			return 0, err
		}
		return n * n, nil
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(squares) // [1 4 9 16]
}

example_test.go has runnable examples for every entry point: ExampleGo, ExampleGroup, ExampleParallelMap, ExamplePool, ExampleLimiter and ExampleAdaptive.

Choosing a primitive
Use When
Future (Go, Completed, Failed) One asynchronous result you await later.
Group (NewGroup) A scoped batch of related, possibly different callbacks that share cancellation and join their errors.
ParallelMap The same function over a slice, results in input order.
Pool (NewPool) An ongoing stream of typed inputs through one worker function, with back-pressure and a future per job. One job's error does not affect the others.
Limiter (NewLimiter) Cap operations or bytes per second.
Adaptive (NewAdaptive) The right concurrency is unknown and should follow downstream feedback such as HTTP 429 or 503.
Futures

The context passed to Go controls the work; the context passed to Await controls only that wait. A result that is already published wins over a canceled wait.

Groups

NewGroup(parent, limit) creates a group; Go blocks while limit callbacks run. The first callback error cancels the group context with that error as the cause. Wait closes the group (blocked and later Go calls return ErrClosed), waits for admitted callbacks and returns their errors joined in submission order.

Pools

NewPool(ctx, workers, queue, worker) admits at most workers + queue submissions and runs at most workers at once. Submit waits for admission under its own context and returns a *Future[O]; once admitted, the worker runs with the pool context. Always Close the pool and then Wait for admitted work:

pool, err := concurrency.NewPool(ctx, 2, 2, func(_ context.Context, value int) (int, error) {
	return value * value, nil
})
if err != nil {
	return err
}
future, err := pool.Submit(ctx, 3)
// …
pool.Close()
pool.Wait()
value, err := future.Await(ctx) // 9, nil
Token-bucket Limiter

NewLimiter(rate, burst) creates a full bucket holding at most burst tokens that refills at rate tokens per second. Wait(ctx, n) blocks until n tokens are available and takes them; TryAcquire(n) takes them only if they are available now and no waiter is queued. SetRate changes the rate and re-evaluates waiters immediately. A rate of 0 never refills; a rate of math.Inf(1) grants every request, including requests above burst.

// Limit uploads to 8 MiB/s with bursts of up to 1 MiB.
limiter, err := concurrency.NewLimiter(8<<20, 1<<20)
if err != nil {
	return err
}
if err := limiter.Wait(ctx, len(chunk)); err != nil {
	return err
}
Adaptive concurrency

NewAdaptive(AdaptiveOptions{Max: 32}) admits up to Limit() permits. Release each permit with the outcome of its work: Success counts toward raising the limit by one (up to Max), Overload scales it by DecreaseFactor (down to Min), Failure leaves it unchanged. Min defaults to 1, Initial to Min, DecreaseFactor to DefaultAdaptiveDecreaseFactor (0.7); IncreaseAfter of 0 grows the limit by about one per window of completed work.

permit, err := adaptive.Acquire(ctx)
if err != nil {
	return err
}
err = call(ctx)
switch {
case errors.Is(err, errThrottled):
	permit.Release(concurrency.Overload)
case err != nil:
	permit.Release(concurrency.Failure)
default:
	permit.Release(concurrency.Success)
}

Packages

Package Description
github.com/justusschock/concurrency (package concurrency) Futures, groups, ParallelMap, pools, Limiter, Adaptive and the sentinel errors.

This is the only public package. Anything under internal/ (none today) is not part of the API.

Design and guarantees

  • Concurrency safety. Futures, groups, pools, limiters and permits are safe for concurrent use. Every goroutine the library starts exits when its work returns; the limiter uses timers, not background goroutines.
  • Cancellation. Blocking calls take a context.Context and return context.Cause(ctx) when it ends first. Waiting contexts never cancel shared work. When a grant (result, tokens, permit) and a cancellation race, a grant made first wins.
  • Bounds and fairness. Groups run at most limit callbacks; pools admit at most workers + queue and run at most workers. Limiter.Wait and Adaptive.Acquire serve waiters in FIFO order, so large requests are not starved. An Adaptive limiter decreases at most once per overload burst.
  • Shutdown. Group.Wait and Pool.Close unblock callers waiting for capacity with ErrClosed; admitted work runs to completion.
  • Errors. Sentinels ErrClosed, ErrInvalidLimit and ErrNilFunction have stable texts; compare with errors.Is. Group.Wait and ParallelMap join every callback error in submission order with errors.Join; ParallelMap never returns partial results. Callback errors are not wrapped.
  • Scope. In-process only. No retries or backoff (use a dedicated library such as github.com/cenkalti/backoff/v5), no distributed or persistent execution, no priorities, no dynamic pool resizing, no panic recovery.
  • Stability. The module is v0.x: minor releases may break the API. Every break is listed in CHANGELOG.md and backed by an ADR.

Documentation

Contributing

Contributions go through pull requests against main; nothing is pushed to main directly, and a pull request merges only with green CI. Read AGENTS.md first: it describes the docs-first workflow, the public API rules and the checks to run locally.

License

Licensed under the Apache License, Version 2.0. See LICENSE and NOTICE.

Documentation

Overview

Package concurrency provides small, typed building blocks for in-process concurrent work: futures, bounded structured groups, ordered parallel maps, reusable worker pools, a token-bucket rate limiter and an adaptive (AIMD) concurrency limiter.

Choose an abstraction by the shape and lifetime of the work:

  • Future, created by Go, Completed or Failed: one asynchronous result that is awaited later.
  • Group: a scoped batch of related callbacks that share cancellation and join their errors.
  • ParallelMap: one function applied to a slice with bounded concurrency, results in input order.
  • Pool: an ongoing stream of typed inputs processed by one reusable worker function, with separate worker and queue limits.
  • Limiter: a token bucket that caps the rate of operations or bytes.
  • Adaptive: a concurrency limit that follows downstream feedback.

Futures, groups, pools, limiters and permits are safe for concurrent use. Operations that block take a context.Context and return context.Cause when it is done first. Configuration and state errors are the sentinels ErrClosed, ErrInvalidLimit and ErrNilFunction; compare them with errors.Is.

The package depends only on the Go standard library and does no logging.

Example

Square numbers with at most two concurrent calls; results keep input order.

package main

import (
	"context"
	"fmt"

	concurrency "github.com/justusschock/concurrency"
)

func main() {
	ctx := context.Background()

	squares, err := concurrency.ParallelMap(ctx, []int{1, 2, 3, 4}, 2, func(ctx context.Context, n int) (int, error) {
		if err := context.Cause(ctx); err != nil {
			return 0, err
		}
		return n * n, nil
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(squares)
}
Output:
[1 4 9 16]

Index

Examples

Constants

View Source
const DefaultAdaptiveDecreaseFactor = 0.7

DefaultAdaptiveDecreaseFactor is the AdaptiveOptions.DecreaseFactor used when the option is zero.

Variables

View Source
var (
	// ErrClosed is returned by Group.Go after Group.Wait was called and by
	// Pool.Submit after Pool.Close was called.
	ErrClosed = errors.New("concurrency: closed")
	// ErrInvalidLimit is returned for an invalid group or map limit, pool
	// worker or queue size, limiter rate, burst or token count, or adaptive
	// option.
	ErrInvalidLimit = errors.New("concurrency: invalid limit")
	// ErrNilFunction is returned when a required callback or worker function
	// is nil.
	ErrNilFunction = errors.New("concurrency: nil function")
)

Sentinel errors returned by this package. Their values and texts are part of the API; compare with errors.Is.

Functions

func ParallelMap

func ParallelMap[T, R any](ctx context.Context, values []T, limit int, fn func(context.Context, T) (R, error)) ([]R, error)

ParallelMap calls fn for every element of values with at most limit calls running at once and returns the results in input order. Calls share a context derived from ctx that is canceled by the first error. On any error ParallelMap stops admitting new elements, waits for the admitted calls and returns a nil slice with the callback errors joined in input order, or with the admission error (such as the cancellation cause of ctx) if no callback failed. It returns ErrNilFunction for a nil fn and ErrInvalidLimit for a non-positive limit.

Example
package main

import (
	"context"
	"fmt"

	concurrency "github.com/justusschock/concurrency"
)

func main() {
	values, _ := concurrency.ParallelMap(context.Background(), []int{1, 2, 3}, 2, func(_ context.Context, value int) (int, error) {
		return value * value, nil
	})
	fmt.Println(values)
}
Output:
[1 4 9]

Types

type Adaptive

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

Adaptive is a concurrency limiter whose limit adapts with additive increase and multiplicative decrease (AIMD). Successes slowly raise the limit up to Max; overloads quickly lower it down to Min. Blocked Acquire calls are admitted in FIFO order whenever a permit is released or the limit grows. An Adaptive is safe for concurrent use.

After the limit decreases, overloads reported by permits acquired before that decrease do not decrease it again, so one burst of concurrent overloads shrinks the limit once rather than once per in-flight request.

Example
package main

import (
	"context"
	"fmt"

	concurrency "github.com/justusschock/concurrency"
)

func main() {
	adaptive, err := concurrency.NewAdaptive(concurrency.AdaptiveOptions{
		Min:            1,
		Max:            8,
		Initial:        4,
		IncreaseAfter:  1,
		DecreaseFactor: 0.5,
	})
	if err != nil {
		panic(err)
	}

	permit, err := adaptive.Acquire(context.Background())
	if err != nil {
		panic(err)
	}
	permit.Release(concurrency.Success)
	fmt.Println(adaptive.Limit())

	permit, err = adaptive.Acquire(context.Background())
	if err != nil {
		panic(err)
	}
	permit.Release(concurrency.Overload) // For example, the server answered 429.
	fmt.Println(adaptive.Limit())
}
Output:
5
2

func NewAdaptive

func NewAdaptive(options AdaptiveOptions) (*Adaptive, error)

NewAdaptive returns an AIMD concurrency limiter. It returns ErrInvalidLimit unless 1 <= Min <= Initial <= Max after defaults, IncreaseAfter >= 0, and DecreaseFactor is in (0, 1).

func (*Adaptive) Acquire

func (a *Adaptive) Acquire(ctx context.Context) (Permit, error)

Acquire blocks until fewer than Limit permits are in flight and no earlier Acquire is waiting, then returns a permit. If ctx is done first, it returns context.Cause(ctx); a permit granted before the cancellation was observed wins and is returned with a nil error.

func (*Adaptive) InFlight

func (a *Adaptive) InFlight() int

InFlight returns the number of acquired permits that are not yet released. It can exceed Limit briefly after a decrease.

func (*Adaptive) Limit

func (a *Adaptive) Limit() int

Limit returns the current concurrency limit.

type AdaptiveOptions

type AdaptiveOptions struct {
	Min            int
	Max            int
	Initial        int
	IncreaseAfter  int
	DecreaseFactor float64
}

AdaptiveOptions configures NewAdaptive.

Max is required. Min defaults to 1 and Initial defaults to Min. IncreaseAfter is the number of Success releases that raise the limit by one; 0 uses the current limit, which grows the limit by about one per window of completed work. DecreaseFactor in (0, 1) scales the limit down on Overload and defaults to DefaultAdaptiveDecreaseFactor.

type Future

type Future[T any] struct {
	// contains filtered or unexported fields
}

Future is the result of one asynchronous operation: a value of type T and an error. It is resolved exactly once; later resolutions are ignored. The zero Future is not usable; create futures with Go, Completed or Failed, or obtain them from Pool.Submit. A Future is safe for concurrent use and may be awaited by any number of goroutines.

func Completed

func Completed[T any](value T) *Future[T]

Completed returns a future that is already resolved with value and a nil error.

func Failed

func Failed[T any](err error) *Future[T]

Failed returns a future that is already resolved with the zero value and err.

func Go

func Go[T any](ctx context.Context, fn func(context.Context) (T, error)) *Future[T]

Go runs fn(ctx) in a new goroutine and returns a future for its result. ctx controls the work; Go itself never blocks. If fn is nil, the returned future is already resolved with ErrNilFunction. Panics in fn are not recovered.

Example
package main

import (
	"context"
	"errors"
	"fmt"

	concurrency "github.com/justusschock/concurrency"
)

func main() {
	workCtx, cancelWork := context.WithCancel(context.Background())
	defer cancelWork()

	release := make(chan struct{})
	future := concurrency.Go(workCtx, func(ctx context.Context) (int, error) {
		select {
		case <-release:
			return 42, nil
		case <-ctx.Done():
			return 0, context.Cause(ctx)
		}
	})

	// Canceling the context of one Await does not cancel the work.
	waitCtx, cancelWait := context.WithCancel(context.Background())
	cancelWait()
	_, err := future.Await(waitCtx)
	fmt.Println(errors.Is(err, context.Canceled))

	close(release)
	value, err := future.Await(context.Background())
	fmt.Println(value, err)
}
Output:
true
42 <nil>

func (*Future[T]) Await

func (f *Future[T]) Await(ctx context.Context) (T, error)

Await blocks until the future is resolved or ctx is done. It returns the published value and error. If ctx is done first, Await returns the zero value and context.Cause(ctx); a result that is already published wins over the cancellation. Canceling ctx affects only this wait, never the work.

func (*Future[T]) Done

func (f *Future[T]) Done() <-chan struct{}

Done returns a channel that is closed once the future is resolved, for use in select statements.

func (*Future[T]) Try

func (f *Future[T]) Try() (value T, err error, ok bool)

Try reports the result without blocking. ok is false, with a zero value and nil error, while the future is pending.

type Group

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

Group runs a scoped batch of related callbacks with bounded concurrency. Callbacks share a context derived from the group's parent; the first callback error cancels it with that error as the cause. Wait closes the group to new work, drains admitted callbacks and joins their errors in submission order. A Group is single-use and safe for concurrent use.

Example
package main

import (
	"context"
	"fmt"

	concurrency "github.com/justusschock/concurrency"
)

func main() {
	group, err := concurrency.NewGroup(context.Background(), 2)
	if err != nil {
		panic(err)
	}

	inputs := []int{1, 2, 3}
	results := make([]int, len(inputs))
	for index, value := range inputs {
		if err := group.Go(func(ctx context.Context) error {
			if err := context.Cause(ctx); err != nil {
				return err
			}
			results[index] = value * value
			return nil
		}); err != nil {
			_ = group.Wait()
			panic(err)
		}
	}
	if err := group.Wait(); err != nil {
		panic(err)
	}
	fmt.Println(results)
}
Output:
[1 4 9]

func NewGroup

func NewGroup(parent context.Context, limit int) (*Group, error)

NewGroup returns a group whose callbacks run under a context derived from parent, with at most limit callbacks running at once. It returns ErrInvalidLimit if limit is not positive.

func (*Group) Go

func (g *Group) Go(fn func(context.Context) error) error

Go admits fn and runs it in a new goroutine with the group context. It blocks while limit callbacks are running. It returns ErrNilFunction for a nil fn, ErrClosed once Wait has been called (including while Go is blocked waiting for capacity), and the context cause if the group context is done before fn is admitted; in those cases fn does not run. Panics in fn are not recovered.

func (*Group) Wait

func (g *Group) Wait() error

Wait closes the group to new callbacks, blocks until every admitted callback has returned and then cancels the group context. It returns the callback errors joined with errors.Join in submission order, or nil if every callback succeeded. Wait may be called more than once.

type Limiter

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

Limiter is a token bucket. It holds at most burst tokens and refills at rate tokens per second. It starts full. Waiters are served in FIFO order, so a large request is not starved by smaller ones. A Limiter is safe for concurrent use.

A rate of 0 never refills: only the initial burst is available until SetRate raises the rate. A rate of math.Inf(1) is unlimited: every request succeeds immediately, including requests larger than burst.

Example
package main

import (
	"context"
	"fmt"

	concurrency "github.com/justusschock/concurrency"
)

func main() {
	limiter, err := concurrency.NewLimiter(1000, 2)
	if err != nil {
		panic(err)
	}
	fmt.Println(limiter.TryAcquire(2), limiter.TryAcquire(1))
	fmt.Println(limiter.Wait(context.Background(), 1))
}
Output:
true false
<nil>

func NewLimiter

func NewLimiter(rate float64, burst int) (*Limiter, error)

NewLimiter returns a full token bucket with the given refill rate in tokens per second and capacity burst. It returns ErrInvalidLimit if rate is negative or NaN, or if burst is not positive.

func (*Limiter) Burst

func (l *Limiter) Burst() int

Burst returns the bucket capacity.

func (*Limiter) Rate

func (l *Limiter) Rate() float64

Rate returns the current refill rate in tokens per second.

func (*Limiter) SetRate

func (l *Limiter) SetRate(rate float64) error

SetRate changes the refill rate. Tokens accrued at the previous rate are kept, leaving an unlimited rate starts from a full bucket, and blocked waiters are re-evaluated immediately. It returns ErrInvalidLimit, leaving the rate unchanged, if rate is negative or NaN.

func (*Limiter) TryAcquire

func (l *Limiter) TryAcquire(n int) bool

TryAcquire takes n tokens if they are available now and no Wait call is queued ahead of it. It never blocks. It reports false for negative n and, unless the rate is unlimited, for n greater than burst.

func (*Limiter) Wait

func (l *Limiter) Wait(ctx context.Context, n int) error

Wait blocks until n tokens are available and takes them, or until ctx is done. It returns ErrInvalidLimit for negative n and, unless the rate is unlimited, for n greater than burst. If ctx is done first, Wait returns context.Cause(ctx) and takes no tokens; tokens granted before the cancellation was observed win, and Wait returns nil.

type Outcome

type Outcome int

Outcome reports how the work guarded by a Permit went.

const (
	// Success counts toward an additive increase of the limit.
	Success Outcome = iota
	// Overload multiplicatively decreases the limit. Use it for signals that
	// the downstream is saturated, such as HTTP 429 or 503 responses and
	// timeouts.
	Overload
	// Failure leaves the limit unchanged. Use it for errors that say nothing
	// about downstream capacity.
	Failure
)

type Permit

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

Permit is one unit of admitted concurrency. Release it exactly once when the guarded work finishes; later calls are no-ops. The zero Permit is a no-op.

func (Permit) Release

func (p Permit) Release(outcome Outcome)

Release returns the permit and adjusts the limit for outcome. Unknown outcomes are treated as Failure.

type Pool

type Pool[I, O any] struct {
	// contains filtered or unexported fields
}

Pool processes typed inputs with one reusable worker function. At most workers worker calls run at once, and at most workers+queue submissions are admitted (running or queued) at a time. Each admitted submission gets its own Future; a worker error resolves only that future and does not affect other submissions. Call Close to reject new submissions and Wait to drain admitted work. A Pool is safe for concurrent use.

Example
package main

import (
	"context"
	"fmt"

	concurrency "github.com/justusschock/concurrency"
)

func main() {
	ctx := context.Background()
	pool, err := concurrency.NewPool(ctx, 2, 2, func(_ context.Context, value int) (int, error) {
		return value * value, nil
	})
	if err != nil {
		panic(err)
	}

	futures := make([]*concurrency.Future[int], 0, 4)
	for _, value := range []int{1, 2, 3, 4} {
		future, err := pool.Submit(ctx, value)
		if err != nil {
			panic(err)
		}
		futures = append(futures, future)
	}
	pool.Close()
	pool.Wait()

	for _, future := range futures {
		value, err := future.Await(ctx)
		fmt.Println(value, err)
	}
}
Output:
1 <nil>
4 <nil>
9 <nil>
16 <nil>

func NewPool

func NewPool[I, O any](ctx context.Context, workers, queue int, worker func(context.Context, I) (O, error)) (*Pool[I, O], error)

NewPool returns a pool that runs worker with ctx for every admitted input. It returns ErrInvalidLimit if workers is not positive or queue is negative and ErrNilFunction if worker is nil.

func (*Pool[I, O]) Close

func (p *Pool[I, O]) Close()

Close rejects new submissions and unblocks submissions waiting for capacity with ErrClosed. Admitted work keeps running. Close is idempotent.

func (*Pool[I, O]) Submit

func (p *Pool[I, O]) Submit(ctx context.Context, input I) (*Future[O], error)

Submit blocks until the pool admits input or ctx is done, and returns the future of the admitted job. ctx bounds only the admission wait: once admitted, the worker runs with the pool context and canceling ctx does not cancel it. Submit returns ErrClosed after Close (including while blocked waiting for capacity) and context.Cause(ctx) if ctx is done before admission. Panics in the worker are not recovered.

func (*Pool[I, O]) Wait

func (p *Pool[I, O]) Wait()

Wait blocks until every admitted job has finished. Call Close first, or concurrent submissions may extend the wait.

Jump to

Keyboard shortcuts

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