Skip to content

Commit 58f52df

Browse files
authored
Merge pull request #28 from GRACENOBLE/feat/18-asynq-redis-streams
feat(queue): integrate Asynq + Redis Streams for background jobs and event-driven messaging
2 parents 99c064f + 94c8d6b commit 58f52df

28 files changed

Lines changed: 1249 additions & 17 deletions

‎backend/cmd/api/main.go‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,10 @@ import (
1010
"syscall"
1111
"time"
1212

13+
"github.com/hibiken/asynq"
14+
1315
"backend/internal/bootstrap"
16+
"backend/internal/infrastructure/queue"
1417
"backend/internal/infrastructure/ws"
1518
"backend/internal/server"
1619
)
@@ -60,6 +63,23 @@ func main() {
6063
hub := ws.NewHub()
6164
go hub.Run(hubCtx)
6265

66+
var workerCancel context.CancelFunc
67+
if app.Config.RedisURL != "" {
68+
workerCtx, wCancel := context.WithCancel(context.Background())
69+
workerCancel = wCancel
70+
worker, err := queue.NewWorker(app.Config.RedisURL)
71+
if err != nil {
72+
fmt.Fprintf(os.Stderr, "startup failed: %v\n", err)
73+
os.Exit(1)
74+
}
75+
worker.Register(queue.TypeWelcomeEmail, asynq.HandlerFunc(queue.HandleWelcomeEmail))
76+
go func() {
77+
if err := worker.Run(workerCtx); err != nil {
78+
slog.Error("queue: worker error", "err", err)
79+
}
80+
}()
81+
}
82+
6383
srv, err := server.NewServer(app, hub)
6484
if err != nil {
6585
fmt.Fprintf(os.Stderr, "startup failed: %v\n", err)
@@ -75,12 +95,21 @@ func main() {
7595
}
7696

7797
<-done
98+
99+
if workerCancel != nil {
100+
workerCancel() // stop worker before hub (in-flight jobs drain first)
101+
}
78102
hubCancel() // stop hub after all WS connections have been closed by server shutdown
79103

80104
if app.Cache != nil {
81105
if err := app.Cache.Close(); err != nil {
82106
slog.Error("cache close error", "error", err)
83107
}
84108
}
109+
if app.Enqueuer != nil {
110+
if err := app.Enqueuer.Close(); err != nil {
111+
slog.Error("enqueuer close error", "error", err)
112+
}
113+
}
85114
slog.Info("graceful shutdown complete")
86115
}

‎backend/docs/_index.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,5 @@ The `docs` agent reads this index first to locate the right file before diving i
1616
| Firebase Auth (token verification, middleware, MeHandler) | [auth.md](auth.md) | `internal/usecase/auth_usecase.go`, `internal/transport/middleware/auth.go`, `internal/transport/handlers/auth_handler.go`, `pkg/firebase/admin.go`, `internal/bootstrap/bootstrap.go` |
1717
| Observability (Sentry error tracking) | [observability.md](observability.md) | `internal/transport/middleware/sentry.go`, `internal/bootstrap/bootstrap.go`, `internal/transport/handlers/routes.go` |
1818
| WebSocket (Hub, client, GET /ws, auth, wiring) | [websocket.md](websocket.md) | `internal/infrastructure/ws/`, `internal/transport/handlers/ws_handler.go`, `internal/transport/handlers/routes.go`, `internal/server/server.go`, `cmd/api/main.go` |
19+
| Background job queue (Asynq, task definitions, worker, Asynqmon UI) | [queue.md](queue.md) | `internal/usecase/enqueuer.go`, `internal/infrastructure/queue/tasks.go`, `internal/infrastructure/queue/client.go`, `internal/infrastructure/queue/worker.go`, `internal/infrastructure/queue/handlers.go`, `internal/transport/handlers/routes.go`, `cmd/api/main.go` |
20+
| Redis Streams event fan-out (producer, consumer, consumer groups) | [streams.md](streams.md) | `internal/infrastructure/streams/events.go`, `internal/infrastructure/streams/producer.go`, `internal/infrastructure/streams/consumer.go` |

‎backend/docs/middleware.md‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,22 +15,26 @@ All middleware lives in `internal/transport/middleware/` and follows the Gin `Ha
1515
## Registration order
1616

1717
```go
18-
// 1. Recovery + logger (debug: gin.Logger, release: middleware.Logger)
18+
// 1. Sentry error reporting
19+
r.Use(middleware.SentryMiddleware(sentryDSN))
20+
// 2. Recovery + logger (debug: gin.Logger, release: middleware.Logger)
1921
r.Use(gin.Recovery(), middleware.Logger())
20-
// 2. Rate limiter (no-op when RPS <= 0)
22+
// 3. Prometheus metrics collection
23+
r.Use(middleware.PrometheusMiddleware())
24+
// 4. Rate limiter (no-op when RPS <= 0)
2125
r.Use(middleware.RateLimit(rps, burst))
22-
// 3. CORS
26+
// 5. CORS
2327
r.Use(cors.New(...))
2428

2529
// Global routes (no auth):
2630
r.GET("/", h.HelloWorldHandler)
2731
r.GET("/health", h.HealthHandler)
2832
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
2933

30-
// Protected group — FirebaseAuth applied when verifier != nil:
34+
// Protected group — FirebaseAuth applied when h.verifier != nil:
3135
api := r.Group("/api/v1")
32-
if verifier != nil {
33-
api.Use(middleware.FirebaseAuth(verifier))
36+
if h.verifier != nil {
37+
api.Use(middleware.FirebaseAuth(h.verifier))
3438
}
3539
api.GET("/me", h.MeHandler)
3640
```
@@ -71,7 +75,7 @@ val, _ := c.Get(middleware.FirebaseClaimsKey)
7175
token, ok := val.(*usecase.FirebaseToken)
7276
```
7377

74-
Pass `nil` as the `verifier` to `RegisterRoutes` to skip Firebase auth entirely (development without credentials).
78+
Pass `nil` as the `verifier` to `NewHandler` to skip Firebase auth entirely (development without credentials). `RegisterRoutes` reads `h.verifier` from the struct — it is not a parameter of `RegisterRoutes`.
7579

7680
## Adding new middleware
7781

‎backend/docs/queue.md‎

Lines changed: 206 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,206 @@
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.

‎backend/docs/routing.md‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@ func NewHandler(healthUC usecase.HealthUseCase, verifier usecase.FirebaseTokenVe
3030
The `Handler` struct holds use case interfaces and infrastructure dependencies — not `*sql.DB` directly. `verifier` is stored on the struct (not passed to `RegisterRoutes`) so the WebSocket handler can read it inline for query-param auth.
3131

3232
## Wiring (server.go)
33-
`internal/server/server.go` contains `NewServer(app *bootstrap.App) *http.Server` — wiring only, no logic.
34-
It receives the already-validated `*bootstrap.App` (which holds `*sql.DB`, `Cache`, `Firebase`, and `Config`), constructs the repository, use case, and handler in order, then returns a configured `*http.Server`. It does not read env vars or return an error.
33+
`internal/server/server.go` contains `NewServer(app *bootstrap.App, hub *ws.Hub) (*http.Server, error)` — wiring only, no logic.
34+
It receives the already-validated `*bootstrap.App` (which holds `*sql.DB`, `Cache`, `Firebase`, and `Config`) and a `*ws.Hub`, constructs the repository, use case, and handler in order, then returns a configured `*http.Server`. Errors from initialisation steps are returned to the caller.
3535

3636
```go
3737
healthRepo := postgres.NewHealthRepository(app.DB)
@@ -44,13 +44,13 @@ return &http.Server{
4444
IdleTimeout: time.Minute,
4545
ReadTimeout: 10 * time.Second,
4646
WriteTimeout: 30 * time.Second,
47-
}
47+
}, nil
4848
```
4949

5050
## Route registration
5151
All routes registered in `RegisterRoutes()` on `*Handler`, which returns `http.Handler`.
5252
`rps` and `burst` come from `bootstrap.Config` (env vars `RATE_LIMIT_RPS` / `RATE_LIMIT_BURST`); pass `rps=0` to disable.
53-
`verifier` is a `usecase.FirebaseTokenVerifier`; pass `nil` to skip Firebase auth (development only — see [auth](auth.md)).
53+
`h.verifier` (set via `NewHandler`) controls Firebase auth — the verifier is read from the struct, not passed to `RegisterRoutes`; a `nil` verifier skips Firebase auth (development only — see [auth](auth.md)).
5454

5555
```go
5656
func (h *Handler) RegisterRoutes(rps float64, burst int, sentryDSN string) http.Handler {
@@ -109,13 +109,14 @@ Allowed methods: GET, POST, PUT, DELETE, OPTIONS, PATCH.
109109
| GET | `/` | none | `HelloWorldHandler` — returns `{"message": "Hello World"}` | `hello_handler.go` |
110110
| GET | `/health` | none | `HealthHandler` — returns `HealthStats`; 503 when DB is down | `health_handler.go` |
111111
| GET | `/ws` | `?token=` query param | `WsHandler` — upgrades to WebSocket; 401 when token missing/invalid | `ws_handler.go` |
112+
| GET | `/metrics` | `LocalNetworkOnly()` | Prometheus scrape endpoint; restricted to loopback/RFC 1918 in staging/production | `metrics_handler.go` |
112113
| GET | `/api/v1/me` | FirebaseAuth header | `MeHandler` — returns verified `FirebaseToken` claims | `auth_handler.go` |
113114

114115
## Graceful shutdown
115116
Wired in `cmd/api/main.go` via `signal.NotifyContext` for SIGINT/SIGTERM.
116117
5-second shutdown timeout. Server notifies `done chan bool` when complete.
117118
`main()` calls `bootstrap.Run(ctx)` first; on failure it writes to stderr and calls `os.Exit(1)`.
118-
`server.NewServer` does not return an error — all fallible startup work is in bootstrap.
119+
`server.NewServer` returns `(*http.Server, error)` — the caller in `cmd/api/main.go` checks the error and exits on failure.
119120
Do not add shutdown logic to `internal/` — it belongs in `cmd/`.
120121

121122
## Adding a new route — checklist

0 commit comments

Comments
 (0)