Skip to content Skip to sidebar Skip to footer

Promise Retry Pattern Memory Footprint

Consider a function to make a HTTP request until it succeeds: function fetch_retry(url) { return fetch(url).catch(function(error) { return fetch_retry(url); }); }

Solution 1:

As the number of failure increases, does the memory consumption increase?

It does not. Modern implementations of Promises have no memory of promises they were originated from. I can verify that this is the case in Firefox, Chrome, Safari and Edge.

'old' implementations had this problem (think Q). Modern browsers and fast libraries like bluebird 'detach' the reference after resolving.

That said, there is no reason to implement this recursively now, you can just do:

asyncfunctionfetch_retry(url) {
  while(true) { // or limit retries somehowtry {
      awaitfetch(url);
    } catch { }
  }
}

Note that retrying forever is a bad idea, I warmly recommend being friendlier to the backend and using exponential backoff when making retries and limiting the amount of retries.

Caveat

This will actually be hard to measure from your end since when the debugger is attached in V8 (Chrome's JavaScript engine) async stack traces are collected and in your recursive example memory will grow.

You can turn off async stack traces from the Chrome devtools (there is a checkbox).

This will leak a little bit (the stack frames) in development but not in production.

Other caveats

If fetch itself leaks memory on errors (which it has done before at times for certain types of requests) then the code will obviously leak. As far as I know all evergreen browsers fixed found leaks but there might be one in the future.

Solution 2:

return fetch(url).catch(function(error) {
    return fetch_retry(url);
    // Function exits, losing reference to closure// Closure gets garabge collected soon
});

When the callback (catch) got called, it will loose the reference to the catched function, therefore the functions closure will get carbage collected. Only the outer promise and the one that is currently pending stay there.

As the number of failure increases, does the memory consumption increase?

No.

Post a Comment for "Promise Retry Pattern Memory Footprint"