Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 10 additions & 8 deletions docs/content/en/docs/documentation/rate-limiting.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,15 @@ implementation, in particular, on how long a typical reconciliation takes.

Rate limiting is configured per controller, see [ControllerConfiguration](https://github.com/operator-framework/java-operator-sdk/blob/e976fb80d62f6bd0f714d78cec0a7a38d9b4a928/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/api/config/ControllerConfiguration.java#L81).

## The default LinearRateLimiter
## Default rate limiter

We provide a generic rate limiter implementation:
[`LinearRateLimiter`](https://github.com/java-operator-sdk/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/LinearRateLimiter.java).
The SDK uses `LinearRateLimiter` by default for compatibility with existing
applications. This deprecated class delegates to
[`SlidingWindowRateLimiter`](https://github.com/operator-framework/java-operator-sdk/blob/main/operator-framework-core/src/main/java/io/javaoperatorsdk/operator/processing/event/rate/SlidingWindowRateLimiter.java).

To configure it, use the `@RateLimited` annotation on your `Reconciler` class. The following
configuration limits each resource to reconcile at most twice within a 3 second interval:
configuration allows each resource up to two reconciliation submissions in any rolling
three-second interval:

```java
@RateLimited(maxReconciliations = 2, within = 3, unit = TimeUnit.SECONDS)
Expand All @@ -31,10 +33,10 @@ public class MyReconciler implements Reconciler<MyCR> {
}
```

Thus, if a given resource was reconciled twice in one second, no further reconciliation for this
resource will happen before two seconds have elapsed. Note that, since rate limiting is on a
per-resource basis, other resources can still be reconciled at the same time, as long as
they stay within their own rate limits.
A resource can use both permits in quick succession. Once it uses both, its next
reconciliation is eligible three seconds after the older submission. Each resource
has its own rate limit. If you change the permit limit with `initFrom`, submissions
already recorded in the rolling window count toward the new limit.

## Custom Rate Limiter

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,26 @@

import java.time.Duration;
import java.util.Optional;
import java.util.function.LongSupplier;

import io.javaoperatorsdk.operator.api.config.AnnotationConfigurable;

/** A simple rate limiter that limits the number of permission for a time interval. */
/**
* @deprecated Use {@link SlidingWindowRateLimiter} instead.
*/
@Deprecated
public class LinearRateLimiter
implements RateLimiter<RateState>, AnnotationConfigurable<RateLimited> {

/** To turn off rate limiting set limit for period to a non-positive number */
public static final int NO_LIMIT_PERIOD = -1;
public static final int NO_LIMIT_PERIOD = SlidingWindowRateLimiter.NO_LIMIT_PERIOD;

public static final int DEFAULT_REFRESH_PERIOD_SECONDS = 10;
public static final int DEFAULT_REFRESH_PERIOD_SECONDS =
SlidingWindowRateLimiter.DEFAULT_REFRESH_PERIOD_SECONDS;
public static final Duration DEFAULT_REFRESH_PERIOD =
Duration.ofSeconds(DEFAULT_REFRESH_PERIOD_SECONDS);
SlidingWindowRateLimiter.DEFAULT_REFRESH_PERIOD;

private Duration refreshPeriod;
private int limitForPeriod;
private final SlidingWindowRateLimiter delegate;

public static LinearRateLimiter deactivatedRateLimiter() {
return new LinearRateLimiter();
Expand All @@ -43,48 +47,40 @@ public LinearRateLimiter() {
}

public LinearRateLimiter(Duration refreshPeriod, int limitForPeriod) {
this.refreshPeriod = refreshPeriod;
this.limitForPeriod = limitForPeriod;
this(refreshPeriod, limitForPeriod, System::nanoTime);
}

LinearRateLimiter(Duration refreshPeriod, int limitForPeriod, LongSupplier nanoTime) {
delegate = new SlidingWindowRateLimiter(refreshPeriod, limitForPeriod, nanoTime);
}

@Override
public Optional<Duration> isLimited(RateLimitState rateLimitState) {
if (!isActivated() || !(rateLimitState instanceof RateState actualState)) {
return Optional.empty();
}
var now = System.nanoTime();
var periodNanos = refreshPeriod.toNanos();
var elapsedNanos = now - actualState.getLastRefreshNanos();
if (elapsedNanos > periodNanos) {
actualState.reset(now);
}
if (actualState.getCount() < limitForPeriod) {
actualState.increaseCount();
if (!isActivated() || !(rateLimitState instanceof RateState)) {
return Optional.empty();
}
return Optional.of(Duration.ofNanos(Math.max(0, periodNanos - elapsedNanos)));
return delegate.isLimited(rateLimitState);
}

@Override
public RateState initState() {
return RateState.initialState();
return new RateState();
}

@Override
public void initFrom(RateLimited configuration) {
this.refreshPeriod = Duration.of(configuration.within(), configuration.unit().toChronoUnit());
this.limitForPeriod = configuration.maxReconciliations();
delegate.initFrom(configuration);
}

public boolean isActivated() {
return limitForPeriod > 0;
return delegate.isActivated();
}

public int getLimitForPeriod() {
return limitForPeriod;
return delegate.getLimitForPeriod();
}

public Duration getRefreshPeriod() {
return refreshPeriod;
return delegate.getRefreshPeriod();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,36 +15,8 @@
*/
package io.javaoperatorsdk.operator.processing.event.rate;

import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter.RateLimitState;

class RateState implements RateLimitState {

private long lastRefreshNanos;
private int count;

public static RateState initialState() {
return new RateState(System.nanoTime(), 0);
}

RateState(long lastRefreshNanos, int count) {
this.lastRefreshNanos = lastRefreshNanos;
this.count = count;
}

public void increaseCount() {
count = count + 1;
}

public void reset(long nowNanos) {
lastRefreshNanos = nowNanos;
count = 0;
}

public long getLastRefreshNanos() {
return lastRefreshNanos;
}

public int getCount() {
return count;
}
}
/**
* @deprecated Use {@link SlidingWindowRateState} instead.
*/
@Deprecated
class RateState extends SlidingWindowRateState {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* Copyright Java Operator SDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.javaoperatorsdk.operator.processing.event.rate;

import java.time.Duration;
import java.util.Optional;
import java.util.function.LongSupplier;

import io.javaoperatorsdk.operator.api.config.AnnotationConfigurable;

/** Limits reconciliation submissions per resource over a rolling time window. */
public class SlidingWindowRateLimiter
implements RateLimiter<SlidingWindowRateState>, AnnotationConfigurable<RateLimited> {

/** To turn off rate limiting set limit for period to a non-positive number */
public static final int NO_LIMIT_PERIOD = -1;

public static final int DEFAULT_REFRESH_PERIOD_SECONDS = 10;
public static final Duration DEFAULT_REFRESH_PERIOD =
Duration.ofSeconds(DEFAULT_REFRESH_PERIOD_SECONDS);

private final LongSupplier nanoTime;
private Duration refreshPeriod;
private int limitForPeriod;

public static SlidingWindowRateLimiter deactivatedRateLimiter() {
return new SlidingWindowRateLimiter();
}

public SlidingWindowRateLimiter() {
this(DEFAULT_REFRESH_PERIOD, NO_LIMIT_PERIOD);
}

public SlidingWindowRateLimiter(Duration refreshPeriod, int limitForPeriod) {
this(refreshPeriod, limitForPeriod, System::nanoTime);
}

SlidingWindowRateLimiter(Duration refreshPeriod, int limitForPeriod, LongSupplier nanoTime) {
this.nanoTime = nanoTime;
this.refreshPeriod = refreshPeriod;
this.limitForPeriod = limitForPeriod;
}

@Override
public Optional<Duration> isLimited(RateLimitState rateLimitState) {
if (!isActivated() || !(rateLimitState instanceof SlidingWindowRateState actualState)) {
return Optional.empty();
}
var waitNanos =
actualState.tryAcquire(nanoTime.getAsLong(), refreshPeriod.toNanos(), limitForPeriod);
return waitNanos == 0 ? Optional.empty() : Optional.of(Duration.ofNanos(waitNanos));
}

@Override
public SlidingWindowRateState initState() {
return new SlidingWindowRateState();
}

@Override
public void initFrom(RateLimited configuration) {
this.refreshPeriod = Duration.of(configuration.within(), configuration.unit().toChronoUnit());
this.limitForPeriod = configuration.maxReconciliations();
}

public boolean isActivated() {
return limitForPeriod > 0;
}

public int getLimitForPeriod() {
return limitForPeriod;
}

public Duration getRefreshPeriod() {
return refreshPeriod;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright Java Operator SDK Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.javaoperatorsdk.operator.processing.event.rate;

import io.javaoperatorsdk.operator.processing.event.rate.RateLimiter.RateLimitState;

public class SlidingWindowRateState implements RateLimitState {

private long[] grants;
private int firstGrantIndex;
private int size;

long tryAcquire(long now, long periodNanos, int limit) {
while (size > 0 && now - grants[firstGrantIndex] >= periodNanos) {
firstGrantIndex = grantIndex(1);
size--;
}
if (size >= limit) {
var elapsedNanos = now - grants[grantIndex(size - limit)];
return periodNanos - elapsedNanos;
}
if (grants == null) {
grants = new long[1];
} else if (size == grants.length) {
grow(limit);
}
grants[grantIndex(size)] = now;
size++;
return 0;
}

private int grantIndex(int offset) {
var remaining = grants.length - firstGrantIndex;
return offset < remaining ? firstGrantIndex + offset : offset - remaining;
}

private void grow(int limit) {
var capacity = grants.length;
var expanded = new long[capacity + Math.min(capacity, limit - capacity)];
var remaining = capacity - firstGrantIndex;
System.arraycopy(grants, firstGrantIndex, expanded, 0, remaining);
System.arraycopy(grants, 0, expanded, remaining, firstGrantIndex);
grants = expanded;
firstGrantIndex = 0;
}
}
Loading