Answer
No, Moleculer’s built‑in API gateway cannot route a configurable percentage of requests to different service versions; it only supports static version matching.
Confirmed facts
- The gateway’s route definition accepts a
version string or array, but there is no weight, split or traffic‑split option in the source (packages/moleculer-web/src/gateway.js).
- When a request matches a version, the gateway forwards it to all service instances that declare that version, treating them equally.
Likely explanation
The gateway treats version as a deterministic selector; adding probabilistic distribution would require a layer that decides which version to target before the gateway’s internal lookup.
Steps to add canary‑style splitting with custom middleware
- Create a middleware function that examines the version indicator (e.g.,
X-API-Version header or URL path).
- Based on a configurable weight (e.g., 90 % v1, 10 % v2), choose a target version and set
ctx.meta.version to that value.
- Call
next() so the gateway proceeds with its normal version lookup using the overridden meta.
- Register the middleware in the gateway options (
use array) before the default handler.
// trafficSplitMiddleware.js
function trafficSplitMiddleware({ weights }) {
return function (ctx, next) {
// assume version is supplied via header X-API-Version; fallback to 'v1'
const header = ctx.meta.headers?.['x-api-version'] || 'v1';
const rand = Math.random();
let acc = 0;
let chosen = header;
for (const [ver, w] of Object.entries(weights)) {
acc += w;
if (rand <= acc) {
chosen = ver;
break;
}
}
// override the version used by the gateway
ctx.meta.version = chosen;
return next();
};
}
// gateway configuration
const gatewayOptions = {
routes: [
{
path: '/api',
aliases: { ... },
// versioning still works; the middleware decides which version to send
}
],
use: [ trafficSplitMiddleware({ weights: { v1: 0.9, v2: 0.1 } }) ]
};
const apiGateway = broker.createService(require('moleculer-web'), gatewayOptions);
Missing diagnostic detail
To finalize the middleware you need to confirm how your clients indicate the desired version (header, query string, or URL prefix). Let me know which method you use so the example can be adjusted.