Dealing with server load from LiveView reconnects on rolling restarts

I find the default reconnectAfterMs to be far too aggressive, it currently tries to first reconnect after 10 and then 50 ms:

I usually use something more like this in production apps:

function defaultReconnectAfterMs(tries: number) {
  const nominalMs =
    [250, 500, 1_000, 2_500, 5_000, 10_000][tries - 1] || 15_000;

  const jitterRatio = getRandomInt(75, 125) / 100;
  return nominalMs * jitterRatio;
}

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#getting_a_random_integer_between_two_values
function getRandomInt(min, max) {
  const minCeiled = Math.ceil(min);
  const maxFloored = Math.floor(max);
  return Math.floor(Math.random() * (maxFloored - minCeiled) + minCeiled); // The maximum is exclusive and the minimum is inclusive
}

This helps to spread out the load of all of the reconnects.

20 Likes