goncordia
Background job queue on the database you already use (Postgres, MySQL, SQLite, MongoDB, Redis and more), with transactional enqueue and typed futures
About goncordia
This large README is shown as a plain-text preview. Read the full README at the source
# goncordia
[](https://github.com/kirimatt/goncordia/actions/workflows/ci.yml)
[](https://codecov.io/gh/kirimatt/goncordia)
[](https://pkg.go.dev/github.com/kirimatt/goncordia/v2)
[](https://github.com/kirimatt/goncordia/releases)
[](go.mod)
[](LICENSE)
[](https://github.com/avelino/awesome-go#messaging)
[](https://context7.com/kirimatt/goncordia)
[Documentation](https://goncordia.docs7.io) · [Changelog](CHANGELOG.md) · [API reference](https://pkg.go.dev/github.com/kirimatt/goncordia/v2) · [Migrating to v2](MIGRATING_TO_V2.md) · [Who uses it](ADOPTERS.md)
**A background job queue for Go that runs on the database you already have.**
Enqueue jobs in the same transaction as your data, process them with retries,
schedules, and priorities, and await a job's typed result when you need it —
on Postgres, MySQL, MariaDB, SQLite, MongoDB, Redis, Cassandra, ClickHouse,
DynamoDB, Firestore, or in memory. No new broker to run.
Use it for the jobs a Go service sends to the background: emails and
notifications, webhooks, report and thumbnail generation, syncing with
external APIs, and periodic cleanups. It covers the role of Sidekiq or Celery
in Go, plus the transactional outbox pattern.
One `Driver[TTx]` interface, parameterized by your database library's native
transaction type (`pgx.Tx`, `*sql.Tx`, `*gorm.DB`, `bun.Tx`, `*mongo.Session`,
…), connects the client and workers to storage without an adapter layer.
`EnqueueTx` implements the [transactional outbox pattern](https://microservices.io/patterns/data/transactional-outbox.html): the job is written inside your existing transaction and becomes visible to workers only after commit. If the transaction rolls back, the job disappears — no separate relay process, no dual-write risk.
```go
tx, _ := pool.Begin(ctx)
_, _ = queries.CreateOrder(ctx, tx, order)
_, _ = client.EnqueueTx(ctx, tx, SendConfirmationArgs{OrderID: order.ID}, nil)
tx.Commit(ctx) // job and order appear atomically
```
---
## Features
- **Transactional inserts** — `EnqueueTx` shares your existing transaction; the job appears if and only if that transaction commits
- **Scheduled jobs** — `InsertOpts.RunAt` for future execution
- **Priority queues** — higher priority processed first within a queue
- **Unique jobs** — deduplicate by kind, args, queue, or time window
- **Retry with backoff** — exponential (default), fixed, or custom `RetryPolicy`
- **Crash recovery** — abandoned `running` jobs are automatically returned to the queue
- **Execution controls** — global and per-kind concurrency, per-job timeouts, stable worker IDs
- **Pipelines** — serialize jobs sharing a `PipelineID` locally or, optionally, across worker processes
- **Fair multi-queue scheduling** — weighted round-robin with per-queue concurrency and composable local/global execution rate limits
- **Payload evolution** — versioned payloads with ordered upcasters and permanent decode failures
- **Batch enqueue** — shared options or independent per-item options, with transactional variants
- **Futures** — enqueue a job and `Await` the value its handler returns, with local wake-up and polling fallback; `Call` runs a one-shot job like a function call
- **Retention by default** — old completed, cancelled, and discarded jobs and future results are pruned under a leader lease
- **Queue pause/resume** — drain a queue without stopping workers
- **Push notifications** — LISTEN/NOTIFY (Postgres), Change Streams (MongoDB), Pub/Sub (Redis); polling fallback elsewhere
- **SKIP LOCKED** — lock-free concurrent fetching on Postgres and MySQL
- **Periodic / cron jobs** — lease-based single-leader scheduling across multiple instances
- **Admin and metrics** — embeddable dashboard, JSON API, health probes, and Prometheus endpoint
- **`clock.Manual`** — injected deterministic time for clients, workers, schedulers, and drivers
---
## Backends
| Driver | Package | Tx type | Atomic insert | Notes |
|---|---|---|---|---|
| PostgreSQL (pgx v5) | `driver/pgxv5` | `pgx.Tx` | ✅ | LISTEN/NOTIFY, lease leadership, SKIP LOCKED |
| PostgreSQL / MySQL / MariaDB / SQLite | `driver/stdlib` | `*sql.Tx` | ✅ | pgx stdlib, go-sql-driver/mysql (MySQL 8, MariaDB 10.6+), modernc sqlite |
| gorm | `driver/gorm` | `*gorm.DB` | ✅ | thin adapter over stdlib |
| bun | `driver/bun` | `bun.Tx` | ✅ | thin adapter over stdlib |
| MongoDB 4.0+ | `driver/mongodbv2` | `*mongo.Session` (mongo-driver v2) | ✅ | replica set required |
| MongoDB 4.0+ (deprecated) | `driver/mongodb` | `mongo.SessionContext` (mongo-driver v1) | ✅ | use `driver/mongodbv2` |
| Redis | `driver/redis` | `NoTx` | ❌ | at-least-once; Pub/Sub notifications |
| Cassandra 3.11+ | `driver/cassandra` | `NoTx` | ❌ | LWT claiming; ScyllaDB / DSE compatible |
| ClickHouse 23+ | `driver/clickhouse` | `NoTx` | ❌ | ReplacingMergeTree; at-least-once |
| Amazon DynamoDB | `driver/dynamodb` | `NoTx` | ❌ | conditional writes; at-least-once |
| Cloud Firestore | `driver/firestore` | `*firestore.Transaction` | ✅ | RunTransaction; composite index required |
| In-memory | `driver/memory` | `memory.NoTx` | ❌ | synchronized operations, no rollback; for tests |
---
## How it compares
| | goncordia | [River](https://github.com/riverqueue/river) | [Asynq](https://github.com/hibiken/asynq) | [Machinery](https://github.com/RichardKnop/machinery) |
|---|---|---|---|---|
| Backends | Postgres, MySQL, SQLite, MongoDB, Redis, Cassandra, ClickHouse, DynamoDB, Firestore, memory | **PostgreSQL only** | **Redis only** | Redis, RabbitMQ, SQS, MongoDB |
| Transactional insert (outbox pattern) | ✅ where backend supports tx | ✅ Postgres only | ❌ | ❌ |
| Generic `Driver[TTx]` interface | ✅ | ✅ (Postgres only) | — | — |
| Scheduled / cron jobs | ✅ | ✅ | ✅ | ✅ |
| Unique jobs | ✅ | ✅ | ✅ | ❌ |
| Priority queues | ✅ | ✅ | ✅ | ❌ |
| New-job wake-up | ✅ LISTEN/NOTIFY, Change Streams, Pub/Sub; polling elsewhere | ✅ LISTEN/NOTIFY | ❌ polling (`TaskCheckInterval`, 1 s) | ✅ blocking pop on Redis (`BLPOP`); broker-dependent |
| Web UI | ✅ embeddable | ✅ (River UI, Pro) | ✅ (asynqmon) | ❌ |
| Await a job's typed result | ✅ `future.Func.Call` / `Await` | ❌ | stores results, no await | ✅ `AsyncResult.Get` |
| Unit tests without Docker | ✅ in-memory driver + `gontest` | needs Postgres | needs Redis | needs a broker |
| Workflow primitives (chains, chords) | ❌ | ❌ | ❌ | ✅ |
### Performance
Same workloads on the same servers, every library with its default settings
(full method, `-tuned` variants and latency in
[Against river, asynq and machinery](#against-river-asynq-and-machinery);
code in [`bench/compare`](bench/compare)). Jobs per second, higher is better:
| Postgres | goncordia (pgxv5) | River | River, 10 ms fetch interval |
|---|---|---|---|
| Enqueue, one per call | **1,044** | 671 | 670 |
| Enqueue, batches of 100 | 31,237 | 34,427 | **34,827** |
| Drain 20,000 jobs, 10 workers | **5,801** | 99 | 4,726 |
| Drain 20,000 jobs, 100 workers | 20,610 | 999 | **22,588** |
| Idle pickup latency, p50 | **2.8 ms** | 100 ms | 15 ms |
| Redis | goncordia (redis) | Asynq | Machinery |
|---|---|---|---|
| Enqueue, one per call | 3,232 | **3,669** | 1,910 |
| Enqueue, batches of 100 | **61,826** | no batch API | no batch API |
| Drain 20,000 jobs, 10 workers | **11,450** | 3,040 | 2,263 |
| Drain 20,000 jobs, 100 workers | **21,205** | 3,021 | 2,243 |
| Idle pickup latency, p50 | **0.7 ms** | 1,036 ms | 1.6 ms |
On Postgres goncordia is on par with River once River's fetch interval is
lowered (River's default 100 ms `FetchCooldown` caps a drain at about
10 × workers jobs/s); River is ~10% ahead on batch inserts and on a drain with
100 workers. On Redis goncordia drains 4–9× faster than Asynq and Machinery;
Asynq is ~10% ahead on single inserts. Asynq's idle latency follows its
`TaskCheckInterval` (1 s by default; 11 ms with 10 ms). Every drain is checked
for exactly-once execution; no library ran a job twice. Other goncordia
backends are not in this table because River runs only on Postgres and Asynq
only on Redis; their own numbers are in [Benchmarks](#benchmarks).
**Choose goncordia** when you want the transactional outbox pattern and don't want to introduce Redis or a dedicated Postgres instance — it works with whatever database your application already uses. It also fits when a caller needs the value a background job returns (`future.Func.Call`), or when you want unit tests of enqueue and worker code without Docker.
**Choose River** if you're on Postgres and want a mature, battle-tested library with a polished UI and a professional support tier.
**Choose Asynq** if Redis is already in your stack, you don't need transactional inserts, and you want a built-in web dashboard.
**Choose Machinery** if you need Celery-style workflow primitives (chains, chords, groups) across RabbitMQ or SQS.
Moving over from one of them? Migration guides: [Asynq](https://goncordia.docs7.io/migrating-from-asynq), [River](https://goncordia.docs7.io/migrating-from-river), [Machinery](https://goncordia.docs7.io/migrating-from-machinery).
---
## Using goncordia with AI coding agents
Up-to-date, version-specific docs for Cursor, Claude Code, Copilot, Windsurf
and other agents:
- **Context7 MCP**: library ID `/kirimatt/goncordia`. With the
[Context7 MCP server](https://github.com/upstash/context7) installed, add
`use context7` or `use library /kirimatt/goncordia` to your prompt.
Versions are indexed per release (`/kirimatt/goncordia/v2.11.0`).
- **Plain text, no MCP**: [context7.com/kirimatt/goncordia/llms.txt](https://context7.com/kirimatt/goncordia/llms.txt)
(add `?topic=EnqueueTx` to narrow it) and
[goncordia.docs7.io/llms.txt](https://goncordia.docs7.io/llms.txt).
- **In your repository**: copy the rules from [AGENTS.md](AGENTS.md) into
your own `AGENTS.md` / `CLAUDE.md` / `.cursor/rules`, so the agent uses
`EnqueueTx`, the `/v2` import paths and the in-memory test driver.
### Let the agent operate your queue (MCP server)
The [`mcpserver`](mcpserver) module serves your queues and jobs over MCP, so an
agent can find failed jobs, read their errors and retry them, without you
opening the dashboard:
```go
import "github.com/kirimatt/goncordia/mcpserver/v2"
srv := mcpserver.New(d) // read-only tools
mux.Handle("/mcp", requireAdmin(mcpserver.Handler(srv))) // or srv.Run(ctx, &mcp.StdioTransport{})
```
Tools: `list_queues`, `list_jobs`, `get_job`, `get_metrics`, and with
`mcpserver.WithWriteTools()` also `retry_job`, `reschedule_job`, `cancel_job`,
`delete_job`, `pause_queue`, `resume_queue`. Payloads are hidden by default.
See [the MCP guide](https://goncordia.docs7.io/mcp).
## Installation
Requires Go 1.26 or newer.
```bash
go get github.com/kirimatt/goncordia/[email protected]
```
Pick a driver:
```bash
# PostgreSQL via pgx v5
go get github.com/kirimatt/goncordia/driver/pgxv5/[email protected]
# PostgreSQL / MySQL / MariaDB / SQLite via database/sql
go get github.com/kirimatt/goncordia/driver/stdlib/[email protected]
# gorm adapter
go get github.com/kirimatt/goncordia/driver/gorm/[email protected]
# bun adapter
go get github.com/kirimatt/goncordia/driver/bun/[email protected]
# MongoDB (replica set required)
go get github.com/kirimatt/goncordia/driver/mongodbv2/[email protected]
# Redis
go get github.com/kirimatt/goncordia/driver/redis/[email protected]
# Cassandra / ScyllaDB
go get github.com/kirimatt/goncordia/driver/cassandra/[email protected]
# ClickHouse
go get github.com/kirimatt/goncordia/driver/clickhouse/[email protected]
# Amazon DynamoDB
go get github.com/kirimatt/goncordia/driver/dynamodb/[email protected]
# Cloud Firestore
go get github.com/kirimatt/goncordia/driver/firestore/[email protected]
```
The root v1 module intentionally does not download every database SDK. Driver,
OpenTelemetry, and testing dependencies arrive only when their submodule is
selected. See [Migrating to v2](MIGRATING_TO_V2.md) for upgrade commands.
---
## Quick start
### PostgreSQL (pgx v5)
```go
import (
"github.com/kirimatt/goncordia/v2"
"github.com/kirimatt/goncordia/v2/core"
pgxdriver "github.com/kirimatt/goncordia/driver/pgxv5/v2"
"github.com/jackc/pgx/v5/pgxpool"
)
pool, _ := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
defer pool.Close()
d := pgxdriver.New(pool)
d.Migrate(ctx)
type SendEmailArgs struct {
To string `json:"to"`
Subject string `json:"subject"`
}
func (SendEmailArgs) Kind() string { return "send_email" }
registry := core.NewRegistry()
core.RegisterWorker(registry, core.WorkerFunc[SendEmailArgs](
func(ctx context.Context, job *core.Job[SendEmailArgs]) error {
return sendEmail(job.Args.To, job.Args.Subject)
},
), core.WorkerOpts{MaxRetry: 5})
client := pgxdriver.NewClient(d, goncordia.ClientConfig{})
client.Enqueue(ctx, SendEmailArgs{To: "[email protected]", Subject: "Welcome"}, nil)
wp := pgxdriver.NewWorkerPool(d, registry, goncordia.WorkerConfig{
Queues: []string{"default"},
Concurrency: 10,
})
wp.Start(ctx) // blocks
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_ = wp.Shutdown(shutdownCtx) // reports an incomplete drain
```
### Transactional insert (PostgreSQL)
```go
tx, _ := pool.Begin(ctx)
_, _ = queries.CreateOrder(ctx, tx, orderParams)
_, _ = client.EnqueueTx(ctx, tx, SendConfirmationArgs{OrderID: id}, nil)
tx.Commit(ctx) // job and order are atomic
```
### MongoDB
```go
import (
mongodriver "github.com/kirimatt/goncordia/driver/mongodbv2/v2"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
client, _ := mongo.Connect(options.Client().ApplyURI(os.Getenv("MONGO_URI")))
defer client.Disconnect(ctx)
d, err := mongodriver.New(ctx, client, "myapp") // fails if not a replica set
d.Migrate(ctx)
mqClient := mongodriver.NewClient(d, goncordia.ClientConfig{})
// Transactional insert: the transaction type is *mongo.Session
session, _ := client.StartSession()
defer session.EndSession(ctx)
_, err = session.WithTransaction(ctx, func(ctx context.Context) (any, error) {
if _, err := db.Collection("orders").InsertOne(ctx, order); err != nil {
return nil, err
}
return mqClient.EnqueueTx(ctx, session, SendConfirmationArgs{OrderID: order.ID}, nil)
})
```
`driver/mongodb` is the same driver on the deprecated mongo-driver v1, with
`mongo.SessionContext` as the transaction type. Both use the same collections
and document format, so you can switch processes one by one: replace the
import, connect with mongo-driver v2, and pass the session to `EnqueueTx`.
### gorm
```go
import (
gormdriver "github.com/kirimatt/goncordia/driver/gorm/v2"
"gorm.io/gorm"
)
d, _ := gormdriver.New(db) // db is *gorm.DB
d.Migrate(ctx)
client := gormdriver.NewClient(d, goncordia.ClientConfig{})
db.Transaction(func(tx *gorm.DB) error {
tx.Create(&order)
client.EnqueueTx(ctx, tx, SendConfirmationArgs{OrderID: order.ID}, nil)
return nil // commit — job appears atomically with the order
})
```
### bun
```go
import (
bundriver "github.com/kirimatt/goncordia/driver/bun/v2"
"github.com/uptrace/bun"
)
d := bundriver.New(db) // db is *bun.DB
d.Migrate(ctx)
client := bundriver.NewClient(d, goncordia.ClientConfig{})
tx, _ := db.BeginTx(ctx, nil)
tx.NewInsert().Model(&order).Exec(ctx)
client.EnqueueTx(ctx, tx, SendConfirmationArgs{OrderID: order.ID}, nil)
tx.Commit()
```
### Redis
```go
import (
redisdriver "github.com/kirimatt/goncordia/driver/redis/v2"
"github.com/redis/go-redis/v9"
)
rdb := redis.NewClient(&redis.Options{Addr: "localhost:6379"})
defer rdb.Close()
d := redisdriver.New(rdb)
d.Migrate(ctx) // verifies connectivity, rejects allkeys-* eviction, backfills the admin index
client := redisdriver.NewClient(d, goncordia.ClientConfig{})
client.Enqueue(ctx, SendEmailArgs{To: "[email protected]", Subject: "Welcome"}, nil)
// EnqueueTx is not supported on the Redis driver:
// there is no rollback guarantee. Use Enqueue (post-commit pattern) instead.
```
Jobs and results are Redis keys without a TTL. Under an `allkeys-*`
`maxmemory-policy`, Redis may evict them under memory pressure, silently
dropping pending jobs and stored results, so `Migrate` fails with
`redisdriver.ErrEvictionPolicy`. Use `noeviction` (writes fail loudly when
memory is full) or a `volatile-*` policy, which never touches keys without a
TTL. `redisdriver.WithAllowEviction()` disables the check; when `CONFIG` is
blocked, as on some managed services, the check is skipped. If a result is
evicted anyway, `Await` returns `future.ErrResultLost` rather than the
misleading `future.ErrNoResult`.
`Migrate` also builds the retention indexes for jobs written before v2.5.0.
During a rolling upgrade, older instances keep finalizing jobs without
indexing them, so run `Migrate` once more after every instance is upgraded.
### Cassandra / ScyllaDB
```go
import (
cassandradriver "github.com/kirimatt/goncordia/driver/cassandra/v2"
"github.com/gocql/gocql"
)
cluster := gocql.NewCluster("localhost")
cluster.Keyspace = "myapp" // keyspace must already exist
session, _ := cluster.CreateSession()
defer session.Close()
d := cassandradriver.New(session)
d.Migrate(ctx) // creates tables and runs idempotent lookup backfills
client := cassandradriver.NewClient(d, goncordia.ClientConfig{})
client.Enqueue(ctx, SendEmailArgs{To: "[email protected]", Subject: "Welcome"}, nil)
// EnqueueTx returns an unsupported-operation error on Cassandra.
// Enqueue after the business transaction commits and keep workers idempotent.
```
### ClickHouse
```go
import (
clickhousedriver "github.com/kirimatt/goncordia/driver/clickhouse/v2"
"github.com/ClickHouse/clickhouse-go/v2"
)
conn, _ := clickhouse.Open(&clickhouse.Options{
Addr: []string{"localhost:9000"},
Auth: clickhouse.Auth{Database: "myapp"},
})
defer conn.Close()
d := clickhousedriver.New(conn)
d.Migrate(ctx) // creates ReplacingMergeTree tables (idempotent)
client := clickhousedriver.NewClient(d, goncordia.ClientConfig{})
client.Enqueue(ctx, SendEmailArgs{To: "[email protected]", Subject: "Welcome"}, nil)
// ClickHouse has no transactions. Jobs use at-least-once delivery — workers
// should be idempotent. Best suited for high-throughput analytics pipelines.
```
### Amazon DynamoDB
```go
import (
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
dynamodbdriver "github.com/kirimatt/goncordia/driver/dynamodb/v2"
)
cfg, _ := config.LoadDefaultConfig(ctx)
svc := dynamodb.NewFromConfig(cfg)
d := dynamodbdriver.New(svc)
d.Migrate(ctx) // creates goncordia_jobs, _uniq, _queues, _leaders, _schedule_cursors, _job_results (idempotent)
client := dynamodbdriver.NewClient(d, goncordia.ClientConfig{})
client.Enqueue(ctx, SendEmailArgs{To: "[email protected]", Subject: "Welcome"}, nil)
// DynamoDB has no cross-table transactions. EnqueueTx returns an error.
// Unique-key deduplication uses PutItem with attribute_not_exists condition.
// Jobs are claimed with conditional UpdateItem — safe for concurrent workers.
```
### Cloud Firestore
```go
import (
"cloud.google.com/go/firestore"
firestoredriver "github.com/kirimatt/goncordia/driver/firestore/v2"
)
fsClient, _ := firestore.NewClient(ctx, "my-gcp-project")
defer fsClient.Close()
d := firestoredriver.New(fsClient)
// Migrate is a no-op; create two composite indexes in Firebase console:Frequently Asked Questions
What is goncordia?
goncordia is a Messaging library for the Go programming language. Background job queue on the database you already use (Postgres, MySQL, SQLite, MongoDB, Redis and more), with transactional enqueue and typed futures
How do I install goncordia?
Install goncordia with the Go module system using `go get kirimatt/goncordia`. Check the repository for the current installation instructions.
What category does goncordia belong to?
goncordia is listed under Messaging, specifically Messaging.