Skip to content

Instantly share code, notes, and snippets.

Scaling your API with rate limiters

The following are examples of the four types rate limiters discussed in the accompanying blog post. In the examples below I've used pseudocode-like Ruby, so if you're unfamiliar with Ruby you should be able to easily translate this approach to other languages. Complete examples in Ruby are also provided later in this gist.

In most cases you'll want all these examples to be classes, but I've used simple functions here to keep the code samples brief.

Request rate limiter

This uses a basic token bucket algorithm and relies on the fact that Redis scripts execute atomically. No other operations can run between fetching the count and writing the new count.

MetricRegistry metrics = new MetricRegistry();
GraphiteReporter reporter = GraphiteReporter.forRegistry(metrics)
.prefixedWith(metricPrefix)
.build(new Graphite(graphiteHost, graphitePort));
reporter.start(reportingPeriod, TimeUnit.MINUTES);
Meter meter = metrics.meter(meterName);
String output = "value";
ListenableFuture<String> future = Futures.immediateFuture(output);
Optional<String> transformedOutput = Promise.wrap(future)
.then(value -> value + "_a")
.then(value -> value + "_b")
.get(exception -> log.error(exception.getMessage()));
String output = "value";
ListenableFuture<String> future = Futures.immediateFuture(output);
String transformedOutput = Promise.wrap(future)
.then(value -> value + "_a")
.then(value -> value + "_b")
.get();
String output = "value";
ListenableFuture<String> future = Futures.immediateFuture(output);
ListenableFuture<String> firstTransformedFuture = Futures.transform(
future, (Function<String, String>) value -> value + "_a"
);
ListenableFuture<String> secondTransformedFuture = Futures.transform(
firstTransformedFuture, (Function<String, String>) value -> value + "_b"
);
public boolean isValid(Data data) {
boolean valid = validator.validate(data);
if (!valid) {
monitoringServiceClient.notifyOfInvalidData(data);
}
return valid;
}
// This is the fake we create
Database fakeDatabase = new Database() {
Map<Long, ApplicationKey> applications = Maps.newHashMap(
APP_ID, new ApplicationKey(APP_ID, Status.REVOKED)
);
@Override
public ApplicationKey getApplicationKey(Long id) {
return applications.get(id);
}
// This is the stub generated by our fictional framework
Database mockDatabase = mock(Database.class);
// Class that we want to test and that uses mockDatabase
ApplicationService service = new ApplicationService(stubDatabase);
// Here we are telling the stub what to return
when(mockDatabase.getApplicationKey(APP_ID))
.thenReturn(new ApplicationKey(APP_ID, Status.REVOKED));
// This is the stub generated by our fictional framework
Database stubDatabase = stub(Database.class);
// Class that we want to test and that uses stubDatabase
ApplicationService service = new ApplicationService(stubDatabase);
// Here we are telling the stub what to return
when(stubDatabase.getApplicationKey(APP_ID))
.thenReturn(new ApplicationKey(APP_ID, Status.REVOKED));
public interface Database {
// ...
}
public class RealDatabase implements Database {
// ...
}
public class TestDoubleDatabase implements Database {
// ...