 # Golang implements weighted polling load balancing

Posted on Dec. 2, 2022, 3:18 a.m. by Miss Chelsea Akhtar
Category: The back-end Tag: Load balancing Go

This is the 17th day of my participation in the More text Challenge. For more details, see more text Challenge

If ❤️ my article is helpful, welcome to like, follow. This is the greatest encouragement for me to continue my technical creation. [More on this series on my blog] Coderdao.github. IO /

# Golang implements weighted polling load balancing

## Implements weighted polling load balancing

The code implements a weighted load balancing

• Weight Specifies the Weight of the node that is agreed upon during initialization
• CurrentWeight is a temporary node weight that changes every round
• EffectiveWeight indicates the effectiveWeight of the node. The value is the same as Weight by default
• TotalWeight sum of the effectiveWeight of all nodes: sum(effectiveWeight)

The code implements a weighted load balancing

1. currentWeight = currentWeight+effecitveWeight
2. Select the node with the largest currentWeight as the selected node
3. currentWeight = currentWeight-totalWeight (4+3+2=9)

So we can simulate what happens in the table:

Number of requests Request before currentWelght Selected node After the request currentWelght
1 [serverA=4,serverB=3,serverC=2] serverA [serverA=-1,serverB=6,serverC=4]
2 [serverA=-1,serverB=6,serverC=4] serverB [serverA=3,serverB=0,serverC=6]
3 [serverA=3,serverB=0,serverC=6] serverc [serverA=7,serverB=3,serverC=-1]
4 [serverA=7,serverB=3,serverC=-1] serverA [serverA=2,serverB=6,serverC=1]
5 [serverA=2,serverB=6,serverC=1] serverB [serverA=6,serverB=0,serverC=3]
6 [serverA=6,serverB=0,serverC=3] serverA [serverA=1,serverB=3,serverC=5]
7 [serverA=1,serverB=3,serverC=5] serverc [serverA=5,serverB=6,serverC=-2]

## Weighted polling load balancing code ## The test code ## The test results

``````\$ go test
2021/06/18 19:17:57 Failed to connect to 127.0. 01.:2181: dial tcp 127.0. 01.:2181: i/o timeout
127.0. 01.:2003
127.0. 01.:2005
127.0. 01.:2003
127.0. 01.:2003
127.0. 01.:2005
127.0. 01.:2003
127.0. 01.:2003
127.0. 01.:2003
127.0. 01.:2005
127.0. 01.:2003
127.0. 01.:2005
127.0. 01.:2003
127.0. 01.:2003
127.0. 01.:2005
127.0. 01.:2003
127.0. 01.:2003
127.0. 01.:2003
127.0. 01.:2003
127.0. 01.:2005
PASS