agentleFS
weedboxweedbox/skills/workqueue-modules/SKILL.md

workqueue-modules

Skill1 starsChanged 4 months agoApache-2.0View on GitHub

Priority: HIGH — Self-contained reference. This file and its sub-files (modules/*.md) contain ALL necessary code examples and configuration guides. DO NOT fetch source code from GitHub. Reference guide for weedbox/workqueue-modules - task queue modules for weedbox applications. Use when: enqueueing and consuming background tasks, delaying or scheduling task delivery, retrying failed tasks with exponential backoff, inspecting or requeueing dead-lettered tasks, or choosing between memory, GORM, PostgreSQL, and NATS JetStream queue backends. Covers: WorkQueue interface, task enqueue/consume, delayed tasks, retry with backoff, dead-letter queue (DLQ), competing consumers, multi-process workers, at-least-once delivery, FOR UPDATE SKIP LOCKED, LISTEN/NOTIFY, JetStream work-queue streams, conformance testing. Keywords: workqueue, work queue, task queue, job queue, background job, background task, enqueue, consume, worker, worker pool, delayed task, scheduled task, retry, backoff, dead letter, DLQ, requeue, memory_workqueue, gorm_workqueue, postgres_workqueue, nats_workqueue, workqueuetest, SKIP LOCKED, LISTEN NOTIFY, pg_notify, JetStream, competing consumers, at-least-once, lease, idempotent handler.

The file

We split this skill into the rules it gives an agent

1 rule. About 0 are common, 1 is distinctive, and 0 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Every backend delivers at-least-once.

    line 90

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Workqueue Modules Reference

This skill provides detailed usage instructions for all packages in github.com/weedbox/workqueue-modules — a single workqueue.WorkQueue interface with interchangeable backends, so application code stays backend-agnostic.

Module Index

Shared Interface

PackageDescriptionDocumentation
workqueueWorkQueue interface, Task model, enqueue/consume options, backoff helperworkqueue.md

Backends

PackageDescriptionDocumentation
memory_workqueueIn-process, in-memory backend for development and testsmemory_workqueue.md
gorm_workqueueDatabase rows on any database.DatabaseConnector (PostgreSQL, SQLite, ...); optimistic claims, lease-based crash recoverygorm_workqueue.md
postgres_workqueuePostgreSQL-native; FOR UPDATE SKIP LOCKED claims and LISTEN/NOTIFY push wakeupspostgres_workqueue.md
nats_workqueueNATS JetStream; push-based delivery with per-queue task and dead-letter streamsnats_workqueue.md

Testing

PackageDescriptionDocumentation
workqueuetestConformance test suite every backend must passworkqueuetest.md

⚠️ Critical Rules

Source of Truth — Do NOT Fetch from GitHub

This file and its sub-files (modules/*.md) are the complete reference for weedbox/workqueue-modules. DO NOT browse github.com/weedbox/workqueue-modules to look up source code.

Inject the Interface, NOT a Concrete Backend

Application code MUST depend on workqueue.WorkQueue, never on a backend type:

// ✅ Correct - use interface
type Params struct {
    fx.In
    WorkQueue workqueue.WorkQueue
}

// ❌ Wrong - using concrete implementation
type Params struct {
    fx.In
    WorkQueue *gorm_workqueue.GormWorkQueue
}

Single-Load Needs No name Tag; Multi-Load Does

Backends register via fxmodule.InterfaceModule[workqueue.WorkQueue], so the single-load / multi-load rules match common-modules connectors:

// Single backend loaded → no name tag
WorkQueue workqueue.WorkQueue

// Multiple backends loaded side by side → disambiguate by scope
Jobs   workqueue.WorkQueue `name:"jobs"`   // gorm_workqueue.Module("jobs")
Events workqueue.WorkQueue `name:"events"` // nats_workqueue.Module("events")

In tests running multiple fx.App instances in one process, call fxmodule.ResetClaim[workqueue.WorkQueue]() between apps.

Handlers Must Be Idempotent

Every backend delivers at-least-once. Crash recovery (expired leases, unacked JetStream messages) can redeliver a task whose handler already ran. Design handlers so a duplicate execution is harmless.


Quick Start

go get github.com/weedbox/workqueue-modules@latest

Load one backend module and inject the interface:

import (
    "github.com/weedbox/common-modules/postgres_connector"
    "github.com/weedbox/workqueue-modules/postgres_workqueue"
    "github.com/weedbox/workqueue-modules/workqueue"
)

func loadModules() ([]fx.Option, error) {
    return []fx.Option{
        postgres_connector.Module("database"),
        postgres_workqueue.Module("workqueue"), // Phase 2, after its connector
    }, nil
}

Enqueue and consume:

task, err := p.WorkQueue.Enqueue(ctx, "emails", payload,
    workqueue.WithDelay(30*time.Second),
    workqueue.WithMaxRetries(5),
    workqueue.WithMetadata(map[string]string{"tenant": "acme"}),
)

sub, err := p.WorkQueue.Consume(ctx, "emails",
    func(ctx context.Context, task *workqueue.Task) error {
        return send(task.Payload)
    },
    workqueue.WithConcurrency(4),
)
defer sub.Stop(context.Background())

Loading order: backend modules belong in Phase 2 (loadModules) and must be declared after their backing connector (postgres_connector / sqlite_connector for the database backends, nats_connector for nats_workqueue). memory_workqueue has no dependency.


Choosing a Backend

memory_workqueuegorm_workqueuepostgres_workqueuenats_workqueue
Durabilitynone (process-local)database rowsdatabase rowsreplicated JetStream streams
Multi-process workersnoyes (optimistic claims)yes (SKIP LOCKED)yes (shared durable consumer)
Cross-process delivery latencyn/apoll interval (default 1s)push (LISTEN/NOTIFY)push, immediate
Extra infranoneexisting database (any dialect)existing PostgreSQLNATS with JetStream
Best fortests, developmentSQLite or mixed-dialect apps, modest volumeapps on PostgreSQLhigh-volume or low-latency pipelines

Decision shortcuts:

  • Multiple replicas in production → any backend except memory_workqueue; gorm_workqueue, postgres_workqueue, and nats_workqueue all support competing consumers across processes (see the multi-instance rule)
  • SQLite / single process → gorm_workqueue (local enqueues wake workers immediately; scheduled tasks fire on time)
  • Already on PostgreSQL → postgres_workqueue (same table layout as gorm_workqueue; switching later needs no data migration)
  • Already running NATS or need high volume → nats_workqueue
  • Unit tests → memory_workqueue, or run workqueuetest.Run against your target backend

Shared Semantics (all backends)

  • Task.Attempts = number of handler invocations (first delivery = 1); a handler panic counts as a failed attempt
  • A task fails permanently after MaxRetries + 1 failed attempts, then moves to the dead-letter queue with LastError and DiedAt set
  • Retry delay: RetryBackoff(base, max, attempt) = min(base * 2^(attempt-1), max); defaults 10s base / 10m cap
  • ListDeadTasks orders oldest-first with limit/offset paging; RequeueDeadTask resets the attempt counter; unknown IDs return workqueue.ErrTaskNotFound
  • Subscription.Stop(ctx) waits for in-flight handlers; Done() closes once fully stopped
  • Handlers receive context.Background(), not the Consume call's context

See workqueue.md for the full API reference.


Related Skills

  • common-modules - Database and NATS connectors the backends build on
  • module-dev - fxmodule.InterfaceModule pattern used by every backend
  • project-dev - Project structure and application setup

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.