Skip to content

Instantly share code, notes, and snippets.

View ciaranlee's full-sized avatar

Ciaran Lee ciaranlee

View GitHub Profile

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.

@gregorymostizky
gregorymostizky / sinatra_fiber.rb
Created December 28, 2010 18:27
Patches async sinatra to use Fiber.new{}.resume for every request
#encoding: utf-8
# Patches async sinatra to use Fiber.new{}.resume for every request
require "sinatra/async"
require "fiber"
module Sinatra
module Async
module Helpers
require "resque"
require "resque/failure/multiple"
require "resque/failure/redis"
require 'exceptional'
# Configure Resque connection from config/resque.yml. This file should look
# something like:
# development: localhost:6379
# test: localhost:6379:15
# production: localhost:6379
desc "A Task watched by Exceptional"
task :do_something => :environment do
Exceptional.rescue('Error doing something') do
# do something
end
end
# checkout: http://github.com/igrigorik/async-rails/
From bb2a78858cffa7c6937642986e9aca1a4f862c0d Mon Sep 17 00:00:00 2001
From: Ilya Grigorik <ilya@igvita.com>
Date: Thu, 10 Jun 2010 00:46:48 -0400
Subject: [PATCH] async rails3
---
Gemfile | 6 ++++++
app/controllers/widgets_controller.rb | 6 ++++++