Skip to content

Instantly share code, notes, and snippets.

@jyemin
Created May 1, 2026 14:19
Show Gist options
  • Select an option

  • Save jyemin/cb586710884d282980736453ef952196 to your computer and use it in GitHub Desktop.

Select an option

Save jyemin/cb586710884d282980736453ef952196 to your computer and use it in GitHub Desktop.
MongoDB topology description change listener showing server latency windows
const { MongoClient } = require('mongodb');
// localThresholdMS: The latency window in milliseconds (default is 15)
const client = new MongoClient("mongodb://localhost:27017,localhost:27018,localhost:27019", {
localThresholdMS: 15
});
client.on('topologyDescriptionChanged', (event) => {
const servers = event.newDescription.servers;
// 1. Find the "Fastest" RTT among usable servers to determine the threshold
let minAvgRtt = Infinity;
servers.forEach(s => {
if (s.roundTripTime > -1 && s.type !== 'Unknown') {
if (s.roundTripTime < minAvgRtt) minAvgRtt = s.roundTripTime;
}
});
const localThresholdMS = client.options.localThresholdMS;
const fastest = minAvgRtt === Infinity ? 'N/A' : minAvgRtt + 'ms';
console.log(`\n--- Topology Update (Fastest Node: ${fastest}, window: ${localThresholdMS}ms) ---`);
// 2. Evaluate each server
const entries = [];
servers.forEach((server, address) => {
const avgRtt = server.roundTripTime;
const isConnected = server.type !== 'Unknown' && server.type !== 'PossiblePrimary';
const isWithinLatencyWindow = isConnected && (avgRtt <= (minAvgRtt + localThresholdMS));
entries.push({ address, avgRtt, isConnected, isWithinLatencyWindow });
});
const group = e => !e.isConnected ? 2 : e.isWithinLatencyWindow ? 0 : 1;
entries.sort((a, b) => {
if (group(a) !== group(b)) return group(a) - group(b);
if (a.avgRtt !== b.avgRtt) return a.avgRtt - b.avgRtt;
return a.address.localeCompare(b.address);
});
const groupHeaders = ['suitable, within latency window', 'suitable, outside latency window', 'not suitable'];
let lastGroup = null;
entries.forEach(entry => {
const { address, avgRtt, isConnected, isWithinLatencyWindow } = entry;
const g = group(entry);
if (g !== lastGroup) {
if (lastGroup !== null) console.log();
console.log(`[${groupHeaders[g]}]`);
}
lastGroup = g;
const suitable = isConnected ? 'yes' : 'no';
const rtt = avgRtt > -1 ? avgRtt + 'ms' : 'N/A';
const withinLatencyWindow = !isConnected ? 'N/A' : isWithinLatencyWindow ? 'yes' : 'no';
console.log(` ${address} suitable=${suitable}, rtt=${rtt}, withinLatencyWindow=${withinLatencyWindow}`);
});
});
client.connect();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment