A Simplest Storage-Agnostic and Zero-dep Message Queue for Your Concurrent Go Program
A Simplest Storage-Agnostic and Zero-dep Message Queue for Your Concurrent Go Program
NewWorker - Fire-and-forget operations (most performant)NewErrWorker - Returns only error (when result isn't needed)NewResultWorker - Returns result and errorgo get github.com/goptics/varmqpackage main
import (
"fmt"
"time"
"github.com/goptics/varmq"
)
func main() {
worker := varmq.NewWorker(func(j varmq.Job[int]) {
fmt.Printf("Processing %d\n", j.Data())
time.Sleep(500 * time.Millisecond)
}, 10) // with concurrency 10 or set 0 for parallelism
defer worker.WaitUntilIdle()
queue := worker.BindQueue()
for i := range 100 {
queue.Add(i)
}
}You can use priority queue to prioritize jobs based on their priority. Lower number = higher priority
// just bind priority queue
queue := worker.BindPriorityQueue()
// add jobs to priority queue
for i := range 10 {
queue.Add(i, i%2) // prioritize even tasks
}VarMQ supports both persistent and distributed queue processing through adapter interfaces:
Usage is simple:
// For persistent queues (with any IPersistentQueue adapter)
queue := worker.WithPersistentQueue(persistentQueueAdapter)
// For distributed queues (with any IDistributedQueue adapter)
queue := worker.WithDistributedQueue(distributedQueueAdapter)See complete working examples in the examples directory:
Create your own adapters by implementing the IPersistentQueue or IDistributedQueue interfaces.
[!Note] Before testing examples, make sure to start the Redis server using
docker compose up -d.
Bind multiple queues to a single worker, enabling efficient processing of jobs from different sources with configurable strategies. The worker supports four strategies:
…VarMQ provides a NewResultWorker that returns both the result and error for each job processed. This is useful when you need to handle both success and failure cases.
…NewErrWorker is similar to NewResultWorker but it returns only error.
VarMQ provides helper functions that enable direct function submission similar to the Submit() pattern in other pool packages like Pond or Ants
Func(): For basic functions with no return values - use with NewWorkerErrFunc(): For functions that return errors - use with NewErrWorkerResultFunc[R](): For functions that return a result and error - use with NewResultWorkerworker := varmq.NewWorker(varmq.Func(), 10)
defer worker.WaitUntilIdle()
queue := worker.BindQueue()
for i := range 100 {
queue.Add(func() {
time.Sleep(500 * time.Millisecond)
fmt.Println("Processing", i)
})
}[!Important] Function helpers don't support persistence or distribution since functions cannot be serialized.
VarMQ provides a built-in HTTP REST API for inspecting worker status and managing worker state remotely. Register the handler on any http.Server to expose endpoints:
mux := http.NewServeMux()
mux.Handle("/varmq/", varmq.Handler("/varmq"))
http.ListenAndServe(":8080", mux)Available endpoints:
| Method | Path | Description |
|---|---|---|
GET |
/health |
Health check |
GET |
/workers |
List all workers (summary) |
GET |
/workers/{name} |
Get worker details + metrics |
PATCH |
/workers/{name}/actions/{action} |
Pause, resume, stop, restart |
PATCH |
/workers/{name}/config/concurrency/{n} |
Adjust concurrency |
[!Warning] The REST API is unauthenticated by design. Protect it with middleware, network isolation, or a reverse proxy before exposing to untrusted networks.
goos: linux
goarch: amd64
pkg: github.com/goptics/varmq
cpu: 13th Gen Intel(R) Core(TM) i7-13700Add OperationCommand: go test -run=^$ -benchmem -bench '^(BenchmarkAdd)$' -cpu=1
Why use
-cpu=1? Since the benchmark doesn’t test with more than 1 concurrent worker, a single CPU is ideal to accurately measure performance.
| Worker Type | Queue Type | Time (ns/op) | Memory (B/op) | Allocations (allocs/op) |
|---|---|---|---|---|
| Worker | Queue | 1,045 | 113 | 2 |
| Priority | 1,072 | 128 | 3 | |
| ErrWorker | ErrQueue | 1,153 | 289 | 5 |
| ErrPriority | 1,145 | 304 | 6 | |
| ResultWorker | ResultQueue | 1,167 | 337 | 5 |
| ResultPriority | 1,155 | 352 | 6 |
AddAll OperationCommand: go test -run=^$ -benchmem -bench '^(BenchmarkAddAll)$' -cpu=1
| Worker Type | Queue Type | Time (ns/op) | Memory (B/op) | Allocations (allocs/op) |
|---|---|---|---|---|
| Worker | Queue | 649,822 | 130,601 | 3,002 |
| Priority | 776,409 | 146,139 | 4,002 | |
| ErrWorker | ErrQueue | 684,882 | 154,895 | 3,505 |
| ErrPriority | 808,360 | 170,661 | 4,505 | |
| ResultWorker | ResultQueue | 690,249 | 171,540 | 3,005 |
| ResultPriority | 803,115 | 187,262 | 4,005 |
[!Note]
AddAllbenchmarks use a batch of 1000 items per call. The reported numbers (ns/op,B/op,allocs/op) are totals for the whole batch. For per-item values, divide each by 1000. e.g. for defaultQueue, the average time per item is approximately 650ns.
Why is AddAll faster than individual Add calls? Here's what makes the difference:
We conducted comprehensive benchmarking between VarMQ and Pond v2, as both packages provide similar worker pool functionalities. While VarMQ draws inspiration from some of Pond's design patterns, VarMQ offers unique advantages in queue management and persistence capabilities.
Key Differences:
VarMQ provides multiple queue variants (standard, priority, persistent, distributed) vs Pond's single pool typeVarMQ supports binding multiple queues to a single worker with configurable strategies (Priority, RoundRobin, MaxLen, MinLen)For detailed performance comparisons and benchmarking results, visit:
For the complete package documentation, types, and method signatures, browse the GoDoc.
VarMQ's concurrency model is built around a smart event loop that keeps everything running smoothly.
The event loop continuously monitors for pending jobs in queues and available workers in the pool. When both conditions are met, jobs get distributed to workers instantly. When there's no work to distribute, the system enters a low-power wait state.
Workers operate independently - they process jobs and immediately signal back when they're ready for more work. This triggers the event loop to check for new jobs and distribute them right away.
The system handles worker lifecycle automatically. Idle workers either stay in the pool or get cleaned up based on your configuration, so you never waste resources or run short on capacity.
Contributions are welcome! Please feel free to submit a Pull Request or open an issue.
Please note that this project has a Code of Conduct. By participating in this project, you agree to abide by its terms.
No open issues yet, or sync has not completed.