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.

@pas256
pas256 / disable-branch-protection.sh
Created October 22, 2022 04:39 — forked from tiesmaster/disable-branch-protection.sh
Enable/disable branch protection on GitHub through their API
#!/bin/bash
OAUTH2_TOKEN=<fill in your own OAUTH2 token>
OWNER=tiesmaster
REPO=Coolkit.Converters # retrieve this with: basename $(git config --get remote.origin.url) .git
curl https://api.github.com/repos/${OWNER}/${REPO}/branches/master \
-H "Authorization: token $OAUTH2_TOKEN" \
-H "Accept: application/vnd.github.loki-preview+json" \
@pas256
pas256 / ribalancer.py
Last active September 17, 2018 22:06 — forked from dialtone/ribalancer.py
Balance RI Instances
import boto3
import argparse
from pprint import pprint as pp
from dateutil.tz import tzutc
from datetime import datetime, timedelta
from collections import defaultdict as dd
class IL(object):
"""