Practice/Microsoft/Design a Circuit Breaker
Object Oriented DesignMust
Design and implement a rate-limited API client that controls the frequency of outbound requests to prevent overloading external services. Your implementation should use the token bucket algorithm to enforce rate limits while allowing controlled bursts of traffic.
The client must track available request capacity, automatically refill tokens over time, handle concurrent requests safely, and provide visibility into usage patterns through metrics. This is a common pattern used in production systems to ensure reliability when interacting with third-party APIs that have rate limits.
Example 1: Basic rate limiting
` client = RateLimitedAPIClient(rate_limit=2, bucket_capacity=2)
response1 = client.make_request("/api/users") # Success response2 = client.make_request("/api/posts") # Success
response3 = client.make_request("/api/comments") # Throttled
time.sleep(0.5) response4 = client.make_request("/api/likes") # Success `
Example 2: Burst handling
` client = RateLimitedAPIClient(rate_limit=5, bucket_capacity=10)
for i in range(10): response = client.make_request(f"/api/data/{i}") # All succeed
response = client.make_request("/api/data/10") # Throttled
metrics = client.get_metrics()
`
Example 3: Token refill over time
` client = RateLimitedAPIClient(rate_limit=3, bucket_capacity=5)
for i in range(5): client.make_request(f"/api/endpoint/{i}")
time.sleep(2)
for i in range(5): client.make_request(f"/api/endpoint/{i}") # All succeed `