Skip to content

Commit 9877359

Browse files
authored
Merge pull request #2966 from murgatroid99/load_balancing_example
Add load balancing example
2 parents 7548f41 + 972bb23 commit 9877359

File tree

3 files changed

+192
-0
lines changed

3 files changed

+192
-0
lines changed

examples/load_balancing/README.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# Load balancing
2+
3+
This examples shows how `Client` can pick different load balancing policies.
4+
5+
## Try it
6+
7+
```
8+
node server.js
9+
```
10+
11+
```
12+
node client.js
13+
```
14+
15+
## Explanation
16+
17+
Two echo servers are serving on "0.0.0.0:50051" and "0.0.0.0:50052". They will include their serving address in the response. So the server on "0.0.0.0:50051" will reply to the RPC with this is examples/load_balancing (from 0.0.0.0:50051).
18+
19+
Two clients are created, to connect to both of these servers. Each client picks a different load balancer (using the `grpc.service_config` option): `pick_first` or `round_robin`.
20+
21+
Note that balancers can also be switched using service config, which allows service owners (instead of client owners) to pick the balancer to use. Service config doc is available at https://github.com/grpc/grpc/blob/master/doc/service_config.md.
22+
23+
### pick_first
24+
25+
The first client is configured to use `pick_first`. `pick_first` tries to connect to the first address, uses it for all RPCs if it connects, or try the next address if it fails (and keep doing that until one connection is successful). Because of this, all the RPCs will be sent to the same backend. The responses received all show the same backend address.
26+
27+
```
28+
this is examples/load_balancing (from 0.0.0.0:50051)
29+
this is examples/load_balancing (from 0.0.0.0:50051)
30+
this is examples/load_balancing (from 0.0.0.0:50051)
31+
this is examples/load_balancing (from 0.0.0.0:50051)
32+
this is examples/load_balancing (from 0.0.0.0:50051)
33+
this is examples/load_balancing (from 0.0.0.0:50051)
34+
this is examples/load_balancing (from 0.0.0.0:50051)
35+
this is examples/load_balancing (from 0.0.0.0:50051)
36+
this is examples/load_balancing (from 0.0.0.0:50051)
37+
this is examples/load_balancing (from 0.0.0.0:50051)
38+
```
39+
40+
### round_robin
41+
42+
The second client is configured to use `round_robin`. `round_robin` connects to all the addresses it sees, and sends an RPC to each backend one at a time in order. E.g. the first RPC will be sent to backend-1, the second RPC will be sent to backend-2, and the third RPC will be sent to backend-1 again.
43+
44+
```
45+
this is examples/load_balancing (from 0.0.0.0:50051)
46+
this is examples/load_balancing (from 0.0.0.0:50051)
47+
this is examples/load_balancing (from 0.0.0.0:50052)
48+
this is examples/load_balancing (from 0.0.0.0:50051)
49+
this is examples/load_balancing (from 0.0.0.0:50052)
50+
this is examples/load_balancing (from 0.0.0.0:50051)
51+
this is examples/load_balancing (from 0.0.0.0:50052)
52+
this is examples/load_balancing (from 0.0.0.0:50051)
53+
this is examples/load_balancing (from 0.0.0.0:50052)
54+
this is examples/load_balancing (from 0.0.0.0:50051)
55+
```
56+
57+
Note that it's possible to see two consecutive RPC sent to the same backend. That's because `round_robin` only picks the connections ready for RPCs. So if one of the two connections is not ready for some reason, all RPCs will be sent to the ready connection.

examples/load_balancing/client.js

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*
2+
*
3+
* Copyright 2025 gRPC authors.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*
17+
*/
18+
19+
const grpc = require('@grpc/grpc-js');
20+
const protoLoader = require('@grpc/proto-loader');
21+
22+
const PROTO_PATH = __dirname + '/../protos/echo.proto';
23+
24+
const packageDefinition = protoLoader.loadSync(
25+
PROTO_PATH,
26+
{keepCase: true,
27+
longs: String,
28+
enums: String,
29+
defaults: true,
30+
oneofs: true
31+
});
32+
const echoProto = grpc.loadPackageDefinition(packageDefinition).grpc.examples.echo;
33+
34+
const addressString = 'ipv4:///127.0.0.1:50051,127.0.0.1:50052';
35+
36+
function callUnaryEcho(client, message) {
37+
return new Promise((resolve, reject) => {
38+
const deadline = new Date();
39+
deadline.setSeconds(deadline.getSeconds() + 1);
40+
client.unaryEcho({message}, {deadline}, (error, response) => {
41+
if (error) {
42+
reject(error);
43+
} else {
44+
console.log(response.message);
45+
resolve(response);
46+
}
47+
});
48+
});
49+
}
50+
51+
async function makeRPCs(client, count) {
52+
for (let i = 0; i < count; i++) {
53+
await callUnaryEcho(client, "this is examples/load_balancing");
54+
}
55+
}
56+
57+
async function main() {
58+
// "pick_first" is the default, so there's no need to set the load balancing policy.
59+
const pickFirstClient = new echoProto.Echo(addressString, grpc.credentials.createInsecure());
60+
console.log("--- calling helloworld.Greeter/SayHello with pick_first ---");
61+
await makeRPCs(pickFirstClient, 10);
62+
console.log();
63+
64+
const roundRobinServiceConfig = {
65+
methodConfig: [],
66+
loadBalancingConfig: [{ round_robin: {} }]
67+
};
68+
const roundRobinClient = new echoProto.Echo(addressString, grpc.credentials.createInsecure(), {'grpc.service_config': JSON.stringify(roundRobinServiceConfig)});
69+
console.log("--- calling helloworld.Greeter/SayHello with round_robin ---");
70+
await makeRPCs(roundRobinClient, 10);
71+
pickFirstClient.close();
72+
roundRobinClient.close();
73+
}
74+
75+
main();

examples/load_balancing/server.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
*
3+
* Copyright 2025 gRPC authors.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*
17+
*/
18+
19+
const grpc = require('@grpc/grpc-js');
20+
const protoLoader = require('@grpc/proto-loader');
21+
22+
const PROTO_PATH = __dirname + '/../protos/echo.proto';
23+
24+
const packageDefinition = protoLoader.loadSync(
25+
PROTO_PATH,
26+
{keepCase: true,
27+
longs: String,
28+
enums: String,
29+
defaults: true,
30+
oneofs: true
31+
});
32+
const echoProto = grpc.loadPackageDefinition(packageDefinition).grpc.examples.echo;
33+
34+
function startServer(address) {
35+
return new Promise((resolve, reject) => {
36+
const server = new grpc.Server();
37+
server.addService(echoProto.Echo.service, {
38+
unaryEcho: (call, callback) => {
39+
callback(null, {message: `${call.request.message} (from ${address})`});
40+
}
41+
});
42+
server.bindAsync(address, grpc.ServerCredentials.createInsecure(), (error, port) => {
43+
if (error) {
44+
reject(error);
45+
} else {
46+
resolve(server);
47+
}
48+
});
49+
});
50+
}
51+
52+
const addresses = ['0.0.0.0:50051', '0.0.0.0:50052'];
53+
54+
async function main() {
55+
for (const address of addresses) {
56+
await startServer(address)
57+
}
58+
}
59+
60+
main();

0 commit comments

Comments
 (0)