Skip to content
Advertisement

How do I make multiple fetch calls without getting 429 error?

I came across a problem in a book which I can’t seem to figure out. Unfortunately, I don’t have a live link for it, so if anyone could help me with my approach to this theoretically, I’d really appreciate it.

The process:

  • I get from a fetch call an array of string codes (["abcde", "fghij", "klmno", "pqrst"]).
  • I want to make a call to a link with each string code. example:
JavaScript
  • Each of the calls is going to give me a number code, as shown.
  • I need to get the highest number of the 5 and get its afferent string code and make another call with that.

“abcde” => 1234

“fghij” => 5314

“klmno” => 3465

“pqrst” => 7234 <— winner

JavaScript

What I tried:

JavaScript
  • One of the problems with my approach so far seems to be that it makes too many requests and I get 429 error. I sometimes get the number codes all right, but not too often.

Advertisement

Answer

Like you already found out the 429 means that you send too many requests:

429 Too Many Requests

The user has sent too many requests in a given amount of time (“rate limiting”).

The response representations SHOULD include details explaining the condition, and MAY include a Retry-After header indicating how long to wait before making a new request.

For example:

JavaScript

Note that this specification does not define how the origin server identifies the user, nor how it counts requests. For example, an origin server that is limiting request rates can do so based upon counts of requests on a per-resource basis, across the entire server, or even among a set of servers. Likewise, it might identify the user by its authentication credentials, or a stateful cookie.

Responses with the 429 status code MUST NOT be stored by a cache.

To handle this issue you should reduce the amount of requests made in a set amount of time. You should iterate your codes with a delay, spacing out the request by a few seconds. If not specified in the API documentation or the 429 response, you have to use trial and error approach to find a delay that works. In the example below I’ve spaced them out 2 seconds (2000 milliseconds).

The can be done by using the setTimeout() to execute some piece of code later, combine this with a Promise to create a sleep function. When iterating the initially returned array, make sure to await sleep(2000) to create a 2 second delay between each iteration.

An example could be:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement