Skip to content

Totoro-jam/battle-tested-patterns

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

400 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Battle-Tested Patterns

Code-level programming patterns extracted from production codebases.

Interactive visualizations · Precise source links · Multi-language · Runnable exercises

📖 Documentation · 📖 中文文档

English | 简体中文

CI Deploy License: MIT PRs Welcome

LRU Cache pattern — interactive visualization, property table, and sidebar navigation

46 Patterns at a Glance

🧠 Data Structures

⚡ Concurrency

🏗️ Systems

♻️ Memory

🔄 Behavioral

📊 Proven In

  • React · Linux · Go
  • Redis · PostgreSQL
  • Kafka · Chromium
  • Tokio · Erlang/OTP
  • LevelDB · RocksDB · etcd
  • Nginx · Akka
  • LLVM · Vue · Godot
  • PyTorch · CPython · ZFS

The Gap This Fills

What exists What's missing
Design patterns books Too abstract, too OOP-centric
Algorithm repos Disconnected from real engineering
System design guides Architecture-level, not code-level

This project: code-level techniques from React, Linux, Go, Chromium — each with verifiable source links.

Patterns

Pattern What It Does Proven In
Bitmask Pack N flags into one integer, check any combo in O(1) React Flags · Linux stat.h
Double Buffering Swap two copies atomically, zero allocation React Fiber · SDL
Cooperative Scheduling Yield control between work chunks to stay responsive React Scheduler · Go Runtime
Min Heap O(1) peek at highest priority, O(log n) push/pop React MinHeap · Linux CFS
Diff / Patch Compute minimal edits between two sequences React Reconciler · Git
Object Pool Pre-allocate and reuse to avoid GC pressure Go sync.Pool · Godot
Ring Buffer Fixed-size circular queue, zero allocation LMAX Disruptor · Linux
State Machine Explicit states, impossible transitions unrepresentable XState · Linux TCP
Copy-on-Write Share by reference, copy only on mutation Git objects · Rust Cow
Observer Subscribe to events, decouple producers from consumers Node EventEmitter · Redux
Iterator Lazy sequences, zero intermediate allocations Rust Iterator · Python gen
Semaphore Bounded concurrency with a counter Linux · Go x/sync
Batch Processing Accumulate ops, execute as group Kafka
Retry with Backoff Exponential delay + jitter on failure Kubernetes · gRPC
Event Loop Single-threaded loop multiplexes I/O via epoll/kqueue libuv · Redis ae
Flyweight Share identical objects, avoid duplicates Python int cache
Bloom Filter Probabilistic set membership, zero false negatives LevelDB · Chromium
Circuit Breaker Stop calling failing services, fail fast Hystrix · gobreaker
Arena Allocator Bump-allocate, free all at once bumpalo · Go arena
B+ Tree High-fanout balanced tree — internal nodes guide, leaves store and link for range scans PostgreSQL · SQLite
Backpressure Slow producers when consumers can't keep up Node.js Streams · Reactive Streams
Write-Ahead Log Log mutations before applying, crash recovery etcd · PostgreSQL
Logical Clock Monotonic counter orders events without wall-clock time etcd · LevelDB
LRU Cache Evict least recently used, O(1) get/put groupcache · Linux
Consistent Hashing Add/remove nodes remaps ~1/n keys groupcache · HAProxy
Trie O(k) lookup, shared prefixes share nodes Linux FIB · Redis rax
Skip List Probabilistic O(log n) sorted structure Redis · LevelDB
Rate Limiter Token bucket controls throughput Go rate · Nginx
Reference Counting Atomic counter tracks owners, auto-cleanup at zero CPython · Rust Arc
Registry Components self-register into a global lookup table by name TensorFlow · gRPC-Go
Work Stealing Idle threads steal from busy queues Go proc.go · Tokio
MVCC Timestamped versions, readers never block PostgreSQL · etcd
Free List O(1) alloc/free via linked freed slots Go mfixalloc · Linux SLUB
Dependency Graph DAG + toposort for execution order Cargo · pnpm
Dirty Flag Mark "dirty" on mutation, defer recomputation until needed Chromium/Blink · React
Actor Model Private state + mailbox, no locks Akka · Erlang/OTP
Tagged Union Type tag + union for safe dispatch Godot Variant · PyTorch IValue
Interning Deduplicate values, O(1) equality Rust Symbol · CPython
Vtable Function pointer struct for polymorphism Linux file_operations · CPython PyTypeObject
Visitor Dispatch callbacks on tree nodes LLVM InstVisitor · Vue transforms
Merkle Tree Hash upward to root for integrity Git tree.c · ZFS blkptr
Merge Iterator K-way merge of sorted streams LevelDB merger · RocksDB merge
Middleware Chain Compose handlers where each wraps the next — bidirectional pipeline gRPC-Go · Koa.js
LSM Tree Buffer writes, flush to sorted files LevelDB DBImpl · RocksDB MemTable
Checkpointing Snapshot state, recover from checkpoint PostgreSQL · Redis RDB
Tombstone Mark deleted with a tombstone, background reclaims later LevelDB · Cassandra

