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.

@vasanthk
vasanthk / System Design.md
Last active July 15, 2024 10:23
System Design Cheatsheet

System Design Cheatsheet

Picking the right architecture = Picking the right battles + Managing trade-offs

Basic Steps

  1. Clarify and agree on the scope of the system
  • User cases (description of sequences of events that, taken together, lead to a system doing something useful)
    • Who is going to use it?
    • How are they going to use it?
@pdu
pdu / inorder_traversal_iterative.cpp
Last active December 10, 2015 08:08
Given a binary tree, return the inorder traversal of its nodes' values. http://www.leetcode.com/onlinejudge
#include <stack>
using namespace std;
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
@pdu
pdu / MyRWLock.cpp
Last active May 19, 2016 02:06
algos: use mutex to implement read-write lock
extern "C"
{
#include <pthread.h>
}
class MyRWLock
{
public:
MyRWLock();
~MyRWLock();