2020-01-06 01:06:23 +08:00
# Asynq
2021-01-30 14:59:28 +08:00
![Build Status ](https://github.com/hibiken/asynq/workflows/build/badge.svg )
2020-01-21 07:17:41 +08:00
[![GoDoc ](https://godoc.org/github.com/hibiken/asynq?status.svg )](https://godoc.org/github.com/hibiken/asynq)
2021-01-14 22:26:01 +08:00
[![Go Report Card ](https://goreportcard.com/badge/github.com/hibiken/asynq )](https://goreportcard.com/report/github.com/hibiken/asynq)
[![License: MIT ](https://img.shields.io/badge/license-MIT-green.svg )](https://opensource.org/licenses/MIT)
2020-01-21 07:17:41 +08:00
[![Gitter chat ](https://badges.gitter.im/go-asynq/gitter.svg )](https://gitter.im/go-asynq/community)
2019-12-01 01:38:46 +08:00
2020-04-12 07:33:35 +08:00
## Overview
2020-01-15 13:19:06 +08:00
2020-09-06 23:03:30 +08:00
Asynq is a Go library for queueing tasks and processing them asynchronously with workers. It's backed by Redis and is designed to be scalable yet easy to get started.
2020-04-12 07:33:35 +08:00
Highlevel overview of how Asynq works:
- Client puts task on a queue
- Server pulls task off queues and starts a worker goroutine for each task
2020-04-20 22:39:52 +08:00
- Tasks are processed concurrently by multiple workers
2020-04-12 07:33:35 +08:00
Task queues are used as a mechanism to distribute work across multiple machines.
A system can consist of multiple worker servers and brokers, giving way to high availability and horizontal scaling.
![Task Queue Diagram ](/docs/assets/overview.png )
2019-12-01 01:38:46 +08:00
2020-04-12 00:26:51 +08:00
## Stability and Compatibility
2020-04-20 22:39:52 +08:00
**Important Note**: Current major version is zero (v0.x.x) to accomodate rapid development and fast iteration while getting early feedback from users (Feedback on APIs are appreciated!). The public API could change without a major version update before v1.0.0 release.
2020-04-12 00:26:51 +08:00
**Status**: The library is currently undergoing heavy development with frequent, breaking API changes.
2020-03-28 23:37:50 +08:00
## Features
2020-04-20 22:39:52 +08:00
- Guaranteed [at least one execution ](https://www.cloudcomputingpatterns.org/at_least_once_delivery/ ) of a task
2020-03-28 23:37:50 +08:00
- Scheduling of tasks
- Durability since tasks are written to Redis
2020-04-20 22:39:52 +08:00
- [Retries ](https://github.com/hibiken/asynq/wiki/Task-Retry ) of failed tasks
2020-07-06 07:55:33 +08:00
- Automatic recovery of tasks in the event of a worker crash
2020-04-20 22:39:52 +08:00
- [Weighted priority queues ](https://github.com/hibiken/asynq/wiki/Priority-Queues#weighted-priority-queues )
- [Strict priority queues ](https://github.com/hibiken/asynq/wiki/Priority-Queues#strict-priority-queues )
2020-03-28 23:37:50 +08:00
- Low latency to add a task since writes are fast in Redis
2020-04-20 22:39:52 +08:00
- De-duplication of tasks using [unique option ](https://github.com/hibiken/asynq/wiki/Unique-Tasks )
2020-05-04 07:47:55 +08:00
- Allow [timeout and deadline per task ](https://github.com/hibiken/asynq/wiki/Task-Timeout-and-Cancelation )
- [Flexible handler interface with support for middlewares ](https://github.com/hibiken/asynq/wiki/Handler-Deep-Dive )
2020-06-08 21:15:45 +08:00
- [Ability to pause queue ](/tools/asynq/README.md#pause ) to stop processing tasks from the queue
2020-10-12 21:47:43 +08:00
- [Periodic Tasks ](https://github.com/hibiken/asynq/wiki/Periodic-Tasks )
2020-09-06 23:03:30 +08:00
- [Support Redis Cluster ](https://github.com/hibiken/asynq/wiki/Redis-Cluster ) for automatic sharding and high availability
- [Support Redis Sentinels ](https://github.com/hibiken/asynq/wiki/Automatic-Failover ) for high availability
2021-02-01 14:27:59 +08:00
- [Web UI ](#web-ui ) to inspect and remote-control queues and tasks
2020-04-20 22:39:52 +08:00
- [CLI ](#command-line-tool ) to inspect and remote-control queues and tasks
2020-03-28 23:37:50 +08:00
2020-02-06 13:58:05 +08:00
## Quickstart
2020-01-21 07:17:41 +08:00
2020-01-27 11:58:48 +08:00
First, make sure you are running a Redis server locally.
2020-01-23 22:33:34 +08:00
```sh
2020-02-07 22:45:36 +08:00
$ redis-server
2020-01-23 22:33:34 +08:00
```
2020-03-24 01:35:17 +08:00
Next, write a package that encapsulates task creation and task handling.
2020-01-15 13:19:06 +08:00
```go
2020-03-15 06:51:23 +08:00
package tasks
import (
"fmt"
"github.com/hibiken/asynq"
)
2020-04-20 22:39:52 +08:00
// A list of task types.
2020-03-15 06:51:23 +08:00
const (
2020-09-06 23:03:30 +08:00
TypeEmailDelivery = "email:deliver"
TypeImageResize = "image:resize"
2020-03-15 06:51:23 +08:00
)
2020-05-17 01:44:39 +08:00
//----------------------------------------------
// Write a function NewXXXTask to create a task.
// A task consists of a type and a payload.
//----------------------------------------------
2020-03-15 06:51:23 +08:00
func NewEmailDeliveryTask(userID int, tmplID string) *asynq.Task {
payload := map[string]interface{}{"user_id": userID, "template_id": tmplID}
2020-09-06 23:03:30 +08:00
return asynq.NewTask(TypeEmailDelivery, payload)
2020-03-15 06:51:23 +08:00
}
2020-09-06 23:03:30 +08:00
func NewImageResizeTask(src string) *asynq.Task {
payload := map[string]interface{}{"src": src}
return asynq.NewTask(TypeImageResize, payload)
2020-03-15 06:51:23 +08:00
}
2020-05-17 01:44:39 +08:00
//---------------------------------------------------------------
// Write a function HandleXXXTask to handle the input task.
// Note that it satisfies the asynq.HandlerFunc interface.
2020-09-06 23:03:30 +08:00
//
// Handler doesn't need to be a function. You can define a type
2020-05-17 01:44:39 +08:00
// that satisfies asynq.Handler interface. See examples below.
//---------------------------------------------------------------
2020-03-15 06:51:23 +08:00
func HandleEmailDeliveryTask(ctx context.Context, t *asynq.Task) error {
userID, err := t.Payload.GetInt("user_id")
if err != nil {
return err
}
tmplID, err := t.Payload.GetString("template_id")
if err != nil {
return err
2020-01-27 11:58:48 +08:00
}
2020-03-15 06:51:23 +08:00
fmt.Printf("Send Email to User: user_id = %d, template_id = %s\n", userID, tmplID)
2020-09-06 23:03:30 +08:00
// Email delivery code ...
2020-03-15 06:51:23 +08:00
return nil
}
2020-01-15 13:19:06 +08:00
2020-05-17 01:44:39 +08:00
// ImageProcessor implements asynq.Handler interface.
2020-11-25 22:11:00 +08:00
type ImageProcessor struct {
2020-04-20 22:39:52 +08:00
// ... fields for struct
}
func (p *ImageProcessor) ProcessTask(ctx context.Context, t *asynq.Task) error {
2020-03-15 06:51:23 +08:00
src, err := t.Payload.GetString("src")
if err != nil {
return err
}
2020-09-06 23:03:30 +08:00
fmt.Printf("Resize image: src = %s\n", src)
// Image resizing code ...
2020-03-15 06:51:23 +08:00
return nil
}
2020-04-20 22:39:52 +08:00
func NewImageProcessor() *ImageProcessor {
// ... return an instance
}
2020-03-15 06:51:23 +08:00
```
2020-09-06 23:03:30 +08:00
In your application code, import the above package and use [`Client` ](https://pkg.go.dev/github.com/hibiken/asynq?tab=doc#Client ) to put tasks on the queue.
2020-03-15 06:51:23 +08:00
```go
package main
import (
2020-12-17 22:05:16 +08:00
"fmt"
"log"
2020-03-15 06:51:23 +08:00
"time"
"github.com/hibiken/asynq"
"your/app/package/tasks"
)
const redisAddr = "127.0.0.1:6379"
func main() {
2020-04-18 23:03:58 +08:00
r := asynq.RedisClientOpt{Addr: redisAddr}
2020-03-14 05:50:03 +08:00
c := asynq.NewClient(r)
2020-05-08 21:19:48 +08:00
defer c.Close()
2019-12-01 01:38:46 +08:00
2020-05-17 01:44:39 +08:00
// ------------------------------------------------------
2020-03-14 05:50:03 +08:00
// Example 1: Enqueue task to be processed immediately.
2020-04-20 22:39:52 +08:00
// Use (*Client).Enqueue method.
2020-05-17 01:44:39 +08:00
// ------------------------------------------------------
2020-03-14 05:50:03 +08:00
2020-03-15 06:51:23 +08:00
t := tasks.NewEmailDeliveryTask(42, "some:template:id")
2020-07-03 20:49:52 +08:00
res, err := c.Enqueue(t)
2020-03-14 05:50:03 +08:00
if err != nil {
log.Fatal("could not enqueue task: %v", err)
2020-03-15 06:51:23 +08:00
}
2020-07-03 20:49:52 +08:00
fmt.Printf("Enqueued Result: %+v\n", res)
2019-12-01 01:38:46 +08:00
2020-01-23 22:33:34 +08:00
2020-05-17 01:44:39 +08:00
// ------------------------------------------------------------
2020-03-14 05:50:03 +08:00
// Example 2: Schedule task to be processed in the future.
2020-09-06 23:03:30 +08:00
// Use ProcessIn or ProcessAt option.
2020-05-17 01:44:39 +08:00
// ------------------------------------------------------------
2020-01-23 22:33:34 +08:00
2020-03-15 06:51:23 +08:00
t = tasks.NewEmailDeliveryTask(42, "other:template:id")
2020-09-06 23:03:30 +08:00
res, err = c.Enqueue(t, asynq.ProcessIn(24*time.Hour))
2020-03-14 05:50:03 +08:00
if err != nil {
log.Fatal("could not schedule task: %v", err)
}
2020-07-03 20:49:52 +08:00
fmt.Printf("Enqueued Result: %+v\n", res)
2020-02-24 07:40:04 +08:00
2020-05-17 01:44:39 +08:00
// ----------------------------------------------------------------------------
2020-09-06 23:03:30 +08:00
// Example 3: Set other options to tune task processing behavior.
2020-04-20 22:39:52 +08:00
// Options include MaxRetry, Queue, Timeout, Deadline, Unique etc.
2020-05-17 01:44:39 +08:00
// ----------------------------------------------------------------------------
2020-03-14 05:50:03 +08:00
2020-12-17 22:05:16 +08:00
c.SetDefaultOptions(tasks.TypeImageResize, asynq.MaxRetry(10), asynq.Timeout(3*time.Minute))
2020-04-26 22:48:38 +08:00
2020-09-06 23:03:30 +08:00
t = tasks.NewImageResizeTask("some/blobstore/path")
2020-07-03 20:49:52 +08:00
res, err = c.Enqueue(t)
2020-04-26 22:48:38 +08:00
if err != nil {
log.Fatal("could not enqueue task: %v", err)
}
2020-07-03 20:49:52 +08:00
fmt.Printf("Enqueued Result: %+v\n", res)
2020-04-26 22:48:38 +08:00
2020-05-17 01:44:39 +08:00
// ---------------------------------------------------------------------------
2020-04-26 22:48:38 +08:00
// Example 4: Pass options to tune task processing behavior at enqueue time.
// Options passed at enqueue time override default ones, if any.
2020-05-17 01:44:39 +08:00
// ---------------------------------------------------------------------------
2020-04-26 22:48:38 +08:00
2020-09-06 23:03:30 +08:00
t = tasks.NewImageResizeTask("some/blobstore/path")
2020-07-03 20:49:52 +08:00
res, err = c.Enqueue(t, asynq.Queue("critical"), asynq.Timeout(30*time.Second))
2020-03-14 05:50:03 +08:00
if err != nil {
log.Fatal("could not enqueue task: %v", err)
}
2020-07-03 20:49:52 +08:00
fmt.Printf("Enqueued Result: %+v\n", res)
2020-01-23 22:33:34 +08:00
}
```
2020-09-06 23:03:30 +08:00
Next, start a worker server to process these tasks in the background.
2020-04-13 08:16:44 +08:00
To start the background workers, use [`Server` ](https://pkg.go.dev/github.com/hibiken/asynq?tab=doc#Server ) and provide your [`Handler` ](https://pkg.go.dev/github.com/hibiken/asynq?tab=doc#Handler ) to process the tasks.
2019-12-01 01:38:46 +08:00
2020-03-15 06:51:23 +08:00
You can optionally use [`ServeMux` ](https://pkg.go.dev/github.com/hibiken/asynq?tab=doc#ServeMux ) to create a handler, just as you would with [`"net/http"` ](https://golang.org/pkg/net/http/ ) Handler.
2020-03-02 03:08:00 +08:00
```go
2020-03-15 06:51:23 +08:00
package main
2020-03-02 03:08:00 +08:00
2020-03-15 06:51:23 +08:00
import (
2020-04-26 22:48:38 +08:00
"log"
2020-03-15 06:51:23 +08:00
"github.com/hibiken/asynq"
"your/app/package/tasks"
)
const redisAddr = "127.0.0.1:6379"
2020-03-02 03:08:00 +08:00
2019-12-01 01:38:46 +08:00
func main() {
2020-04-18 23:03:58 +08:00
r := asynq.RedisClientOpt{Addr: redisAddr}
2019-12-01 01:38:46 +08:00
2020-04-13 08:16:44 +08:00
srv := asynq.NewServer(r, asynq.Config{
2020-01-27 11:58:48 +08:00
// Specify how many concurrent workers to use
2020-01-15 13:19:06 +08:00
Concurrency: 10,
2020-02-24 07:40:04 +08:00
// Optionally specify multiple queues with different priority.
2020-02-13 14:23:25 +08:00
Queues: map[string]int{
2020-01-27 11:58:48 +08:00
"critical": 6,
"default": 3,
"low": 1,
},
// See the godoc for other configuration options
2019-12-30 08:55:51 +08:00
})
2019-12-01 01:38:46 +08:00
2020-03-02 22:40:53 +08:00
// mux maps a type to a handler
2020-03-02 03:08:00 +08:00
mux := asynq.NewServeMux()
2020-09-06 23:03:30 +08:00
mux.HandleFunc(tasks.TypeEmailDelivery, tasks.HandleEmailDeliveryTask)
mux.Handle(tasks.TypeImageResize, tasks.NewImageProcessor())
2020-03-02 03:08:00 +08:00
// ...register other handlers...
2019-12-28 08:26:11 +08:00
2020-04-13 23:14:55 +08:00
if err := srv.Run(mux); err != nil {
log.Fatalf("could not run server: %v", err)
}
2020-03-02 03:08:00 +08:00
}
2019-12-28 08:26:11 +08:00
```
2020-01-27 11:58:48 +08:00
For a more detailed walk-through of the library, see our [Getting Started Guide ](https://github.com/hibiken/asynq/wiki/Getting-Started ).
2020-01-23 22:33:34 +08:00
2020-03-02 22:40:53 +08:00
To Learn more about `asynq` features and APIs, see our [Wiki ](https://github.com/hibiken/asynq/wiki ) and [godoc ](https://godoc.org/github.com/hibiken/asynq ).
2020-01-21 07:17:41 +08:00
2021-02-01 14:27:59 +08:00
## Web UI
[Asynqmon ](https://github.com/hibiken/asynqmon ) is a web based tool for monitoring and administrating Asynq queues and tasks.
Please see the tool's [README ](https://github.com/hibiken/asynqmon ) for details.
Here's a few screenshots of the web UI.
**Queues view**
![Web UI QueuesView ](/docs/assets/asynqmon-queues-view.png )
**Tasks view**
![Web UI TasksView ](/docs/assets/asynqmon-task-view.png )
2020-01-23 22:33:34 +08:00
## Command Line Tool
2020-01-15 13:19:06 +08:00
2020-01-23 22:33:34 +08:00
Asynq ships with a command line tool to inspect the state of queues and tasks.
2020-01-19 12:31:22 +08:00
2020-03-02 22:40:53 +08:00
Here's an example of running the `stats` command.
![Gif ](/docs/assets/demo.gif )
2020-04-13 07:49:49 +08:00
For details on how to use the tool, refer to the tool's [README ](/tools/asynq/README.md ).
2020-03-02 22:40:53 +08:00
## Installation
To install `asynq` library, run the following command:
```sh
go get -u github.com/hibiken/asynq
```
To install the CLI tool, run the following command:
2020-01-19 12:31:22 +08:00
2020-02-07 22:45:36 +08:00
```sh
2020-04-13 07:49:49 +08:00
go get -u github.com/hibiken/asynq/tools/asynq
2020-02-07 22:45:36 +08:00
```
2020-01-19 12:31:22 +08:00
2020-03-02 22:40:53 +08:00
## Requirements
| Dependency | Version |
| -------------------------- | ------- |
2020-09-06 23:03:30 +08:00
| [Redis ](https://redis.io/ ) | v3.0+ |
2020-03-18 21:49:39 +08:00
| [Go ](https://golang.org/ ) | v1.13+ |
2020-01-15 13:19:06 +08:00
2020-02-09 01:34:14 +08:00
## Contributing
We are open to, and grateful for, any contributions (Github issues/pull-requests, feedback on Gitter channel, etc) made by the community.
Please see the [Contribution Guide ](/CONTRIBUTING.md ) before contributing.
2020-01-06 01:06:23 +08:00
## Acknowledgements
- [Sidekiq ](https://github.com/mperham/sidekiq ) : Many of the design ideas are taken from sidekiq and its Web UI
2020-02-24 12:43:24 +08:00
- [RQ ](https://github.com/rq/rq ) : Client APIs are inspired by rq library.
2020-04-13 07:49:49 +08:00
- [Cobra ](https://github.com/spf13/cobra ) : Asynq CLI is built with cobra
2020-01-06 01:06:23 +08:00
2019-12-28 08:26:11 +08:00
## License
Asynq is released under the MIT license. See [LICENSE ](https://github.com/hibiken/asynq/blob/master/LICENSE ).