Skip to content

Commit 3f36579

Browse files
committed
single flights topic creation; makes duplicate async
1 parent 904fa68 commit 3f36579

File tree

1 file changed

+15
-9
lines changed

1 file changed

+15
-9
lines changed

Diff for: pkg/distributor/tenant_topic_tee.go

+15-9
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515
"github.com/twmb/franz-go/pkg/kadm"
1616
"github.com/twmb/franz-go/pkg/kerr"
1717
"github.com/twmb/franz-go/pkg/kgo"
18+
"golang.org/x/sync/singleflight"
1819

1920
"github.com/grafana/loki/v3/pkg/kafka"
2021
"github.com/grafana/loki/v3/pkg/kafka/client"
@@ -156,6 +157,7 @@ type ShardedPartitionResolver struct {
156157
admin *kadm.Client
157158
topicPrefix string
158159

160+
sflight singleflight.Group // for topic creation
159161
// tenantShards maps tenant IDs to their active shards
160162
// map[tenant]map[shard]struct{}
161163
tenantShards map[string]map[int32]struct{}
@@ -204,15 +206,15 @@ func (r *ShardedPartitionResolver) createShard(ctx context.Context, tenant strin
204206
topic := r.topicName(tenant, shard)
205207
replicationFactor := 2 // TODO: expose RF
206208

207-
// TODO(owen-d): ensure this only runs once
208-
// at a time.
209-
_, err := r.admin.CreateTopic(
210-
ctx,
211-
1,
212-
int16(replicationFactor),
213-
nil,
214-
topic,
215-
)
209+
_, err, _ := r.sflight.Do(topic, func() (interface{}, error) {
210+
return r.admin.CreateTopic(
211+
ctx,
212+
1,
213+
int16(replicationFactor),
214+
nil,
215+
topic,
216+
)
217+
})
216218

217219
// Topic creation errors are returned in the response
218220
if err != nil && !errors.Is(err, kerr.TopicAlreadyExists) {
@@ -320,6 +322,10 @@ func (t *TenantTopicWriter) partitionsForRateLimit(bytesRateLimit float64) uint3
320322

321323
// Duplicate implements the Tee interface
322324
func (t *TenantTopicWriter) Duplicate(tenant string, streams []KeyedStream) {
325+
go t.write(tenant, streams)
326+
}
327+
328+
func (t *TenantTopicWriter) write(tenant string, streams []KeyedStream) {
323329
if len(streams) == 0 {
324330
return
325331
}

0 commit comments

Comments
 (0)