Adopt and audit production-proven implementation patterns.

version
0.1.0
GitHub stars
344

Install

/plugin install pattern-skills@battle-tested-patterns

Run it inside Claude Code after adding the marketplace with /plugin marketplace add Totoro-jam/battle-tested-patterns.

Contents

Discovered from source

Skills 2

Adopt a Pattern

Overview

The Battle-Tested Patterns catalog documents 46 patterns, each in a GitHub source doc (URLs in the catalog below) with a When to Use / When NOT to Use / Related Patterns decision guide, a Production Proof table of real source links, and a multi-language Implementation. Those doc pages are the source of truth — fetch the relevant one rather than relying on memory. This skill routes a developer's problem to the right pattern and then drives a disciplined adoption into their codebase; it does not reproduce the pattern content here.

Two principles do the work:

  1. A pattern is only worth adopting if it fits — the common failure is reaching for a named pattern that doesn't match the problem; the fit-gate catches that before any code is written.
  2. A pattern adopted without a durable test for its invariant is not done — a correct-looking implementation that leaves no regression test lets the invariant rot on the next edit. The verify step leaves that test behind.

When to use

  • A developer names a pattern and wants it in their code.
  • A developer describes a problem (see the catalog cues) without naming a pattern.
  • A developer asks "which pattern fits?" or "X vs Y — which?".

When NOT to use: general feature work with no pattern in play, or a problem no catalog entry matches (say so plainly rather than forcing a fit).

Workflow

Work the four steps in order. Do not skip the fit-gate.

1. Match

Map the problem to candidate patterns using the catalog below. If the developer named a pattern, still confirm it against the cue. If a problem matches several (e.g. "throttle requests" → Rate Limiter, Semaphore, Backpressure), keep 2–3 candidates for the fit-gate.

2. Fit-gate

Fetch only the candidate patterns' doc pages (the Doc URL in the catalog) and focus on When to Use, When NOT to Use, and Related Patterns.

  • If the pattern fits, continue to step 3.
  • If When NOT to Use describes the developer's situation, stop and steer to the better-fit pattern named in Related Patterns. Explain why in one or two sentences.
  • If nothing fits, say so. Do not adopt a pattern to satisfy the request.

Do not fetch all 46 docs. Fetch the 1–3 you are actually deciding between.

3. Adapt

Read the chosen doc's Implementation (in the developer's language) and skim Production Proof for how real systems shape it. Then write it into their codebase — match their naming, types, error handling, and module boundaries.

  • Adapt, do not copy-paste. The reference impl is a teaching version; production code needs the project's conventions and edge-case handling.
  • Carry over the invariants the doc calls out (e.g. a ring buffer's overwrite-on- full rule, a circuit breaker's half-open probe). Those are the point.

4. Verify — leave a durable invariant test

This is where adoption is won or lost: a capable agent will usually pick the right pattern and implement it correctly, then "confirm it works" with a throwaway check and move on — leaving nothing that protects the invariant on the next edit.

Write a focused test as a committed file in the developer's own project and runner that exercises the pattern's defining behavior — use the doc's Exercises and Challenge Questions as a checklist of cases (the boundary conditions, not the happy path). Run it. An inline or throwaway check does not count. A pattern adopted without a durable test for its invariant is not done.

Pattern catalog

Each row links to the pattern's doc source on GitHub — fetch it during the fit-gate. (Maintainers: this block is generated; see the skill's source repo.)

46 patterns. Match the developer's problem to a row, then fetch only that pattern's doc URL.

🧠 Data Structures

