queue

package
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: MIT Imports: 9 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.

README

queue

Backed by Redis Streams. Supports per-type worker pools, delayed jobs, automatic retry, dead-letter queue, and stuck-job reclaiming.

import (
    "github.com/thanhbvha/go-common/queue"
    "github.com/thanhbvha/go-common/queue/registry"
)

cfg := queue.DefaultConfig()
cfg.Logger = log

q := queue.New(rdb, cfg) // rdb satisfies queue.RedisStreamer

// Register tasks via registry
registry.Register("email", queue.JobTypeOptions{
    Concurrency: 4,
    MaxRetry:    5,
    BatchSize:   10,
}, func(job queue.Job) error {
    // job.Data holds your payload
    return sendEmail(job.Data)
})

// Apply registered tasks to the queue
registry.ApplyToQueue(q)

q.Start(ctx)
defer q.Stop()

// Immediate
q.Enqueue(ctx, "email", payload)

// Delayed
q.EnqueueDelayed(ctx, "email", payload, 30*time.Second)

// Unique / deduplicated (window: 5 min)
q.EnqueueUnique(ctx, "email", "welcome-user-42", payload, 5*time.Minute)

// Options
q.Enqueue(ctx, "email", payload,
    queue.WithMaxRetry(10),
    queue.WithDelay(5),
)
Architecture
Enqueue ──► Redis Stream (per job type)
              │
              ▼
         Worker pool ──► handler()
              │               │
         success            error
              │               │
             ACK          retry (re-enqueue)
                               │
                          max retries exceeded
                               │
                              DLQ stream
Symbol Description
Queue Central struct — owns workers, reclaimer, dispatcher
Config All tuneable parameters with DefaultConfig() helper
JobTypeOptions Per-type concurrency, retry, stream key, group override
Job Payload envelope (ID, Type, Data, Retry, Delay, …)
JobHandler func(Job) error — return non-nil to trigger retry
RedisStreamer Interface — any Redis client satisfying it works

Documentation

Overview

Package queue implements a durable, Redis-Streams-backed job queue with support for delayed execution, per-type worker pools, automatic retry with exponential back-off, and a dead-letter queue (DLQ) for exhausted jobs.

The queue package depends only on a RedisStreamer interface, so it is not coupled to any specific Redis client implementation. The *redis.Client provided by github.com/thanhbvha/go-common/redis satisfies this interface out of the box.

Basic usage:

rdb := redis.MustConnect(ctx, redis.DefaultConfig())
redis.SetDefault(rdb)

cfg := queue.DefaultConfig()
q := queue.New(rdb, cfg)

q.RegisterJobType("email", queue.JobTypeOptions{Concurrency: 4, MaxRetry: 5})
q.RegisterHandler("email", func(job queue.Job) error { /* … */ return nil })

q.Start(ctx)
defer q.Stop()

q.Enqueue(ctx, "email", payload)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// StreamPrefix is prepended to all stream names created by this queue.
	// Default: "queue:stream".
	StreamPrefix string

	// DefaultGroup is the consumer group name when a job type has no custom group.
	// Default: "workers".
	DefaultGroup string

	// DefaultMaxLen is the approximate maximum number of entries kept in each
	// stream (MAXLEN ~ trimming). Default: 20_000.
	DefaultMaxLen int64

	// DefaultMaxRetry is the number of retries before a job is moved to the DLQ.
	// Default: 3.
	DefaultMaxRetry int

	// DefaultWorkerCount is the fallback worker pool size used when no job types
	// are registered. Default: 5.
	DefaultWorkerCount int

	// DelayedStreamKey is the Redis stream that holds deferred jobs.
	// Default: "queue:stream:delayed".
	DelayedStreamKey string

	// DelayCheckInterval controls how often the delay dispatcher wakes up.
	// Default: 2s.
	DelayCheckInterval time.Duration

	// DLQStreamKey is the Redis stream that receives exhausted jobs.
	// Default: "queue:stream:dlq".
	DLQStreamKey string

	// DLQMaxLen is the approximate maximum number of entries kept in the DLQ.
	// Default: 50_000.
	DLQMaxLen int64

	// DLQRetention is the age after which DLQ entries are deleted.
	// Default: 15 days.
	DLQRetention time.Duration

	// DLQCleanupInterval controls how often the DLQ cleanup goroutine runs.
	// Default: 5 minutes.
	DLQCleanupInterval time.Duration

	// ReclaimMinIdle is the minimum time a pending message must be idle before
	// it is eligible for reclaiming. Default: 5 minutes.
	ReclaimMinIdle time.Duration

	// ReclaimInterval controls how often each reclaim goroutine runs.
	// Default: 1 minute.
	ReclaimInterval time.Duration

	// ReclaimBatchSize is the maximum number of pending messages processed in
	// a single reclaim cycle. Default: 100.
	ReclaimBatchSize int64

	// Logger receives operational log events. Set to nil to suppress logging.
	Logger Logger

	// ShutdownTimeout is the maximum time to wait for workers to finish
	// processing in-flight jobs during graceful shutdown. Default: 10s.
	ShutdownTimeout time.Duration
}

