shardpool

package
v1.9.1 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: Apache-2.0 Imports: 5 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.

Documentation

Overview

Package shardpool runs tasks on a pool of workers grouped in shards, with every task queued on the shard its key picks. A shard's queue is served by one worker while that worker keeps up with it, and a busy goroutine stays on its P, so the tasks of one key keep running on the same CPU. That is the point of the pool: when a key is a connection, the kernel then finds the connection's socket and timers in that CPU's caches. Spread over every CPU, as a single shared queue spreads them, a loopback echo's turns ran on another CPU than the connection's previous turn 96% of the time (12% here, with 512 connections on 24 Ps, and 27% with 4096), its delayed-ACK and retransmit timers migrated between timer bases on every send, and the kernel's share of each request, which is most of its cost, measured 3% higher.

A shard takes more workers only for a backlog: a worker that takes a task and finds another queued behind it first brings in a second worker, so the backlog never waits behind a task that runs long or blocks, and a task that blocks costs its shard one worker. When a shard has no idle worker and no room for another, an idle worker of another shard serves it, or a new worker starts in a shard with room; when the whole pool has neither, the next worker to go idle serves every shard once. Workers stay parked while they are needed and exit after MaxIdle without work, one per shard staying.

SubmitBehind queues a task without bringing in a worker when one is draining its shard already: that worker takes it once its current task ends. It suits tasks submitted one at a time from outside the pool, which would otherwise wake a second worker for nearly every task: write turns submitted by 24 goroutines replying to echo requests ran 3-5% slower that way than on a shared queue whose workers rarely park, and as fast or faster with SubmitBehind. A monitor that runs while such tasks are queued brings in a worker for a shard whose head has not moved for watchTick, so a task that blocks holds up the tasks behind it for about that long.

The pool keeps one shard per P until the caller reports, through AddKey, SplitKeysPerShard keys per shard, and doubles its shards there and again at SplitKeysPerShard4, until the count drops back through the matching merge thresholds. A shard serving many keys keeps a backlog, and every worker the backlog brings in takes its next task from whichever key is next, so the more keys a shard has the more of their tasks change workers: with 4096 echoing connections on 24 Ps a task ran on the worker of its key's previous task 71% of the time with a shard per P and 83% with two, and throughput rose 2%. Longer queues are also a longer wait for everyone in them, which is why the doubling goes on: with 10000 echoing connections the second doubling halved the median round trip and raised throughput 2%. With 512 the extra shards only park and wake their workers more often, which cost 3%, and the first doubling waits for 64 keys per base shard. A key whose shard changes when the count does is the caller's to keep consistent: the pool orders nothing across shards.

Index

Constants

