Using Bottleneck with Rails


This post is a next part of my previous post about Bottleneck gem.


Useful links:

Rails gem called Bottleneck.

And Rails Application to demonstrate gem usage.


Simple Rails based application, which uses https://github.com/maratgaliev/bottleneck as a requests rate limiter.

Application configuration

First of all we need to create for example Rails application with api flag, and add bottleneck gem into Gemfile.

gem 'bottleneck'

And we need two config files for application configuration:

bottleneck.yml

limits:
  time_period_seconds: 3600
  max_requests_count: 100

redis.yml

host: 'localhost'
port: 6379

Super simple implementation of rate limitter with before_action in our ApplicationController:

class ApplicationController < ActionController::API
  before_action :check_limit

  private

  def check_limit
    result = Bottleneck.check(request.remote_ip)
    render status: result[:status], json: { message: result[:message] }
  end
end

Let’s check how it works

Normal request:

ok

Limit reached:

limit