Every "Proven In" link goes to the exact lines in the source code. Not a directory. Not a file. The lines.

What a Pattern Looks Like

Each pattern follows a consistent structure — here's a taste from Bitmask:

  Bit position:   7    6    5    4    3    2    1    0
                ┌────┬────┬────┬────┬────┬────┬────┬────┐
  Flags:        │    │    │    │ SN │ CB │ RF │ UP │ PL │
                └────┴────┴────┴──┬─┴──┬─┴──┬─┴──┬─┴──┬─┘
                                  │    │    │    │    └── Placement  (1 << 0)
                                  │    │    │    └─────── Update     (1 << 1)
                                  │    │    └──────────── Ref        (1 << 2)
                                  │    └───────────────── Callback   (1 << 3)
                                  └────────────────────── Snapshot   (1 << 4)

Implementations in 4 languages, each idiomatic:

// TypeScript                          // Python
const READ  = 1 << 0;                  READ  = 1 << 0
const WRITE = 1 << 1;                  WRITE = 1 << 1
const perms = READ | WRITE;            perms = READ | WRITE
(perms & READ) !== 0;  // true         bool(perms & READ)  # True

Then exercises at 2 difficulty levels — all with tests you can run.

What's Inside

Feature Details
46 patterns Bitmask, LRU Cache, MVCC, Work Stealing, Actor Model, and 41 more
46 interactive visualizations Hands-on SVG visualizations — click, drag, experiment to build intuition
93 TS exercises + 46 per lang 4 languages (TS/Rust/Go/Python), 1,073+ tests across real-world scenarios
184 challenge questions "Guess what happens" scenario Q&A to test understanding
9 system case studies How React, Linux, Go, Git, Node.js, Rust, game engines, and distributed systems compose patterns
4 languages TypeScript, Go, Python, Rust — idiomatic implementations
Bilingual Full English + Chinese documentation
Learning guides Learning Paths · Complexity Cheat Sheet · Pattern Comparison · Study Plan

Quick Start

Prerequisites

Tool Version Required for
Node.js ≥ 22 Docs site, TypeScript exercises
pnpm ≥ 9 Package manager
Rust stable Rust exercises (optional)
Go ≥ 1.23 Go exercises (optional)
Python ≥ 3.10 Python exercises (optional)
git clone https://github.com/Totoro-jam/battle-tested-patterns.git
cd battle-tested-patterns && pnpm install

# Run exercises in any language
pnpm test:exercises               # TypeScript (491 tests, Vitest)
cd exercises/rust && cargo test   # Rust (173 tests)
cd exercises/go && go test ./...  # Go (176 tests)
cd exercises/python && pytest     # Python (233 tests)

pnpm test                         # Run ALL tests (exercises + docs components)

pnpm dev                          # Local docs site

See the Exercise Guide for detailed setup instructions per language.

Contributing

See CONTRIBUTING.md. The bar is intentionally high:

  1. ≥ 2 production proofs with verified, line-number-precise source links
  2. TypeScript + ≥ 1 other language — idiomatic, not translated
  3. Exercise files in all 4 languages (TS/Rust/Go/Python) + answer files
  4. Chinese translation with identical code blocks
  5. All tests pass (pnpm test · cargo test · go test ./... · pytest), no lint errors
  6. Source links checked weekly by CI — broken links auto-open an Issue

Contributors

Thanks to these wonderful people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!

Star History

Star History Chart

License

MIT © Totoro-jam