Sobes.tech
Middle+

Implement the logic of the Allow function for the rate limiter. How will you track events and check limits?

sobes.tech AI

Answer from AI

To implement the Allow function in a rate limiter, you need to track events (e.g., requests) and check whether the limit has been exceeded within a specified time interval.

Here's a simple implementation example in Go using a token bucket:

package main

import (
	"sync"
	"time"
)

type RateLimiter struct {
	mu        sync.Mutex
	tokens    int
	maxTokens int
	interval  time.Duration
	lastRefill time.Time
}

func NewRateLimiter(maxTokens int, interval time.Duration) *RateLimiter {
	return &RateLimiter{
		tokens:    maxTokens,
		maxTokens: maxTokens,
		interval:  interval,
		lastRefill: time.Now(),
	}
}

func (rl *RateLimiter) refill() {
	now := time.Now()
	delta := now.Sub(rl.lastRefill)
	if delta >= rl.interval {
		rl.tokens = rl.maxTokens
		rl.lastRefill = now
	}
}

func (rl *RateLimiter) Allow() bool {
	rl.mu.Lock()
	defer rl.mu.Unlock()

	rl.refill()

	if rl.tokens > 0 {
		rl.tokens--
		return true
	}
	return false
}

// Usage:
// rl := NewRateLimiter(10, time.Minute)
// if rl.Allow() {
//     // allow action
// } else {
//     // deny, limit exceeded
// }

In this implementation:

  • tokens is the current number of available requests.
  • maxTokens is the maximum number of requests within the interval.
  • interval is the period after which the limit resets.
  • The Allow method checks if tokens are available and decrements the count if allowed.
  • The refill method replenishes tokens after the interval.

This approach helps control event frequency and prevent system overload.