Totoro-jam/battle-tested-patterns
À propos
Des modèles de programmation éprouvés, tirés du code en production de React, Linux, Go, Chromium et d’autres projets. Avec des liens précis vers les sources, des exemples dans plusieurs langages et des exercices exécutables.
Développement web et applicatifProgression mesurée des étoiles
- in 24h
- 0
- in 7 days
- +2
- in 15 days
- +2
- in 1 month
- Historique en cours
Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.
README.md
OriginalBattle-Tested Patterns
Code-level programming patterns extracted from production codebases.
Interactive visualizations with time-travel playback · Precise source links · Multi-language · Runnable exercises
English | 简体中文
46 Patterns at a Glance
🧠 Data Structures
|
⚡ Concurrency
|
🏗️ Systems
|
♻️ Memory
|
🔄 Behavioral
|
📊 Proven In
|
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, then undo or replay any step with the time-travel playback bar |
| 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 # All 4 languages (TS/Rust/Go/Python)
pnpm test:ts # TypeScript only (491 tests, Vitest)
pnpm test:rust # Rust only (173 tests)
pnpm test:go # Go only (176 tests)
pnpm test:python # Python only (233 tests)
pnpm test # Run ALL tests: docs components + all 4 exercise languages
pnpm dev # Local docs site
See the Exercise Guide for detailed setup instructions per language.
Agent Skills
Two agent skills let AI coding assistants work with the pattern catalog:
- adopt-pattern — given a problem, find the right pattern and adapt it to your codebase with a regression test
- audit-pattern — grade an existing codebase's patterns against the catalog and flag mislabels
Install via Claude Code plugin marketplace:
/plugin marketplace add Totoro-jam/battle-tested-patterns
/plugin install pattern-skills@battle-tested-patterns
Or use the npx skills installer (works with Claude Code, Codex, Copilot, and more):
npx skills add Totoro-jam/battle-tested-patterns/plugins/pattern-skills
Both skills fetch pattern doc URLs at runtime, so you can also invoke them without installing — they'll read the catalog from the repo.
Contributing
See CONTRIBUTING.md. The bar is intentionally high:
- ≥ 2 production proofs with verified, line-number-precise source links
- TypeScript + ≥ 1 other language — idiomatic, not translated
- Exercise files in all 4 languages (TS/Rust/Go/Python) + answer files
- Chinese translation with identical code blocks
- All tests pass (
pnpm testruns all 4 languages + docs), no lint errors - Source links checked weekly by CI — broken links auto-open an Issue
Contributors
Totoro-jam 💻 📖 🎨 🚧 🤔 |
Raymond Feng 💻 📖 🤔 |
小朝 🐛 |
This project follows the all-contributors specification. Contributions of any kind welcome!
Star History
License
MIT © Totoro-jam
Explorer des projets similaires
Chargement…