Config holds all tuneable parameters for a Queue instance. Use DefaultConfig for a pre-filled value and override only what you need.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config pre-populated with production-ready defaults.

type Job

type Job struct {
	// ID is a globally unique identifier assigned at enqueue time.
	ID string `json:"id"`
	// Type identifies the handler that should process this job.
	Type string `json:"type"`
	// Data is the arbitrary payload passed to the handler.
	Data interface{} `json:"data"`
	// Retry is the number of times this job has been attempted.
	Retry int `json:"retry"`
	// MaxRetry is the maximum number of attempts before DLQ routing.
	MaxRetry int `json:"max_retry"`
	// Delay is the number of seconds to wait before first execution.
	// Set via WithDelay option; 0 means immediate.
	Delay int64 `json:"delay"`
	// MaxLen is the approximate maximum stream length for this job's stream.
	MaxLen int64 `json:"max_len"`
	// CreatedAt is the wall-clock time the job was enqueued.
	CreatedAt time.Time `json:"created_at"`
}

Job represents a unit of work dispatched through the queue.

type JobHandler

type JobHandler func(job Job) error

JobHandler is a function that processes a single Job. Return a non-nil error to signal failure; the queue will retry up to MaxRetry times before routing the job to the dead-letter queue.

type JobOption

type JobOption func(*Job)

JobOption is a functional option applied to a Job before it is enqueued.

func WithDelay

func WithDelay(seconds int64) JobOption

WithDelay sets the number of seconds to wait before the job is dispatched.

func WithMaxLen

func WithMaxLen(max int64) JobOption

WithMaxLen overrides the approximate stream length cap for the job's stream.

func WithMaxRetry

func WithMaxRetry(max int) JobOption

WithMaxRetry overrides the maximum number of retry attempts for the job.

type JobTypeOptions

type JobTypeOptions struct {
	// Concurrency is the number of parallel worker goroutines. Default: 1.
	Concurrency int

	// MaxRetry overrides Config.DefaultMaxRetry for this type. 0 = use default.
	MaxRetry int

	// MaxLen overrides Config.DefaultMaxLen for this type. 0 = use default.
	MaxLen int64

	// BatchSize is the number of messages fetched per XReadGroup call. Default: 1.
	BatchSize int64

	// StreamKey overrides the auto-generated stream key. Empty = auto.
	StreamKey string

	// Group overrides the auto-generated consumer group name. Empty = auto.
	Group string
}

JobTypeOptions configures a specific job type registered with Queue.RegisterJobType.

type Logger

type Logger interface {
	Info(msg string, args ...any)
	Warn(msg string, args ...any)
	Error(msg string, args ...any)
	InfoAsync(msg string, args ...any)
	ErrorAsync(msg string, args ...any)
	WarnAsync(msg string, args ...any)
}

Logger is the logging interface consumed by Queue. It mirrors the interface in the sibling redis package so both can be satisfied by the same logger without an import cycle.

