How do I configure nginx to return 429 http code when rate limiting?

Solution 1:

Good news, with Version 1.3.15 http://mailman.nginx.org/pipermail/nginx/2013-March/038306.html

we have the "limit_req_status" and "limit_conn_status" directives. I just tested them on Gentoo Linux (note that you need to have the modules limit_req and limit_con compiled in).

With these settings I think you can achieve what you've asked for:

limit_req_status 429;
limit_conn_status 429;

I have verified this with a quick:

ab2 -n 100000 -c 55 "http://127.0.0.1/api/v1

On which most request failed after activating the directive due to the high request rate and the configured limit in nginx:

limit_req zone=api burst=15 nodelay;

Solution 2:

Based on VBart's response and other comments, it is clear that the best option is to map 503 errors to 429s.

error_page 503 = 429 /too-many-requests.html

Since nginx (1.3.x) only uses 503 status codes for limit_req and limit_conn, this should be a fine approach.