Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(livestream): skip publishing events with no subscriber (#109338)

Daniel915b514d91f8
diff --git a/livestream/configs/configs.go b/livestream/configs/configs.go
index b19a78fd8e20..c185ae7afcfa 100644
--- a/livestream/configs/configs.go
+++ b/livestream/configs/configs.go
@@ -24,13 +24,15 @@ type SessionRecordingConfig struct {
}
type RedisConfig struct {
- Address string `mapstructure:"address"`
- Port string `mapstructure:"port"`
- TLS bool `mapstructure:"tls"`
- FlushIntervalMs int `mapstructure:"flush_interval_ms"`
- UsePubSub bool `mapstructure:"use_pub_sub"`
- PublishBufferSize int `mapstructure:"publish_buffer_size"`
- PublishWorkers int `mapstructure:"publish_workers"`
+ Address string `mapstructure:"address"`
+ Port string `mapstructure:"port"`
+ TLS bool `mapstructure:"tls"`
+ FlushIntervalMs int `mapstructure:"flush_interval_ms"`
+ UsePubSub bool `mapstructure:"use_pub_sub"`
+ PublishBufferSize int `mapstructure:"publish_buffer_size"`
+ PublishWorkers int `mapstructure:"publish_workers"`
+ // Skip publishing events for tokens that have no registered subscriber. Off by default.
+ SubscriberAware bool `mapstructure:"subscriber_aware"`
}
// ConsumerConfig holds connection and tuning parameters for a single Kafka consumer.
@@ -142,6 +144,7 @@ func InitConfigs(filename, configPath string) {
_ = viper.BindEnv("redis.use_pub_sub") // LIVESTREAM_REDIS_USE_PUB_SUB
_ = viper.BindEnv("redis.publish_buffer_size") // LIVESTREAM_REDIS_PUBLISH_BUFFER_SIZE
_ = viper.BindEnv("redis.publish_workers") // LIVESTREAM_REDIS_PUBLISH_WORKERS
+ _ = viper.BindEnv("redis.subscriber_aware") // LIVESTREAM_REDIS_SUBSCRIBER_AWARE
}
func LoadConfig() (*Config, error) {
diff --git a/livestream/events/redis_event_broker.go b/livestream/events/redis_event_broker.go
index ead2cad3cc0a..a9479e17679a 100644
--- a/livestream/events/redis_event_broker.go
+++ b/livestream/events/redis_event_broker.go
@@ -17,10 +17,23 @@ func channelName(token string) string {
return fmt.Sprintf("livestream:events:%s", token)
}
+// PublishGate decides whether an event for a token must be published. A nil gate means
+// publish everything (the default, subscriber-aware publishing off).
+type PublishGate interface {
+ ShouldPublish(token string) bool
+}
+
type RedisEventBroker struct {
client rueidis.Client
publishCh chan PostHogEvent
numWorkers int
+ gate PublishGate
+}
+
+// SetPublishGate enables subscriber-aware publishing: events whose token has no registered
+// subscriber are skipped before they reach the publish buffer.
+func (b *RedisEventBroker) SetPublishGate(gate PublishGate) {
+ b.gate = gate
}
func NewRedisEventBroker(cfg configs.RedisConfig) (*RedisEventBroker, error) {
@@ -48,6 +61,13 @@ func (b *RedisEventBroker) Publish(ctx context.Context, event PostHogEvent) {
if event.Token == "" {
return
}
+ // Skip tokens nobody is watching. Gating here (before the buffer) also keeps
+ // unsubscribed events from saturating the publish buffer. The gate fails open, so
+ // uncertainty never drops a watched event.
+ if b.gate != nil && !b.gate.ShouldPublish(event.Token) {
+ metrics.RedisPublishSkippedTotal.Inc()
+ return
+ }
select {
case b.publishCh <- event:
default:
@@ -120,6 +140,14 @@ type TokenRouter struct {
allSubs map[uint64]Subscription
msgCh chan rueidis.PubSubMessage
channelCancels map[string]context.CancelFunc
+ registry *SubscriberRegistry
+}
+
+// SetRegistry enables subscriber-aware publishing on the subscribe side: the router
+// registers a token the moment its first subscriber connects and re-registers all active
+// tokens on a heartbeat. A nil registry (the default) leaves behavior unchanged.
+func (tr *TokenRouter) SetRegistry(registry *SubscriberRegistry) {
+ tr.registry = registry
}
func NewTokenRouter(client rueidis.Client, subChan, unSubChan chan Subscription) *TokenRouter {
@@ -141,11 +169,23 @@ func (tr *TokenRouter) Run(ctx context.Context) {
}
}()
+ // Heartbeat active tokens into the shared registry while subscriber-aware publishing is
+ // on. A nil channel never fires, so the registry-off path is unchanged.
+ var heartbeatC <-chan time.Time
+ if tr.registry != nil {
+ ht := time.NewTicker(tr.registry.HeartbeatInterval())
+ defer ht.Stop()
+ heartbeatC = ht.C
+ }
+
for {
select {
case <-ctx.Done():
return
+ case <-heartbeatC:
+ tr.heartbeatRegistry(ctx)
+
case newSub := <-tr.SubChan:
token := newSub.Token
tr.allSubs[newSub.SubID] = newSub
@@ -154,6 +194,9 @@ func (tr *TokenRouter) Run(ctx context.Context) {
if len(tr.tokenSubs[token]) == 1 {
tr.subscribeChannel(ctx, token)
+ // Register synchronously with the first subscriber so publishers can pick
+ // the token up on their next snapshot refresh.
+ tr.registerToken(ctx, token)
}
case unSub := <-tr.UnSubChan:
@@ -253,3 +296,39 @@ func (tr *TokenRouter) unsubscribeChannel(token string) {
metrics.RedisSubscribeTotal.Dec()
}
}
+
+// registerToken writes a single token into the subscriber registry. It runs off the Run
+// loop so a slow Redis write never stalls message delivery. A lost write is harmless: the
+// next heartbeat re-registers the token, and publishers fail open until then.
+func (tr *TokenRouter) registerToken(ctx context.Context, token string) {
+ if tr.registry == nil {
+ return
+ }
+ go func() {
+ writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ if err := tr.registry.Heartbeat(writeCtx, []string{token}); err != nil {
+ log.Printf("subscriber registry register %s: %v", token, err)
+ }
+ }()
+}
+
+// heartbeatRegistry re-registers every token that currently has subscribers. The token set
+// is snapshotted on the Run goroutine (safe read of tokenSubs) before the write goroutine
+// starts, so tokenSubs is never touched concurrently.
+func (tr *TokenRouter) heartbeatRegistry(ctx context.Context) {
+ if tr.registry == nil || len(tr.tokenSubs) == 0 {
+ return
+ }
+ tokens := make([]string, 0, len(tr.tokenSubs))
+ for token := range tr.tokenSubs {
+ tokens = append(tokens, token)
+ }
+ go func() {
+ writeCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ if err := tr.registry.Heartbeat(writeCtx, tokens); err != nil {
+ log.Printf("subscriber registry heartbeat: %v", err)
+ }
+ }()
+}
diff --git a/livestream/events/subscriber_aware_publish_test.go b/livestream/events/subscriber_aware_publish_test.go
new file mode 100644
index 000000000000..920f8fc4b448
--- /dev/null
+++ b/livestream/events/subscriber_aware_publish_test.go
@@ -0,0 +1,57 @@
+package events
+
+import (
+ "context"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+type fakeGate struct {
+ allow map[string]bool
+ def bool
+}
+
+func (f fakeGate) ShouldPublish(token string) bool {
+ if v, ok := f.allow[token]; ok {
+ return v
+ }
+ return f.def
+}
+
+func TestBrokerPublish_SubscriberAwareGating(t *testing.T) {
+ event := func(token string) PostHogEvent {
+ return PostHogEvent{Token: token, Event: "$pageview", Uuid: "uuid-1", DistinctId: "user-1"}
+ }
+
+ t.Run("skips and does not buffer when no subscriber", func(t *testing.T) {
+ b := NewRedisEventBrokerFromClient(nil, 8, 1)
+ b.SetPublishGate(fakeGate{def: false})
+
+ b.Publish(context.Background(), event("tok"))
+ assert.Equal(t, 0, len(b.publishCh), "unsubscribed event must not enter the publish buffer")
+ })
+
+ t.Run("buffers when the token has a subscriber", func(t *testing.T) {
+ b := NewRedisEventBrokerFromClient(nil, 8, 1)
+ b.SetPublishGate(fakeGate{allow: map[string]bool{"tok": true}})
+
+ b.Publish(context.Background(), event("tok"))
+ assert.Equal(t, 1, len(b.publishCh))
+ })
+
+ t.Run("no gate buffers everything (feature off)", func(t *testing.T) {
+ b := NewRedisEventBrokerFromClient(nil, 8, 1)
+
+ b.Publish(context.Background(), event("tok"))
+ assert.Equal(t, 1, len(b.publishCh), "with the gate off, behavior is unchanged")
+ })
+
+ t.Run("empty token is always dropped", func(t *testing.T) {
+ b := NewRedisEventBrokerFromClient(nil, 8, 1)
+ b.SetPublishGate(fakeGate{def: true})
+
+ b.Publish(context.Background(), event(""))
+ assert.Equal(t, 0, len(b.publishCh))
+ })
+}
diff --git a/livestream/events/subscriber_registry.go b/livestream/events/subscriber_registry.go
new file mode 100644
index 000000000000..87ce1d0bd694
--- /dev/null
+++ b/livestream/events/subscriber_registry.go
@@ -0,0 +1,267 @@
+package events
+
+import (
+ "context"
+ "log"
+ "maps"
+ "strconv"
+ "sync"
+ "time"
+
+ "github.com/posthog/posthog/livestream/configs"
+ "github.com/posthog/posthog/livestream/metrics"
+ "github.com/redis/rueidis"
+)
+
+/*
+SubscriberRegistry powers subscriber-aware publishing.
+
+Without it, every consumed event is SPUBLISH'd to livestream:events:<token>, even
+when no viewer is watching that token. In practice the vast majority of tokens have
+no subscriber, so that publish is pure waste: it crosses AZs to the shard primary and
+saturates the publish buffer.
+
+The registry lets publishers skip tokens that nobody is watching, while never dropping
+an event a viewer is actually watching:
+
+ - Subscribers (TokenRouter) register their active tokens here on subscribe and on a
+ periodic heartbeat, in a single sorted set (member = token, score = last-heartbeat
+ unix seconds) in the SAME Redis/Valkey. The key auto-expires so a crashed subscriber
+ ages out on its own.
+ - Publishers (RedisEventBroker) keep a locally-cached snapshot of the active-token set,
+ refreshed every few seconds with one cheap read (never per-event), and skip SPUBLISH
+ for tokens not in the set.
+
+Correctness (never drop a watched event) is enforced by:
+
+ - Registering a token synchronously the moment its first subscriber connects, so the
+ registry reflects it before the next publisher refresh.
+ - A TTL (activeWindow) that is several heartbeats long, so a live token survives a few
+ lost heartbeats.
+ - A publisher-side grace, so a token that just disappeared from the registry keeps being
+ published for a short while (absorbs read/prune/clock-skew races).
+ - Fail-open: if the snapshot has never loaded, the last read errored, or the snapshot is
+ stale, publishers publish everything. When in doubt, publish.
+
+Single key note: like StatsInRedis, this uses one key, so in cluster mode every command
+hits the same hash slot and pipelines are safe. The read/write volume is tiny (one read
+per refresh interval per publisher, one pipelined write per heartbeat), so the single-slot
+concentration is not a concern versus the per-event publishes it removes.
+*/
+
+const subscriberRegistryKey = "livestream:subscribers"
+
+// Tunables for subscriber-aware publishing. The numbers below are chosen so that a live
+// subscription is never starved while still skipping the ~99% of tokens nobody watches.
+const (
+ // A token counts as active if it was heartbeated within this window. It doubles as the
+ // subscriber-side prune cutoff, so the read and the prune agree. At 3x the heartbeat
+ // interval it tolerates two consecutive lost heartbeats before a live token could drop.
+ // It is also the trailing grace: after the last viewer leaves, publishing continues for
+ // up to this long.
+ defaultRegistryActiveWindow = 30 * time.Second
+
+ // How often subscribers re-register their active tokens.
+ defaultRegistryHeartbeat = 10 * time.Second
+
+ // How often publishers re-read the active-token snapshot. This bounds the
+ // subscribe->first-publish window: a newly subscribed token is picked up within one
+ // refresh interval.
+ defaultRegistrySnapshotRefresh = 2 * time.Second
+
+ // Publisher-side grace: a token that stops appearing in reads stays publishable for this
+ // long. It absorbs a read landing mid-prune, brief registry blips, and clock skew between
+ // a subscriber process and a publisher process.
+ defaultRegistryGrace = 5 * time.Second
+
+ // If a publisher has not refreshed the snapshot successfully within this window, it fails
+ // open and publishes everything. Guards against a stalled refresher goroutine on top of
+ // the immediate fail-open on any read error.
+ defaultRegistryStaleAfter = 15 * time.Second
+)
+
+// SubscriberRegistry is the shared active-token registry. It is safe for concurrent use:
+// ShouldPublish is called from every publish worker, refreshOnce from the refresher
+// goroutine, and Heartbeat from the TokenRouter.
+type SubscriberRegistry struct {
+ client rueidis.Client
+ key string
+
+ activeWindow time.Duration
+ heartbeat time.Duration
+ refresh time.Duration
+ grace time.Duration
+ staleAfter time.Duration
+
+ // readActive reads the current active-token set. It is a field so tests can inject
+ // deterministic results and errors without a live Redis.
+ readActive func(ctx context.Context) ([]string, error)
+
+ mu sync.RWMutex
+ active map[string]struct{} // tokens present in the last good read; publishable while the snapshot is fresh
+ publishUntil map[string]time.Time // token that just left the active set -> grace deadline
+ lastGoodRefresh time.Time
+ healthy bool
+}
+
+// NewSubscriberRegistry creates a registry with its own Redis connection.
+func NewSubscriberRegistry(cfg configs.RedisConfig) (*SubscriberRegistry, error) {
+ client, err := newRedisClient(cfg)
+ if err != nil {
+ return nil, err
+ }
+ return newSubscriberRegistryFromClient(client), nil
+}
+
+func newSubscriberRegistryFromClient(client rueidis.Client) *SubscriberRegistry {
+ r := &SubscriberRegistry{
+ client: client,
+ key: subscriberRegistryKey,
+ activeWindow: defaultRegistryActiveWindow,
+ heartbeat: defaultRegistryHeartbeat,
+ refresh: defaultRegistrySnapshotRefresh,
+ grace: defaultRegistryGrace,
+ staleAfter: defaultRegistryStaleAfter,
+ active: make(map[string]struct{}),
+ publishUntil: make(map[string]time.Time),
+ }
+ r.readActive = r.readActiveFromRedis
+ return r
+}
+
+// HeartbeatInterval is how often subscribers should re-register their active tokens.
+func (r *SubscriberRegistry) HeartbeatInterval() time.Duration {
+ return r.heartbeat
+}
+
+// ShouldPublish reports whether an event for token must be published. It fails open
+// (returns true) whenever the active set is unknown, stale, or the last read errored, so
+// uncertainty never drops a watched event.
+func (r *SubscriberRegistry) ShouldPublish(token string) bool {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ if !r.healthy || r.lastGoodRefresh.IsZero() || time.Since(r.lastGoodRefresh) > r.staleAfter {
+ return true
+ }
+
+ // A token in the last good snapshot is actively watched: publish for as long as the
+ // snapshot is fresh (the staleness check above bounds that), so a lagging refresh never
+ // drops a watched event before the fail-open. A token that just left the snapshot keeps
+ // publishing until its grace deadline, to absorb read/prune/clock-skew races.
+ if _, ok := r.active[token]; ok {
+ return true
+ }
+ deadline, ok := r.publishUntil[token]
+ return ok && time.Now().Before(deadline)
+}
+
+// RunSnapshotRefresher keeps the publisher snapshot fresh until ctx is cancelled.
+func (r *SubscriberRegistry) RunSnapshotRefresher(ctx context.Context) {
+ if err := r.refreshOnce(ctx); err != nil {
+ log.Printf("subscriber registry initial refresh: %v", err)
+ }
+
+ ticker := time.NewTicker(r.refresh)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ if err := r.refreshOnce(ctx); err != nil {
+ log.Printf("subscriber registry refresh: %v", err)
+ }
+ }
+ }
+}
+
+func (r *SubscriberRegistry) readActiveFromRedis(ctx context.Context) ([]string, error) {
+ cutoff := strconv.FormatInt(time.Now().Add(-r.activeWindow).Unix(), 10)
+ return r.client.Do(ctx, r.client.B().Zrangebyscore().Key(r.key).Min(cutoff).Max("+inf").Build()).AsStrSlice()
+}
+
+// refreshOnce loads the active-token set and rebuilds the publisher snapshot. On error it
+// marks the snapshot unhealthy (fail open) and returns the error.
+func (r *SubscriberRegistry) refreshOnce(ctx context.Context) error {
+ tokens, err := r.readActive(ctx)
+ now := time.Now()
+
+ if err != nil {
+ r.mu.Lock()
+ r.healthy = false
+ r.mu.Unlock()
+ metrics.SubscriberRegistryReadErrorsTotal.Inc()
+ return err
+ }
+
+ r.mu.Lock()
+ active := make(map[string]struct{}, len(tokens))
+ for _, t := range tokens {
+ active[t] = struct{}{}
+ }
+ // A token that was active last refresh but is now gone starts its grace countdown from now.
+ // A token already counting down keeps its original deadline, so grace measures from when a
+ // token first left the active set, never longer.
+ grace := make(map[string]time.Time)
+ for t := range r.active {
+ if _, stillActive := active[t]; !stillActive {
+ grace[t] = now.Add(r.grace)
+ }
+ }
+ for t, deadline := range r.publishUntil {
+ if _, stillActive := active[t]; !stillActive && deadline.After(now) {
+ grace[t] = deadline
+ }
+ }
+ r.active = active
+ r.publishUntil = grace
+ r.lastGoodRefresh = now
+ r.healthy = true
+ r.mu.Unlock()
+
+ metrics.SubscriberRegistryActiveTokens.Set(float64(len(tokens)))
+ return nil
+}
+
+// Heartbeat registers or refreshes the given tokens as having active subscribers. Called on
+// subscribe (single token) and on the periodic heartbeat (all active tokens). All commands
+// target the single registry key, so they share one hash slot in cluster mode.
+func (r *SubscriberRegistry) Heartbeat(ctx context.Context, tokens []string) error {
+ if len(tokens) == 0 {
+ return nil
+ }
+
+ now := time.Now()
+ score := float64(now.Unix())
+ members := make(map[string]float64, len(tokens))
+ for _, t := range tokens {
+ if t != "" {
+ members[t] = score
+ }
+ }
+ if len(members) == 0 {
+ return nil
+ }
+
+ cutoff := strconv.FormatInt(now.Add(-r.activeWindow).Unix(), 10)
+ keyTTL := int64((r.activeWindow + r.grace).Seconds())
+
+ cmds := make(rueidis.Commands, 3)
+ cmds[0] = r.client.B().Zadd().Key(r.key).Gt().ScoreMember().ScoreMemberIter(maps.All(members)).Build()
+ cmds[1] = r.client.B().Zremrangebyscore().Key(r.key).Min("-inf").Max(cutoff).Build()
+ cmds[2] = r.client.B().Expire().Key(r.key).Seconds(keyTTL).Build()
+
+ for _, res := range r.client.DoMulti(ctx, cmds...) {
+ if err := res.Error(); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// Close releases the registry's Redis connection.
+func (r *SubscriberRegistry) Close() {
+ r.client.Close()
+}
diff --git a/livestream/events/subscriber_registry_test.go b/livestream/events/subscriber_registry_test.go
new file mode 100644
index 000000000000..5abff3d80759
--- /dev/null
+++ b/livestream/events/subscriber_registry_test.go
@@ -0,0 +1,138 @@
+package events
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/alicebob/miniredis/v2"
+ "github.com/redis/rueidis"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSubscriberRegistry_ShouldPublish(t *testing.T) {
+ r := newSubscriberRegistryFromClient(nil)
+
+ // Never refreshed => fail open so startup never drops a watched event.
+ assert.True(t, r.ShouldPublish("tok"))
+
+ // Healthy snapshot with no subscribers => skip (this is the ~99% waste we remove).
+ r.mu.Lock()
+ r.healthy = true
+ r.lastGoodRefresh = time.Now()
+ r.publishUntil = map[string]time.Time{}
+ r.mu.Unlock()
+ assert.False(t, r.ShouldPublish("tok"))
+
+ // A subscribed token within its window => publish; an unrelated token => skip.
+ r.mu.Lock()
+ r.publishUntil["tok"] = time.Now().Add(time.Second)
+ r.mu.Unlock()
+ assert.True(t, r.ShouldPublish("tok"))
+ assert.False(t, r.ShouldPublish("other"))
+
+ // Stale snapshot (refresher stalled) => fail open.
+ r.mu.Lock()
+ r.lastGoodRefresh = time.Now().Add(-2 * r.staleAfter)
+ r.mu.Unlock()
+ assert.True(t, r.ShouldPublish("other"))
+}
+
+func TestSubscriberRegistry_FailsOpenOnReadError(t *testing.T) {
+ ctx := context.Background()
+ r := newSubscriberRegistryFromClient(nil)
+
+ // A good load first: only the registered token publishes.
+ r.readActive = func(context.Context) ([]string, error) { return []string{"tok"}, nil }
+ require.NoError(t, r.refreshOnce(ctx))
+ assert.True(t, r.ShouldPublish("tok"))
+ assert.False(t, r.ShouldPublish("other"))
+
+ // Reads start failing: publishers must fail open and skip nothing.
+ r.readActive = func(context.Context) ([]string, error) { return nil, errors.New("redis unavailable") }
+ require.Error(t, r.refreshOnce(ctx))
+ assert.True(t, r.ShouldPublish("tok"))
+ assert.True(t, r.ShouldPublish("other"))
+
+ // Recovery: the next good read resumes filtering.
+ r.readActive = func(context.Context) ([]string, error) { return []string{"tok"}, nil }
+ require.NoError(t, r.refreshOnce(ctx))
+ assert.True(t, r.ShouldPublish("tok"))
+ assert.False(t, r.ShouldPublish("other"))
+}
+
+func TestSubscriberRegistry_GraceWindowKeepsJustExpiredTokenPublished(t *testing.T) {
+ ctx := context.Background()
+ r := newSubscriberRegistryFromClient(nil)
+ r.grace = 60 * time.Millisecond
+ r.staleAfter = time.Hour // isolate the grace behavior from the staleness fail-open
+
+ active := []string{"tok"}
+ r.readActive = func(context.Context) ([]string, error) { return active, nil }
+
+ require.NoError(t, r.refreshOnce(ctx))
+ assert.True(t, r.ShouldPublish("tok"))
+
+ // The token disappears from the registry (viewer left, or a brief read flap). During the
+ // grace window an in-flight event for it must still be published, never dropped.
+ active = nil
+ require.NoError(t, r.refreshOnce(ctx))
+ assert.True(t, r.ShouldPublish("tok"), "just-expired token must stay published during grace")
+
+ // Once the grace window elapses, the token is skipped.
+ time.Sleep(80 * time.Millisecond)
+ require.NoError(t, r.refreshOnce(ctx))
+ assert.False(t, r.ShouldPublish("tok"), "token must be skipped after the grace window")
+}
+
+func TestSubscriberRegistry_ActiveTokenStaysPublishableWhenRefreshLagsPastGrace(t *testing.T) {
+ ctx := context.Background()
+ r := newSubscriberRegistryFromClient(nil)
+ r.grace = 20 * time.Millisecond
+ r.staleAfter = time.Hour // a lagging refresh, not a stale snapshot: fail-open must not be what saves us
+
+ r.readActive = func(context.Context) ([]string, error) { return []string{"tok"}, nil }
+ require.NoError(t, r.refreshOnce(ctx))
+ assert.True(t, r.ShouldPublish("tok"))
+
+ // The refresher lags well past the grace window but stays within staleAfter. An actively
+ // watched token must keep publishing the whole time, never dropped at the grace boundary.
+ time.Sleep(3 * r.grace)
+ assert.True(t, r.ShouldPublish("tok"), "active token must stay published when refresh lags past grace but within staleAfter")
+}
+
+// TestSubscriberRegistry_RedisRoundTrip exercises the real ZADD/ZRANGEBYSCORE path against
+// an in-process Redis: a heartbeated token is seen by the publisher snapshot, an
+// unregistered one is not.
+func TestSubscriberRegistry_RedisRoundTrip(t *testing.T) {
+ mr := miniredis.RunT(t)
+ client, err := rueidis.NewClient(rueidis.ClientOption{
+ InitAddress: []string{mr.Addr()},
+ DisableCache: true,
+ })
+ require.NoError(t, err)
+ t.Cleanup(client.Close)
+
+ ctx := context.Background()
+ r := newSubscriberRegistryFromClient(client)
+
+ // A healthy read of an empty registry => skip everything.
+ require.NoError(t, r.refreshOnce(ctx))
+ assert.False(t, r.ShouldPublish("tokA"))
+
+ // Register two tokens; the snapshot must then see exactly those.
+ require.NoError(t, r.Heartbeat(ctx, []string{"tokA", "tokB"}))
+ require.NoError(t, r.refreshOnce(ctx))
+ assert.True(t, r.ShouldPublish("tokA"))
+ assert.True(t, r.ShouldPublish("tokB"))
+ assert.False(t, r.ShouldPublish("tokC"))
+}
+
+func TestSubscriberRegistry_HeartbeatNoTokensIsNoop(t *testing.T) {
+ // A nil client would panic if Heartbeat issued any command; it must short-circuit.
+ r := newSubscriberRegistryFromClient(nil)
+ require.NoError(t, r.Heartbeat(context.Background(), nil))
+ require.NoError(t, r.Heartbeat(context.Background(), []string{""}))
+}
diff --git a/livestream/main.go b/livestream/main.go
index 2067b22e9e65..befe83065a1d 100644
--- a/livestream/main.go
+++ b/livestream/main.go
@@ -345,6 +345,20 @@ func setupRedisPubSub(
tokenRouter := events.NewTokenRouter(subscriberClient, subChan, unSubChan)
+ var registry *events.SubscriberRegistry
+ if redisConfig.SubscriberAware {
+ registry, err = events.NewSubscriberRegistry(redisConfig)
+ if err != nil {
+ subscriberClient.Close()
+ broker.Close()
+ return nil, fmt.Errorf("create subscriber registry: %w", err)
+ }
+ broker.SetPublishGate(registry)
+ tokenRouter.SetRegistry(registry)
+ go registry.RunSnapshotRefresher(ctx)
+ log.Printf("Subscriber-aware publishing enabled: events for tokens with no registered subscriber are skipped")
+ }
+
consumer.Broker = broker
go broker.Run(ctx)
go tokenRouter.Run(ctx)
@@ -352,6 +366,9 @@ func setupRedisPubSub(
cleanup = func() {
subscriberClient.Close()
broker.Close()
+ if registry != nil {
+ registry.Close()
+ }
}
return cleanup, nil
}
diff --git a/livestream/metrics/metrics.go b/livestream/metrics/metrics.go
index 77f94abf2584..915ac629e748 100644
--- a/livestream/metrics/metrics.go
+++ b/livestream/metrics/metrics.go
@@ -183,6 +183,20 @@ var (
Help: "How much of the Redis publish buffer is used",
})
+ // Subscriber-aware publishing metrics
+ RedisPublishSkippedTotal = promauto.NewCounter(prometheus.CounterOpts{
+ Name: "livestream_redis_publish_skipped_total",
+ Help: "Events not published because no subscriber is registered for the token (subscriber-aware publishing)",
+ })
+ SubscriberRegistryActiveTokens = promauto.NewGauge(prometheus.GaugeOpts{
+ Name: "livestream_subscriber_registry_active_tokens",
+ Help: "Tokens with at least one registered subscriber, as seen by the publisher snapshot",
+ })
+ SubscriberRegistryReadErrorsTotal = promauto.NewCounter(prometheus.CounterOpts{
+ Name: "livestream_subscriber_registry_read_errors_total",
+ Help: "Failed reads of the subscriber registry snapshot; publishers fail open on these",
+ })
+
// /notifications handler metrics
NotificationSubs = promauto.NewGauge(prometheus.GaugeOpts{
Name: "livestream_active_notification_subscriptions",