Hooks: Handling hook failures and the time limit for exponential backoff

I have created a hook that runs a process on my server to onboard a user to my own database in addition. I wanted to use the approach to use exponential backoff in case of maybe the server being unreachable for any scenario of which the request might fail.

However, there’s a limit to how long a hook can run in Auth0. If a hook exceeds this time limit, it will generate an unhandled asynchronous exception and return a 500 error with the message “Script execution time exceeded”.

This creates a dilemma for hooks that use exponential backoff, as it’s possible for the delay between retries to exceed the time limit, resulting in a failure that cannot be handled by the hook itself.

I am not sure how to protect from this as this data ideal would be captured on user registration.

Here is the code for my hook for context:

module.exports = function (user, context, callback) {
  const baseURL = 'https://{hidden}.ngrok.io';
  const route = '/api/db/user';

  // Define the base delay and maximum delay in milliseconds
  const baseDelay = 2000; // 1 second
  const maxDelay = 86400000; // 1 day in milliseconds

  // Define the current delay, starting at the base delay
  let currentDelay = baseDelay;

  // Define the function to make the API call with exponential backoff
  function makeAPICall() {
    const options = {
      url: baseURL + route,
      method: 'POST',
      data: {
        user: user
      }
    };

    axios(options)
      .then(response => {
        console.log('User created successfully');
        callback(null, user, context);
      })
      .catch(error => {
        console.log('Error creating user', user.id, error);

        // Increase the delay exponentially, up to the maximum delay
        currentDelay = Math.min(currentDelay * 2, maxDelay);

        // Retry the API call after the current delay
        setTimeout(makeAPICall, currentDelay);
      });
  }

  makeAPICall();
};
`

Hi @brandon.zeal,

First, I would suggest using Actions unless you have an explicit reason to use the legacy feature, Hooks.

As for the timeout, these post-registration extensibility points aren’t meant to be long-running jobs. You could either deal with the user creation in your DB another way – for example: Add the user to your DB when you see a token with a new user on your backend/API, or attempt to add the user on each login if a flag isn’t present in the user’s app_metadata – or retry until you hit the timeout.

Hope this helps

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.