Skip to content

Commit 4034ed4

Browse files
committed
fix(streams): unwire consumer goroutine; leave infrastructure ready to use
The blocking XReadGroup poll holds a persistent Redis connection even when there is no business logic consuming events, wasting a connection slot on managed Redis plans. The consumer is not wired at startup until a concrete use case exists. All infrastructure remains in place (Producer, Consumer, events, types) and the producer still publishes UserCreatedEvent on FCM registration. A fully worked example of how to wire the consumer back in is left as a comment in cmd/api/main.go. Also adds MaxIdleConns=1 and ConnMaxIdleTime=8s to the consumer client so idle connections are recycled before managed Redis providers kill them, preventing i/o timeout noise if the consumer is re-enabled.
1 parent a0e3627 commit 4034ed4

2 files changed

Lines changed: 34 additions & 34 deletions

File tree

‎backend/cmd/api/main.go‎

Lines changed: 20 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package main
22

33
import (
44
"context"
5-
"encoding/json"
65
"fmt"
76
"log/slog"
87
"net/http"
@@ -13,7 +12,6 @@ import (
1312

1413
"backend/internal/bootstrap"
1514
"backend/internal/infrastructure/queue"
16-
"backend/internal/infrastructure/streams"
1715
"backend/internal/infrastructure/ws"
1816
"backend/internal/server"
1917
)
@@ -80,31 +78,26 @@ func main() {
8078
}()
8179
}
8280

83-
// Start Redis Streams consumer: fan-out UserCreated events → welcome email queue.
84-
var streamCancel context.CancelFunc
85-
if app.StreamProducer != nil && app.Enqueuer != nil {
86-
streamCtx, sCancel := context.WithCancel(context.Background())
87-
streamCancel = sCancel
88-
consumer, err := streams.NewConsumer(app.Config.RedisURL, streams.StreamUserCreated, "api", "api-1")
89-
if err != nil {
90-
slog.Error("streams: failed to create consumer", "err", err)
91-
} else {
92-
go func() {
93-
_ = consumer.Run(streamCtx, func(ctx context.Context, data []byte) error {
94-
var evt streams.UserCreatedEvent
95-
if err := json.Unmarshal(data, &evt); err != nil {
96-
return err
97-
}
98-
payload, err := json.Marshal(queue.WelcomeEmailPayload{UserID: evt.UserID, Email: evt.Email, Name: evt.Name})
99-
if err != nil {
100-
return err
101-
}
102-
return app.Enqueuer.Enqueue(ctx, queue.TypeWelcomeEmail, payload)
103-
})
104-
_ = consumer.Close()
105-
}()
106-
}
107-
}
81+
// --- Redis Streams consumer (unwired — add when you have a concrete use case) ---
82+
// The streams infrastructure (Producer, Consumer, events) is fully implemented.
83+
// Wire a consumer here following this pattern when you need it:
84+
//
85+
// streamCtx, streamCancel := context.WithCancel(context.Background())
86+
// consumer, err := streams.NewConsumer(app.Config.RedisURL, streams.StreamUserCreated, "api", "api-1")
87+
// if err != nil {
88+
// slog.Error("streams: failed to create consumer", "err", err)
89+
// } else {
90+
// go func() {
91+
// _ = consumer.Run(streamCtx, func(ctx context.Context, data []byte) error {
92+
// var evt streams.UserCreatedEvent
93+
// if err := json.Unmarshal(data, &evt); err != nil { return err }
94+
// payload, _ := json.Marshal(queue.WelcomeEmailPayload{UserID: evt.UserID, Email: evt.Email, Name: evt.Name})
95+
// return app.Enqueuer.Enqueue(ctx, queue.TypeWelcomeEmail, payload)
96+
// })
97+
// _ = consumer.Close()
98+
// }()
99+
// }
100+
// // In the shutdown sequence below, call: streamCancel()
108101

109102
srv, err := server.NewServer(app, hub)
110103
if err != nil {
@@ -122,9 +115,6 @@ func main() {
122115

123116
<-done
124117

125-
if streamCancel != nil {
126-
streamCancel() // stop streams consumer
127-
}
128118
if workerCancel != nil {
129119
workerCancel() // stop worker before hub (in-flight jobs drain first)
130120
}

‎backend/internal/infrastructure/streams/consumer.go‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,12 @@ func NewConsumer(redisURL, stream, group, consumer string) (*Consumer, error) {
2828
if err != nil {
2929
return nil, fmt.Errorf("streams: parse redis url: %w", err)
3030
}
31+
// Proactively close idle connections after 8 s so the client pool recycles
32+
// them before managed Redis providers (Upstash, Redis Cloud) kill them at
33+
// their own idle timeout (~10–60 s depending on plan). This eliminates the
34+
// i/o timeout errors that otherwise surface from blocking XReadGroup calls.
35+
opts.MaxIdleConns = 1
36+
opts.ConnMaxIdleTime = 8 * time.Second
3137
return &Consumer{
3238
client: redis.NewClient(opts),
3339
stream: stream,
@@ -57,13 +63,17 @@ func (c *Consumer) Run(ctx context.Context, h Handler) error {
5763
if err == redis.Nil {
5864
continue
5965
}
60-
// Managed Redis (Upstash, Redis Cloud) kills idle connections, which
61-
// surfaces as an i/o timeout on the blocking XReadGroup call. The
62-
// go-redis pool reconnects automatically on the next attempt, so
63-
// treat this as WARN and retry without delay.
66+
// i/o timeout means the server closed an idle connection. The pool
67+
// will reconnect on the next attempt; back off briefly to avoid
68+
// rapid connection cycling and unnecessary I/O.
6469
var netErr net.Error
6570
if errors.As(err, &netErr) && netErr.Timeout() {
6671
slog.Warn("streams: connection timeout, reconnecting", "stream", c.stream)
72+
select {
73+
case <-ctx.Done():
74+
return nil
75+
case <-time.After(2 * time.Second):
76+
}
6777
continue
6878
}
6979
slog.Error("streams: read error", "stream", c.stream, "err", err)

0 commit comments

Comments
 (0)