Weighted routing cannot be configured directly in IBM API Connect but can be handled via underlying IBM Datapower Gateway by setting up load balancers or as an alternate workaround by writing a gateway script to simulate weighted routing.
Today we are going to see how using gateway script we can set-up weight-based routing to backend targets in IBM APIC.
In IBM APIC we use gatewayscript policy to write custom code and will use that to achieve weight-based routing by leveraging the Math.random() function. This method allows us to distribute incoming requests among multiple backend targets based on predefined weights.
We will assign weights to each backend target representing their relative capacity. These weights are positive numbers that sum up to 1. Then calculate the cumulative weights for backend targets and select backend target by generating a random number and comparing with cumulative weights.
Example Gateway Script-
const backendtargets = [
{ target: 'https://fake-json-api.mock.beeceptor.com', weight: 0.3 },
{ target: 'https://httpbin.org/ip', weight: 0.7 }
];
let totalWeights = [];
let sum = 0;
for (let i = 0; i < backendtargets.length; i++) {
sum += backendtargets[i].weight;
totalWeights[i] = sum;
}
function selectBackendTarget() {
const random = Math.random();
for (let i = 0; i < totalWeights.length; i++) {
if (random < totalWeights[i]) {
return backendtargets[i].target;
}
}
}
const targeturl = selectBackendTarget()
context.set('targeturl',targeturl)