We are building a rate limiter as a service. The requirements are:
- Quotas: We need to set a maximum number of requests allowed per time window (e.g., 100 requests per minute).
- Tokens: We can use the token bucket algorithm for bursting and to allow for variable rates.
- Bursting: The ability to handle short bursts above the average rate.
- Isolation: Different clients (or keys) should be isolated, meaning one client's usage doesn't affect another.
We'll design a Token Bucket rate limiter for each key (client identifier). The token bucket algorithm:
- We have a bucket with a maximum capacity (burst size) and a refill rate (tokens per second).
- Each request consumes one token (or more, but we'll assume one token per request for simplicity).
- When a request comes in, we try to take a token from the bucket.
- If there's at least one token, we allow the request and remove a token.
- If there are no tokens, we reject the request (or wait, but we'll reject for simplicity).
- The bucket is refilled at a fixed rate over time. We can refill lazily (when we check) or periodically.
We want to have:
- A way to set the rate (tokens per second) and burst capacity for each key.
- The ability to change the rate and burst for a key (if needed, but we'll design for fixed configuration per key for now).
However, note that the requirement says "quotas" which might be thought of as fixed number of requests in a time window (like 100 per minute).
But with token bucket, we can set:
- The bucket size (burst) to the quota for the window? Not exactly.
Let's clarify:
- If we have 100 requests per minute, that's about 1.666 tokens per second.
- But the token bucket allows bursting up to the bucket size. So if we set bucket size=100 and refill rate=100/60, then:
- Initially, we can have 100 tokens (so 100 requests at once, then it will refill at 100/60 per second).
- But over a minute, we cannot exceed 100 tokens refilled? Actually, no: the refill rate is 100/60 per second, so in 60 seconds we refill 100 tokens. So the average rate is 100 per minute.
However, note that the token bucket algorithm allows for bursts. But the quota in a fixed window (like per minute) is exactly 100.
But with token bucket, if we do 100 requests at the start of the minute, then we have to wait until tokens are refilled.
But if we do 50 requests at the start and 50 at the end of the minute, we might be able to do 100 in the same minute? Actually, the token bucket doesn't have a fixed window.
It's a continuous algorithm. So the quota per minute might not be exactly 100 if we allow bursts.
But the requirement says "quotas", which I interpret as a maximum number of requests in a given time window (e.g., 100 per minute).
However, with token bucket we can also achieve a fixed window limit by setting the bucket size to the quota and the refill rate to quota/window, and then resetting the bucket at the end of the window?
That would be a fixed window algorithm, but then we lose the bursting control? Not exactly: if we reset the bucket at the end of the window, then we allow a burst of up to the quota at the start of the window.
Alternatively, we can use a sliding window log or sliding window counter, but the requirement also says "bursting", which is naturally supported by token bucket.
Let me re-read: "quotas, tokens, bursting, and isolation."
So, I think we are being asked to build a rate limiter that:
- Enforces a quota (max requests per time unit) but allows for bursts (so token bucket is a good fit).
- Uses tokens (so token bucket).
- Is isolated per client.
So we'll implement a token bucket per client (key).
Steps for the token bucket per key:
For a given key, we store:
- capacity: the maximum tokens the bucket can hold (burst size)
- refillRate: tokens per second (the average rate)
- tokens: current number of tokens in the bucket
- lastRefillTimestamp: the last time we updated the bucket (to know how many tokens to add)
When a request comes for a key:
1. Calculate the number of tokens to add based on the time elapsed since lastRefillTimestamp:
tokensToAdd = (currentTime - lastRefillTimestamp) * refillRate
newTokens = min(capacity, tokens + tokensToAdd)
2. Update the bucket's tokens to newTokens and set lastRefillTimestamp to currentTime.
3. If tokens >= 1, then:
tokens = tokens - 1
allow the request.
Else:
reject the request.
But note: step 1 and 2 are done on every request? That might be acceptable if we have a small number of keys, but if we have many keys, we might want to avoid updating every key on every request.
Alternatively, we can do lazy refill: only when we check for a key, we update that key's bucket.
However, we have to be careful about concurrency. We'll assume we are in a multi-threaded environment and we need to handle concurrent requests for the same key.
We can use a lock per key? But that might be heavy. Alternatively, we can use atomic operations and a data structure that allows for lock-free updates?
But for simplicity, let's assume we are using a language that provides atomic operations (like Java's AtomicReference) or we use a lock per key.
Since this is a design, we can describe:
We'll have a map from key to a TokenBucket object. The TokenBucket object will have:
capacity (int)
refillRate (double, tokens per second)
tokens (double, because we might have fractional tokens? Actually, we can use double for tokens and then when consuming, we consume 1.0. But if we want to support fractional consumption, we might need double. However, for simplicity, we can use integer tokens and then refillRate can be fractional? Then we have to handle fractional tokens.
Alternatively, we can store the lastRefillTimestamp and capacity and refillRate, and then when we check, we compute the available tokens without storing the current tokens? But then we have to store the lastRefillTimestamp and the fact that we might have consumed tokens in between.
Actually, we need to store the current tokens and the lastRefillTimestamp.
But note: if two requests come at the same time for the same key, we might have a race condition on updating the tokens and lastRefillTimestamp.
We can do:
synchronized (key) {
// update tokens based on time passed
// then consume if possible
}
But if we have many keys, we don't want to synchronize on a global lock. We can have a ConcurrentHashMap of key to TokenBucket, and then for each key, we synchronize on that TokenBucket object.
However, if the TokenBucket object is stored in the map, we can do:
TokenBucket bucket = map.get(key);
synchronized (bucket) {
// update and consume
}
But what if the bucket is not in the map? We have to create it. So we need to do:
TokenBucket bucket = map.computeIfAbsent(key, k -> new TokenBucket(capacity, refillRate));
But note: the capacity and refillRate might be different per key? The problem says "isolation", but doesn't specify if each key has its own configuration.
Let's assume that we have a configuration for each key? Or maybe we have a default configuration and then per key overrides?
We can design:
We have a configuration service that can give the rate limit configuration for a key.
But for simplicity, let's assume that the rate limiter is initialized with a default configuration, and then we can set per key configuration.
However, the problem doesn't specify. So let's assume we have a way to get the configuration (capacity and refillRate) for a key.
Steps:
TokenBucket bucket = map.get(key);
if (bucket == null) {
// get the configuration for the key (or use default)
Config config = getConfigForKey(key);
bucket = new TokenBucket(config.capacity, config.refillRate);
TokenBucket existing = map.putIfAbsent(key, bucket);
if (existing != null) {
bucket = existing;
}
}
synchronized (bucket) {
// update tokens based on current time
// then try to consume
}
But note: what if the configuration for a key changes? We might need to update the bucket's capacity and refillRate. But then we have to be careful because we are in the synchronized block.
Alternatively, we can have the configuration stored separately and then in the synchronized block, we can check if the configuration has changed and update the bucket accordingly.
However, for simplicity, let's assume the configuration is fixed per key and doesn't change.
But the requirement says "quotas", which might be set by an admin and might change. So we need to support dynamic configuration.
We can store the configuration in a separate map (configMap) and then in the TokenBucket, we can have a reference to the current config. But then if we change the config, we have to update the bucket.
Alternatively, we can have the TokenBucket read the config every time? But that would be expensive.
Let's do:
We have a ConfigProvider that can give the current config for a key.
Then in the synchronized block:
Config currentConfig = configProvider.getConfig(key);
// if the bucket's config doesn't match the currentConfig, then update the bucket's capacity and refillRate.
But note: the bucket might have been created with a different config. We can store the config in the bucket and then compare.
However, what if the bucket's capacity is increased? Then we can just set the new capacity and the current tokens might be less than the new capacity, so we don't need to adjust tokens? Actually, we can set the tokens to min(currentTokens, newCapacity) when increasing? But if we decrease the capacity, then we should set the tokens to min(currentTokens, newCapacity). But note: the tokens might have been accumulated based on the old refillRate? That's a problem.
Alternatively, we can reset the bucket when the config changes? But that might break the current tokens.
Given the complexity, maybe we don't support dynamic config change for now? But the requirement says "as a service", so we might need to.
Let's think: if we change the rate, we want the new rate to take effect immediately. But what about the tokens in the bucket? They were accumulated with the old rate. We have two options:
Option 1: Reset the tokens to 0 (or to the new capacity?) when the config changes. But that might be unfair if the user had built up tokens.
Option 2: Keep the tokens and just change the refillRate and capacity. But then the tokens might be above the new capacity? Then we set to the new capacity.
So when we change the config:
newTokens = min(oldTokens, newCapacity)
But the oldTokens were accumulated with the old refillRate. That might be acceptable because we are just changing the rate going forward.
However, if we increase the capacity, we don't want to lose the extra tokens? Actually, we are setting the tokens to min(oldTokens, newCapacity). So if oldTokens is 50 and newCapacity is 100, then we keep 50. But if oldTokens is 120 and newCapacity is 100, then we set to 100.
And then we change the refillRate to the new one.
But note: the lastRefillTimestamp is still the same. So when we next update, we will refill at the new rate from the lastRefillTimestamp? That might be wrong because the lastRefillTimestamp was for the old rate? Actually, the lastRefillTimestamp is just the last time we updated the bucket. The refillRate is used to calculate how many tokens to add from that time to now. So if we change the refillRate, then from the lastRefillTimestamp to now, we should have refilled at the new rate? But we didn't. So we have a problem.
Alternatively, we can update the lastRefillTimestamp when we change the config? But then we lose the time that passed? Not good.
Let's re-think: the token bucket algorithm is defined by:
tokens = min(capacity, tokens + (now - lastRefillTime) * refillRate)
If we change the refillRate at time T, then from the lastRefillTime (which is before T) to T, we should have refilled at the old rate. Then from T to now, at the new rate.
So we can do:
Let oldRefillRate = oldConfig.refillRate
Let newRefillRate = newConfig.refillRate
We have:
tokens = min(oldCapacity, tokens + (T - lastRefillTime) * oldRefillRate) [at time T, when we change]
Then we set:
lastRefillTime = T (so that from T to now, we use newRefillRate)
But note: we are in the middle of a request? We are changing the config at any time? We need to synchronize on the bucket when changing the config.
Alternatively, we can avoid changing the config on the fly and instead have a way to update the bucket's config in a way that is consistent.
Given the complexity, maybe we don't support dynamic config change for the bucket? But the requirement might not need it.
Since the problem says "as a service", we might have an admin that can change the rate limits. So we need to support it.
Let's design a way:
We have a ConfigProvider that holds the current config for each key. It can be updated.
In the TokenBucket, we store:
volatile Config currentConfig; // but we need to update atomically?
Actually, we are synchronizing on the bucket, so we can safely update the config in the synchronized block.
Steps in the synchronized block:
Config config = configProvider.getConfig(key);
if (bucket.config != config) {
// update the bucket's config
// First, we need to adjust the tokens and lastRefillTime?
// Let's say the current time is now, and the bucket's lastRefillTime is lastTime.
// The tokens were last updated at lastTime with the old config.
// We want to update the config to the new one, but we don't want to lose the tokens that were already there.
// We can recalc the tokens as if we had the new config from the beginning? That's not straightforward.
// Alternatively, we can reset the bucket? But that might be harsh.
// Given the complexity, maybe we just update the capacity and refillRate without adjusting the tokens and lastRefillTime?
// Then from the lastRefillTime (which is in the past) to now, we will refill at the new rate? That's not correct because the time from lastRefillTime to now should have been refilled at the old rate.
// So we need to adjust the tokens to account for the change in refillRate?
// Let me define:
// oldTokens = current tokens in the bucket (without any refill since lastRefillTime)
// We are at time now.
// The tokens that should be in the bucket if we had the old config until now:
// oldTokens + (now - lastRefillTime) * oldRefillRate, capped at oldCapacity.
// But we are changing to new config at time now. So we want to set:
// tokens = min(newCapacity, oldTokens + (now - lastRefillTime) * oldRefillRate)
// lastRefillTime = now
// And then set the new config.
// But note: if the oldCapacity was 100 and newCapacity is 50, then we cap at 50.
// So:
double now = currentTime;
double timePassed = now - bucket.lastRefillTimestamp;
double refilledTokens = timePassed * bucket.config.refillRate;
double newTokens = Math.min(bucket.config.capacity, bucket.tokens + refilledTokens);
// Now we update to new config:
bucket.tokens = Math.min(newConfig.capacity, newTokens);
bucket.lastRefillTimestamp = now;
bucket.config = newConfig;
// But wait, we are using the old refillRate to refill? Actually, we are using the old refillRate because the bucket was using the old config until now.
// Then we set the new config and set lastRefillTimestamp to now so that going forward we use the new refillRate.
}
Then we proceed with the current request: we try to consume one token from the bucket (with the new config).
However, note that the above adjustment is done only when the config changes. And we are in the synchronized block, so it's safe.
But what if the config changes frequently? We are doing this adjustment on every request when the config has changed? That might be acceptable if changes are rare.
Alternatively, we can have a background process that updates the buckets? But that would be complex.
Given the above, we can do:
In the synchronized block:
// Update the config if changed
Config newConfig = configProvider.getConfig(key);
if (bucket.config != newConfig) {
// Adjust the bucket for the config change
adjustBucketForConfigChange(bucket, newConfig);
}
// Then do the normal token bucket update (refill based on time passed) and consume.
But note: in adjustBucketForConfigChange, we already did a refill from lastRefillTimestamp to now (using the old rate) and then set lastRefillTimestamp to now.
Then in the normal update, we will refill from now (which is the same as the current time) to now? That would be 0. So we don't want to do the normal refill again.
So we can do:
In the synchronized block:
long now = System.currentTimeMillis();
// First, if the config changed, adjust the bucket and set lastRefillTimestamp to now.
// Then, if the config hasn't changed, we do the normal refill.
if (bucket.config != newConfig) {
adjustBucketForConfigChange(bucket, newConfig, now);
} else {
// normal refill
double timePassed = (now - bucket.lastRefillTimestamp) / 1000.0; // in seconds
double tokensToAdd = timePassed * bucket.config.refillRate;
bucket.tokens = Math.min(bucket.config.capacity, bucket.tokens + tokensToAdd);
bucket.lastRefillTimestamp = now;
}
// Then try to consume
if (bucket.tokens >= 1) {
bucket.tokens -= 1;
return true;
} else {
return false;
}
But wait, in adjustBucketForConfigChange we already set lastRefillTimestamp to now and updated tokens. So we don't need to do the normal refill.
So we can restructure:
long now = System.currentTimeMillis();
if (bucket.config != newConfig) {
// Adjust the bucket for the config change, which also sets lastRefillTimestamp to now and updates tokens.
adjustBucketForConfigChange(bucket, newConfig, now);
} else {
// Normal refill
double timePassed = (now - bucket.lastRefillTimestamp) / 1000.0;
double tokensToAdd = timePassed * bucket.config.refillRate;
bucket.tokens = Math.min(bucket.config.capacity, bucket.tokens + tokensToAdd);
bucket.lastRefillTimestamp = now;
}
// Then consume
This way, we only do one refill (either the config change adjustment or the normal refill) and then consume.
However, note that in the config change adjustment, we are using the old refillRate to refill from the lastRefillTimestamp (which was with the old config) to now, and then setting lastRefillTimestamp to now. Then going forward, we use the new refillRate.
This seems correct.
But note: the config change might happen at any time, and we are only adjusting when we process a request for that key. So if a key is not used for a long time and then the config changes, the next request will adjust. That's acceptable.
Now, about the configuration: we need a way to set the configuration for a key. We can have:
interface ConfigProvider {
Config getConfig(String key);
}
And we can have a default config for keys that are not explicitly configured.
We also need to consider the data structure for the map. We can use a ConcurrentHashMap.
However, we are synchronizing on the bucket, so we don't need to synchronize on the map. But when we create a new bucket, we have to put it in the map. We can use computeIfAbsent to avoid duplicate creation.
But note: computeIfAbsent might lock the entire map? In Java, ConcurrentHashMap's computeIfAbsent locks only the bucket (segment) for that key. So it's acceptable.
Steps for the rate limiter:
public boolean tryAcquire(String key) {
TokenBucket bucket = map.computeIfAbsent(key, k -> new TokenBucket(defaultConfig));
synchronized (bucket) {
// Get the current config for the key (might be different from the bucket's config)
Config currentConfig = configProvider.getConfig(key);
long now = System.currentTimeMillis();
if (bucket.config != currentConfig) {
adjustBucketForConfigChange(bucket, currentConfig, now);
} else {
// Normal refill
double timePassed = (now - bucket.lastRefillTimestamp) / 1000.0;
double tokensToAdd = timePassed * bucket.config.refillRate;
bucket.tokens = Math.min(bucket.config.capacity, bucket.tokens + tokensToAdd);
bucket.lastRefillTimestamp = now;
}
if (bucket.tokens >= 1) {
bucket.tokens -= 1;
return true;
} else {
return false;
}
}
}
Where adjustBucketForConfigChange:
private void adjustBucketForConfigChange(TokenBucket bucket, Config newConfig, long now) {
// First, refill the tokens from the lastRefillTimestamp (with the old config) to now.
double timePassed = (now - bucket.lastRefillTimestamp) / 1000.0;
double tokensToAdd = timePassed * bucket.config.refillRate;
double newTokens = Math.min(bucket.config.capacity, bucket.tokens + tokensToAdd);
// Now set the new config and adjust tokens to the new capacity.
bucket.tokens = Math.min(newConfig.capacity, newTokens);
bucket.lastRefillTimestamp = now;
bucket.config = newConfig;
}
But note: what if the old config and new config have the same capacity and refillRate? Then we don't need to adjust? We are comparing bucket.config != newConfig.
But if the Config object doesn't override equals, then we might adjust even if the values are the same? We can override equals in Config to compare the fields.
Alternatively, we can compare the fields:
if (bucket.config.capacity != newConfig.capacity || bucket.config.refillRate != newConfig.refillRate) {
adjust...
}
But note: we might have other fields in Config? Let's assume Config has only capacity and refillRate.
However, if we have a Config object that is immutable and we get a new instance for the same values, then we want to avoid adjusting if the values are the same.
So we can override equals in Config.
Alternatively, we can store the config as two separate fields in the bucket? But then we have to update both.
Let's keep it simple: we'll assume Config is a class with capacity and refillRate, and we override equals and hashCode.
But note: the bucket's config might be changed by the adjustBucketForConfigChange, so we are setting bucket.config = newConfig.
Now, about the TokenBucket class:
class TokenBucket {
double tokens;
long lastRefillTimestamp;
Config config;
TokenBucket(Config config) {
this.config = config;
this.tokens = config.capacity; // start full?
this.lastRefillTimestamp = System.currentTimeMillis();
}
}
We start with a full bucket? That's common. But we might want to start with 0? The requirement doesn't specify. Let's start full.
However, if we start full, then a new client can immediately burst up to the capacity. That might be acceptable.
Now, what about the time unit? We are using milliseconds for timestamps, but the refillRate is in tokens per second. So we convert timePassed to seconds.
But note: the tokens and refillRate are double, so we can have fractional tokens? But we only consume integer tokens (1 per request). So we can have fractional tokens in the bucket, but when we check, we only care if tokens >= 1.
Alternatively, we can use integer tokens and refillRate in tokens per millisecond? But then we lose precision? We can use long for tokens and refillRate in tokens per millisecond as a double? It's messy.
Let's use:
tokens: double (to allow fractional refill)
refillRate: double (tokens per second)
Then when we refill:
tokensToAdd = (now - lastRefillTimestamp) / 1000.0 * refillRate
And then we cap at capacity.
This is standard.
Now, about isolation: we are using a separate bucket per key, so that's isolated.
But what about memory? If we have many keys, we might have many TokenBucket objects. We need to clean up unused keys? We can have a background thread that removes buckets that haven't been used for a while? But the requirement doesn't specify.
We can add a lastAccessTimestamp to the TokenBucket and then have a background cleaner. But for now, we'll skip.
Now, what about the initial configuration? We need a default config.
Let's define:
Config defaultConfig = new Config(100, 100.0/60.0); // 100 per minute
But the problem says "quotas", so we might set the quota per minute and then convert to tokens per second.
We can let the user specify the quota and the window? But the token bucket uses a rate (per second) and a burst (capacity).
We can compute:
refillRate = quota / windowInSeconds
And set capacity = quota (to allow a burst of the entire quota at once).
But note: the quota might be per minute, but we are allowing a burst of the entire quota at the start of the window? That's exactly what we want.
So if the quota is 100 per minute, then:
refillRate = 100 / 60 = 1.666... tokens per second
capacity = 100
Then in the first minute, you can do 100 requests at once, then you have to wait for tokens to refill. But then over the next minute, you can do 100 more? Actually, the refillRate is 1.666 per second, so in 60 seconds you get 100 tokens. So the total in a sliding window of 60 seconds is 100? Not exactly, because the token bucket doesn't have a fixed window. It's a continuous leaky bucket.
But the token bucket algorithm with capacity=quota and refillRate=quota/window gives you:
- You can burst up to quota at any time.
- The average rate over a long period is quota/window.
However, in a fixed window of length window, you cannot exceed quota because the bucket can only hold quota tokens and they refill at quota/window per second. So in a window of window seconds, the maximum tokens you can have is quota (if you start with a full bucket) and then you can use them all, and then you have to wait for refill. But note: if you use some tokens at the beginning of the window and then wait, the tokens will refill and you might be able to use more than the initial quota within the same window? Actually, no because the bucket capacity is quota, so you can never have more than quota tokens. So in any window of window seconds, the maximum number of tokens you can have is quota (if you start with a full bucket) and then you use them, and then they refill. But if you use 50 at the start, then 50 tokens remain, and then you wait, the tokens refill up to quota. So if you wait long enough, you can use up to quota again? But note: the window is sliding? The token bucket doesn't have a window.
Actually, the token bucket algorithm does not guarantee a fixed window limit. It guarantees that the average rate does not exceed the refillRate, and that you can burst up to the capacity.
If we want a fixed window (like 100 per minute, resetting every minute), then we should use a fixed window counter. But the requirement says "bursting", so token bucket is better.
So we are using token bucket to approximate a quota with bursting.
Now, let's code the classes.
We'll have:
class Config {
final int capacity;
final double refillRate; // tokens per second
// constructor, equals, hashCode
}
class TokenBucket {
volatile double tokens; // we update in synchronized block, so volatile might not be needed? But we read tokens in the synchronized block, so it's safe.
volatile long lastRefillTimestamp;
volatile Config config;
TokenBucket(Config config) {
this.config = config;
this.tokens = config.capacity;
this.lastRefillTimestamp = System.currentTimeMillis();
}
}
public class RateLimiterService {
private final ConcurrentHashMap<String, TokenBucket> map = new ConcurrentHashMap<>();
private final ConfigProvider configProvider;
private final Config defaultConfig;
public RateLimiterService(ConfigProvider configProvider, Config defaultConfig) {
this.configProvider = configProvider;
this.defaultConfig = defaultConfig;
}
public boolean tryAcquire(String key) {
TokenBucket bucket = map.computeIfAbsent(key, k -> new TokenBucket(defaultConfig));
synchronized (bucket) {
Config currentConfig = configProvider.getConfig(key);
long now = System.currentTimeMillis();
if (bucket.config != currentConfig) {
adjustBucketForConfigChange(bucket, currentConfig, now);
} else {
// Normal refill
double timePassed = (now - bucket.lastRefillTimestamp) / 1000.0;
double tokensToAdd = timePassed * bucket.config.refillRate;
bucket.tokens = Math.min(bucket.config.capacity, bucket.tokens + tokensToAdd);
bucket.lastRefillTimestamp = now;
}
if (bucket.tokens >= 1) {
bucket.tokens -= 1;
return true;
} else {
return false;
}
}
}
private void adjustBucketForConfigChange(TokenBucket bucket, Config newConfig, long now) {
double timePassed = (now - bucket.lastRefillTimestamp) / 1000.0;
double tokensToAdd = timePassed * bucket.config.refillRate;
double newTokens = Math.min(bucket.config.capacity, bucket.tokens + tokensToAdd);
bucket.tokens = Math.min(newConfig.capacity, newTokens);
bucket.lastRefillTimestamp = now;
bucket.config = newConfig;
}
}
But note: in adjustBucketForConfigChange, we are using the old bucket.config.refillRate and capacity. That's correct because until now, the bucket was using the old config.
However, what if the old config was changed by another thread? But we are in the synchronized block on the bucket, so no other thread can change the bucket's config at the same time.
Also, the configProvider.getConfig(key) might return a new Config object (if the config changed) even if the values are the same? That's why we compare the config objects with equals.
We need to make sure that Config overrides equals and hashCode.
Alternatively, we can compare the fields:
if (bucket.config.capacity != currentConfig.capacity || bucket.config.refillRate != currentConfig.refillRate) {
adjust...
}
But then we have to update the bucket's config fields individually? We can do:
if (bucket.config.capacity != currentConfig.capacity || bucket.config.refillRate != currentConfig.refillRate) {
adjust...
// Then set the bucket's config to currentConfig? But in adjust we set bucket.config = newConfig?
// Actually, in adjust we set bucket.config = newConfig (which is currentConfig). So we are setting the entire config.
So we can do:
if (bucket.config.capacity != currentConfig.capacity || bucket.config.refillRate != currentConfig.refillRate) {
adjustBucketForConfigChange(bucket, currentConfig, now);
} else {
// normal refill
}
But then we are comparing the fields, and we don't need to override equals.
Let's do that to avoid creating a new Config object for every request? Actually, the configProvider might return a new Config object every time even if the values are the same. So we compare the fields.
Alternatively, we can cache the config in the bucket and then compare the cached config with the current config by value.
We can change the TokenBucket to store:
int capacity;
double refillRate;
And then we don't need a Config object.
But then the configProvider returns a Config object? We can change the ConfigProvider to return a pair (capacity, refillRate) or we can have a Config class and then in the bucket we store the two fields.
Let's keep the Config class and then in the bucket we store:
int capacity;
double refillRate;
And then we compare these two fields.
Alternatively, we can store the Config object and compare by value (using equals). I think that's cleaner.
Let's stick with Config and override equals.
But note: the Config class might have more fields in the future? We don't know. So using equals is better.
So we'll override equals in Config.
Now, what about the initial tokens? We start with capacity. But what if we want to start with 0? We can have a flag in the Config? Or we can have a separate initialTokens?
The requirement doesn't specify. We'll start full.
Now, about the map: we are using ConcurrentHashMap and computeIfAbsent. But if two threads call tryAcquire for the same key at the same time, computeIfAbsent will only create one bucket. But then both threads will synchronize on the same bucket? Yes.
However, note that the bucket is created with the defaultConfig, but then when we enter the synchronized block, we might adjust to the currentConfig (which might be different). So that's okay.
But what if the config for the key is different from the default? Then the first request will adjust the bucket to the currentConfig. The second request will see the same bucket (with the adjusted config) and then compare with the currentConfig (which is the same) and do normal refill.
So it works.
Now, what about the case where the config is changed to a lower capacity? Then we adjust the tokens to min(newCapacity, oldTokens). That means we might lose tokens? Yes, but that's expected because the capacity is reduced.
Similarly, if the capacity is increased, then we keep the old tokens (which might be less than the new capacity) and then we can refill up to the new capacity.
Now, about the refillRate: if we change the refillRate, then from the lastRefillTimestamp (which was with the old rate) to now, we use the old rate to refill. Then we set the new rate going forward.
That seems correct.
However, note that the lastRefillTimestamp is set to now after the adjustment. So we are not losing the time that passed? We are using the old rate for the time that passed and then setting the new rate.
Now, what about the case where the config changes multiple times between requests? We are only adjusting once per request (to the current config). So if the config changed from A to B and then to C between two requests, then:
First request: bucket has config A, currentConfig is B -> adjust to B.
Second request: bucket has config B, currentConfig is C -> adjust to C.
But note: in the first adjustment, we refilled from lastRefillTimestamp (with A) to now (with A) and then set to B. Then in the second adjustment, we refill from lastRefillTimestamp (which is the time of the first request) to now (with B) and then set to C.
That seems correct.
Now, what about the case where the config changes and then changes back? We are comparing the current bucket's config with the currentConfig. If they are the same, we do normal refill. So if it changes back, we will do normal refill (which uses the current config, which is the same as the bucket's config). That's correct.
Now, let's consider performance: we are synchronizing on the bucket. If we have a hot key, then all requests for that key are serialized. That's acceptable because we are only doing a few operations (a few arithmetic operations and a map lookup). But if we have a very high QPS for a single key, then the lock might be a bottleneck.
We can try to use an atomic operation? But the token bucket update requires reading and writing multiple fields (tokens and lastRefillTimestamp) and also conditionally updating the config. So it's not a single atomic operation.
Alternatively, we can use a lock-free algorithm? That would be complex.
Given that the lock is per key, and if we have many keys, the contention should be low. For a single key, the lock might be a bottleneck if we have thousands of requests per second for that key. But then we might need to shard the key? Or use a different algorithm.
But for a general solution, this is acceptable.
Now, what about the map growing indefinitely? We need to clean up old buckets. We can add a lastAccessTimestamp to the TokenBucket and then have a background thread that removes buckets that haven't been accessed for, say, 1 hour.
We can do:
In the TokenBucket, add:
volatile long lastAccessTimestamp;
In tryAcquire, after we acquire the bucket (and before we release the lock? or after?), we update the lastAccessTimestamp to now.
But note: we are in the synchronized block, so we can update it safely.
Then we have a background thread that:
for (String key : map.keySet()) {
TokenBucket bucket = map.get(key);
if (bucket != null && (now - bucket.lastAccessTimestamp) > CLEANUP_THRESHOLD) {
map.remove(key, bucket); // remove only if the bucket is still the same (to avoid removing a bucket that was just replaced)
}
}
But note: the map might be very large, so iterating over all keys might be expensive. We can use a delay queue or a separate data structure for cleanup.
Alternatively, we can use a LinkedHashMap with access order and then remove the eldest entries? But we don't have a fixed maximum size.
Given the complexity, we might skip the cleanup for now, but in production we would need it.
Now, let's write the code with cleanup:
class TokenBucket {
double tokens;
long lastRefillTimestamp;
Config config;
volatile long lastAccessTimestamp; // updated on every request
TokenBucket(Config config) {
this.config = config;
this.tokens = config.capacity;
this.lastRefillTimestamp = System.currentTimeMillis();
this.lastAccessTimestamp = this.lastRefillTimestamp;
}
}
In tryAcquire, after we have the bucket and in the synchronized block, we update lastAccessTimestamp at the end (or beginning) to now.
But note: we are updating lastAccessTimestamp in the synchronized block, so it's safe.
Then we have a background thread that runs periodically and removes old buckets.
However, the background thread will need to iterate the map and remove old buckets. We can do:
public void startCleanupThread() {
new Thread(() -> {
while (true) {
try {
Thread.sleep(60 * 60 * 1000); // every hour
long now = System.currentTimeMillis();
for (Map.Entry<String, TokenBucket> entry : map.entrySet()) {
TokenBucket bucket = entry.getValue();
if (now - bucket.lastAccessTimestamp > 60 * 60 * 1000) {
map.remove(entry.getKey(), bucket);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}).start();
}
But note: the map.entrySet() might be large and we are removing while iterating? We are using ConcurrentHashMap, so we can remove during iteration? Actually, the iterator of ConcurrentHashMap's entrySet is weakly consistent. So we can remove.
However, we are removing by key and value (map.remove(key, bucket)) which is safe.
But we are holding the iterator and then removing? That's okay.
Alternatively, we can use map.entrySet().removeIf(entry -> ...) but that's not atomic? Actually, removeIf is atomic on the entrySet? Not sure.
We can do:
map.entrySet().removeIf(entry -> {
TokenBucket bucket = entry.getValue();
return now - bucket.lastAccessTimestamp > 60 * 60 * 1000;
});
But note: the condition uses bucket.lastAccessTimestamp, which is volatile. But we are in the cleanup thread and the bucket might be updated by another thread? We are reading lastAccessTimestamp without synchronization? It's volatile, so we get the latest value. But what if the bucket is being updated (lastAccessTimestamp is being set) by another thread? We might read a partially updated value? No, because long is atomic in Java (64-bit, but on 32-bit might not be? Actually, volatile long is atomic). So it's safe.
However, we are removing the bucket while another thread might be using it? The other thread has synchronized on the bucket, so if we remove the bucket from the map, the other thread still has a reference to the bucket and will update it. That's okay because we are only removing the mapping from the map. The bucket object might still be in use by a thread that already retrieved it. But then when that thread releases the lock, the bucket might be orphaned? But that's okay because we are only removing the mapping. The bucket will be garbage collected when no one references it.
But what if after we remove the mapping, a new request comes for the same key? It will create a new bucket. That's acceptable.
So we can do:
public void cleanup() {
long now = System.currentTimeMillis();
map.entrySet().removeIf(entry -> {
TokenBucket bucket = entry.getValue();
return now - bucket.lastAccessTimestamp > 60 * 60 * 1000; // 1 hour
});
}
And run this periodically.
Now, let's put it all together.
We'll design:
Config: immutable, with capacity and refillRate, overrides equals and hashCode.
TokenBucket: as above, with lastAccessTimestamp.
RateLimiterService:
- map: ConcurrentHashMap<String, TokenBucket>
- configProvider: ConfigProvider
- defaultConfig: Config
- cleanupThread: optional
Methods:
- tryAcquire(String key)
- startCleanupThread() (optional)
But note: the configProvider might be called on every request? That might be expensive if the config is stored remotely. We can cache the config in the bucket? But we are already caching the config in the bucket (bucket.config). And we compare the current config from the provider with the bucket's config. So if the config hasn't changed, we don't call the provider? Actually, we call the provider on every request to get the currentConfig.
That might be a problem if the configProvider is slow. We can cache the config in the bucket and then only call the provider if we suspect it changed? But we don't have a way to know.
Alternatively, we can have the configProvider be a local cache? Or we can have a separate thread that updates the bucket's config periodically? That's getting too complex.
Given the requirement, we assume the configProvider is fast (maybe in-memory). If it's remote, we might need to cache.
Let's change: we can have the bucket store the config and also a version or a timestamp of when the config was last updated? But the configProvider doesn't provide that.
Alternatively, we can have the configProvider implement a caching layer? That's outside the rate limiter.
For now, we assume the configProvider is fast.
Now, let's code.
But note: the problem says "as a service", so we might want to expose an API. We are just building the core.
We'll write the code in Java-like pseudocode.
Let's write the Config class:
public class Config {
private final int capacity;
private final double refillRate;
public Config(int capacity, double refillRate) {
this.capacity = capacity;
this.refillRate = refillRate;
}
// getters
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Config config = (Config) o;
return capacity == config.capacity && Double.compare(config.refillRate, refillRate) == 0;
}
@Override
public int hashCode() {
return Objects.hash(capacity, refillRate);
}
}
Then the TokenBucket:
class TokenBucket {
private double tokens;
private long lastRefillTimestamp;
private Config config;
private volatile long lastAccessTimestamp;
TokenBucket(Config config) {
this.config = config;
this.tokens = config.getCapacity();
this.lastRefillTimestamp = System.currentTimeMillis();
this.lastAccessTimestamp = this.lastRefillTimestamp;
}
// getters and setters? We are accessing from the synchronized block in the same class? Actually, we are in the RateLimiterService, which is a different class. So we need to make the fields package-private or provide getters/setters? We'll make them package-private and put them in the same package? Or we can make them private and provide synchronized methods? But we are synchronizing on the bucket in the RateLimiterService.
Let's make the fields private and provide synchronized methods? But then we would synchronize on the bucket in the TokenBucket methods, and then in the RateLimiterService we also synchronize on the bucket? That would be double synchronization? Not good.
Alternatively, we can make the fields package-private and put TokenBucket as a static nested class in RateLimiterService? Then RateLimiterService can access the fields.
Let's do:
public class RateLimiterService {
private static class TokenBucket {
double tokens;
long lastRefillTimestamp;
Config config;
volatile long lastAccessTimestamp;
TokenBucket(Config config) {
this.config = config;
this.tokens = config.capacity;
this.lastRefillTimestamp = System.currentTimeMillis();
this.lastAccessTimestamp = this.lastRefillTimestamp;
}
}
}
Then in RateLimiterService, we can access the fields directly.
}
Then the RateLimiterService:
public class RateLimiterService {
private final ConcurrentHashMap<String, TokenBucket> map = new ConcurrentHashMap<>();
private final ConfigProvider configProvider;
private final Config defaultConfig;
public RateLimiterService(ConfigProvider configProvider, Config defaultConfig) {
this.configProvider = configProvider;
this.defaultConfig = defaultConfig;
}
public boolean tryAcquire(String key) {
TokenBucket bucket = map.computeIfAbsent(key, k -> new TokenBucket(defaultConfig));
synchronized (bucket) {
Config currentConfig = configProvider.getConfig(key);
long now = System.currentTimeMillis();
if (bucket.config.capacity != currentConfig.capacity || bucket.config.refillRate != currentConfig.refillRate) {
adjustBucketForConfigChange(bucket, currentConfig, now);
} else {
// Normal refill
double timePassed = (now - bucket.lastRefillTimestamp) / 1000.0;
double tokensToAdd = timePassed * bucket.config.refillRate;
bucket.tokens = Math.min(bucket.config.capacity, bucket.tokens + tokensToAdd);
bucket.lastRefillTimestamp = now;
}
// Update lastAccessTimestamp
bucket.lastAccessTimestamp = now;
if (bucket.tokens >= 1) {
bucket.tokens -= 1;
return true;
} else {
return false;
}
}
}
private void adjustBucketForConfigChange(TokenBucket bucket, Config newConfig, long now) {
double timePassed = (now - bucket.lastRefillTimestamp) / 1000.0;
double tokensToAdd = timePassed * bucket.config.refillRate;
double newTokens = Math.min(bucket.config.capacity, bucket.tokens + tokensToAdd);
bucket.tokens = Math.min(newConfig.capacity, newTokens);
bucket.lastRefillTimestamp = now;
bucket.config = newConfig;
}
public void startCleanupThread() {
new Thread(() -> {
while (true) {
try {
Thread.sleep(60 * 60 * 1000); // 1 hour
cleanup();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}).start();
}
private void cleanup() {
long now = System.currentTimeMillis();
map.entrySet().removeIf(entry -> {
TokenBucket bucket = entry.getValue();
return now - bucket.lastAccessTimestamp > 60 * 60 * 1000;
});
}
}
But note: in adjustBucketForConfigChange, we are using bucket.config (the old config) to refill. Then we set bucket.config to newConfig.
Also, in the normal refill, we use bucket.config (which is the current config, because we already adjusted if needed).
Now, what about the case where the config changes and the new config has a lower refillRate? Then the tokensToAdd in the adjustment will be less than if we had the new rate? Actually, we are using the old rate for the time passed, which is correct because the bucket was operating under the old rate until now.
Now, what about the case where the config changes and the new config has a higher refillRate? Then we are undercounting the tokens that should have been refilled? No, because the old rate was lower, so we are adding fewer tokens than if we had the new rate for the entire period? But that's correct because the bucket was only refilling at the old rate until now.
So the adjustment is correct.
However, note that we are not accounting for the fact that the bucket might have been using the old rate for the entire period, and then we switch to the new rate. That's exactly what we want.
Now, what about the lastAccessTimestamp? We update it in every request (both in the adjustment and normal refill) to now. That's correct.
Now, what about the initial state? We start with a full bucket and lastAccessTimestamp = lastRefillTimestamp = creation time.
Now, let's test with an example:
Config: capacity=10, refillRate=1 token per second.
t=0: create bucket, tokens=10, lastRefill=0.
Request at t=1:
timePassed=1, tokensToAdd=1, tokens=min(10, 10+1)=10 (capped), then consume 1 -> tokens=9.
Request at t=2:
timePassed=1, tokensToAdd=1, tokens=10 -> 9+1=10, then consume -> 9.
So we are at a steady state of 9 tokens? Actually, we start with 10, then after first request we have 9, then we refill to 10 and then consume to 9. So we stay at 9? That's because we are refilling to capacity and then consuming. But if we have a steady state of 1 request per second, we should have 10 tokens? Let's see:
At t=0: 10 tokens.
At t=1: we have 10 tokens, we consume 1 -> 9, then we refill 1 -> 10? Actually, we do:
tokens = min(10, 9 + 1) = 10, then consume -> 9.
Then at t=2: tokens = min(10, 9 + 1) = 10, then consume -> 9.
So we are always at 9 after the first second? That's because we are refilling 1 token every second and then consuming 1, so we stay at 9? But we started with 10, then after 1 second we refill 1 (so 10) and then consume 1 -> 9. Then every second we do the same.
Actually, the bucket should be able to hold 10 tokens, and if we consume 1 per second, we should stay at 10? Let's think:
We have 10 tokens at t=0.
At t=1: we consume 1 -> 9, then we refill 1 -> 10.
So at the end of t=1, we have 10.
But in our code, we refill first and then consume. So:
At t=1: we refill from lastRefill (0) to 1: 1 token, so tokens become 10 (min(10, 10+1)=10). Then we consume 1 -> 9.
That's because we are using the time from lastRefill to now, which is 1 second, and we add 1 token. But we already had 10 tokens, so we are capped at 10. Then we consume 1, leaving 9.
Then at t=2: lastRefill is 1, now 2, timePassed=1, tokensToAdd=1, tokens=9+1=10, then consume -> 9.
So we are stuck at 9. That's not correct.
The issue is that we are refilling and then consuming in the same step. But the tokens should be refilled continuously. The algorithm should be:
tokens = min(capacity, tokens + (now - lastRefill) * refillRate)
Then we consume.
But in our example, at t=1:
tokens = min(10, 10 + 1*1) = 10
then consume 1 -> 9
Then at t=2:
tokens = min(10, 9 + 1*1) = 10
then consume 1 -> 9
So we are always at 9 after the first second. That means we are not allowing the bucket to fill up to capacity? But we are, because we are refilling to 10 and then immediately consuming 1.
Actually, the steady state should be:
Let T be the time between requests. Then:
tokens_before_refill = tokens_previous
tokens_after_refill = min(capacity, tokens_before_refill + T * refillRate)
tokens_after_consume = tokens_after_refill - 1
In steady state, tokens_previous = tokens_after_consume.
So:
tokens_after_consume = min(capacity, tokens_after_consume + T * refillRate) - 1
If T * refillRate >= 1, then we can have:
tokens_after_consume = tokens_after_consume + T * refillRate - 1 (if tokens_after_consume + T * refillRate <= capacity)
Then:
0 = T * refillRate - 1 => T = 1/refillRate.
So if we have a request every 1 second and refillRate=1, then we should have:
tokens_after_consume = tokens_after_consume + 1 - 1 = tokens_after_consume.
So any tokens_after_consume is a steady state? But we are capping at capacity.
Let's simulate with T=1, refillRate=1, capacity=10:
t=0: tokens=10
t=1: refill 1 -> 10 (capped), consume 1 -> 9.
t=2: refill 1 -> 10 (9+1=10), consume 1 -> 9.
So we are at 9.
But if we start with 10 and then we have a request every second, we should be able to have 10 tokens at the beginning of each second? Actually, no because we are consuming 1 every second and refilling 1 every second, so we are net 0 change. But we started with 10, then after 1 second we have 9, then we refill to 10 and consume to 9. So we are always at 9 after the first second.
This is because we are refilling and then consuming in the same instant. But in reality, the refill is continuous. So at t=1, we have 10 tokens (because we refilled 1 from t=0 to t=1) and then we consume 1, leaving 9. Then at t=2, we have refilled 1 from t=1 to t=2, so we have 10 again? But we only had 9 at t=1 after consuming. So from t=1 to t=2, we refill 1, so 9+1=10. Then we consume 1 -> 9.
So the steady state is 9? That means we are not using the full capacity? Actually, we are using 9 tokens on average? But we started with 10 and then we are at 9.
If we start with 0, then:
t=0: 0 tokens.
t=1: refill 1 -> 1, consume 1 -> 0.
t=2: refill 1 -> 1, consume 1 -> 0.
So we are at 0.
The steady state depends on the initial tokens and the timing of requests.
Actually, the token bucket algorithm doesn't guarantee that we will be at capacity in steady state. It only guarantees that we cannot exceed the capacity and that the average rate does not exceed the refillRate.
So our simulation is correct.
But note: if we have a burst of 10 at the beginning, we can do 10 requests. Then we have to wait 10 seconds to get 10 tokens back? Actually, if we do 10 requests at t=0, then we have 0 tokens. Then at t=10, we have 10 tokens (if refillRate=1). So we can do 10 requests at t=0 and then 10 more at t=10.
That's the intended behavior.
So the code seems correct.
Now, let's consider the case where we have two requests at the same time for the same key? They will be serialized by the synchronized block. The first one will update the bucket and consume, then the second one will update again (with the new lastRefillTimestamp set by the first) and then try to consume.
That's correct.
Now, what about the case where we have two requests for different keys? They will use different buckets, so no contention.
Now, about the cleanup: we update lastAccessTimestamp on every request. So if a key is used frequently, lastAccessTimestamp is recent and won't be cleaned.
Now, what about the case where the config is changed and we adjust the bucket? We set lastAccessTimestamp to now. That's correct.
Now, let's think about the adjustBucketForConfigChange: we are using the old config to refill from the lastRefillTimestamp to now. But what if the lastRefillTimestamp is very old and the tokens were already at capacity? Then we are adding tokens that shouldn't be there? Actually, if the tokens were at capacity, then we don't add any because we cap at the old capacity. That's correct.
Example:
Old config: capacity=100, refillRate=1.
At t=0: tokens=100.
No requests until t=1000.
Then at t=1000, we change config to capacity=200, refillRate=2.
In adjust:
timePassed = 1000
tokensToAdd = 1000 * 1 = 1000, but capped at old capacity (100) so newTokens = 100 (because tokens was 100, and we cap at 100? Actually, tokens was 100, and we add 1000, but we cap at 100 -> 100).
Then we set tokens to min(200, 100) = 100.
Then we set lastRefillTimestamp to 1000 and config to the new one.
Then if we try to consume, we have 100 tokens.
But note: from t=0 to t=1000, we should have refilled 1000 tokens at rate 1? But the bucket capacity is 100, so we were at 100 the whole time. So we didn't gain any extra tokens. Then we change the capacity to 200, but we still have 100 tokens. Then going forward, we refill at 2 per second.
That's correct.
Now, what if the old config had a lower refillRate and we change to a higher one?
Old: capacity=100, refillRate=1.
At t=0: tokens=0.
Then at t=100, we change to capacity=200, refillRate=2.
Adjust:
timePassed=100
tokensToAdd=100*1=100 -> tokens=0+100=100 (capped at 100? old capacity=100, so we cap at 100 -> 100)
Then set tokens = min(200, 100) = 100.
Then we have 100 tokens at t=100, which is correct because with the old rate we would have 100 tokens at t=100.
Then going forward, we refill at 2 per second.
Now, what if we change to a lower refillRate?
Old: capacity=100, refillRate=2.
At t=0: tokens=0.
At t=50: change to capacity=200, refillRate=1.
Adjust:
timePassed=50
tokensToAdd=50*2=100 -> tokens=100 (capped at 100) -> 100.
Then set tokens = min(200,100)=100.
Then at t=50, we have 100 tokens. Then going forward, we refill at 1 per second.
But note: at t=50, with the old rate we would have 100 tokens (50*2). So that's correct.
Now, what if we change the capacity to a lower one?
Old: capacity=100, refillRate=1.
At t=0: tokens=100.
At t=0 (immediately): change to capacity=50, refillRate=1.
Adjust:
timePassed=0, tokensToAdd=0 -> tokens=100.
Then set tokens = min(50, 100) = 50.
So we lose 50 tokens. That's expected because the new capacity is 50.
Now, what if we change the capacity to a higher one?
Old: capacity=50, refillRate=1.
At t=0: tokens=50.
At t=0: change to capacity=100, refillRate=1.
Adjust:
timePassed=0, tokensToAdd=0 -> tokens=50.
Then set tokens = min(100,50)=50.
So we keep 50 tokens, which is less than the new capacity. Then we can refill up to 100.
This seems correct.
Now, what about the normal refill when the config hasn't changed? We do:
tokens = min(capacity, tokens + timePassed * refillRate)
That's correct.
Now, one more thing: the tokens are double, so we might have fractional tokens. But we only consume integer tokens. That's okay because we are using double for tokens and then we check if tokens >= 1.
But note: if we have 0.5 tokens, then we cannot consume. That's correct.
However, when we refill, we might get fractional tokens. That's acceptable.
Now, what about the time precision? We are using System.currentTimeMillis() which is in milliseconds. The refillRate is per second, so we convert to seconds.
This might cause some inaccuracy, but it's acceptable.
Now, let's consider the case where we have a very high refillRate and a very small timePassed? We might get a very small tokensToAdd. That's okay.
Now, we need to consider the case where the system clock changes? We are using System.currentTimeMillis() which can go backwards if the system clock is adjusted. We might want to use a monotonic clock? In production, we might use System.nanoTime() for elapsed time? But note: nanoTime is for elapsed time, not for wall-clock time. We are using the time difference between now and lastRefillTimestamp. If we use nanoTime, then we are measuring elapsed time, which is not affected by wall-clock changes. But then we cannot compare with real time? Actually, we don't need real time, we need elapsed time. So we can use nanoTime for the refill calculation.
But note: the lastRefillTimestamp is stored as a long (milliseconds). If we use nanoTime, we have to store the lastRefillNanoTime. And then when we adjust for config change, we use the same clock.
Let's change:
We'll use System.nanoTime() for the refill calculations. But note: nanoTime returns nanoseconds, but we don't need that precision. We can convert to seconds.
However, the refillRate is in tokens per second, so we want the time passed in seconds.
So:
long now = System.nanoTime();
double timePassed = (now - lastRefillNanoTime) / 1_000_000_000.0;
But then we are storing lastRefillNanoTime as a long (nanoseconds). And we update it to the current nanoTime.
This avoids problems with system clock changes.
But note: the config change adjustment and the normal refill both use the same clock.
We can change the TokenBucket to store lastRefillNanoTime (long) instead of lastRefillTimestamp (milliseconds).
And then in the code, we use:
long now = System.nanoTime();
And then:
double timePassed = (now - bucket.lastRefillNanoTime) / 1_000_000_000.0;
And set bucket.lastRefillNanoTime = now.
And for the cleanup, we are using lastAccessTimestamp which is in wall-clock time? We are updating lastAccessTimestamp to System.currentTimeMillis()? Or to nanoTime? We are using it for cleanup, which is based on real time (wall-clock). So we should use currentTimeMillis for lastAccessTimestamp.
So we have two clocks:
- For token refill: we use a monotonic clock (nanoTime) to avoid issues with clock changes.
- For cleanup: we use wall-clock time (currentTimeMillis) because we want to clean up based on real time (e.g., 1 hour of real time).
So in the TokenBucket:
private long lastRefillNanoTime;
private volatile long lastAccessTimestamp; // wall-clock
In the constructor:
this.lastRefillNanoTime = System.nanoTime();
this.lastAccessTimestamp = System.currentTimeMillis();
In tryAcquire:
synchronized (bucket) {
long nowNano = System.nanoTime();
long nowMillis = System.currentTimeMillis();
// ... use nowNano for refill, and nowMillis for lastAccessTimestamp.
But note: we update lastAccessTimestamp to nowMillis, which is the wall-clock time of the request.
And for the config change adjustment, we use nowNano for the refill.
That should be okay.
However, what if the system clock changes between the time we update lastRefillNanoTime and lastAccessTimestamp? They are two different clocks, so it's okay.
Let's update the code accordingly.
But note: the initial lastRefillNanoTime and lastAccessTimestamp are set at the same time (in the constructor) but using two different clocks. That's okay because we are only using them for different purposes.
Now, we have to change the adjustBucketForConfigChange to use nanoTime.
We'll change:
In tryAcquire:
long nowNano = System.nanoTime();
long nowMillis = System.currentTimeMillis();
if (bucket.config.capacity != currentConfig.capacity || bucket.config.refillRate != currentConfig.refillRate) {
adjustBucketForConfigChange(bucket, currentConfig, nowNano);
} else {
double timePassed = (nowNano - bucket.lastRefillNanoTime) / 1_000_000_000.0;
double tokensToAdd = timePassed * bucket.config.refillRate;
bucket.tokens = Math.min(bucket.config.capacity, bucket.tokens + tokensToAdd);
bucket.lastRefillNanoTime = nowNano;
}
bucket.lastAccessTimestamp = nowMillis;
And adjustBucketForConfigChange:
private void adjustBucketForConfigChange(TokenBucket bucket, Config newConfig, long nowNano) {
double timePassed = (nowNano - bucket.lastRefillNanoTime) / 1_000_000_000.0;
double tokensToAdd = timePassed * bucket.config.refillRate;
double newTokens = Math.min(bucket.config.capacity, bucket.tokens + tokensToAdd);
bucket.tokens = Math.min(newConfig.capacity, newTokens);
bucket.lastRefillNanoTime = nowNano;
bucket.config = newConfig;
}
And in the TokenBucket:
long lastRefillNanoTime;
volatile long lastAccessTimestamp;
And in the constructor:
this.lastRefillNanoTime = System.nanoTime();
this.lastAccessTimestamp = System.currentTimeMillis();
Now, the cleanup uses lastAccessTimestamp (wall-clock) and removes if older than 1 hour (in milliseconds).
This should be robust.
Now, we have to consider that the lastRefillNanoTime and lastAccessTimestamp are updated at different times? Actually, we update both in the same synchronized block, but using different clocks. That's okay.
However, note that the lastRefillNanoTime is updated in the refill step (either adjustment or normal) and lastAccessTimestamp is updated at the end of the synchronized block (after refill and consume). So they are not exactly the same time, but that's okay because they serve different purposes.
Now, what about the case where the system time (wall-clock) changes? The lastAccessTimestamp is wall-clock, so if the system time jumps, then the cleanup might not work as expected? But cleanup is based on real time, so if the system time jumps forward, we might clean up too early? Or if it jumps backward, we might not clean up? That's a general problem with using wall-clock for cleanup. We might want to use a monotonic clock for cleanup too? But then we cannot set a fixed time (like 1 hour) because we don't know the real time.
Alternatively, we can use the same monotonic clock for cleanup? But then we are cleaning up based on elapsed time (since the last access) in terms of the monotonic clock. That's actually better because it's not affected by wall-clock changes.
Let's change: use a monotonic clock for both refill and cleanup.
We can store:
private volatile long lastAccessNanoTime;
And update it to nowNano in the synchronized block.
Then cleanup:
long nowNano = System.nanoTime();
map.entrySet().removeIf(entry -> {
TokenBucket bucket = entry.getValue();
return nowNano - bucket.lastAccessNanoTime > 60L * 60 * 1_000_000_000; // 1 hour in nanoseconds
});
But note: the cleanup thread might run for a long time, and the nanoTime might wrap around? nanoTime wraps around in about 292 years? So it's acceptable.
Alternatively, we can use millis for cleanup? But then we have the same problem with wall-clock changes.
So let's use nanoTime for both.
We change:
In TokenBucket:
private long lastRefillNanoTime;
private volatile long lastAccessNanoTime;
In constructor:
this.lastRefillNanoTime = System.nanoTime();
this.lastAccessNanoTime = this.lastRefillNanoTime;
In tryAcquire:
long nowNano = System.nanoTime();
// ... refill using nowNano
bucket.lastAccessNanoTime = nowNano;
In cleanup:
long nowNano = System.nanoTime();
map.entrySet().removeIf(entry -> {
TokenBucket bucket = entry.getValue();
return nowNano - bucket.lastAccessNanoTime > 60L * 60 * 1_000_000_000;
});
This way, we are using a monotonic clock for everything.
Now, the code is complete.
Let's write the final code.
Note: We are using a lot of double arithmetic, which might be a bit slow. We can use long for tokens if we use a fixed-point representation? But that's an optimization.
We'll leave it as double for simplicity.
Now, we have to consider that the tokens are double and we are comparing with 1. We can do:
if (bucket.tokens >= 1.0) ...
But note: due to floating point inaccuracies, we might have 0.9999999 and then we reject, but we should accept? Actually, we should not accept because we don't have a full token. But if we are refilling and we have 0.9999999, that means we are just short of a token. So it's correct.
However, if we are refilling and we get 1.0000001, then we accept and then subtract 1, leaving 0.0000001. That's okay.
Now, what about the case where we have 1.5 tokens? Then we can consume 1 and leave 0.5. That's acceptable.
So the code is:
public class RateLimiterService {
private static class TokenBucket {
double tokens;
long lastRefillNanoTime;
Config config;
volatile long lastAccessNanoTime;
TokenBucket(Config config) {
this.config = config;
this.tokens = config.capacity;
long now = System.nanoTime();
this.lastRefillNanoTime = now;
this.lastAccessNanoTime = now;
}
}
private final ConcurrentHashMap<String, TokenBucket> map = new ConcurrentHashMap<>();
private final ConfigProvider configProvider;
private final Config defaultConfig;
public RateLimiterService(ConfigProvider configProvider, Config defaultConfig) {
this.configProvider = configProvider;
this.defaultConfig = defaultConfig;
}
public boolean tryAcquire(String key) {
TokenBucket bucket = map.computeIfAbsent(key, k -> new TokenBucket(defaultConfig));
synchronized (bucket) {
Config currentConfig = configProvider.getConfig(key);
long nowNano = System.nanoTime();
if (bucket.config.capacity != currentConfig.capacity || bucket.config.refillRate != currentConfig.refillRate) {
adjustBucketForConfigChange(bucket, currentConfig, nowNano);
} else {
double timePassed = (nowNano - bucket.lastRefillNanoTime) / 1_000_000_000.0;
double tokensToAdd = timePassed * bucket.config.refillRate;
bucket.tokens = Math.min(bucket.config.capacity, bucket.tokens + tokensToAdd);
bucket.lastRefillNanoTime = nowNano;
}
bucket.lastAccessNanoTime = nowNano;
if (bucket.tokens >= 1.0) {
bucket.tokens -= 1.0;
return true;
} else {
return false;
}
}
}
private void adjustBucketForConfigChange(TokenBucket bucket, Config newConfig, long nowNano) {
double timePassed = (nowNano - bucket.lastRefillNanoTime) / 1_000_000_000.0;
double tokensToAdd = timePassed * bucket.config.refillRate;
double newTokens = Math.min(bucket.config.capacity, bucket.tokens + tokensToAdd);
bucket.tokens = Math.min(newConfig.capacity, newTokens);
bucket.lastRefillNanoTime = nowNano;
bucket.config = newConfig;
}
public void startCleanupThread() {
new Thread(() -> {
while (true) {
try {
Thread.sleep(60 * 60 * 1000); // 1 hour in milliseconds? But we are using nanoTime for cleanup? We are using nanoTime for cleanup in the cleanup method.
// But we are sleeping for 1 hour in millis, which is okay.
cleanup();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}).start();
}
private void cleanup() {
long nowNano = System.nanoTime();
map.entrySet().removeIf(entry -> {
TokenBucket bucket = entry.getValue();
return nowNano - bucket.lastAccessNanoTime > 60L * 60 * 1_000_000_000;
});
}
}
But note: the cleanup thread sleeps for 1 hour (in milliseconds) and then runs cleanup. The cleanup uses nanoTime, so it's consistent.
However, the sleep might not be exactly 1 hour, but that's okay.
Now, we have a rate limiter that:
- Isolates keys.
- Supports token bucket with bursting (capacity) and average rate (refillRate).
- Supports dynamic configuration changes (with adjustment).
- Cleans up unused buckets.
This should meet the requirements.
However, note that the configProvider.getConfig(key) is called on every request. If the configProvider is slow, we might want to cache the config in the bucket and only call the provider when we suspect a change? But we don't have a way to know. We can have the configProvider implement a push model? That's beyond the scope.
Alternatively, we can have the bucket store the config and a version number, and the configProvider returns a config with a version. Then we compare the version. But that's similar.
We'll leave it as is.
Now, what about the case where the config is changed and we adjust the bucket, but then the same request that triggered the adjustment also consumes a token? That's intended.
Now, what about the case where we have a burst that exceeds the capacity? We reject the excess.
Now, what about the case where we have a very high QPS for a single key? The synchronized block on the bucket might be a bottleneck. We can try to use a striped lock? But then we have to map the key to a stripe. That would reduce contention for hot keys? Actually, if we have one hot key, we still have to synchronize on the same stripe. So it doesn't help for a single key.
We can use an atomic operation? We can try to use an atomic reference to the bucket and then use compareAndSet? But we have to update multiple fields (tokens, lastRefillNanoTime, config). That's not atomic.
Alternatively, we can use a data structure that allows lock-free updates? That's complex.
Given that the lock is per key, and if we have a very high QPS for a single key, we might need to shard that key? But that's application specific.
We can leave it as is.
This is a basic implementation. In production, we might need to consider:
- More efficient data structures (e.g., using LongAdder for tokens? But we need to update multiple fields atomically).
- A more sophisticated cleanup (e.g., using a priority queue of lastAccessNanoTime).
- Metrics and monitoring.
- etc.
But for the purpose of this problem, this should be acceptable.
Let me know if you have any questions.
I'll design a comprehensive rate limiter service that handles quotas, token buckets, bursting, and isolation. This will be a distributed-ready service with multiple implementation options.
Architecture Overview
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Client App │───▶│ Rate Limiter │───▶│ Backend API │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐
│ Storage Layer │
│ (Redis/DB/Cache)│
└─────────────────┘
Core Components
1. Token Bucket Algorithm with Bursting
class TokenBucket:
def __init__(self, capacity: int, refill_rate: float):
"""
capacity: max tokens (burst size)
refill_rate: tokens per second (average rate)
"""
self.capacity = capacity
self.refill_rate = refill_rate # tokens/second
self.tokens = capacity # start full
self.last_refill = time.time()
def consume(self, tokens: int = 1) -> bool:
now = time.time()
# Refill based on elapsed time
elapsed = now - self.last_refill
self.tokens = min(
self.capacity,
self.tokens + elapsed * self.refill_rate
)
self.last_refill = now
if self.tokens >= tokens:
self.tokens -= tokens
return True
return False
2. Quota Management (Fixed Window + Sliding Window)
class QuotaManager:
def __init__(self):
# Fixed window counter (simple quotas)
self.fixed_windows = defaultdict(lambda: defaultdict(int))
# Sliding window log (for precise quotas)
self.request_logs = defaultdict(list)
def check_quota(self, key: str, quota: int, window_seconds: int) -> bool:
now = time.time()
# Fixed window approach (simpler, less precise)
window_key = f"{key}:{int(now // window_seconds)}"
if self.fixed_windows[window_key] >= quota:
return False
# Sliding window log (more precise, memory heavy)
cutoff = now - window_seconds
self.request_logs[key] = [t for t in self.request_logs[key] if t > cutoff]
if len(self.request_logs[key]) >= quota:
return False
return True
def record_request(self, key: str):
self.fixed_windows[f"{key}:{int(time.time() // 60)}"] += 1
self.request_logs[key].append(time.time())
3. Isolation Strategies
class IsolationManager:
def __init__(self):
# Hierarchical rate limiting
self.hierarchical_limits = {
"global": TokenBucket(10000, 100), # Global limit
"tenant": {}, # Per-tenant limits
"user": {}, # Per-user limits
"endpoint": {} # Per-endpoint limits
}
# Connection pooling per client
self.connection_pools = defaultdict(ConnectionPool)
# Memory/cpu isolation (if using containerization)
self.resource_limits = {}
def is_isolated_violation(self, client_id: str, limit_type: str) -> bool:
"""Check if client is violating isolation boundaries"""
# Check hierarchical limits
for level in ["global", "tenant", "user", "endpoint"]:
if not self.check_limit(client_id, level):
return True
return False
4. Distributed Implementation (Redis-based)
import redis
import json
import time
class RedisTokenBucket:
def __init__(self, redis_client: redis.Redis, key: str,
capacity: int, refill_rate: float):
self.redis = redis_client
self.key = key
self.capacity = capacity
self.refill_rate = refill_rate
self.lua_script = """
local tokens = tonumber(redis.call('GET', KEYS[1]))
local last_refill = tonumber(redis.call('GET', KEYS[2]))
local now = tonumber(ARGV[1])
local requested = tonumber(ARGV[2])
local capacity = tonumber(ARGV[3])
local refill_rate = tonumber(ARGV[4])
if tokens == nil then
tokens = capacity
last_refill = now
else
local delta = now - last_refill
tokens = math.min(capacity, tokens + delta * refill_rate)
last_refill = now
end
if tokens >= requested then
tokens = tokens - requested
redis.call('SET', KEYS[1], tokens)
redis.call('SET', KEYS[2], last_refill)
return 1
else
redis.call('SET', KEYS[1], tokens)
redis.call('SET', KEYS[2], last_refill)
return 0
end
"""
def consume(self, tokens: int = 1) -> bool:
now = time.time()
result = self.redis.eval(
self.lua_script,
2,
f"{self.key}:tokens",
f"{self.key}:last_refill",
now, tokens, self.capacity, self.refill_rate
)
return bool(result)
5. Complete Service Implementation
from typing import Optional, Dict, Any
from dataclasses import dataclass
from enum import Enum
import asyncio
class LimitType(Enum):
REQUESTS = "requests"
BANDWIDTH = "bandwidth"
COMPUTE = "compute"
@dataclass
class RateLimitConfig:
tenant_id: str
user_id: Optional[str] = None
endpoint: Optional[str] = None
limits: Dict[LimitType, Dict[str, float]] = None # {type: {"capacity": int, "rate": float}}
def __post_init__(self):
if self.limits is None:
self.limits = {}
class RateLimiterService:
def __init__(self,
storage_backend: str = "redis",
redis_url: str = "redis://localhost:6379",
default_quota: int = 1000,
default_window: int = 60):
self.storage = self._init_storage(storage_backend, redis_url)
self.default_quota = default_quota
self.default_window = default_window
self.configs = {} # In-memory config cache
self.isolation = IsolationManager()
def _init_storage(self, backend: str, url: str):
if backend == "redis":
import redis
return redis.Redis.from_url(url)
# Add other backends: memory, memcached, database
return InMemoryStorage()
async def check_rate_limit(self,
client_id: str,
config: RateLimitConfig,
limit_type: LimitType = LimitType.REQUESTS) -> Dict[str, Any]:
"""
Comprehensive rate limit check with bursting and isolation
Returns: {
"allowed": bool,
"remaining": int,
"reset_after": float,
"violations": list[str]
}
"""
violations = []
# 1. Check isolation violations
if self.isolation.is_isolated_violation(client_id, "global"):
violations.append("global_isolation_violation")
# 2. Check hierarchical limits
for level in ["tenant", "user", "endpoint"]:
bucket_key = self._get_bucket_key(client_id, config, level, limit_type)
bucket = self._get_or_create_bucket(bucket_key, config, level, limit_type)
if not bucket.consume():
violations.append(f"{level}_limit_exceeded")
# 3. Check quota
quota_key = self._get_quota_key(client_id, config, limit_type)
if not self._check_quota(quota_key, config, limit_type):
violations.append("quota_exceeded")
# 4. Check burst limits
burst_key = self._get_burst_key(client_id, config, limit_type)
if not self._check_burst(burst_key, config, limit_type):
violations.append("burst_limit_exceeded")
return {
"allowed": len(violations) == 0,
"remaining": self._get_remaining(client_id, config, limit_type),
"reset_after": self._get_reset_time(client_id, config, limit_type),
"violations": violations
}
def _get_bucket_key(self, client_id: str, config: RateLimitConfig,
level: str, limit_type: LimitType) -> str:
parts = [config.tenant_id]
if level == "user" and config.user_id:
parts.append(f"user:{config.user_id}")
if level == "endpoint" and config.endpoint:
parts.append(f"endpoint:{config.endpoint}")
parts.append(limit_type.value)
return ":".join(parts)
def _get_or_create_bucket(self, key: str, config: RateLimitConfig,
level: str, limit_type: LimitType):
# Get from cache or storage
if key not in self.configs:
limit_config = config.limits.get(limit_type, {})
capacity = limit_config.get("capacity", self.default_quota)
rate = limit_config.get("rate", self.default_quota / self.default_window)
self.configs[key] = self.storage.get_bucket(key) or \
TokenBucket(capacity, rate)
return self.configs[key]
def _check_quota(self, key: str, config: RateLimitConfig,
limit_type: LimitType) -> bool:
# Simplified: use sliding window log
now = time.time()
window = config.limits.get(limit_type, {}).get("window", self.default_window)
quota = config.limits.get(limit_type, {}).get("quota", self.default_quota)
logs = self.storage.get_logs(key, now - window, now)
return len(logs) < quota
def _check_burst(self, key: str, config: RateLimitConfig,
limit_type: LimitType) -> bool:
# Separate burst bucket (smaller capacity, faster refill)
burst_key = f"{key}:burst"
burst_capacity = config.limits.get(limit_type, {}).get("burst_capacity", 10)
burst_rate = config.limits.get(limit_type, {}).get("burst_rate", 100)
bucket = self._get_or_create_bucket(burst_key, config, "burst", limit_type)
return bucket.consume()
6. Configuration Management
class ConfigManager:
def __init__(self):
self.configs = {
# Default tier configurations
"free": {
RateLimitType.REQUESTS: {"capacity": 100, "rate": 1.67}, # 100/hour
RateLimitType.BANDWIDTH: {"capacity": 1024*1024, "rate": 1024} # 1MB/s
},
"basic": {
RateLimitType.REQUESTS: {"capacity": 1000, "rate": 16.67}, # 1000/hour
RateLimitType.BANDWIDTH: {"capacity": 10*1024*1024, "rate": 10*1024}
},
"premium": {
RateLimitType.REQUESTS: {"capacity": 10000, "rate": 166.67},
RateLimitType.BANDWIDTH: {"capacity": 100*1024*1024, "rate": 100*1024}
}
}
def get_config(self, tenant_id: str, tier: str) -> RateLimitConfig:
base_config = self.configs.get(tier, self.configs["free"]).copy()
# Apply tenant-specific overrides
overrides = self._get_tenant_overrides(tenant_id)
base_config.update(overrides)
return RateLimitConfig(
tenant_id=tenant_id,
limits=base_config
)
7. Monitoring & Metrics
class MetricsCollector:
def __init__(self):
self.stats = defaultdict(lambda: defaultdict(lambda: {
"allowed": 0,
"blocked": 0,
"burst_used": 0,
"quota_used": 0
}))
def record(self, client_id: str, limit_type: LimitType, allowed: bool):
key = f"{client_id}:{limit_type.value}"
self.stats[key]["allowed" if allowed else "blocked"] += 1
def get_usage_report(self, client_id: str) -> Dict:
return dict(self.stats.get(client_id, {}))
8. Service API (FastAPI Example)
from fastapi import FastAPI, Request, HTTPException, Depends
from fastapi.responses import JSONResponse
app = FastAPI()
rate_limiter = RateLimiterService(
storage_backend="redis",
redis_url="redis://localhost:6379"
)
@app.middleware("http")
async def rate_limit_middleware(request: Request, call_next):
client_id = request.headers.get("X-Client-ID", "anonymous")
tenant_id = request.headers.get("X-Tenant-ID", "default")
config = ConfigManager().get_config(tenant_id, "free")
result = await rate_limiter.check_rate_limit(
client_id=client_id,
config=config,
limit_type=LimitType.REQUESTS
)
if not result["allowed"]:
raise HTTPException(
status_code=429,
detail="Too many requests",
headers={
"X-RateLimit-Limit": str(config.limits[LimitType.REQUESTS]["capacity"]),
"X-RateLimit-Remaining": str(result["remaining"]),
"X-RateLimit-Reset": str(result["reset_after"]),
"Retry-After": str(int(result["reset_after"]))
}
)
response = await call_next(request)
response.headers["X-RateLimit-Limit"] = str(config.limits[LimitType.REQUESTS]["capacity"])
response.headers["X-RateLimit-Remaining"] = str(result["remaining"])
return response
@app.get("/admin/usage/{client_id}")
async def get_usage(client_id: str):
return rate_limiter.get_usage_report(client_id)
@app.post("/admin/config/{tenant_id}")
async def update_config(tenant_id: str, config: RateLimitConfig):
# Dynamic config updates
rate_limiter.update_config(tenant_id, config)
return {"status": "updated"}
Key Features Explained
1. Quotas (Fixed Allocation)
- Fixed Window: Simple counting within time windows (e.g., 100 requests/minute)
- Sliding Window: More precise using request logs
- Configurable per tenant/user/endpoint
2. Token Buckets (Bursting)
- Capacity: Max tokens = burst size
- Refill Rate: Sustainable rate (tokens/second)
- Allows bursts up to capacity while maintaining average rate
3. Hierarchical Isolation
Global Limit (10k req/s)
├── Tenant A (5k req/s)
│ ├── User A1 (1k req/s)
│ └── User A2 (1k req/s)
└── Tenant B (5k req/s)
├── User B1 (500 req/s)
└── User B2 (500 req/s)
- Each level enforces its own limits
- Violations cascade up the hierarchy
4. Multi-Dimensional Limits
- Requests: API call count
- Bandwidth: Data transfer
- Compute: CPU/time units
- Concurrent Connections: Active sessions
5. Distributed Considerations
- Redis Lua scripts for atomic operations
- Local cache for hot keys (Caffeine/Guava)
- Eventual consistency for config updates
- Clock synchronization (use monotonic clocks)
6. Burst Handling Strategies
# Different burst profiles:
configs = {
"ecommerce": {
"requests": {"capacity": 100, "rate": 10}, # 100 burst, 10/s sustained
"burst_profile": "aggressive" # allow large initial bursts
},
"analytics": {
"requests": {"capacity": 10, "rate": 1}, # Small bursts
"burst_profile": "conservative"
}
}
Deployment Recommendations
-
Storage Selection:
- Redis: Best for distributed, low-latency
- Memcached: Simpler, but no persistence
- Database: For audit trails, but slower
- In-memory: Single node, fastest
-
Scaling:
# Horizontal scaling with consistent hashing
sharding:
strategy: "consistent_hash"
virtual_nodes: 100
replication: 2
-
High Availability:
- Redis Cluster/Sentinel
- Active-active replication
- Local cache fallback
-
Monitoring:
# Key metrics
rate_limiter_requests_total{client="abc",result="allowed"}
rate_limiter_bucket_tokens{client="abc",level="user"}
rate_limiter_violations_total{type="quota_exceeded"}
Trade-offs
| Strategy | Pros | Cons | Use Case |
|---|
| Token Bucket | Smooth bursting, simple | Memory per key | General APIs |
| Fixed Window | Simple, no state | Burst at window boundaries | Simple quotas |
| Sliding Log | Precise, no bursts | Memory grows with requests | Billing systems |
| Leaky Bucket | Constant output rate | No bursting | Traffic shaping |
Advanced Features (Optional)
- Dynamic Adjustment: ML-based rate adjustment based on usage patterns
- Priority Queues: Premium customers get preferential treatment
- Grace Periods: Allow temporary violations with warning
- Cost-based Limiting: Different costs for different endpoints
- Geo-distributed: Region-aware rate limiting
This implementation provides a production-ready, scalable rate limiter with:
- ✅ Quotas: Fixed allocation per time window
- ✅ Tokens: Token bucket for smooth rate control
- ✅ Bursting: Configurable burst capacity
- ✅ Isolation: Multi-level hierarchical limits
- ✅ Distributed: Redis-based for horizontal scaling
- ✅ Observable: Full metrics and monitoring
- ✅ Flexible: Multiple limit types and strategies
Would you like me to elaborate on any specific component or add additional features like priority queues, dynamic adjustment algorithms, or specific storage backend implementations?