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.

using System;
using FortniteReplayReader;
using Unreal.Core.Models.Enums;
using System.Threading.Tasks;
using Fortnite_API;
using Fortnite_API.Objects.V1;
using FortniteReplayReader.Models;
using System.CommandLine;
require 'benchmark/ips'
require 'set'
sizes = [3, 5, 10, 15, 100]
sizes.each do |size|
Benchmark.ips do |x|
range = 1..size
array = range.to_a
hash = array.each_with_object({}) {|x, memo| memo[x] = x}
@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 / mixed.rb
Created April 18, 2019 11:50
spam filter: proof of concept
tests = %w(
лошадь
horse
horse123
h0rse
лошадb
slоn
)
package main
import (
"bytes"
"fmt"
"strconv"
"sync"
"testing"
)
@stulentsev
stulentsev / keybase.md
Created February 7, 2019 22:06
keybase.md

Keybase proof

I hereby claim:

  • I am stulentsev on github.
  • I am stulentsev (https://keybase.io/stulentsev) on keybase.
  • I have a public key ASAHjuCvisMwyIgXMFulA_a6Bq9BCF8TWwp3KaPqXv3tago

To claim this, I am signing this object:

@stulentsev
stulentsev / boilerplate.cpp
Last active February 7, 2019 09:48
hackerrank boilerplate
#include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
// Complete the sockMerchant function below.
int sockMerchant(int n, vector<int> ar) {
@stulentsev
stulentsev / golang_job_queue.md
Created December 23, 2018 01:46 — forked from harlow/golang_job_queue.md
Job queues in Golang
RUN echo "https://mirror.yandex.ru/mirrors/alpine/v3.7/main" > /etc/apk/repositories \
&& echo "https://mirror.yandex.ru/mirrors/alpine/v3.7/community" >> /etc/apk/repositories \
&& echo "https://mirror.yandex.ru/mirrors/alpine/v3.5/main" >> /etc/apk/repositories \