Oracle interview

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2023-10-26Added By Anonymous
Source: Link

Company: Oracle
Role: ic-2, ic-3
Interview Stage: Phone Screen
Location: unknown
Year: unknown

Original Post Content:

Design a rate limiter for API not more than 2 api's can appear within 5 seconds and no 5 api's can appear within 30 minutes:-

public class RateLimiter {
    private Map<String, Map<Long, Integer>> apiCallCounts;

    public RateLimiter() {
        apiCallCounts = new HashMap<>();
    }

    public boolean isAllowed(String apiName) {
        long currentTime = System.currentTimeMillis();
        Map<Long, Integer> timestampCounts = apiCallCounts.get(apiName);

        // Initialize the timestamp count if not present
        if (timestampCounts == null) {
            timestampCounts = new HashMap<>();
            apiCallCounts.put(apiName, timestampCounts);
        }

        // Remove timestamps older than 5 minutes
        long fiveMinutesAgo = currentTime - 5 * 60 * 1000;
        timestampCounts.entrySet().removeIf(entry -> entry.getKey() < fiveMinutesAgo);

        // Increment the count for the current timestamp
        int count = timestampCounts.getOrDefault(currentTime, 0) + 1;
        timestampCounts.put(currentTime, count);

        // Check if the count exceeds 2 within 5 minutes
        if (count > 2) {
            System.out.println("Error: Rate limit exceeded for API " + apiName);
            return false;
        }

        // API call is allowed
        System.out.println("200 OK: API " + apiName + " called at " + currentTime);
        return true;
    }

Comments