View Source
const (
	// DefaultCapacity is the queue capacity of a shard New is given none
	// for. A task that finds its shard full gets a goroutine of its own,
	// which then helps drain the shard.
	DefaultCapacity = 4096
	// MaxWorkers bounds a shard's workers, and so the tasks of one shard
	// that can block at once without holding up its others.
	MaxWorkers = 512
	// MaxIdle is how long a parked worker beyond the first of its shard
	// waits for work before it exits.
	MaxIdle = 30 * time.Second
	// The keys per base shard at which the pool doubles its active shards,
	// and the counts it goes back at. SplitKeysPerShard and MergeKeysPerShard
	// are the first doubling, SplitKeysPerShard4 and MergeKeysPerShard4 the
	// second; the gap between a split and its merge keeps a count that hovers
	// around one from switching back and forth. More shards mean shorter
	// queues per shard and more of them drained at once, which is what a
	// connection's wait divides over: with 10000 echoing connections on 24 Ps
	// (417 per base shard), the second doubling cut the median round trip from
	// 3.1ms to 1.6ms and raised throughput 2%; at 6000 connections, and on
	// four and eight Ps at the same connections per shard, it was a wash,
	// which is why it waits for 256. Every tier's queues are allocated up
	// front, 16 KiB per shard.
	SplitKeysPerShard  = 64
	MergeKeysPerShard  = 32
	SplitKeysPerShard4 = 256
	MergeKeysPerShard4 = 192
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Pool

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

Pool runs tasks of type T. Create it with New.

func New

func New[T any](procs, capacity int, key func(T) uint32, run func(T)) *Pool[T]

New creates a pool for procs Ps: procs shards, and as many more for when the keys are many, each queueing up to capacity tasks, rounded up to a power of two; DefaultCapacity when capacity is not positive. Every shard's queue is allocated up front. key picks a task's shard, run runs it. A panic in run is not recovered.

func (*Pool[T]) AddKey

func (pool *Pool[T]) AddKey()

AddKey and RemoveKey count the keys the pool serves, such as open connections, and switch the number of active shards when the count reaches a threshold. Count and tier updates are one lifecycle operation: a delayed threshold update must not overwrite a later split or merge. Queue submission only reads active and never takes keyMu.

func (*Pool[T]) RemoveKey

func (pool *Pool[T]) RemoveKey()

func (*Pool[T]) Rescue added in v1.9.0

func (pool *Pool[T]) Rescue(now int64) bool

Rescue brings a worker to a shard whose queue has stalled: it held tasks through rescueStalls scans in a row without moving, with no worker draining it while one woken for it had not arrived. The runtime queues a woken goroutine on its waker's P, behind the goroutine running there, and a worker draining a busy shard can hold that P for up to 10ms: on a 64-P host at 16384 echoing connections such stalls put the 99th percentile round trip near 60ms. One worker per scan is brought in, so the caller's P, where they queue, runs it next instead of stacking them as the stall did; with that, scans a millisecond apart brought the 99th percentile to 26-31ms and cost no throughput. now is the caller's clock; scans are at least rescueEvery apart and never overlap. Rescue reports whether it brought in a worker, which the caller should yield for.

func (*Pool[T]) Stats added in v1.9.0

func (pool *Pool[T]) Stats() Stats

Stats reads the pool's lock-free shard counters without allocating or taking any mutex. Because shards run concurrently, the returned totals are an approximate point-in-time view.

func (*Pool[T]) Stop

func (pool *Pool[T]) Stop()

Stop runs the tasks still queued and waits for every worker to exit: the parked ones are sent to drain their shards, and each worker exits when it next finds nothing to do. It waits for the goroutines that took tasks a full shard could not queue as well, since they run those tasks and help drain the shard. No worker starts any more, so tasks a shard could not hand to one are run on the caller's goroutine. A task a full shard refused at the moment Stop begins is dropped with the goroutine that would have run it: the caller must not submit during or after Stop, and tasks submitted after Stop returns are never run.

func (*Pool[T]) Submit

func (pool *Pool[T]) Submit(task T) bool

Submit queues one task on its shard. It never blocks and never runs the task on the caller's goroutine. It reports whether it woke or started a worker for the task.

The runtime queues a goroutine woken by another on the waker's P, where it waits until the waker blocks, yields or is preempted, up to 10ms later. A worker submitting from a task returns to its queue soon after, but a goroutine that goes on with other work should yield when Submit reports a wakeup, so the worker runs now: on a host whose Ps were all busy, write turns woken by 24 replying goroutines waited 3.6ms on average before running.

func (*Pool[T]) SubmitBatch

func (pool *Pool[T]) SubmitBatch(tasks []T)

SubmitBatch queues tasks and notifies each shard they touched once, as Submit does: a batch never waits behind a task its shard's worker is running. It does not retain the slice.

func (*Pool[T]) SubmitBehind

func (pool *Pool[T]) SubmitBehind(task T) bool

SubmitBehind is Submit for a task that may wait for the one its shard is running: when a worker drains the shard, it is left to that worker, and SubmitBehind reports false. See the package comment.

type Stats added in v1.9.0

type Stats struct {
	ActiveShards   int
	Keys           int64
	Queued         int64
	RunningWorkers int
	IdleWorkers    int
}

Stats is a point-in-time, zero-allocation snapshot of a Pool's queues and worker goroutines.

Jump to

Keyboard shortcuts

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