Couchbase API rate limiter

Couchbase API rate limiter

Couchbase API rate limiter

If you are building any kind of API then you now, or at least you should now, that limiting the number of requests is one of the most important parts of your system. You don't want to allow anyone to hammer your endpoints without any kind of limitations. The more popular your app is becoming, the more you have to care about protecting your API endpoints.

Most PHP frameworks today have a concept of the middleware. The middleware is a layer that stands between the user request and your app, and this is the perfect place to put the request limiting mechanism. Before any request reaches your app, it has to pass through middleware. To count the number of incoming request per user you must have some sort of storage to persist data, and this storage has to be fast, in order to avoid slowing down your app.

NoSQL databases are growing in popularity every day, and because their key/value nature they are the perfect storage for request limiting layer. Couchbase is one of the most popular NoSQL databases today, and if you are creating an app that uses this database, then using it also to store request data is a perfect solution. My recommendation is to create a separate bucket for storing temporary data, in order to avoid mixing it with your business data.

I created a simple middleware that counts the number of incoming request from IP addresses per unit of time. IP address is saved as a key, and the number of requests from that address is an integer value. When you combine this, with a Couchbase document that has an expiration date (so called time to live - TTL), you get simple but powerful and fast rate limiter. This package was originally written for integration with Slim framework, but you could use it with your custom project or with other frameworks. To install the package, use Composer:

composer require gnikolovski/cb-rate-limiter

If you want to see the documentation or code please visit project's Github page, where you will find more details on how to use this package.

You may also like

Drupal 8 and Behat tests

Adding automated tests to small or create-and-forget projects probably doesn't make sense. You will spend additional time writing those tests, and this will only increase the project's cost. And you will get almost nothing in return. But, if you are working on a project that will be maintained in the future and new features will be added on a regular basis, then you most certainly need to add automated tests.

Drupal 8, nginx and Let's Encrypt

This site is powered by Drupal 8. I'm using nginx as a web server and Let's Encrypt to add HTTPS encryption to my site. In this post I will show you how my nginx config file looks like.