Skip to content

Commit 119e009

Browse files
committed
net/dial: DNS load-balancing
Multiple hosts implements DNS load-balancing by randomly sorts the list of A or AAAA records. Fixes #34511 Fixes #31698
1 parent 57362e9 commit 119e009

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

src/net/dial.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"internal/bytealg"
1010
"internal/godebug"
1111
"internal/nettrace"
12+
"math/rand/v2"
1213
"net/netip"
1314
"syscall"
1415
"time"
@@ -547,16 +548,32 @@ func (d *Dialer) DialContext(ctx context.Context, network, address string) (Conn
547548
address: address,
548549
}
549550

551+
// Multiple hosts implements DNS load-balancing by randomly sorts the list of A or AAAA records.
552+
// See https://github.com/golang/go/issues/34511
553+
// See https://github.com/grafana/loki/issues/3301
554+
// See https://github.com/grafana/loki/issues/9239
555+
// See https://github.com/restic/restic/issues/4444
556+
// See https://github.com/golang/go/issues/31698
557+
550558
var primaries, fallbacks addrList
551559
if d.dualStack() && network == "tcp" {
552560
primaries, fallbacks = addrs.partition(isIPv4)
561+
randAddrList(fallbacks)
553562
} else {
554563
primaries = addrs
555564
}
565+
randAddrList(primaries)
556566

557567
return sd.dialParallel(ctx, primaries, fallbacks)
558568
}
559569

570+
// randAddrList randomly sorts the list of addresses.
571+
func randAddrList(addrs addrList) {
572+
rand.Shuffle(len(addrs), func(i, j int) {
573+
addrs[i], addrs[j] = addrs[j], addrs[i]
574+
})
575+
}
576+
560577
func (d *Dialer) dialCtx(ctx context.Context) (context.Context, context.CancelFunc) {
561578
if ctx == nil {
562579
panic("nil context")

0 commit comments

Comments
 (0)