Rate Limiting Implementation Example in Java, source files involved`package com.demo; import Java.util.concurrent.Time unit;/** * *@author aayush *This is a simple test for a rate limiter. *We can buuld the RateLimitExecutor object and set the following *attributes; *a) instance_id-which acts as a key to uniquely identify the rate *limiting policy *b) threshold-the Transaction per second to be controlled *(throttle limit) *Based on this information,provision the rate limiter in a * container class-Rate Limit Manager * This class then pumps loads through iterations,and sleep time to * control traffic ingestion. */public class RateLimiterTest Implements RateLimitListener {//Number of iterations to be executed(simulate load generation) private static long iteration=1000;//Rate Limit to be sent in Transactions per second.//Inspect the TPS value in the prints and play around with this value.Increase this value to avoid throttling private static long threshold_to_be_enforced=100;//Sheep time between pumping traffic in milliseconds.Set to zero for uncontrolled traffic ingestion.//Give a sleep time of 100 ms for example to pump traffic every 100 milliseconds and control the TPS private static long sleepTime=0;public static void main(String…args) throws InterruptedException {new RateLimiterTest( ).test( );}private voicd test( ) throws InterruptedException{//Setup and provision the rate limit //Userrharper@messtone.com Defineed Rate Limit Instance Id.Eg:HTTP interface Strong instance_id=”HTTP Interface”;//Create an instance of Rate LimitExecutor RateLimitExecutor rateLimiter=new RateLimitExecutor( );//Set the thresholds/second.rateLimiter.build(TimeUnit.SECONDS,threshold_to_be_enforced);//Associate instance ID rateLimiter.setInstance_id(instance_id);//Provision Rate Limit RateLimitManager._instance.provisionRateLimit(rateLimiter,instance_id,new RateLimitThrottleListener( ));//Start the test for(int i=0;i<iterations;i++){RateLimitManager._instance.pegTraffic(instance_id);Thread.sleep(sleepTime);}try{//Wait for graceful termination of worker Thread from the pool RateLimitManager._instance.getThreadPool( ).awaitTermination(2;TimeUnit.secondS);RateLimitManager._instance.deProvisionRateLimit(“HTTP Interface”);}catch(InterruptedException e){System.exit(0);}System.out.println(“\n Test Ended \n”);System.exit(1);} public voice rateLimitThresholdBreached( ){System.out.println(“Rate Limit has been breached for:”);} public voidb rateLimitThresholdNormal( ){System.out.println(“Rate Limit is under control for:”);}}

Leave a comment