I wanted to add a way to throttle the number of requests coming on each API from a certain client. So, I wanted to basically limit the number of requests per API per client.
I am using DropWizard as framework. Can somebody recommend the ways to achieve this? I need something that will work for Distributed system.
API throttling is the process of limiting the number of API requests a user can make in a certain period. An application programming interface (API) functions as a gateway between a user and a software application.
Throttling allows you to limit how many requests a session can execute concurrently. This is useful if you have multiple applications connecting to the same Cassandra cluster, and want to enforce some kind of SLA to ensure fair resource allocation.
Best practices to handle throttling The following are best practices for handling throttling: Reduce the degree of parallelism. Reduce the frequency of calls. Avoid immediate retries because all requests accrue against your usage limits.
A simplistic approach would be to use a Filter and wrap it around all your API calls in web.xml
. Assuming your clients send an API keys identifying them in a HTTP header, you could implement a filter like this:
public class MyThrottlingFilter extends Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpreq = (HttpServletRequest) req;
String apiKey = httpreq.getHeader("API_KEY")
if (invocationLimitNotReached(apiKey))
chain.doFilter(req, res);
else
throw ...
}
}
and then register it like this:
<filter>
<filter-name>MyThrottlingFilter</filter-name>
<filter-class>com.my.throttler.MyThrottlingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyThrottlingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Of course, identifying your clients may be more difficult than this, if you use some other authentication methods, but the general idea should be the same.
Do you want to have such logic enclosed in your application? Maybe some external Load Balancer would be a better choice?
You could try out HAProxy and have entire throtlling logic outside of your application.
A big advantage of such approach is the fact you would not have to rebuild and redeploy application whenever throtlling requirements change. Also, HAProxy will take much smaller amount of time to restart than a typical Java application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With