PatternReach for it whenLevelDoc URL
Bitmaskflags in one int — Pack multiple boolean flags into a single integer and manipulate them with bitwise operators for constant-time set operations.beginnerhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/bitmask/index.md
Min Heappriority queue — A binary tree stored in an array where the smallest element is always at the root, enabling O(1) peek and O(log n) insert/remove.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/min-heap/index.md
Ring Bufferfixed-size FIFO — A fixed-size buffer that wraps around using modular arithmetic, enabling constant-time enqueue and dequeue without memory allocation.beginnerhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/ring-buffer/index.md
Trieprefix search — Store strings in a tree where each edge represents a character — shared prefixes share nodes, enabling O(k) lookup by key length.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/trie/index.md
Skip Listprobabilistic order — A probabilistic sorted data structure with O(log n) search, insert, and delete — simpler to implement than balanced trees with comparable performance.advancedhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/skip-list/index.md
Bloom Filterset membership — Test set membership in O(k) time with zero false negatives — at the cost of a tunable false positive rate.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/bloom-filter/index.md
LRU Cacheeviction policy — Evict the least recently used entry when the cache is full — O(1) get and put using a hash map plus a doubly linked list.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/lru-cache/index.md
B+ Treedisk-optimized index — Self-balancing tree with high branching factor — internal nodes guide, leaf nodes store, all leaves linked for efficient range scans.advancedhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/b-plus-tree/index.md
Tagged Uniontype-safe dispatch — Store a type tag alongside a value union so one variable safely holds different types, dispatching behavior via the tag.beginnerhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/tagged-union/index.md
Merkle Treeintegrity proof — Hash leaves, then hash pairs upward to a root — verify any leaf's integrity in O(log n) without re-hashing the entire dataset.advancedhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/merkle-tree/index.md
Merge Iteratork-way merge — Combine K sorted streams into one sorted output using a min-heap — the universal "unified view" over multiple data sources.advancedhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/merge-iterator/index.md

⚡ Concurrency

PatternReach for it whenLevelDoc URL
Semaphorebounded access — Limit the number of concurrent operations by maintaining a counter — acquire before work, release after, block when the limit is reached.beginnerhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/semaphore/index.md
Actor Modelmessage passing — Each actor has a mailbox and processes messages sequentially — no shared state, no locks, just message passing for safe concurrency.advancedhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/actor-model/index.md
Work Stealingload balance — Idle threads steal tasks from busy threads' queues — balancing load dynamically without central coordination.advancedhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/work-stealing/index.md
MVCCsnapshot isolation — Keep multiple timestamped versions of each value so readers never block writers — each transaction sees a consistent snapshot without locks.advancedhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/mvcc/index.md
Cooperative Schedulingyield control — Break long-running work into small chunks, yielding control back to the host between each chunk to keep the system responsive.advancedhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/cooperative-scheduling/index.md
Double Bufferingatomic swap — Maintain two copies of state and atomically swap between them so readers always see a consistent snapshot.beginnerhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/double-buffering/index.md
Backpressureflow control — Slow down producers when consumers can't keep up — use bounded buffers and demand signals to prevent resource exhaustion.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/backpressure/index.md
Event LoopI/O multiplexing — A single-threaded loop that multiplexes I/O via epoll/kqueue, dispatching ready events to callbacks — thousands of connections without threads.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/event-loop/index.md
Logical Clockevent ordering — A monotonically increasing counter that orders events without wall-clock time — enabling consistent snapshots and staleness detection.advancedhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/logical-clock/index.md

🏗️ Systems

PatternReach for it whenLevelDoc URL
Circuit Breakerfault tolerance — Stop calling a failing service by tracking errors and tripping open — fail fast instead of piling up timeouts.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/circuit-breaker/index.md
Rate Limiterthrottle — Protect services from overload by draining tokens from a bucket that refills at a fixed rate — reject requests when empty.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/rate-limiter/index.md
Retry Backoffresilience — When an operation fails, retry it with progressively longer delays plus random jitter to avoid thundering herd.beginnerhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/retry-backoff/index.md
Write-Ahead Logdurability — Log every mutation to durable storage before applying it — replay the log to recover from crashes without data loss.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/write-ahead-log/index.md
Batch Processingthroughput — Accumulate individual operations and execute them together as a group, amortizing per-operation overhead across the batch.beginnerhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/batch-processing/index.md
Consistent Hashingdistribution — Distribute keys across nodes on a virtual ring so that adding or removing a node only remaps ~1/n of the keys.advancedhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/consistent-hashing/index.md
Dependency Graphordering — Model dependencies as a directed acyclic graph and topologically sort to determine a valid execution order — detecting cycles before they deadlock.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/dependency-graph/index.md
Middleware Chainpipeline — Compose handlers where each wraps the next — pre-process, call next, post-process — forming a bidirectional pipeline.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/middleware-chain/index.md
Registryself-register — Components register themselves into a global lookup table by name — consumers discover implementations at runtime without hardcoded dependencies.beginnerhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/registry/index.md
Dirty Flagdeferred recompute — Mark objects as "dirty" on mutation, defer expensive recomputation until the value is actually needed, then clear the flag.beginnerhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/dirty-flag/index.md
LSM Treewrite-optimized store — Buffer writes in memory, flush to sorted files on disk, merge files in background — trading read amplification for fast writes.advancedhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/lsm-tree/index.md
Checkpointingsnapshot recovery — Periodically snapshot consistent state so recovery replays only from the checkpoint — not from the beginning of time.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/checkpointing/index.md

