This a problem statement from a interview I was given the other day
Problem statement:
Given a function makeApiRequests() that makes requests to an external API (maps.google.com),
and a rate limit of 10000 requests per hour, write a rate limitter to restrict the
number of API calls from foo().
< 10000 in last hour -> OK, call foo()
>= 10000 in last hour -> NOT OK, don't call foo()
The interviewer wasn't really strict about the code compiling or the actual frameworks to use for the api calls, just a high level solution
How I went about coding my solution to this problem was putting the rate limitter logic inside my makeApiRequests function.
private static final int API_REQUEST_LIMIT = 10000;
void makeApiCalls(int numCalls) {
if(getAPICalls(milisecondsInHour) + numCalls >= API_REQUEST_LIMIT) {
throw new APIExcessException("Over 10000 requests have been made") ;
}
makeCalls(numCalls)
}
And my getApiCalls function, along with the data structure it uses(List), and APICallSession
class ApiCallSession {
public long timeOfCall;
public int numCalls;
}
private List<ApiCallSession> apiListCalls;
void makeCalls(int numCalls) {
apiCAllsList.add(new ApiCallSession(System.currentTimeInMilisecond, numCalls))
//code for the actual api calls
}
public long getApiCalls(long since) {
int size = apiCallsList.size();
long calls = 0;
int inLastHourIndex = -1;
for(int count = size - 1; count >= 0; count --) {
ApiCallSession call = apiCallsList.get(count);
if(call.timeOfCall >= System.currentTimeInMiliseconds - since) {
calls += call.numCalls;
} else {
inLastHourIndex = count;
break;
}
}
//delete the list from 0 to inLastHourIndex(only care about inLastHourIndex)
deleteListTill(inLastHourIndex);
return calls;
}
I enclose to encapsulate the number of api calls during a session(function call) and the time of those api calls into a single ApiCallSession object? Is this good object oriented design?
When API calls are performed, I update the number of calls that have been made to my data structure(List) to track api calls. One of the concerns the interviewer raised was that the api calls list might be overloaded. To address this, I made a helper function (deleteListTill) that deletes all the ApiCallEntries that were made before the last hour.
Overall when I analyzed my code, I said my overall design takes O(n) space (the List) and the overall time to run the system is O(n) time (the iteration of the list).
Does anyone see any design issues with my code? Was there a better data structure in this situation that would decrease the time and space used? I didn't make it to the next round but I am trying to learn from my experience on this problem.
Aucun commentaire:
Enregistrer un commentaire