Skip to content

Instantly share code, notes, and snippets.

View hawaijar's full-sized avatar
🎯
Focusing

Mayengbam Sushil K hawaijar

🎯
Focusing
View GitHub Profile

Rate Limiter Implementations in Go

Production-ready rate limiting algorithms for protecting APIs and managing resource consumption.

Algorithms Included

1. Token Bucket

  • Best for: APIs needing smooth rate limiting with burst capability
  • Pros: Allows bursts, smooth traffic shaping, memory efficient
  • Cons: Tokens can accumulate leading to large bursts
package ratelimiter
import (
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
)
package main
import (
"fmt"
"log"
"time"
)
func main() {
// Example 1: Token Bucket (smooth rate limiting)
// Package ratelimiter provides multiple rate limiting algorithms for API protection.
// Includes Token Bucket, Sliding Window Log, and Sliding Window Counter implementations.
package ratelimiter
import (
"sync"
"time"
)
// RateLimiter defines the interface for all rate limiters

Consistent Hashing Implementation in Go

A production-ready consistent hashing implementation with virtual nodes for building distributed systems.

Features

  • Virtual nodes for better key distribution (configurable replica count)
  • O(log n) lookups using binary search on sorted ring
  • Thread-safe operations with RWMutex
  • Minimal key redistribution when nodes join/leave
package main
import (
"fmt"
"log"
)
func main() {
// Create a consistent hash ring with 150 virtual nodes per physical node
ring := consistenthash.New(150)
@hawaijar
hawaijar / consistenthash.go
Created August 1, 2025 09:26
consistent-hashing-go
// Package consistenthash implements a thread-safe consistent hash ring with virtual nodes.
// It uses Google's B-tree for efficient O(log n) lookups and provides configurable replication.
package consistenthash
import (
"fmt"
"hash/crc32"
"sort"
"sync"
)
@hawaijar
hawaijar / FibAndCoinIssues.test.ts
Created August 29, 2022 17:27
DP - test cases (nthFibonacci, isSumPossible, minCoinsChange)
import { findNthFib, minChange, sumPossible } from "../FibAndCoinIssues";
describe("Testing Finding Nth Fibonacci", () => {
test("findNthFib(0) == 0", () => {
expect(findNthFib(0)).toBe(0);
});
test("findNthFib(5) == 5", () => {
expect(findNthFib(5)).toBe(5);
});
test("findNthFib(35) == 9227465", () => {
@hawaijar
hawaijar / index.ts
Created August 29, 2022 17:27
DP - nthFibonacci, isSumPossible, minCoinsChange
const cache = [0, 1];
export function findNthFib(n: number, cache = [0, 1]) {
// check if the number is already calculated
if (n in cache) {
return cache[n];
}
cache[n] = findNthFib(n - 1, cache) + findNthFib(n - 2, cache);
return cache[n];
}
@hawaijar
hawaijar / index.ts
Created August 24, 2022 08:14
MinHeap implementation
export class MinHeap {
private length: number = 0;
private data: number[] = [];
private getParentIndex(idx: number): number {
return Math.floor((idx - 1) / 2);
}
private getLeftIndex(idx: number): number {
return 2 * idx + 1;
}