type Queue

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

Queue manages a set of Redis-Streams-backed worker pools, a delayed-job dispatcher, a DLQ cleanup routine, and a per-stream stuck-job reclaimer. Create with New; register job types and handlers before calling Start.

func New

func New(redisClient RedisStreamer, cfg Config) *Queue

New creates a Queue backed by the given RedisStreamer and configured by cfg. The queue is idle until Start is called.

func (*Queue) Enqueue

func (q *Queue) Enqueue(ctx context.Context, jobType string, data interface{}, opts ...JobOption) error

Enqueue adds a job of the given type to the queue for immediate processing. The target stream is determined by the registered JobTypeOptions for jobType; if the stream does not yet exist the job falls back to the default stream.

func (*Queue) EnqueueDelayed

func (q *Queue) EnqueueDelayed(ctx context.Context, jobType string, data interface{}, delay time.Duration, opts ...JobOption) error

EnqueueDelayed adds a job that will not be dispatched until delay has elapsed. Under the hood the job is placed in the delayed stream and moved to the target stream by the delay-dispatcher goroutine.

func (*Queue) EnqueueUnique

func (q *Queue) EnqueueUnique(ctx context.Context, jobType string, dedupeKey string, data interface{}, ttl time.Duration, opts ...JobOption) error

EnqueueUnique adds a job only if no job with the same dedupeKey has been enqueued within ttl. Duplicate submissions within the window are silently dropped (no error is returned).

Deduplication is implemented with a Redis SET NX key so it works across multiple application instances.

func (*Queue) RegisterHandler

func (q *Queue) RegisterHandler(jobType string, handler JobHandler)

RegisterHandler binds handler to jobType. Jobs of that type are dispatched to handler from every worker goroutine assigned to the type. Must be called before Start.

func (*Queue) RegisterJobType

func (q *Queue) RegisterJobType(name string, opts JobTypeOptions)

RegisterJobType declares a named job type with its worker configuration. Must be called before Start. Calling with the same name overwrites the previous registration.

func (*Queue) Start

func (q *Queue) Start(ctx context.Context)

Start initialises consumer groups, then launches all background goroutines: one per registered worker, plus the delayed-job dispatcher, DLQ cleanup, and per-stream reclaim loops. ctx controls the lifetime of all goroutines; cancel it (or call Stop) to begin a graceful shutdown.

func (*Queue) Stop

func (q *Queue) Stop()

Stop signals all goroutines to shut down and waits up to 10 seconds for them to finish processing in-flight jobs.

type RedisStreamer

type RedisStreamer interface {
	BuildKey(key string) string
	XAdd(ctx context.Context, args *goredis.XAddArgs) (string, error)
	XGroupCreateMkStream(ctx context.Context, stream, group, start string) error
	XReadGroup(ctx context.Context, group, consumer string, streams []string, count int64, block time.Duration) ([]goredis.XStream, error)
	XAck(ctx context.Context, stream, group string, ids ...string) (int64, error)
	XDel(ctx context.Context, stream string, ids ...string) (int64, error)
	XRangeN(ctx context.Context, stream, start, stop string, count int64) ([]goredis.XMessage, error)
	XPendingExt(ctx context.Context, stream, group, start, end string, count int64, idle time.Duration) ([]goredis.XPendingExt, error)
	XClaim(ctx context.Context, args *goredis.XClaimArgs) ([]goredis.XMessage, error)
	XAutoClaim(ctx context.Context, args *goredis.XAutoClaimArgs) ([]goredis.XMessage, string, error)
	SetNX(ctx context.Context, key string, value interface{}, ttl time.Duration) (bool, error)
	Exists(ctx context.Context, keys ...string) (int64, error)
	Type(ctx context.Context, key string) (string, error)
	Info(ctx context.Context, section ...string) (string, error)
}

RedisStreamer defines the minimal Redis Streams API required by Queue. *redis.Client from github.com/thanhbvha/go-common/redis satisfies this interface, as does any compatible mock for testing.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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