: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(livestream): skip parsing events nobody is watching (#111908)
Jordan Mryyan48b7131ca771
diff --git a/livestream/events/kafka.go b/livestream/events/kafka.goindex 10de3ed74bfa..6d6d6e226c19 100644--- a/livestream/events/kafka.go+++ b/livestream/events/kafka.go@@ -124,6 +124,25 @@ type PostHogEvent struct {BotName string}+type incomingMessage struct {+ value []byte+ token string+ distinctID string+}++func newIncomingMessage(msg *kafka.Message) incomingMessage {+ in := incomingMessage{value: msg.Value}+ for _, h := range msg.Headers {+ switch h.Key {+ case "token":+ in.token = string(h.Value)+ case "distinct_id":+ in.distinctID = string(h.Value)+ }+ }+ return in+}+type KafkaConsumerInterface interface {SubscribeTopics(topics []string, rebalanceCb kafka.RebalanceCb) errorReadMessage(timeout time.Duration) (*kafka.Message, error)@@ -135,7 +154,7 @@ type PostHogKafkaConsumer struct {topic stringgeolocator geo.GeoLocatorbotClassifier *bot.Classifier- incoming chan []byte+ incoming chan incomingMessageoutgoingChan chan PostHogEventstatsChan chan CountEventparallel int@@ -173,7 +192,7 @@ func NewPostHogKafkaConsumer(topic: consumerConfig.Topic,geolocator: geolocator,botClassifier: bot.NewClassifier(),- incoming: make(chan []byte, (1+parallel)*100),+ incoming: make(chan incomingMessage, (1+parallel)*100),outgoingChan: outgoingChan,statsChan: statsChan,parallel: parallel,@@ -226,17 +245,27 @@ func (c *PostHogKafkaConsumer) Consume(ctx context.Context) {log.Printf("Events message #%d: partition=%d, offset=%d",msgCount, msg.TopicPartition.Partition, msg.TopicPartition.Offset)}- c.incoming <- msg.Value+ observeEventLag(msg.Timestamp)+ c.incoming <- newIncomingMessage(msg)}}func (c *PostHogKafkaConsumer) runParsing(ctx context.Context) {for {- value, ok := <-c.incoming+ in, ok := <-c.incomingif !ok {return}- phEvent := parse(c.geolocator, c.botClassifier, value)+ if in.token != "" && in.distinctID != "" && c.Broker != nil && !c.Broker.ShouldPublish(in.token) {+ select {+ case c.statsChan <- CountEvent{Token: in.token, DistinctID: in.distinctID}:+ case <-ctx.Done():+ return+ }+ metrics.RedisPublishSkippedTotal.Inc()+ continue+ }+ phEvent := parse(c.geolocator, c.botClassifier, in.value)if phEvent.Token == "" {metrics.EventsDroppedNoToken.Inc()n := c.droppedNoToken.Add(1)@@ -273,14 +302,6 @@ func parse(geolocator geo.GeoLocator, classifier *bot.Classifier, kafkaMessage [log.Printf("Error decoding JSON %s: %v", err, string(kafkaMessage))}- if wrapperMessage.Timestamp != "" {- if eventTime, err := time.Parse(time.RFC3339Nano, wrapperMessage.Timestamp); err == nil {- if lag := time.Since(eventTime).Seconds(); lag >= 0 {- metrics.EventLagHistogram.Observe(lag)- }- }- }-phEvent := PostHogEvent{Timestamp: wrapperMessage.Timestamp,Token: "",@@ -387,6 +408,15 @@ func (c *PostHogKafkaConsumer) IncomingRatio() float64 {return float64(len(c.incoming)) / float64(cap(c.incoming))}+func observeEventLag(produced time.Time) {+ if produced.IsZero() {+ return+ }+ if lag := time.Since(produced).Seconds(); lag >= 0 {+ metrics.EventLagHistogram.Observe(lag)+ }+}+func applyKafkaConfigOverrides(config *kafka.ConfigMap, consumerConfig configs.ConsumerConfig) {if consumerConfig.ClientID != "" {_ = config.SetKey("client.id", consumerConfig.ClientID)diff --git a/livestream/events/kafka_test.go b/livestream/events/kafka_test.goindex 320322de0893..efd025de72f4 100644--- a/livestream/events/kafka_test.go+++ b/livestream/events/kafka_test.go@@ -9,11 +9,13 @@ import ("time""github.com/confluentinc/confluent-kafka-go/v2/kafka"+ "github.com/posthog/posthog/livestream/bot""github.com/posthog/posthog/livestream/configs""github.com/posthog/posthog/livestream/geo""github.com/posthog/posthog/livestream/mocks""github.com/stretchr/testify/assert""github.com/stretchr/testify/mock"+ "github.com/stretchr/testify/require")func TestPostHogKafkaConsumer_Consume(t *testing.T) {@@ -30,7 +32,7 @@ func TestPostHogKafkaConsumer_Consume(t *testing.T) {consumer: mockConsumer,topic: "test-topic",geolocator: mockGeoLocator,- incoming: make(chan []byte),+ incoming: make(chan incomingMessage),outgoingChan: outgoingChan,statsChan: statsChan,parallel: 1,@@ -94,7 +96,7 @@ func TestPostHogKafkaConsumer_Close(t *testing.T) {mockConsumer := new(mocks.KafkaConsumerInterface)consumer := &PostHogKafkaConsumer{consumer: mockConsumer,- incoming: make(chan []byte),+ incoming: make(chan incomingMessage),}mockConsumer.On("Close").Return(nil)@@ -249,6 +251,170 @@ func TestParse_InnerTimestampOverridesWrapper(t *testing.T) {assert.Equal(t, "$pageview", got.Event)}+func TestRunParsing_SubscriberGate(t *testing.T) {+ watchedBody := `{"distinct_id":"user-1","uuid":"uuid-1","ip":"","data":"{\"event\":\"$pageview\",\"properties\":{}}","token":"tok"}`++ tests := []struct {+ name string+ in incomingMessage+ withBroker bool+ gate PublishGate+ wantStats CountEvent+ wantPublished bool+ }{+ {+ name: "unwatched token is counted from headers without parsing",+ in: incomingMessage{value: []byte("not json"), token: "tok", distinctID: "user-1"},+ withBroker: true,+ gate: fakeGate{def: false},+ wantStats: CountEvent{Token: "tok", DistinctID: "user-1"},+ },+ {+ name: "watched token is parsed and published",+ in: incomingMessage{value: []byte(watchedBody), token: "tok", distinctID: "user-1"},+ withBroker: true,+ gate: fakeGate{def: true},+ wantStats: CountEvent{Token: "tok", DistinctID: "user-1"},+ wantPublished: true,+ },+ {+ name: "missing headers fall back to parsing the body",+ in: incomingMessage{value: []byte(watchedBody)},+ withBroker: true,+ gate: fakeGate{def: false},+ wantStats: CountEvent{Token: "tok", DistinctID: "user-1"},+ },+ {+ name: "no gate parses and publishes every event",+ in: incomingMessage{value: []byte(watchedBody), token: "tok", distinctID: "user-1"},+ withBroker: true,+ wantStats: CountEvent{Token: "tok", DistinctID: "user-1"},+ wantPublished: true,+ },+ {+ name: "in-memory mode parses every event",+ in: incomingMessage{value: []byte(watchedBody), token: "tok", distinctID: "user-1"},+ wantStats: CountEvent{Token: "tok", DistinctID: "user-1"},+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ consumer := &PostHogKafkaConsumer{+ incoming: make(chan incomingMessage, 1),+ outgoingChan: make(chan PostHogEvent, 1),+ statsChan: make(chan CountEvent, 1),+ }+ if tt.withBroker {+ consumer.Broker = NewRedisEventBrokerFromClient(nil, 1, 1)+ if tt.gate != nil {+ consumer.Broker.SetPublishGate(tt.gate)+ }+ }++ consumer.incoming <- tt.in+ close(consumer.incoming)+ consumer.runParsing(context.Background())++ require.Len(t, consumer.statsChan, 1)+ assert.Equal(t, tt.wantStats, <-consumer.statsChan)+ if tt.withBroker {+ if tt.wantPublished {+ require.Len(t, consumer.Broker.publishCh, 1)+ assert.Equal(t, "$pageview", (<-consumer.Broker.publishCh).Event)+ } else {+ assert.Empty(t, consumer.Broker.publishCh)+ }+ } else {+ require.Len(t, consumer.outgoingChan, 1)+ assert.Equal(t, "$pageview", (<-consumer.outgoingChan).Event)+ }+ })+ }+}++func BenchmarkRunParsingPerEvent(b *testing.B) {+ properties := map[string]any{+ "$current_url": "https://www.example.com/pricing?plan=team&utm_source=newsletter",+ "$pathname": "/pricing",+ "$host": "www.example.com",+ "$referrer": "https://search.example.org/",+ "$referring_domain": "search.example.org",+ "$browser": "Chrome",+ "$browser_version": 141,+ "$os": "Mac OS X",+ "$os_version": "15.6.0",+ "$device_type": "Desktop",+ "$device_id": "019a0000-0000-7000-8000-000000000001",+ "$session_id": "019a0000-0000-7000-8000-000000000002",+ "$window_id": "019a0000-0000-7000-8000-000000000003",+ "$pageview_id": "019a0000-0000-7000-8000-000000000004",+ "$lib": "web",+ "$lib_version": "1.280.0",+ "$screen_height": 1117,+ "$screen_width": 1728,+ "$viewport_height": 982,+ "$viewport_width": 1728,+ "$raw_user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36",+ "$timezone": "America/New_York",+ "$timezone_offset": 240,+ "$is_identified": false,+ "$process_person_profile": true,+ "$configured_session_timeout_ms": 1800000,+ "$sdk_debug_retry_queue_size": 0,+ "$recording_status": "active",+ "$replay_script_config": nil,+ "$active_feature_flags": []string{"new-pricing-page", "checkout-v2"},+ "$feature/new-pricing-page": true,+ "$feature/checkout-v2": "test",+ "utm_source": "newsletter",+ "title": "Pricing - Example",+ "$ip": "",+ "token": "tok",+ "distinct_id": "019a0000-0000-7000-8000-000000000001",+ }+ data, err := json.Marshal(map[string]any{+ "event": "$pageview",+ "properties": properties,+ "timestamp": "2026-10-05T12:00:00.000Z",+ })+ if err != nil {+ b.Fatal(err)+ }+ value, err := json.Marshal(PostHogEventWrapper{+ Uuid: "019a0000-0000-7000-8000-000000000005",+ DistinctId: "019a0000-0000-7000-8000-000000000001",+ Data: string(data),+ Token: "tok",+ Timestamp: "2026-10-05T12:00:00.000Z",+ })+ if err != nil {+ b.Fatal(err)+ }+ msg := &kafka.Message{+ Value: value,+ Headers: []kafka.Header{+ {Key: "token", Value: []byte("tok")},+ {Key: "distinct_id", Value: []byte("019a0000-0000-7000-8000-000000000001")},+ {Key: "event", Value: []byte("$pageview")},+ },+ }+ classifier := bot.NewClassifier()++ b.Run("full parse", func(b *testing.B) {+ b.ReportAllocs()+ for b.Loop() {+ parse(nil, classifier, newIncomingMessage(msg).value)+ }+ })+ b.Run("headers only", func(b *testing.B) {+ b.ReportAllocs()+ for b.Loop() {+ newIncomingMessage(msg)+ }+ })+}+func TestSplitTopics(t *testing.T) {tests := []struct {name stringdiff --git a/livestream/events/live_stats.go b/livestream/events/live_stats.goindex b5503aad426f..689d798eb3f6 100644--- a/livestream/events/live_stats.go+++ b/livestream/events/live_stats.go@@ -79,18 +79,19 @@ func (ts *Stats) KeepStats(statsChan chan CountEvent, flushInterval time.Duratioreturn}- ts.Counter.Increment()- ts.GetStoreForToken(event.Token).Add(event.DistinctID, NoSpaceType{})- ts.GlobalStore.Add(event.DistinctID, NoSpaceType{})metrics.HandledEvents.Inc()- if ts.RedisStore != nil {- if pending[event.Token] == nil {- pending[event.Token] = make(map[string]float64)- }+ if ts.RedisStore == nil {+ ts.Counter.Increment()+ ts.GetStoreForToken(event.Token).Add(event.DistinctID, NoSpaceType{})+ ts.GlobalStore.Add(event.DistinctID, NoSpaceType{})+ continue+ }- pending[event.Token][event.DistinctID] = float64(time.Now().Unix())+ if pending[event.Token] == nil {+ pending[event.Token] = make(map[string]float64)}+ pending[event.Token][event.DistinctID] = float64(time.Now().Unix())case <-ticker.C:ts.flushUsersToRedis(pending)pending = make(map[string]map[string]float64)diff --git a/livestream/events/redis_event_broker.go b/livestream/events/redis_event_broker.goindex a9479e17679a..adf6136a1269 100644--- a/livestream/events/redis_event_broker.go+++ b/livestream/events/redis_event_broker.go@@ -56,6 +56,10 @@ func NewRedisEventBrokerFromClient(client rueidis.Client, bufferSize, numWorkers}}+func (b *RedisEventBroker) ShouldPublish(token string) bool {+ return b.gate == nil || b.gate.ShouldPublish(token)+}+// Publish enqueues an event for async publishing to Redis. Non-blocking, drops and emits a metric if buffer is full.func (b *RedisEventBroker) Publish(ctx context.Context, event PostHogEvent) {if event.Token == "" {diff --git a/livestream/events/redis_stats_test.go b/livestream/events/redis_stats_test.goindex e7db8aaa8029..87eb7f928ace 100644--- a/livestream/events/redis_stats_test.go+++ b/livestream/events/redis_stats_test.go@@ -82,6 +82,24 @@ func TestAddUser_GetUserCount(t *testing.T) {}}+func TestStatsKeepStats_RedisModeKeepsNoLocalStore(t *testing.T) {+ store, _ := setupMiniredis(t)+ stats := NewStatsKeeper()+ stats.RedisStore = store++ statsChan := make(chan CountEvent, 3)+ statsChan <- CountEvent{Token: "tok", DistinctID: "user-1"}+ statsChan <- CountEvent{Token: "tok", DistinctID: "user-2"}+ statsChan <- CountEvent{Token: "tok", DistinctID: "user-1"}+ close(statsChan)+ stats.KeepStats(statsChan, time.Hour)++ count, err := store.GetUserCount(context.Background(), "tok")+ require.NoError(t, err)+ assert.Equal(t, int64(2), count)+ assert.Nil(t, stats.GetExistingStoreForToken("tok"))+}+func TestAddSession_GetSessionCount(t *testing.T) {tests := []struct {name string