♻️ Memory

PatternReach for it whenLevelDoc URL
Object Poolreuse instances — Pre-allocate a set of reusable objects to avoid the cost of repeated allocation and garbage collection on hot paths.beginnerhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/object-pool/index.md
Flyweightshare immutables — Share identical immutable objects instead of creating duplicates, trading a lookup cost for massive memory savings when many instances have the same value.beginnerhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/flyweight/index.md
Arena Allocatorbump alloc — Allocate objects by bumping a pointer in a pre-allocated region — free everything at once when the region is no longer needed.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/arena-allocator/index.md
Free ListO(1) alloc/free — Maintain a linked list of freed slots so allocation and deallocation are O(1) — reuse memory without calling the system allocator.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/free-list/index.md
Copy-on-Writedefer copy — Share data by reference until someone modifies it — only then make a private copy, saving memory and allocation cost for read-heavy workloads.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/copy-on-write/index.md
Reference Countingauto-cleanup — Track owners via atomic counter, auto-cleanup at zero — deterministic resource lifetime without garbage collection.beginnerhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/reference-counting/index.md
Tombstonedeferred deletion — Mark deleted entries with a tombstone marker instead of removing them — a background process reclaims space later.beginnerhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/tombstone/index.md
Interningdeduplicate values — Deduplicate immutable values through a canonical lookup table — O(1) equality by pointer comparison instead of O(n) content comparison.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/interning/index.md

🔄 Behavioral

PatternReach for it whenLevelDoc URL
State Machinetransitions — Model an entity's lifecycle as a set of states with explicit transitions, making impossible states unrepresentable and every state change auditable.beginnerhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/state-machine/index.md
Observerpub/sub — Decouple producers from consumers by letting objects subscribe to events and get notified when something happens, without the source knowing who's listening.beginnerhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/observer/index.md
Iteratorlazy eval — Process sequences one element at a time without materializing the entire collection, enabling composable transformations with zero intermediate allocations.beginnerhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/iterator/index.md
Diff / Patchminimal edits — Compare two sequences to compute the minimal set of operations (insert, delete, move) needed to transform one into the other.intermediatehttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/diff-patch/index.md
Vtablemanual polymorphism — Group function pointers into a struct to achieve runtime polymorphism — the manual foundation behind interfaces, traits, and virtual methods.advancedhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/vtable/index.md
Visitortree traversal dispatch — Decouple tree traversal from operations by dispatching to type-specific callbacks — enabling new operations without modifying the tree.advancedhttps://github.com/Totoro-jam/battle-tested-patterns/blob/main/docs/patterns/visitor/index.md

Common mistakes

  • Skipping the fit-gate because the developer named a pattern. Named ≠ correct — confirm against When NOT to Use first.
  • Copy-pasting the reference implementation verbatim. It teaches the shape; it is not drop-in production code.
  • Loading many pattern docs at once. Match from the catalog cues, then open only the 1–3 candidates.
  • Choosing by familiarity ("I know LRU") instead of fit. Check Related Patterns — the better tool is often one row away.
  • Declaring done without a test for the pattern's invariant.

Example

Developer: "Downloads are hammering the API — I want to cap it at 5 in flight."

  1. Match — "cap concurrent access" → candidates: Semaphore, Rate Limiter, Backpressure.
  2. Fit-gate — the Semaphore doc's When to Use directly lists "control access to a fixed number of resources" and "limit concurrent network requests" — a concurrency cap, which is what the developer asked for. Rate Limiter's When to Use governs rate over time (API rate limiting, traffic shaping), a different axis. → Semaphore.
  3. Adapt — port the doc's TypeScript semaphore into their download module, wrapping the fetch call in acquire()/release() with their existing error/cleanup handling so a failed download always releases its permit.
  4. Verify — test that with the cap at 5 and 20 queued downloads, no more than 5 run concurrently and all 20 eventually complete.

Audit Patterns

Overview

