> ## Documentation index
> Fetch the complete documentation index at: https://goncordia.docs7.io/llms.txt
> Ask it with GET https://goncordia.docs7.io/ask?q=<keywords or question>. Short keywords rank best.
> Use these to discover all available pages before exploring further.

# Workers

> WorkerConfig, enqueue admission, and retry policies

## WorkerConfig

```go
goncordia.WorkerConfig{
	Queues:          []string{"default", "critical"},
	QueuePolicies: map[string]goncordia.QueuePolicy{
		"critical": {Weight: 4, Concurrency: 12},
		"default": {
			Weight: 1,
			KeyConcurrency: []goncordia.KeyConcurrencyLimit{
				{Key: goncordia.RateLimitKeyTag, TagPrefix: "tenant:", Limit: 2},
			},
			RateLimits: []goncordia.QueueRateLimit{
				{Limit: 10, Period: time.Second, Burst: 2},
				{Limit: 300, Period: time.Minute, Burst: 10, Key: goncordia.RateLimitKeyKind},
				{Limit: 5_000, Period: 24 * time.Hour, Scope: goncordia.RateLimitScopeGlobal},
				{Limit: 10_000, Period: 24 * time.Hour, Mode: goncordia.RateLimitModeFixedWindow},
			},
		},
	},
    Concurrency:     20,
    MaxPending:      80,                             // claimed jobs waiting/running; defaults to 4x concurrency
    WorkerID:        "mailer-eu-1",                  // generated when empty
    PollInterval:    500 * time.Millisecond,         // fallback when no push notifications
    RetryPolicy:     core.ExponentialRetry{Base: time.Second, Max: time.Hour},
    ShutdownTimeout: 30 * time.Second,
    StuckJobTimeout: time.Hour,                       // negative disables rescue
    RescueInterval: time.Minute,
	HeartbeatInterval: 20 * time.Minute,              // defaults to one third of StuckJobTimeout
	DistributedPipelines: true,                        // optional cross-process PipelineID lock
	PipelineLeaseDuration: 30 * time.Second,
	RateLimitPollInterval: time.Second,                 // maximum global-permit retry interval
	RequireLifecyclePersistence: true,
	RequireStrictOrdering: true,
    Clock:           clock.NewManual(time.Now()),     // omit in production; inject for tests
    ErrorHandler:    func(err error) { logger.Error("worker", "err", err) },
}

// Per-kind defaults and limits are configured at registration.
core.RegisterWorker(registry, worker, core.WorkerOpts{
    MaxRetry: 3, Timeout: 30 * time.Second, Concurrency: 4,
})
```

Running claims are fenced by worker ID and attempt number. `attempted_at` remains
the immutable claim time and `started_at` records handler entry; active and waiting claims renew `lease_expires_at`,
so rescue does not duplicate healthy long-running work. `Shutdown(ctx)` stops
new claims, keeps active heartbeats alive, and returns `ctx.Err()` if the drain
does not finish. Cancelling the pool context yields an interrupted claim without
consuming an attempt.

Create the pool with `NewWorkerPoolChecked` when configuration errors must be
reported before startup. The source-compatible `NewWorkerPool` reports the same
error from `Start`.

`QueuePolicy.RateLimits` are combined: a handler starts only after every rule
has granted a permit. `Limit` and `Period` express the sustained rate, while
`Burst` controls how many starts may happen without spacing (default 1). Periods
are ordinary Go durations, so second, minute, hour, and day limits use
`time.Second`, `time.Minute`, `time.Hour`, and `24*time.Hour` respectively.

Set `Key` to `RateLimitKeyKind`, `RateLimitKeyPipeline`, or `RateLimitKeyTag`
for independent budgets. Tag policies select the first lexical tag matching
`TagPrefix`; missing tags share an explicit bucket. `KeyConcurrency` applies
the same dimensions to local execution concurrency.

Smooth rules use GCRA. Set `Mode: RateLimitModeFixedWindow` for counters that
reset on UTC-aligned `Period` boundaries; fixed windows ignore `Burst`.

Local rules coordinate one `WorkerPool`. Set `Scope: RateLimitScopeGlobal` to
coordinate all pools that share the same backend, queue name, and rule. Global
permits use an O(1) compare-and-swap cursor and return an exact retry time.
Waiting jobs retain and heartbeat their claims, consume at most one execution
slot per rate-limited queue, and yield without entering the handler during
shutdown.

ClickHouse is rejected for global rate limits and distributed pipelines because
it cannot provide the required linearizable CAS/lease guarantees.

Policies can be replaced while a pool is running:

```go
err := pool.UpdateQueuePolicy("default", goncordia.QueuePolicy{
    RateLimits: []goncordia.QueueRateLimit{{Limit: 20, Period: time.Second}},
})
```

The update is atomic for future starts and wakes existing rate-limit waiters.

SQL, MongoDB, memory, and ClickHouse apply `priority DESC`, `run_at ASC`,
`created_at ASC`, and `id ASC` before limiting. DynamoDB, Firestore, Cassandra,
and Redis use a bounded due-candidate page because their native ready/due index
cannot express the full two-dimensional order. Set `RequireStrictOrdering` to
reject a non-strict driver instead of accepting that tradeoff.

### Enqueue admission

```go
admission, err := goncordia.NewQueueDepthAdmission(d, map[string]int64{
    "default": 50_000,
})
client := goncordia.NewClient(d, goncordia.ClientConfig{Admission: admission})
```

Rejected writes wrap `ErrAdmissionRejected` and expose a typed
`*QueueFullError`. Queue-depth admission is portable backpressure, not an exact
quota: the statistics read and subsequent insert are not atomic.

## Retry policies

```go
// Exponential backoff: 1s, 2s, 4s, … capped at Max, with ±20% jitter
core.ExponentialRetry{Base: time.Second, Max: 24 * time.Hour, Jitter: 0.2}

// Tests can inject deterministic randomization:
core.ExponentialRetry{Base: time.Second, Jitter: 0.2, Random: func() float64 { return 0.5 }}

// Fixed delay
core.FixedRetry{Delay: 30 * time.Second}

// No retry — discard immediately
core.NoRetry{}

// Per-attempt directives returned by a worker
return core.Discard(err)                   // permanent failure
return core.RetryAfter(30*time.Second, err)
return core.RetryAt(nextWindow, err)

// Custom
import "github.com/kirimatt/goncordia/v2/clock"

type MyPolicy struct{}
func (MyPolicy) NextRetryAt(attempt int, err error, clk clock.Clock) time.Time {
    return clk.Now().Add(time.Duration(attempt) * time.Minute)
}
```
