Skip to content

Commit db63e7b

Browse files
feat(lb): Introduce the ability to load balance on composite keys in lb
Right now, there's a problem at high throughput using the load balancer and the `service.name` resource attribute: The load balancers themself get slow. While it's possible to vertically scale them to a point (e.g. about 100k req/sec), as they get slow they star tot back up traffic and block on requests. Applications then can't write as many spans out, and start dropping spans. This commit seeks to address that by extending the load balancing collector to allow create a composite from attributes that can still keep the load balancing decision "consistent enough" to reduce cardinallity, but still spread the load across ${N} collectors. It doesn't make too many assumptions about how the operators will use this, except that the underlying data (the spans) are unlikely to be complete in all cases, and the key generation is "best effort". This is a deviation from the existing design, in which hard-requires "span.name". == Design Notes === Contributor Skill As a contributor, I'm very much new to the opentelemetry collector, and do not anticipate I will be contributing much except for as needs require to tune the collectors that I am responsible for. Given this, the code may violate certain assumptions that are otherwise "well known". === Required Knowledge The biggest surprise in this code was that despite accepting a slice, the routingIdentifierFromTraces function assumes spans have been processed with the batchpersignal.SplitTraces() function, which appears to ensure taht each "trace" contains only a single span (thus allowing them to be multiplexed effectively) This allows the function to be simplified quite substantially. === Use case The primary use case I am thinking about when writing this work is calculating metrics in the spanmetricsconnector component. Essentially, services drive far too much traffic for a single collector instance to handle, so we need to multiplex it in a way that still allows them to be calculated in a single place (limiting cardinality) but also, spreads the load across ${N} collectors. === Traces only implementation This commit addreses this only for traces, as I only care about traces. The logic can likely be extended easily, however.
1 parent 601a99d commit db63e7b

File tree

4 files changed

+259
-21
lines changed

4 files changed

+259
-21
lines changed

exporter/loadbalancingexporter/README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,10 +85,12 @@ Refer to [config.yaml](./testdata/config.yaml) for detailed examples on using th
8585
* This resolver currently returns a maximum of 100 hosts.
8686
* `TODO`: Feature request [29771](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/29771) aims to cover the pagination for this scenario
8787
* The `routing_key` property is used to specify how to route values (spans or metrics) to exporters based on different parameters. This functionality is currently enabled only for `trace` and `metric` pipeline types. It supports one of the following values:
88-
* `service`: Routes values based on their service name. This is useful when using processors like the span metrics, so all spans for each service are sent to consistent collector instances for metric collection. Otherwise, metrics for the same services are sent to different collectors, making aggregations inaccurate.
88+
* `service`: Routes values based on their service name. This is useful when using processors like the span metrics, so all spans for each service are sent to consistent collector instances for metric collection. Otherwise, metrics for the same services are sent to different collectors, making aggregations inaccurate. In addition to resource / span attributes, `span.kind` is also supported.
89+
* `attributes`: Routes based on values in the attributes of the traces. This is similar to service, but useful for situations in which a single service overwhelms any given instance of the collector, and should be split over multiple collectors.
8990
* `traceID`: Routes spans based on their `traceID`. Invalid for metrics.
9091
* `metric`: Routes metrics based on their metric name. Invalid for spans.
9192
* `streamID`: Routes metrics based on their datapoint streamID. That's the unique hash of all it's attributes, plus the attributes and identifying information of its resource, scope, and metric data
93+
* The `routing_attributes` property is used to list the attributes that should be used if the `routing_key` is `attributes`.
9294

9395
Simple example
9496

exporter/loadbalancingexporter/config.go

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ const (
1818
metricNameRouting
1919
resourceRouting
2020
streamIDRouting
21+
attrRouting
2122
)
2223