Grade a codebase against the Battle-Tested Patterns catalog: for each pattern it implements, fetch the canonical doc page and check the implementation against that doc's invariants — not against the name the codebase gave it. The most valuable output of an audit is not a score; it is the mislabel — code called a "semaphore" that is actually a mutex, an "MVCC" that keeps a single version. Those are the claims that mislead developers into expecting guarantees the code does not provide.

Companion skill: Inventory using the adopt-pattern skill's catalog, or the pattern docs at https://github.com/Totoro-jam/battle-tested-patterns/tree/main/docs/patterns. This skill is the inverse of adopt-pattern: that one runs the catalog forward (add a pattern); this one runs it backward (grade patterns already there).

When to use

  • A reviewer asks whether a codebase's patterns are implemented correctly.
  • Someone asks "is this really a <pattern>?" or "do we honor X's invariants?".
  • A periodic conformance check after a release, to catch new mislabels/drift.

When NOT to use: adding a new pattern (use adopt-pattern), or general code review with no pattern claim in play.

Workflow

1. Inventory

List the catalog patterns the codebase implements. Match by shape, not name — a class named RateLimiter may be a different pattern, and a circuit breaker may exist unnamed. Hunt by shape: retry/backoff loops, lock or lease primitives, caches with eviction, state enums with transition switches, ring/circular buffers, breaker/trip counters, subscriber lists. Record the file(s) for each candidate. Only inventory patterns the codebase actually engages; do not pad the audit with absent ones.

2. Conformance — fetch the doc, never grade from memory

For each candidate, fetch the canonical doc page and read Core Idea (the invariant), When NOT to Use, and Production Proof (the reference shape). Then read the actual implementation. Grade against the doc's headline invariant.

3. Gap analysis — classify the deviation

Assign a verdict (scale below). The judgment is distinguishing faithful from divergent from mislabeled:

  • Meets the invariant faithfully → ✅
  • Meets the intent a different way (different algorithm/model) → 🟡
  • The developer/framework enables it but does not provide it → 🔵
  • It is actually a different catalog pattern → 🔁 (the mislabel — flag loudly)
  • Not present → ⚪ (absence is N/A, not a failure, unless the pattern is clearly needed)

4. Evidence — cite code + doc

Every verdict cites a file:line in the codebase and the doc invariant it was graded against. A verdict without a citation is an opinion, not an audit.

Verdict scale

SymbolMeaning
✅Faithful — honors the doc's headline invariant.
🟡Intent met, model/algorithm diverges from the reference.
🔵Enabled, not provided — the developer brings it.
🔁Mislabeled — it is actually a different catalog pattern.
⚪Absent / N-A — not present (only a gap if the pattern is needed).

Scorecard format (the output)

Produce one table, optionally grouped by catalog category:

PatternVerdictEvidence & note
namesympath:line — one-line check against the doc's invariant

Then 2–4 headline findings, leading with the mislabels (🔁) and real gaps — those are what the audit is for. Faithful rows are reassurance, not the point.

Common mistakes

  • Grading from memory instead of fetching the doc — invents invariants. Fetch every candidate's doc page.
  • Accepting the code's own label — you will rubber-stamp a mutex called "Semaphore." Grade against the doc, not the class name.
  • Treating absence as a bug — a pattern not present is ⚪/N-A unless the codebase clearly needs it.
  • Verdicts without file:line — an audit is evidence, not vibes.
  • Auditing all 46 — grade only the patterns the codebase engages.

Example (compressed)

Auditing an HTTP/MCP framework:

PatternVerdictEvidence & note
Actor Model✅in-memory-runtime.ts:144,156 — per-identity serialized turns; handler gets a clone, rollback on throw.
Semaphore🔁redis-actor-runtime.ts:18 — the lease is SET NX (count=1) = mutex; the doc routes max=1 → mutex.
MVCC🟡in-memory-runtime.ts:113 — lease-free reads never block writers, but only one version is kept (snapshot read, not multi-version).
Circuit Breaker⚪Absent across all packages — a real gap for an outbound-heavy framework.

Headline: two over-claims (Semaphore→mutex, MVCC→single-version) that would mislead a developer expecting counting-semaphore or multi-version guarantees; one genuine gap (no circuit breaker).

Sponsors

Details

Marketplace
Totoro-jam/battle-tested-patterns
Source
plugins/pattern-skills
Category
Productivity
Keywords
patterns, agent-skills, code-review, architecture