Question

I have an REST API, which has a rate limit of 1 query per IP per 5 seconds. When the user tries to call the API too often, I respond with the HTTP status code 429 Too Many Requests and a JSON message.

Now the question is, should I tell my API consumer the allowed rate, or should I just return a generic message?

So which of these is the correct way according to REST principles?

{
  "error": {
    "message": "Too many requests"
  }
}

or

{
  "error": {
    "message": "Too many requests, allowed only 1 per 5 second"
  }
}

or should I inform the caller in some completely different way?

Was it helpful?

Solution

Take the point of view of the API consumer. They send a request to a resource, and receive "not right now" as a reply. What do they do with that information?

  • Retry after a 50 ms wait?
  • Retry after a 500 ms wait ?
  • Retry after a 5 s wait ?
  • ...

Of course, your API documentation should tell what the rate limit is, and the developer of the API consumer can hardcode or make configurable a wait value that corresponds to what is documented. Everything is well in the world.

Except at some point later, the API rate limit is changed (maybe temporarily due to performance constraints, maybe due to a change in the API expectations, or ...). Suddenly the client does not work so well, unless someone checks the new rate limit and changes the code or configuration.

So it is a better practice for the server to provide enough information to the client so that it can adapt without having a human intervene everytime something changes there. Hopefully this is something the people who conceived HTTP thought about, and they provide some pointers regarding what is the expected way to convey that kind of information. It is all there in the docs:

  • The simplest documentation in that regard probably is the 429 Too Many Requests page on MDN. It says that a Retry-After header might be used for that.
  • RFC 6585 is the authoritative source for many HTTP status codes. In section 4, 429 Too Many Requests, it tells that the response body should explain why the request was not processed, and also talks about the Retry-After header.

Both these sources are maybe still a little bit too vague for your liking. Thing is, what they tell must be valid in a lot of cases and not just the specific needs of your REST API (or any REST API for that matters). So consider your use case, consider what the needs of your clients will be, and be as specific as needed, while keeping your implementation in line with the recommendations above and as simple as can be.

Licensed under: CC-BY-SA with attribution
scroll top