Is there a risk to returning early from a lambda function while API requests are still running?

Viewed 119

I have a nodeJS lambda function where I want to start 3 API calls immediately, but I receive an unknown number of items back from each API call, and I don't know how long each API call will take to execute. I have a specific priority of the items, so if the the first API call returns enough items, I don't care about the other 2 API calls.

I could just wait until the first one resolves to decide if I want to kick off the 2nd and 3rd API calls, but I like the idea of the calls being run in parallel and only awaiting them if required.

Is there anything wrong with starting all 3 API calls immediately and just returning early if I no longer care about the results of the other 2?

  const getFiveThings = async () => {
    const things = [];
    const redThingsPromise = getRedThings();
    const greenThingsPromise = getGreenThings();
    const blueThingsPromise = getBlueThings();

    const redThings = await redThingsPromise;
    things.push(...redThings);
    if (things.length >= 5) {
      return things;
    }

    const greenThings = await greenThingsPromise;
    things.push(...greenThings);
    if (things.length >= 5) {
      return things;
    }

    const blueThings = await blueThingsPromise;
    things.push(...blueThings);
    return things;
  };
1 Answers

IF you are 100% certain that you can end without the others, then no. Those responses come back from the api's you called but just disappear into the void. I use this on a project where we are about 3x faster than the existing legacy system. We make two asyncronious calls - one to the legacy via its api, one to the new system. which ever one is returned first is returned to the API, and the other async thread is cancelled.

We have some logic in there that if our new system returns an error, then it will NOT cancel the other thread and go ahead and wait for the legacy system as a failsafe during rollout.

The API responses are not handshake responses - they simply are sent back to the requestor - if they are no longer listening, then it falls on deaf ears as it were.

Related