bootgate

package
v0.116.4 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 10 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 bootgate is an opt-in primitive for "do not start heavy boot-time work all at once": it spreads a service's first heavy cycle out in time and backs off while the host is overloaded.

Why this exists

On 2026-10-11 a Docker daemon restart brought ~330 containers up in the same instant (load average 468, daemon unresponsive for minutes), and a backup service that began a multi-GiB job at every boot starved its own HTTP handlers inside a deploy's 6 s smoke window. With 300+ services on one fleet, nothing heavy should ever start all at once; start in small incremental batches instead.

What it does

Wait blocks, in order, for:

  1. BaseDelay (a fixed head start for everything else on the host);
  2. a DETERMINISTIC jitter in [0, JitterMax), derived from an FNV-1a hash of Seed (default: the container hostname, falling back to Name). The same container always gets the same offset across restarts, and a fleet of distinct hostnames spreads evenly over the window instead of clumping the way independent random draws do;
  3. if MaxLoad > 0, the host 1-minute load average (/proc/loadavg) to fall below MaxLoad, polling every PollEvery, for at most MaxWait. The gate never blocks forever: on timeout Wait returns Result.TimedOut = true and a nil error, and the caller proceeds. Where the load average is unavailable (darwin, Windows, unreadable /proc) the gate is skipped and Result.LoadKnown is false.

Wait returns ctx.Err() promptly if the context is cancelled.

Nothing changes unless configured

Every Config field defaults to zero/disabled, and FromEnv reads only the BOOT_* variables below. Importing the package, or calling Wait with an unconfigured service, returns immediately. A service opts in by calling Wait AND an operator opting in by setting env.

BOOT_BASE_DELAY   duration, e.g. 0s
BOOT_JITTER_MAX   duration, e.g. 180s
BOOT_MAX_LOAD     float, 1-minute load average ceiling, e.g. 6 on 8 cores
BOOT_MAX_WAIT     duration, cap on the load gate (default 5m when MaxLoad>0)
BOOT_POLL_EVERY   duration, load poll interval (default 5s)

Invalid or negative values fall back to the disabled default.

Recommended fleet values for heavy workers (backup, indexing, rebuilds): BOOT_BASE_DELAY=0, BOOT_JITTER_MAX between 60s and 300s, BOOT_MAX_LOAD about 0.75 x cores, BOOT_MAX_WAIT=10m. Light, latency-sensitive services should leave it unset.

Usage

A backup-style ticker gates only its first heavy cycle:

func run(ctx context.Context) {
    res, err := bootgate.Wait(ctx, bootgate.FromEnv("fleet-backup"))
    if err != nil {
        return // ctx cancelled while waiting
    }
    log.Printf("fleet-backup: boot gate waited=%s jitter=%s load=%.2f timed_out=%t",
        res.Waited, res.Jitter, res.LoadAtEnd, res.TimedOut)

    t := time.NewTicker(interval)
    defer t.Stop()
    for {
        backupCycle(ctx)
        select {
        case <-ctx.Done():
            return
        case <-t.C:
        }
    }
}

Or, to run a function in the background after the gate, logging one line:

bootgate.Go(ctx, bootgate.FromEnv("fleet-backup"), runBackups)

Rollout

go-common is shared by ~130 services. Adopt this in small batches (a few heavy workers at a time), and enable the env knobs per service, not fleet-wide in one step.

Index

Constants

View Source
const (
	EnvBaseDelay = "BOOT_BASE_DELAY"
	EnvJitterMax = "BOOT_JITTER_MAX"
	EnvMaxLoad   = "BOOT_MAX_LOAD"
	EnvMaxWait   = "BOOT_MAX_WAIT"
	EnvPollEvery = "BOOT_POLL_EVERY"
)

Environment variables read by FromEnv.

View Source
const (
	// DefaultMaxWait caps the load gate when MaxLoad > 0 and MaxWait is 0.
	DefaultMaxWait = 5 * time.Minute
	// DefaultPollEvery is the load poll interval when PollEvery is 0.
	DefaultPollEvery = 5 * time.Second
)

Defaults applied by Wait when the load gate is enabled.

Variables

This section is empty.

Functions

func Go

func Go(ctx context.Context, cfg Config, fn func(context.Context))

Go runs Wait and then fn in a new goroutine, logging one line with the Result. If ctx is cancelled during Wait, fn is not run.

Types

type Config

type Config struct {
	// Name identifies the service in logs and is the fallback Seed.
	Name string
	// BaseDelay is a fixed delay applied before the jitter.
	BaseDelay time.Duration
	// JitterMax is the exclusive upper bound of the deterministic jitter.
	// 0 disables jitter.
	JitterMax time.Duration
	// MaxLoad is the 1-minute load average the host must be below before
	// Wait returns. 0 disables the load gate.
	MaxLoad float64
	// MaxWait caps how long the load gate may block (measured from when the
	// gate starts, after BaseDelay and jitter). 0 means DefaultMaxWait.
	MaxWait time.Duration
	// PollEvery is the load poll interval. 0 means DefaultPollEvery.
	PollEvery time.Duration
	// Seed is hashed to derive the jitter. Empty means the hostname, then
	// Name.
	Seed string
}

Config controls Wait. The zero value disables everything.

func FromEnv

func FromEnv(name string) Config

FromEnv builds a Config for the named service from BOOT_* environment variables. Unset, invalid, or negative values leave the knob disabled.

type Result

type Result struct {
	// Waited is the total time spent in Wait.
	Waited time.Duration
	// Jitter is the deterministic jitter that was applied.
	Jitter time.Duration
	// LoadAtStart and LoadAtEnd are the first and last load samples; zero
	// when LoadKnown is false.
	LoadAtStart, LoadAtEnd float64
	// TimedOut is true if MaxWait elapsed with the load still too high.
	TimedOut bool
	// LoadKnown is true if a load average could be read.
	LoadKnown bool
}

Result describes what Wait did, so callers can log it.

func Wait

func Wait(ctx context.Context, cfg Config) (Result, error)

Wait blocks according to cfg (see the package doc) and reports what it did. It returns ctx.Err() if ctx is cancelled first; a MaxWait timeout is not an error. It never panics and never blocks beyond BaseDelay + JitterMax + MaxWait.

Jump to

Keyboard shortcuts

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