2324
const (
@@ -26,13 +27,22 @@ const (
2627
metricNameRoutingStr = "metric"
2728
resourceRoutingStr = "resource"
2829
streamIDRoutingStr = "streamID"
30+
attrRoutingStr = "attributes"
2931
)
3032

3133
// Config defines configuration for the exporter.
3234
type Config struct {
33-
Protocol Protocol `mapstructure:"protocol"`
34-
Resolver ResolverSettings `mapstructure:"resolver"`
35-
RoutingKey string `mapstructure:"routing_key"`
35+
Protocol Protocol `mapstructure:"protocol"`
36+
Resolver ResolverSettings `mapstructure:"resolver"`
37+
38+
// RoutingKey is a single routing key value
39+
RoutingKey string `mapstructure:"routing_key"`
40+
41+
// RoutingAttributes creates a composite routing key, based on several resource attributes of the application.
42+
//
43+
// Supports all attributes available (both resource and span), as well as the pseudo attributes "span.kind" and
44+
// "span.name".
45+
RoutingAttributes []string `mapstructure:"routing_attributes"`
3646
}
3747

3848
// Protocol holds the individual protocol-specific settings. Only OTLP is supported at the moment.

exporter/loadbalancingexporter/trace_exporter.go

Lines changed: 78 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"context"
88
"errors"
99
"fmt"
10+
"strings"
1011
"sync"
1112
"time"
1213

@@ -22,13 +23,19 @@ import (
2223
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/batchpersignal"
2324
)
2425

26+
const (
27+
pseudoAttrSpanName = "span.name"
28+
pseudoAttrSpanKind = "span.kind"
29+
)
30+
2531
var _ exporter.Traces = (*traceExporterImp)(nil)
2632

2733
type exporterTraces map[*wrappedExporter]ptrace.Traces
2834

2935
type traceExporterImp struct {
3036
loadBalancer *loadBalancer
3137
routingKey routingKey
38+
routingAttrs []string
3239

3340
stopped bool
3441
shutdownWg sync.WaitGroup
@@ -62,6 +69,9 @@ func newTracesExporter(params exporter.Settings, cfg component.Config) (*traceEx
6269
switch cfg.(*Config).RoutingKey {
6370
case svcRoutingStr:
6471
traceExporter.routingKey = svcRouting
72+
case attrRoutingStr:
73+
traceExporter.routingKey = attrRouting
74+
traceExporter.routingAttrs = cfg.(*Config).RoutingAttributes
6575
case traceIDRoutingStr, "":
6676
default:
6777
return nil, fmt.Errorf("unsupported routing_key: %s", cfg.(*Config).RoutingKey)
@@ -96,7 +106,7 @@ func (e *traceExporterImp) ConsumeTraces(ctx context.Context, td ptrace.Traces)
96106
exporterSegregatedTraces := make(exporterTraces)
97107
endpoints := make(map[*wrappedExporter]string)
98108
for _, batch := range batches {
99-
routingID, err := routingIdentifiersFromTraces(batch, e.routingKey)
109+
routingID, err := routingIdentifiersFromTraces(batch, e.routingKey, e.routingAttrs)
100110
if err != nil {
101111
return err
102112
}
@@ -137,7 +147,15 @@ func (e *traceExporterImp) ConsumeTraces(ctx context.Context, td ptrace.Traces)
137147
return errs
138148
}
139149

140-
func routingIdentifiersFromTraces(td ptrace.Traces, key routingKey) (map[string]bool, error) {
150+
// routingIdentifiersFromTraces reads the traces and determines an identifier that can be used to define a position on the
151+
// ring hash. It takes the routingKey, defining what type of routing should be used, and a series of attributes
152+
// (optionally) used if the routingKey is attrRouting.
153+
//
154+
// only svcRouting and attrRouting are supported. For attrRouting, any attribute, as well the "psuedo" attributes span.name
155+
// and span.kind are supported.
156+
//
157+
// In practice, makes the assumption that ptrace.Traces includes only one trace of each kind, in the "trace tree".
158+
func routingIdentifiersFromTraces(td ptrace.Traces, rType routingKey, attrs []string) (map[string]bool, error) {
141159
ids := make(map[string]bool)
142160
rs := td.ResourceSpans()
143161
if rs.Len() == 0 {
@@ -153,18 +171,67 @@ func routingIdentifiersFromTraces(td ptrace.Traces, key routingKey) (map[string]
153171
if spans.Len() == 0 {
154172
return nil, errors.New("empty spans")
155173
}
174+
// Determine how the key should be populated.
175+
switch rType {
176+
case traceIDRouting:
177+
// The simple case is the TraceID routing. In this case, we just use the string representation of the Trace ID.
178+
tid := spans.At(0).TraceID()
179+
ids[string(tid[:])] = true
156180

157-
if key == svcRouting {
158-
for i := 0; i < rs.Len(); i++ {
159-
svc, ok := rs.At(i).Resource().Attributes().Get("service.name")
160-
if !ok {
161-
return nil, errors.New("unable to get service name")
181+
return ids, nil
182+
case svcRouting:
183+
// Service Name is still handled as an "attribute router", it's just expressed as a "pseudo attribute"
184+
attrs = []string{"service.name"}
185+
case attrRouting:
186+
// By default, we'll just use the input provided.
187+
break
188+
default:
189+
return nil, fmt.Errorf("unsupported routing_key: %d", rType)
190+
}
191+
192+
// Composite the attributes together as a key.
193+
for i := 0; i < rs.Len(); i++ {
194+
// rKey will never return an error. See
195+
// 1. https://pkg.go.dev/bytes#Buffer.Write
196+
// 2. https://stackoverflow.com/a/70388629
197+
var rKey strings.Builder
198+
199+
for _, a := range attrs {
200+
201+
// resource spans
202+
rAttr, ok := rs.At(i).Resource().Attributes().Get(a)
203+
if ok {
204+
rKey.WriteString(rAttr.Str())
205+
continue
206+
}
207+
208+
// ils or "instrumentation library spans"
209+
ils := rs.At(0).ScopeSpans()
210+
iAttr, ok := ils.At(0).Scope().Attributes().Get(a)
211+
if ok {
212+
rKey.WriteString(iAttr.Str())
213+
continue
214+
}
215+
216+
// the lowest level span (or what engineers regularly interact with)
217+
spans := ils.At(0).Spans()
218+
219+
if a == pseudoAttrSpanKind {
220+
rKey.WriteString(spans.At(0).Kind().String())
221+
222+
continue
223+
}
224+
225+
sAttr, ok := spans.At(0).Attributes().Get(a)
226+
if ok {
227+
rKey.WriteString(sAttr.Str())
228+
continue
162229
}
163-
ids[svc.Str()] = true
164230
}
165-
return ids, nil
231+
232+
// No matter what, there will be a key here (even if that key is "").
233+
ids[rKey.String()] = true
166234
}
167-
tid := spans.At(0).TraceID()
168-
ids[string(tid[:])] = true
235+
169236
return ids, nil
170237
}

0 commit comments

Comments
 (0)