I recently had a programming interview, where I had to create an Api Gateway. The description is as follows:
You need to create a gateway in which it only allows certain number of callers to call api and rest of them will be blocked within the given timeframe.
For eg : If the time window is 1 minute. You need to allow only 6 calls to be called within that 1 minute window and rest of them will be blocked and will be only allowed in the next window of 1 minute.
In short every window will only allow 6 api calls.
I was not able write a proper code during 30 min round, since my brain started rushing towards all kinds of solutions.
But I tried to do it once I was done with an interview and below is my solution. Please let me know if there is anyway that I can improve in the implementation, in terms of performance or any other aspects.
public class APIGateway {
private Employee emp;
private int count = 0;
private Timer timer;
public APIGateway(Employee emp) {
this.emp = emp;
this.timer = new Timer(this);
Thread t = new Thread(timer);
t.start();
}
public synchronized void create() {
while (!isAccessible()){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
emp.create();
count++;
}
private synchronized boolean isAccessible() {
if(count<6){
return true;
}
return System.currentTimeMillis()<=timer.getElapsetime();
}
private synchronized void unblock(){
count = 0;
notifyAll();
}
private class Timer implements Runnable {
private long startTime;
private APIGateway gateway;
Timer(APIGateway gateway){
startTime = System.currentTimeMillis();
this.gateway = gateway;
}
private long getElapsetime() {
return startTime + 6000;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(60000);
startTime = System.currentTimeMillis();
gateway.unblock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void delete() {
// same like create
}
public void update() {
// same like create
}
}
// Assume this is the api calls.
interface Employee {
void create();
void delete();
void update();
}