Skip to content

Instantly share code, notes, and snippets.

View stulentsev's full-sized avatar

Sergey Tulentsev stulentsev

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.

@stulentsev
stulentsev / pq.go
Created June 26, 2019 11:08 — forked from asaelko/pq.go
import (
"math/big"
"math/rand"
"time"
)
func SplitPQ(pq *big.Int) (p1, p2 *big.Int) {
value_0 := big.NewInt(0)
value_1 := big.NewInt(1)
value_15 := big.NewInt(15)
@stulentsev
stulentsev / golang_job_queue.md
Created December 23, 2018 01:46 — forked from harlow/golang_job_queue.md
Job queues in Golang