Documentation
¶
Overview ¶
Package queue runs durable background work with at-least-once delivery, safe for concurrent workers across goroutines and replicas.
Every queue lives in one Postgres table, queue_tasks; the queue column tells them apart. A queue has its own workers, lease and backoff: give slow and fast work queues of their own, so a long task does not hold up a quick one. Within a queue, Kind selects the handler: a Mux routes each task to the JobFunc registered for its kind.
Usage ¶
q := queue.NewPG(log, db)
if err := q.EnsureSchema(ctx); err != nil { // safe at startup, even across replicas
return err
}
// Producer: a Key makes the enqueue idempotent within the queue.
_, err := q.Schedule(ctx, queue.Params{
Queue: "email",
Kind: "email.welcome",
Key: "welcome:42",
Payload: payload,
})
// Consumer: the workers of the queue claim its tasks and run the Mux.
mux := queue.NewMux()
if err := mux.Register("email.welcome", queue.Decode(sendWelcome)); err != nil {
return err
}
workers, err := queue.Workers(log, q, queue.Config{Queue: "email", Batch: 10},
mux.Handle, queue.WithMetrics(reg))
if err != nil {
return err
}
for _, w := range workers {
group.Add(w) // a worker.Group
}
Scheduling in a transaction ¶
A task that follows a domain change is scheduled in the transaction of that change: it never runs for a change that rolled back, and is never lost for one that committed. A Registry routes the Go type of a value to the queue and kind of its task, and Bind binds it to the transaction:
reg := queue.NewRegistry()
if err := reg.Register[WelcomeEmail]("email", "email.welcome"); err != nil {
return err
}
if err := reg.Check("email", mux); err != nil { // every kind has a handler
return err
}
// In the store, within the transaction of the domain change:
err := queue.Bind(tx, q, reg).Schedule(ctx, WelcomeEmail{UserID: 42})
The domain declares its own interface with Schedule(ctx, v any) error and names neither the queue nor the transaction. The value goes into the Payload as JSON unless WithEncoder sets another Encoder. Drop turns a route off: Schedule writes nothing and returns nil, so the domain does not branch when an integration is off. Check, called at startup with the Mux of each queue, reports the kinds the Registry sends there with no handler of their own — the fallback does not count — whose tasks would go to the dead letters. Key and Delay are for PG.Schedule on the pool.
Outcomes ¶
The error of the handler decides the outcome of a task:
- nil removes the task;
- Permanent(err) sends it to the dead letters of its queue: a payload that does not decode (Decode does this itself), a kind with no handler (ErrUnknownKind), anything no retry fixes;
- Halt(err) retries it with backoff and stops the batch: the rest goes back untouched, and the queue polls again after Config.Poll — for a dependency every task needs, such as a broker that is down;
- any other error retries the task with backoff.
A retried task runs again after a backoff of 2s × 2 up to 5 minutes, with no limit on attempts; WithBackoff changes it, and its MaxAttempts sends the task to the dead letters at that many failures. Task.Attempts counts only the failures: a task released from a stopped batch, or reclaimed after a crash, keeps its attempts. A panic in the handler is recovered and logged with its stack and, by default, retried; WithOnPanic decides otherwise.
Delivery ¶
A claim leases a batch of ready tasks of one queue with SELECT … FOR UPDATE SKIP LOCKED and returns it in run_at order. A task stays leased for 3 × Config.Timeout + 10s: if its worker dies, another reclaims it after that, so delivery is at-least-once and handlers must be idempotent. A batch starts no task once it has run Config.Timeout; at shutdown the task being handled is still marked and the rest goes back. A handled task is removed at once; a dead one stays 7 days for inspection, then the cleaner of its queue removes it.
Metrics ¶
With WithMetrics the workers of a queue record, labeled with the queue, skit_queue_handled_total by kind and result (ok, error — a panic is an error), skit_queue_handle_duration_seconds by kind and, from a loop of their own every 30 seconds, the backlog gauges skit_queue_pending, skit_queue_leased and skit_queue_dead. Every replica reports the same backlog, so a dashboard takes max, not sum. The loops record skit_worker_* under the names queue-<queue>, queue-<queue>-cleaner and queue-<queue>-backlog. The queue opens no spans.
Config and options ¶
- Config: Queue (required), Concurrency (claim loops per process, default 1), Batch (tasks per claim, default 1), Timeout (per task, default 30s), Poll (wait after an empty claim, default 1s).
- WithBackoff(retry.Backoff): the retry delay and the attempt limit.
- WithOnPanic(fn): the outcome of a task whose handler panicked.
- WithMetrics(reg): the registry of the metrics.
- WithFallback(fn): the Mux handler of a kind with no registered handler.
- Registry.Register options: WithEncoder(e) (how the value is written into the Payload, default JSON), Drop() (Schedule writes nothing).
- Params: Queue and Kind (required), Key (dedup within the queue while the task is in it — waiting, leased or dead), Payload, Delay.
Example ¶
A producer schedules a task on the pool, and the workers of its queue run it on every replica. The example needs Postgres, so go test builds it but does not run it.
package main
import (
"context"
"encoding/json"
"log/slog"
"os"
"os/signal"
"syscall"
"time"
"github.com/assanoff/skit/dbx/pg"
"github.com/assanoff/skit/metrics"
"github.com/assanoff/skit/queue"
"github.com/assanoff/skit/worker"
)
type welcomeEmail struct {
UserID int64 `json:"user_id"`
}
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
log := slog.Default()
db, err := pg.Open(pg.Config{Host: "localhost:5432", Name: "shop", DisableTLS: true})
if err != nil {
log.ErrorContext(ctx, "open", "err", err)
return
}
defer func() { _ = db.Close() }()
q := queue.NewPG(log, db)
if err := q.EnsureSchema(ctx); err != nil {
log.ErrorContext(ctx, "schema", "err", err)
return
}
// Producer: the Key makes the enqueue idempotent within the queue.
payload, err := json.Marshal(welcomeEmail{UserID: 42})
if err != nil {
log.ErrorContext(ctx, "encode", "err", err)
return
}
_, err = q.Schedule(ctx, queue.Params{
Queue: "email", Kind: "email.welcome", Key: "welcome:42", Payload: payload,
})
if err != nil {
log.ErrorContext(ctx, "schedule", "err", err)
return
}
// Consumer: the workers of the queue claim its tasks and run the Mux.
mux := queue.NewMux()
err = mux.Register("email.welcome", queue.Decode(
func(ctx context.Context, _ queue.Task, m welcomeEmail) error {
log.InfoContext(ctx, "welcome sent", "user_id", m.UserID)
return nil
}))
if err != nil {
log.ErrorContext(ctx, "register", "err", err)
return
}
cfg := queue.Config{Queue: "email", Batch: 10, Timeout: 10 * time.Second}
workers, err := queue.Workers(log, q, cfg, mux.Handle, queue.WithMetrics(metrics.New()))
if err != nil {
log.ErrorContext(ctx, "workers", "err", err)
return
}
g := worker.NewGroup(log, worker.GroupConfig{ShutdownTimeout: 10 * time.Second})
g.Add(workers...)
if err := g.Run(ctx); err != nil {
log.ErrorContext(ctx, "group stopped", "err", err)
}
}
Output:
Index ¶
- Variables
- func Halt(err error) error
- func Permanent(err error) error
- func Schema() string
- func Workers(log *slog.Logger, q *PG, cfg Config, h JobFunc, opts ...Option) ([]worker.Runnable, error)
- type Config
- type Encoder
- type JobFunc
- type Mux
- type MuxOption
- type Option
- type PG
- type Params
- type Registry
- type RouteOption
- type Scheduler
- type Task
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrUnknownKind = errors.New("queue: no handler registered for kind")
ErrUnknownKind is the error of a task whose Kind has no handler in a Mux without a fallback. It comes marked Permanent: the task goes to the dead letters instead of being retried forever.
Functions ¶
func Halt ¶ added in v0.14.0
Halt marks err as a failure of a dependency every task of the batch needs, such as a broker that is down: the task is retried with backoff, and the batch stops — its rest goes back untouched, with no attempt counted, and the queue polls again after Config.Poll. Halt(nil) is nil.
func Permanent ¶ added in v0.14.0
Permanent marks err as a failure no retry fixes, such as a payload that does not decode: the task goes to the dead letters of its queue. Permanent(nil) is nil.
func Schema ¶
func Schema() string
Schema returns the DDL of queue_tasks: the key index deduplicates within a queue, the ready index serves the claim and the dead index the cleaner and the dead count. Call PG.EnsureSchema at startup to provision it (advisory-lock guarded, replica-safe); Schema is exposed for embedding the DDL in your own migration tooling.
func Workers ¶ added in v0.14.0
func Workers(log *slog.Logger, q *PG, cfg Config, h JobFunc, opts ...Option) ([]worker.Runnable, error)
Workers builds the workers of the queue cfg.Queue: Concurrency loops that claim its tasks and run h on each, the cleaner of its dead letters (kept 7 days) and, with WithMetrics, the loop of its backlog gauges. Supervise them in a worker.Group; run them on every replica — the claim splits the tasks.
The error of h decides the outcome of a task (see JobFunc). A failed task runs again after a backoff (WithBackoff), and its Attempts count only the failures: a task released from a stopped batch, or reclaimed after a crash, keeps them. Workers returns an error on an empty cfg.Queue or a nil h.
Types ¶
type Config ¶ added in v0.14.0
type Config struct {
// Queue names the queue the workers serve; required.
Queue string
// Concurrency is the number of claim loops per process (default 1).
Concurrency int
// Batch is the number of tasks a loop claims at once (default 1).
Batch int
// Timeout bounds the handler of one task (default 30s). A batch starts no
// task once it has run Timeout, and a task stays leased for 3 × Timeout +
// 10s: after that, a task of a crashed worker goes to another.
Timeout time.Duration
// Poll is the wait after a claim that found no task, or after a batch
// stopped by Halt (default 1s). After a full batch the loop claims again at
// once.
Poll time.Duration
}
Config configures the workers of one queue.
type Encoder ¶ added in v0.14.0
Encoder writes a scheduled value into the Payload of its task. ctx is the context of Schedule, so an encoder may carry what it holds, such as the trace of the producer, into the payload.
type JobFunc ¶ added in v0.4.0
JobFunc handles one task. Its error decides the outcome of the task: nil removes it; an error marked by Permanent dead-letters it; one marked by Halt retries it with backoff and stops the batch, whose rest goes back untouched; any other error retries the task with backoff.
func Decode ¶ added in v0.14.0
Decode adapts fn to a JobFunc that decodes the JSON Payload of a task into a T first. A payload that does not decode is Permanent: it never will.
Example ¶
Decode hands the handler the payload as a T. A payload that does not decode never will, so its error is Permanent.
package main
import (
"context"
"fmt"
"github.com/assanoff/skit/queue"
)
type welcomeEmail struct {
UserID int64 `json:"user_id"`
}
func main() {
h := queue.Decode(func(_ context.Context, t queue.Task, m welcomeEmail) error {
fmt.Println("welcome", m.UserID)
return nil
})
ctx := context.Background()
fmt.Println(h(ctx, queue.Task{Kind: "email.welcome", Payload: []byte(`{"user_id":42}`)}))
fmt.Println(h(ctx, queue.Task{Kind: "email.welcome", Payload: []byte(`{"user_id":"42"}`)}))
}
Output: welcome 42 <nil> queue: decode email.welcome: json: cannot unmarshal string into Go struct field welcomeEmail.user_id of type int64
type Mux ¶ added in v0.4.0
type Mux struct {
// contains filtered or unexported fields
}
Mux routes the tasks of a queue to handlers by Kind, so one queue and its workers serve many kinds: register a JobFunc per Kind and pass Mux.Handle to Workers. The claim does not filter by Kind, so the Mux is what makes the Kind column route work.
A Mux is safe for concurrent use. Register every kind at startup, before the workers run.
Example ¶
A Mux routes each task of a queue to the handler of its kind. A kind with no handler fails for good: the task goes to the dead letters.
package main
import (
"context"
"errors"
"fmt"
"github.com/assanoff/skit/queue"
)
func main() {
mux := queue.NewMux()
err := mux.Register("email.welcome", func(_ context.Context, t queue.Task) error {
fmt.Println("send", t.Kind, t.ID)
return nil
})
if err != nil {
fmt.Println(err)
return
}
ctx := context.Background()
fmt.Println(mux.Handle(ctx, queue.Task{ID: 1, Kind: "email.welcome"}))
err = mux.Handle(ctx, queue.Task{ID: 2, Kind: "email.digest"})
fmt.Println(err)
fmt.Println(errors.Is(err, queue.ErrUnknownKind))
}
Output: send email.welcome 1 <nil> queue: no handler registered for kind: "email.digest" true
func NewMux ¶ added in v0.4.0
NewMux builds an empty Mux. By default an unknown Kind fails with ErrUnknownKind; override that with WithFallback.
type MuxOption ¶ added in v0.4.0
type MuxOption func(*Mux)
MuxOption customizes a Mux.
func WithFallback ¶ added in v0.4.0
WithFallback sets the handler invoked for a Kind with no registered handler. Without it, or with a nil fn, an unknown Kind fails with ErrUnknownKind.
type Option ¶ added in v0.14.0
type Option func(*options)
Option customizes the workers of a queue.
func WithBackoff ¶ added in v0.14.0
WithBackoff sets the delay before a failed task runs again; a zero field keeps its default: Base 2s, Factor 2, Max 5m. MaxAttempts 0, the default, retries without limit; a positive MaxAttempts sends the task to the dead letters at that many failed attempts. Jitter is not applied.
func WithMetrics ¶ added in v0.14.0
func WithMetrics(reg prometheus.Registerer) Option
WithMetrics records the metrics of the queue on reg, labeled with the queue:
skit_queue_handled_total{queue,kind,result} — tasks by result: ok or error
skit_queue_handle_duration_seconds{queue,kind} — duration of the handler
skit_queue_pending{queue}, skit_queue_leased{queue}, skit_queue_dead{queue}
and the tick metrics of the loops, skit_worker_*, under the loop names queue-<queue>, queue-<queue>-cleaner and queue-<queue>-backlog. The backlog gauges come from a loop of their own that Workers adds only with WithMetrics. A panic in the handler counts as an error.
func WithOnPanic ¶ added in v0.14.0
WithOnPanic sets what a panic in the handler means for its task: the panic is recovered and logged with its stack, then fn returns the outcome — nil removes the task, Permanent dead-letters it, Halt stops the batch, any other error retries the task. Without it the task is retried.
type PG ¶
type PG struct {
// contains filtered or unexported fields
}
PG is the Postgres store of every queue: one table, queue_tasks, where the queue column tells the queues apart. Schedule enqueues; the workers of a queue (Workers) claim, mark and release its tasks through the unexported methods. Every query is an inline const right next to the method that runs it, and all time math and lease ids happen in Go, so the SQL stays free of NOW()/gen_random_uuid().
PG is safe for concurrent use by goroutines and replicas: a claim takes rows with FOR UPDATE SKIP LOCKED, so each ready task goes to one consumer at a time.
func NewPG ¶
NewPG builds the store over db. It does not create the table; call EnsureSchema at startup.
func (*PG) EnsureSchema ¶
EnsureSchema creates the table and its indexes if they do not exist. It is safe to call at startup, including from several replicas at once: the DDL runs under a transaction-scoped advisory lock, so concurrent boots serialize instead of racing on CREATE TABLE.
type Params ¶ added in v0.14.0
type Params struct {
// Queue is the queue the task goes to; required.
Queue string
// Kind selects the handler of the task within its queue; required.
Kind string
// Key deduplicates the task within Queue: while a task with the same Key
// is in the queue — waiting, leased or dead — Schedule inserts nothing
// and reports false. "" schedules every call.
Key string
// Payload is the opaque body of the task.
Payload []byte
// Delay postpones the task: it runs not before now + Delay.
Delay time.Duration
}
Params describes a task to schedule.
type Registry ¶ added in v0.14.0
type Registry struct {
// contains filtered or unexported fields
}
Registry maps the Go type of a scheduled value to the queue and kind of its task, so the domain schedules a plain typed value and the routing stays a wiring concern: the domain never names a queue.
Populate it once at startup with Register, check it against the Mux of each queue with Check, then hand it to Bind. A Registry is safe for concurrent reads after setup.
func NewRegistry ¶ added in v0.14.0
func NewRegistry() *Registry
NewRegistry returns an empty Registry.
func (*Registry) Check ¶ added in v0.14.0
Check reports the kinds the Registry sends to queue that have no handler of their own in m: their tasks would go to the dead letters as unknown. A fallback of m does not count, and a route with Drop sends nothing. Call it at startup for each queue with its Mux.
Example ¶
Check, at startup, finds the kinds the Registry sends to a queue with no handler in its Mux; a route turned off with Drop sends nothing.
package main
import (
"context"
"errors"
"fmt"
"github.com/assanoff/skit/queue"
)
type welcomeEmail struct {
UserID int64 `json:"user_id"`
}
type passwordReset struct {
UserID int64 `json:"user_id"`
}
func main() {
reg := queue.NewRegistry()
err := errors.Join(
reg.Register[welcomeEmail]("email", "email.welcome"),
reg.Register[passwordReset]("email", "email.reset"),
)
if err != nil {
fmt.Println(err)
return
}
mux := queue.NewMux()
err = mux.Register("email.welcome", queue.Decode(
func(context.Context, queue.Task, welcomeEmail) error { return nil }))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(reg.Check("email", mux))
// The reset emails are off in this environment: Schedule drops them.
reg = queue.NewRegistry()
err = errors.Join(
reg.Register[welcomeEmail]("email", "email.welcome"),
reg.Register[passwordReset]("email", "email.reset", queue.Drop()),
)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(reg.Check("email", mux))
}
Output: queue: check email: queue: no handler registered for kind: ["email.reset"] <nil>
func (*Registry) Register ¶ added in v0.14.0
func (r *Registry) Register[T any](queue, kind string, opts ...RouteOption) error
Register routes the values of the Go type T to kind in queue, written into the Payload as JSON unless WithEncoder sets another Encoder. A pointer type registers its element type, so scheduling T or *T resolves the same route.
It returns an error — it never panics — on an empty queue or kind, or a type registered twice, so the caller surfaces it at startup where the registration is wired.
type RouteOption ¶ added in v0.14.0
type RouteOption func(*route)
RouteOption customizes the route of a registered type.
func Drop ¶ added in v0.14.0
func Drop() RouteOption
Drop makes Schedule write nothing for the values of the type and return nil: an integration that is turned off, such as events with no broker. The domain write goes through, and the domain does not branch.
func WithEncoder ¶ added in v0.14.0
func WithEncoder(e Encoder) RouteOption
WithEncoder sets how the values of the type are written into the Payload (default JSON). A nil e keeps the default.
type Scheduler ¶ added in v0.14.0
type Scheduler struct {
// contains filtered or unexported fields
}
Scheduler schedules tasks in the transaction it is bound to (Bind). The domain declares its own interface with the same method — Schedule(ctx, v any) error — and *Scheduler satisfies it without an adapter, so the domain imports neither queue nor dbx and never names a queue.
func Bind ¶ added in v0.14.0
Bind returns a Scheduler whose Schedule writes tasks into q on tx, routing each value by reg. The tasks commit or roll back with the other writes in tx: no task runs for a change that rolled back, and none is lost for one that committed. A pool in place of tx does not compile; PG.Schedule schedules on the pool.
Example ¶
Bind schedules a task in the transaction of the domain change, routed by the Go type of the value: the task commits or rolls back with the change.
package main
import (
"context"
"log/slog"
"github.com/assanoff/skit/dbx"
"github.com/assanoff/skit/dbx/pg"
"github.com/assanoff/skit/queue"
)
type welcomeEmail struct {
UserID int64 `json:"user_id"`
}
func main() {
ctx := context.Background()
log := slog.Default()
db, err := pg.Open(pg.Config{Host: "localhost:5432", Name: "shop", DisableTLS: true})
if err != nil {
log.ErrorContext(ctx, "open", "err", err)
return
}
defer func() { _ = db.Close() }()
q := queue.NewPG(log, db)
reg := queue.NewRegistry()
if err := reg.Register[welcomeEmail]("email", "email.welcome"); err != nil {
log.ErrorContext(ctx, "register", "err", err)
return
}
err = dbx.WithinTran(ctx, log, db, func(tx *dbx.Tx) error {
const ins = `INSERT INTO users (id, email) VALUES (:id, :email)`
err := dbx.NamedExec(ctx, tx, ins, map[string]any{"id": 42, "email": "ann@example.com"})
if err != nil {
return err
}
return queue.Bind(tx, q, reg).Schedule(ctx, welcomeEmail{UserID: 42})
})
if err != nil {
log.ErrorContext(ctx, "sign up", "err", err)
}
}
Output:
func (*Scheduler) Schedule ¶ added in v0.14.0
Schedule writes a task for v within the bound transaction: the Registry resolves the queue and kind of the type of v, and the Encoder of its route writes the Payload. A type registered with Drop writes nothing and returns nil. An unregistered type, a nil v or a failed encoding is an error, and the transaction stays usable: nothing was written.
type Task ¶
type Task struct {
ID int64
Queue string
Kind string
Key string // dedup key within Queue; "" — none
Payload []byte
CreatedAt time.Time
RunAt time.Time
Attempts int // failed attempts before this one
LastError string // error of the last failed attempt
}
Task is a unit of queued work as its handler sees it. Payload is opaque to the queue: the handler decodes it, typically through Decode.