Code Explainers

Code explainers tagged #rate-limiting

python
import time
from collections import defaultdict
from threading import Lock
 

Sliding-window login rate limiting in Flask

rate-limiting sliding-window thread-safety
Intermediate 7 steps
javascript
const RATE_LIMIT = 100;
const WINDOW_MS = 60 * 1000;
const BLOCK_MS = 5 * 60 * 1000;
 

Building a rate-limiting middleware in Express

rate-limiting middleware closures
Intermediate 9 steps
typescript
function throttle<T extends (...args: any[]) => void>(
  fn: T,
  limit: number
): (...args: Parameters<T>) => void {

Building a trailing-edge throttle in TypeScript

throttling closures generics
Intermediate 7 steps
typescript
interface TokenBucketOptions {
  capacity: number;
  refillPerSecond: number;
}

How a token bucket rate limiter works

rate-limiting token-bucket lazy-evaluation
Intermediate 7 steps
ruby
class SessionsController < ApplicationController
  MAX_ATTEMPTS = 5
  THROTTLE_WINDOW = 15.minutes
 

Throttling failed logins in Rails

rate-limiting authentication caching
Intermediate 7 steps
rust
use std::net::SocketAddr;
use std::time::Duration;
 
use axum::{routing::get, Json, Router};

Per-IP rate limiting in Axum with tower-governor

rate-limiting middleware tower
Intermediate 7 steps
typescript
export function chunk<T>(items: readonly T[], size: number): T[][] {
  if (size <= 0 || !Number.isInteger(size)) {
    throw new RangeError(`chunk size must be a positive integer, got ${size}`);
  }

Splitting work into sequential batches in TypeScript

generics async-await batching
Intermediate 5 steps
python
import time
import threading
 
 

How a thread-safe token bucket rate limiter works

rate-limiting concurrency locking
Intermediate 6 steps
php
<?php
 
namespace App\Security;
 

A fixed-window rate limiter on APCu

rate-limiting fixed-window caching
Intermediate 8 steps
go
package debounce
 
import (
	"sync"

Building a debouncer in Go

concurrency debounce timers
Intermediate 6 steps
ruby
class Throttle
  def initialize(interval)
    @interval = interval
    @mutex = Mutex.new

A thread-safe throttle in Ruby

concurrency rate-limiting mutex
Intermediate 7 steps
javascript
function throttle(fn, wait) {
  let lastCall = 0;
  let timeoutId = null;
  let lastArgs = null;

Building a leading-and-trailing throttle

closures rate-limiting timers
Advanced 6 steps