|
| 1 | +--- |
| 2 | +topic: queue |
| 3 | +last_verified: 2026-06-15 |
| 4 | +sources: |
| 5 | + - internal/usecase/enqueuer.go |
| 6 | + - internal/infrastructure/queue/tasks.go |
| 7 | + - internal/infrastructure/queue/client.go |
| 8 | + - internal/infrastructure/queue/worker.go |
| 9 | + - internal/infrastructure/queue/handlers.go |
| 10 | + - internal/transport/handlers/routes.go |
| 11 | + - cmd/api/main.go |
| 12 | +--- |
| 13 | + |
| 14 | +# Queue (Asynq) |
| 15 | + |
| 16 | +## Overview |
| 17 | + |
| 18 | +Background jobs are processed by [Asynq](https://github.com/hibiken/asynq), which uses |
| 19 | +Redis as its broker. The same `REDIS_URL` env var used by the cache layer is reused — no |
| 20 | +additional env vars are required. When `REDIS_URL` is not set, `app.Enqueuer` is `nil` |
| 21 | +and no worker is started; the rest of the application continues normally. |
| 22 | + |
| 23 | +Asynq handles discrete, retriable background jobs (welcome emails, notifications, |
| 24 | +webhooks). For ordered event fan-out between services see `backend/docs/streams.md`. |
| 25 | + |
| 26 | +## Task definitions |
| 27 | + |
| 28 | +Task type constants and payload structs are co-located in |
| 29 | +`internal/infrastructure/queue/tasks.go`: |
| 30 | + |
| 31 | +```go |
| 32 | +const ( |
| 33 | + TypeWelcomeEmail = "email:welcome" |
| 34 | +) |
| 35 | + |
| 36 | +type WelcomeEmailPayload struct { |
| 37 | + UserID string `json:"user_id"` |
| 38 | + Email string `json:"email"` |
| 39 | +} |
| 40 | +``` |
| 41 | + |
| 42 | +Both the enqueuer (caller side) and the handler (worker side) import these constants so |
| 43 | +the string is never duplicated. |
| 44 | + |
| 45 | +## Enqueuer interface |
| 46 | + |
| 47 | +`internal/usecase/enqueuer.go` defines the port that use cases and handlers depend on: |
| 48 | + |
| 49 | +```go |
| 50 | +type Enqueuer interface { |
| 51 | + Enqueue(ctx context.Context, taskType string, payload []byte) error |
| 52 | + Close() error |
| 53 | +} |
| 54 | +``` |
| 55 | + |
| 56 | +The concrete implementation is created with `queue.NewClient`: |
| 57 | + |
| 58 | +```go |
| 59 | +// internal/infrastructure/queue/client.go |
| 60 | +func NewClient(redisURL string) (usecase.Enqueuer, error) |
| 61 | +``` |
| 62 | + |
| 63 | +`NewClient` parses `redisURL` using `go-redis/v9`'s `ParseURL`, constructs an |
| 64 | +`asynq.Client`, and returns it wrapped as a `usecase.Enqueuer`. |
| 65 | + |
| 66 | +### Enqueueing from a use case or handler |
| 67 | + |
| 68 | +```go |
| 69 | +payload, err := json.Marshal(queue.WelcomeEmailPayload{ |
| 70 | + UserID: userID, |
| 71 | + Email: email, |
| 72 | +}) |
| 73 | +if err != nil { |
| 74 | + return err |
| 75 | +} |
| 76 | +if app.Enqueuer != nil { |
| 77 | + if err := app.Enqueuer.Enqueue(ctx, queue.TypeWelcomeEmail, payload); err != nil { |
| 78 | + return err |
| 79 | + } |
| 80 | +} |
| 81 | +``` |
| 82 | + |
| 83 | +Guard with `!= nil` because `app.Enqueuer` is nil when `REDIS_URL` is unset. |
| 84 | + |
| 85 | +### Bootstrap wiring |
| 86 | + |
| 87 | +`app.Enqueuer` is populated by `bootstrap.Run` when `REDIS_URL` is set (see |
| 88 | +`internal/bootstrap/bootstrap.go`). After the HTTP server shuts down, `main.go` calls |
| 89 | +`app.Enqueuer.Close()` to release the connection. |
| 90 | + |
| 91 | +## Worker setup |
| 92 | + |
| 93 | +`internal/infrastructure/queue/worker.go` |
| 94 | + |
| 95 | +```go |
| 96 | +func NewWorker(redisURL string) (*Worker, error) |
| 97 | +func (w *Worker) Register(taskType string, h asynq.Handler) |
| 98 | +func (w *Worker) Run(ctx context.Context) error // blocking; cancel ctx to stop |
| 99 | +``` |
| 100 | + |
| 101 | +`NewWorker` creates an `asynq.Server` with `Concurrency: 10`. Failed tasks are logged via |
| 102 | +`slog.Error` through the server's `ErrorHandler`. |
| 103 | + |
| 104 | +`Run` starts the server in an inner goroutine and blocks until either `ctx` is cancelled |
| 105 | +(clean shutdown via `w.server.Shutdown()`) or the server returns an error. |
| 106 | + |
| 107 | +### Goroutine wiring in cmd/api/main.go |
| 108 | + |
| 109 | +The worker is started only when `REDIS_URL` is set, using a child context so it can be |
| 110 | +cancelled independently of the hub: |
| 111 | + |
| 112 | +```go |
| 113 | +var workerCancel context.CancelFunc |
| 114 | +if app.Config.RedisURL != "" { |
| 115 | + workerCtx, wCancel := context.WithCancel(context.Background()) |
| 116 | + workerCancel = wCancel |
| 117 | + worker, err := queue.NewWorker(app.Config.RedisURL) |
| 118 | + // ... |
| 119 | + worker.Register(queue.TypeWelcomeEmail, asynq.HandlerFunc(queue.HandleWelcomeEmail)) |
| 120 | + go func() { |
| 121 | + if err := worker.Run(workerCtx); err != nil { |
| 122 | + slog.Error("queue: worker error", "err", err) |
| 123 | + } |
| 124 | + }() |
| 125 | +} |
| 126 | +``` |
| 127 | + |
| 128 | +Shutdown order after `<-done`: |
| 129 | + |
| 130 | +```go |
| 131 | +if workerCancel != nil { |
| 132 | + workerCancel() // stop worker before hub (in-flight jobs drain first) |
| 133 | +} |
| 134 | +hubCancel() |
| 135 | +``` |
| 136 | + |
| 137 | +The worker is cancelled before the hub so that any task handler that calls `hub.Publish` |
| 138 | +can still reach the hub during drain. |
| 139 | + |
| 140 | +## Task handlers |
| 141 | + |
| 142 | +Handler functions have the signature `func(context.Context, *asynq.Task) error` and live |
| 143 | +in `internal/infrastructure/queue/handlers.go`: |
| 144 | + |
| 145 | +```go |
| 146 | +func HandleWelcomeEmail(_ context.Context, t *asynq.Task) error { |
| 147 | + var p WelcomeEmailPayload |
| 148 | + if err := json.Unmarshal(t.Payload(), &p); err != nil { |
| 149 | + return fmt.Errorf("welcome email: unmarshal payload: %w", err) |
| 150 | + } |
| 151 | + slog.Info("queue: welcome email task received", "user_id", p.UserID, "email", p.Email) |
| 152 | + return nil |
| 153 | +} |
| 154 | +``` |
| 155 | + |
| 156 | +Returning a non-nil error causes Asynq to retry the task (up to its configured retry limit). |
| 157 | + |
| 158 | +## Adding a new task |
| 159 | + |
| 160 | +1. Add a `Type<Name> = "<category>:<action>"` constant and `<Name>Payload` struct to |
| 161 | + `internal/infrastructure/queue/tasks.go`. |
| 162 | +2. Write a `Handle<Name>(ctx context.Context, t *asynq.Task) error` function in |
| 163 | + `internal/infrastructure/queue/handlers.go`. |
| 164 | +3. Register the handler in `cmd/api/main.go`: |
| 165 | + ```go |
| 166 | + worker.Register(queue.Type<Name>, asynq.HandlerFunc(queue.Handle<Name>)) |
| 167 | + ``` |
| 168 | +4. Enqueue from the relevant use case or handler using `app.Enqueuer.Enqueue(ctx, queue.Type<Name>, payload)`. |
| 169 | + |
| 170 | +## Asynqmon UI |
| 171 | + |
| 172 | +When running in `gin.DebugMode` and `REDIS_URL` is set, the Asynqmon job-monitoring UI is |
| 173 | +available at: |
| 174 | + |
| 175 | +``` |
| 176 | +http://localhost:8080/admin/queues |
| 177 | +``` |
| 178 | + |
| 179 | +Routes are registered in `RegisterRoutes` only under these conditions: |
| 180 | + |
| 181 | +```go |
| 182 | +if gin.Mode() == gin.DebugMode && h.queueUI != nil { |
| 183 | + r.GET("/admin/queues", gin.WrapH(h.queueUI)) |
| 184 | + r.Any("/admin/queues/*path", gin.WrapH(h.queueUI)) |
| 185 | +} |
| 186 | +``` |
| 187 | + |
| 188 | +The UI is not mounted in staging or production (`gin.ReleaseMode`). |
| 189 | + |
| 190 | +## Testing |
| 191 | + |
| 192 | +**Unit tests** call handler functions directly with `asynq.NewTask` — no Redis required: |
| 193 | + |
| 194 | +```go |
| 195 | +payload, _ := json.Marshal(queue.WelcomeEmailPayload{UserID: "u1", Email: "a@b.com"}) |
| 196 | +task := asynq.NewTask(queue.TypeWelcomeEmail, payload) |
| 197 | +err := queue.HandleWelcomeEmail(context.Background(), task) |
| 198 | +// assert err == nil |
| 199 | +``` |
| 200 | + |
| 201 | +**Integration tests** use Testcontainers Redis (same `TestMain` pattern as |
| 202 | +`internal/infrastructure/cache/redis/cache_test.go`). The `TestMain` function skips |
| 203 | +integration tests gracefully when Docker is unavailable so that unit tests still run. |
| 204 | + |
| 205 | +Enqueuer integration tests construct a real `queue.NewClient`, enqueue a task, and use |
| 206 | +`asynq.NewInspector` (via `queue.NewInspector`) to verify the task appears in the queue. |
0 commit comments