# Vibe Coding 101: full term reference

## tdd

**test-driven development** (development workflow). Let one failing example drive the next implementation.

- Use when: You can describe the behavior before writing it.
- What: TDD cycles through a failing test, enough implementation to pass, and cleanup while tests stay green.
- Why it matters with an agent: A generated test can agree with generated code while both miss the requirement.
- Do: Choose one observable example. Run red, green, then refactor. Check that red failed for the missing behavior.
- Prompt: Use TDD for this behavior. Show the expected failing assertion, implement it, then rerun the relevant tests.
- Avoid: A syntax error is mistaken for proof that the test detects the missing behavior.
- Described as: red green refactor; test first; tests match wrong code; write the test before the code; tests that always pass; red-green-refactor
- Related: refactoring, repro
- Page: https://vibe-coding-101.brighteng.org/c/tdd/

### test-driven development: a worked example

Canonical page: https://vibe-coding-101.brighteng.org/c/tdd/#before-and-after

#### The problem

An agent builds a URL slug function. The requirement is to trim surrounding spaces, lowercase the words, and join whitespace-separated words with a hyphen. Start with that observable behavior before asking for an implementation.

#### Prompt to paste

Use TDD for this behavior. Show the expected failing assertion, implement it, then rerun the relevant tests.

#### Before

A function that returns its input can look complete in a generated diff. A test that expects the unchanged input would also pass, while missing the requested behavior.

#### After

The assertion fixes the expected result independently of the implementation. Run it against the incomplete function to see the mismatch, add only the needed behavior, then rerun it before refactoring.

#### Run the check

Save the following code as tdd.mjs and run `node --test tdd.mjs` with Node.js 22.12 or later.

```js
import test from 'node:test';
import assert from 'node:assert/strict';

function before(text) {
  return text;
}

function after(text) {
  return text.trim().toLowerCase().replace(/\s+/g, '-');
}

test('the initial implementation misses the requirement', () => {
  assert.throws(() => {
    assert.equal(before('  Hello   world  '), 'hello-world');
  }, { code: 'ERR_ASSERTION' });
});

test('the implementation satisfies the chosen examples', () => {
  assert.equal(after('  Hello   world  '), 'hello-world');
  assert.equal(after('One'), 'one');
  assert.equal(after(''), '');
});
```

#### Expected result

For the input '  Hello   world  ', the initial function returns the unchanged string; the revised function returns 'hello-world'. The comparison file checks that the first assertion fails and the revised examples pass. To experience the red step directly, remove the assert.throws wrapper and run that assertion before changing the function.

#### Limits

This demonstrates a small, specified behavior. It does not settle Unicode normalization, punctuation, uniqueness, or URL policy, and passing examples do not prove that the whole product is correct. Add each relevant rule deliberately. TDD includes refactoring after green; writing tests after the implementation is a different workflow.

#### Sources

- [Martin Fowler: Test Driven Development](https://martinfowler.com/bliki/TestDrivenDevelopment.html): The test, implementation, and refactoring cycle. The slug example is our own illustration.
- [Node.js test runner](https://nodejs.org/api/test.html): Running the downloadable comparison with node --test.

Sources checked: 2026-10-09. These are original illustrative examples with automated checks. Human editorial approval is not recorded. Policy: https://vibe-coding-101.brighteng.org/editorial/


## refactoring

**refactoring** (development workflow). Change internal structure while preserving observable behavior.

- Use when: A working implementation is becoming hard to change.
- What: Refactoring changes how code is organized without adding a new product behavior.
- Why it matters with an agent: A cleanup request can accidentally become a feature rewrite.
- Do: Name the behavior to preserve and the scope to improve. Check those behaviors before and after.
- Prompt: Refactor this module while preserving its public behavior. Run the behavior tests before and after; report any intentional test changes.
- Avoid: Changing assertions to accept a behavior change conceals a regression.
- Described as: clean up code; restructure without changing behavior; tidy this file; messy code hard to change; cleanup turned into rewrite
- Related: composition, seam
- Page: https://vibe-coding-101.brighteng.org/c/refactoring/

## repro

**minimal reproduction** (development workflow). The smallest repeatable case that still shows the bug.

- Use when: A bug report says something is broken but cannot show how.
- What: A minimal reproduction isolates the triggering input, necessary setup, and observed failure.
- Why it matters with an agent: An agent can otherwise change code without reproducing the reported problem.
- Do: Remove unrelated setup until the failure is small and repeatable. Check it from a clean starting state.
- Prompt: Create a minimal reproduction for this bug. Record the input, expected result, and actual result before changing the implementation.
- Avoid: Removing the condition that causes the failure produces a different test case.
- Described as: cannot reproduce; bug only on my machine; repro steps; works for me; smallest example that breaks; steps to reproduce
- Related: root-cause-analysis, tdd
- Page: https://vibe-coding-101.brighteng.org/c/repro/

### minimal reproduction: a worked example

Canonical page: https://vibe-coding-101.brighteng.org/c/repro/#before-and-after

#### The problem

A report says the last item disappears from every page of results. Reduce it to an array with one item and a requested page size of one. The expected result is that one item; the actual result is an empty array.

#### Prompt to paste

Create a minimal reproduction for this bug. Record the input, expected result, and actual result before changing the implementation.

#### Before

The slice end subtracts one even though JavaScript excludes the end index already. The smallest input reveals the mismatch without a router, UI, network request, or large fixture.

#### After

Write the failing assertion before changing the endpoint. Use start + size as the exclusive end. Keep the minimal case as a regression check and add a partial last page to cover the neighboring boundary.

#### Run the check

Save the following code as repro.mjs and run `node --test repro.mjs` with Node.js 22.12 or later.

```js
import test from 'node:test';
import assert from 'node:assert/strict';

function before(items, start, size) {
  return items.slice(start, start + size - 1);
}

function after(items, start, size) {
  return items.slice(start, start + size);
}

test('one item and a page size of one reproduce the report', () => {
  const actual = before(['book'], 0, 1);
  assert.deepEqual(actual, []);
  assert.throws(() => assert.deepEqual(actual, ['book']), { code: 'ERR_ASSERTION' });
});

test('the fix keeps the minimal case and neighboring boundaries', () => {
  assert.deepEqual(after(['book'], 0, 1), ['book']);
  assert.deepEqual(after(['a', 'b', 'c'], 0, 2), ['a', 'b']);
  assert.deepEqual(after(['a', 'b', 'c'], 2, 2), ['c']);
  assert.deepEqual(after([], 0, 1), []);
});
```

#### Expected result

The exact one-item input returns [] before and [book] afterward. The comparison captures the original assertion failure and checks a full first page, a partial final page, and an empty list.

#### Limits

A minimal reproduction must still retain the cause. Do not remove the concurrency, permissions, version, or environment that triggers the real bug just to make the example smaller. This example assumes nonnegative integer start and size values; it does not define API validation or pagination across a changing dataset. Record the command and runtime alongside the input.

#### Sources

- [Stack Overflow: Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example): Minimal, complete, reproducible examples and explicit expected behavior.
- [MDN: Array.prototype.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice): The end index is excluded from the returned slice.

Sources checked: 2026-10-11. These are original illustrative examples with automated checks. Human editorial approval is not recorded. Policy: https://vibe-coding-101.brighteng.org/editorial/


## root-cause-analysis

**root cause analysis** (development workflow). Find the mechanism that produces the failure.

- Use when: Fixes keep moving the same bug to another place.
- What: Root cause analysis traces the failure to a causal condition and tests an explanation.
- Why it matters with an agent: Patching the visible symptom can leave the faulty data path intact.
- Do: Trace the input across boundaries. Change one suspected cause. Check whether the original failure changes as predicted.
- Prompt: Find the root cause before patching. Trace the failing value to its origin and test one hypothesis with the smallest change.
- Avoid: Several simultaneous changes hide which explanation was correct.
- Described as: keeps breaking; fix did not work; where bad value comes from; bug keeps coming back; patching symptoms; why is this happening
- Related: repro, query-plan
- Page: https://vibe-coding-101.brighteng.org/c/root-cause-analysis/

## git-worktree

**git worktree** (development workflow). A separate checkout and index sharing the same Git repository.

- Use when: You need another branch without disturbing unfinished edits.
- What: A worktree gives a branch its own working directory. Git history is shared; runtime resources may still overlap.
- Why it matters with an agent: Parallel edits can accidentally touch the current checkout or the same development database.
- Do: Create the checkout and identify shared ports and data. Check git status in both directories.
- Prompt: Create a Git worktree for this task. Check status in both checkouts and identify shared ports, environment files, or databases.
- Avoid: A separate directory still connects to the same database.
- Described as: separate checkout; another branch without stashing; parallel branch; two agents same repo; work on two branches at once
- Related: test-isolation, continuous-integration
- Page: https://vibe-coding-101.brighteng.org/c/git-worktree/

## verification

**verification** (development workflow). Check the claimed result against fresh evidence.

- Use when: The agent says a fix is done, but only describes its edits.
- What: Verification connects a claim to a relevant command or observed behavior on the changed version.
- Why it matters with an agent: A successful build alone cannot show that a particular user flow works.
- Do: Choose the check that would expose the failure. Run it after the final edit and report its actual outcome.
- Prompt: Verify the original failure on the changed version. Run the relevant check and report the result plus anything still unverified.
- Avoid: An earlier passing result is reused after further edits.
- Described as: prove it works; done but not tested; fresh evidence; agent says fixed but it is not; show me it works; claims success without running; hallucination
- Related: repro, e2e
- Page: https://vibe-coding-101.brighteng.org/c/verification/

## reverse-engineering

**reverse engineering** (development workflow). Recover a behavioral specification from an existing system.

- Use when: You need compatibility with an existing product or undocumented module.
- What: You observe how the existing system responds to inputs and edge cases, then write those observations down as examples before building anything that must behave the same way.
- Why it matters with an agent: A visual imitation can miss the behavior callers depend on.
- Do: Record representative interactions and turn the observations into executable examples.
- Prompt: Reverse-engineer this workflow into input/output examples. Verify them against the existing implementation before building its replacement.
- Avoid: Assuming an unobserved edge case behaves like the happy path.
- Described as: no documentation for old system; match existing behavior; clone how the old tool works; undocumented module
- Related: characterization-test, contract-first
- Page: https://vibe-coding-101.brighteng.org/c/reverse-engineering/

## characterization-test

**characterization test** (development workflow). Record the behavior an existing implementation exhibits.

- Use when: You need to change legacy code whose intended behavior is poorly documented.
- What: Characterization tests pin down what the code does today, so a later change shows exactly which behavior moved. They record known bugs as known bugs rather than declaring them correct.
- Why it matters with an agent: A cleanup can silently change an undocumented behavior that a caller relies on.
- Do: Capture representative inputs and outputs; label known defects separately from behavior to preserve.
- Prompt: Add characterization tests around this module before refactoring. Capture current outputs and identify known defects without silently changing expectations.
- Avoid: Freezing incidental output so every harmless edit breaks the suite.
- Described as: golden master; lock in current behavior; legacy code no tests; tests before refactor; approval test
- Related: refactoring, snapshot-test
- Page: https://vibe-coding-101.brighteng.org/c/characterization-test/

## spike

**spike** (development workflow). A short investigation answers one technical unknown.

- Use when: You cannot choose an approach until an integration or performance assumption is tested.
- What: The result of a spike is evidence for a decision. Its code is often thrown away, and its limits are written down so nobody mistakes it for production work.
- Why it matters with an agent: A prototype can accidentally acquire production responsibilities.
- Do: Name the question, time limit, and evidence needed. Record what the experiment does not prove.
- Prompt: Run a bounded spike for this integration question. Report the observed result, limitations, and which prototype code is suitable to keep.
- Avoid: Treating a successful toy example as proof of production readiness.
- Described as: quick experiment; proof of concept; will this even work; timeboxed prototype; try it before deciding
- Related: verification, adr
- Page: https://vibe-coding-101.brighteng.org/c/spike/

## walking-skeleton

**walking skeleton** (development workflow). A minimal working path connects the application’s essential layers.

- Use when: The UI, backend, persistence, and deployment have never worked together.
- What: The skeleton does one tiny thing end to end: screen, API, database, and a real deployment. Features are added to it only after the pieces are known to connect.
- Why it matters with an agent: Separately generated layers may have incompatible contracts.
- Do: Implement one small persistent action and deploy it to an isolated preview.
- Prompt: Build a walking skeleton for creating and reopening one record. Verify the path through UI, API, storage, and the preview deployment.
- Avoid: Mocking away the integration the skeleton is supposed to establish.
- Described as: nothing works together yet; end to end first; hello world deployed; connect frontend backend database; thin end-to-end version
- Related: vertical-slice, e2e
- Page: https://vibe-coding-101.brighteng.org/c/walking-skeleton/

## vertical-slice

**vertical slice** (development workflow). Implement one usable behavior across the layers it requires.

- Use when: Work is divided into complete UI and backend layers with nothing usable yet.
- What: A slice crosses every layer the behavior needs, such as screen, API, and storage, and includes the check that shows a person can complete it.
- Why it matters with an agent: An agent can finish many files without completing one user action.
- Do: Choose one user outcome and trace it through every required layer.
- Prompt: Implement one vertical slice: creating and reopening a draft. Verify the complete journey before expanding to other draft operations.
- Avoid: Calling a collection of disconnected components a finished slice.
- Described as: tracer bullet; nothing usable yet; one feature end to end; lots of files no working feature; finish one thing first
- Related: walking-skeleton, e2e
- Page: https://vibe-coding-101.brighteng.org/c/vertical-slice/

## strangler-fig

**strangler fig** (development workflow). Replace an existing system incrementally by routing selected behavior to a new implementation.

- Use when: A large rewrite needs smaller, reversible releases.
- What: New code takes over one route or feature at a time, behind a switch, while the old system keeps serving everything else. The old path is deleted only after its replacement is proven.
- Why it matters with an agent: A rewrite can drop edge cases hidden in the existing system.
- Do: Move one boundary at a time, compare behavior, and define when the old path will be removed.
- Prompt: Replace this endpoint using the strangler pattern. Preserve its contract, verify the selected path, and document cutover and rollback.
- Avoid: Keeping two implementations indefinitely with no owner for their divergence.
- Described as: incremental rewrite; replace legacy system gradually; migrate piece by piece; big rewrite too risky
- Related: characterization-test, feature-flag
- Page: https://vibe-coding-101.brighteng.org/c/strangler-fig/

## spec-driven

**executable specification** (development workflow). An executable specification makes requirements checkable.

- Use when: The agent keeps filling gaps with different interpretations.
- What: The requirement is written as examples, schemas, or contracts that a test can run, so a disagreement about meaning shows up as a failing check instead of a different guess.
- Why it matters with an agent: A prose goal may omit the rules that distinguish correct behavior.
- Do: Write observable examples and constraints before implementing the uncertain behavior.
- Prompt: Write an executable specification for this workflow, including one rejected case. Implement it and run the checks against the agreed behavior.
- Avoid: A document describes the intended behavior but no check exercises it.
- Described as: prompt as spec; agent keeps interpreting differently; write requirements as tests; spec you can run; acceptance criteria
- Related: bdd, contract-first
- Page: https://vibe-coding-101.brighteng.org/c/spec-driven/

## bdd

**behaviour-driven development** (development workflow). Describe behavior through concrete examples shared by developers and domain experts.

- Use when: Product rules are understood differently by different contributors.
- What: Each rule becomes a scenario in plain language, often written as Given, When, Then, that a developer and a domain expert can both read and a test can run.
- Why it matters with an agent: A generated test may reproduce the code’s assumptions instead of the intended rule.
- Do: Choose examples with observable outcomes, including rejection and boundary cases.
- Prompt: Write Given-When-Then scenarios for this rule. Include a boundary and a rejection, then verify the implementation against them.
- Avoid: Treating scenario syntax alone as proof that the requirement is understood.
- Described as: Given-When-Then; examples of business rules; product and dev disagree on rule; cucumber gherkin scenarios
- Related: spec-driven, tdd
- Page: https://vibe-coding-101.brighteng.org/c/bdd/

## ubiquitous-language

**ubiquitous language** (development workflow). Use a shared domain vocabulary in requirements, code, and conversations.

- Use when: Order, booking, and reservation refer to the same thing in different files.
- What: One word means one thing in requirements, code, and conversation. Real distinctions get separate names instead of being hidden behind synonyms.
- Why it matters with an agent: Inconsistent names can produce duplicate models and conflicting rules.
- Do: Define the domain terms and map existing names before making scoped renames.
- Prompt: Align this feature with the domain vocabulary. Identify conflicting names, update their callers, and verify the behavior remains unchanged.
- Avoid: Renaming distinct business concepts into one word because they look similar.
- Described as: inconsistent naming; same thing different names; domain vocabulary; names do not match business terms; mental model
- Related: adr, refactoring
- Page: https://vibe-coding-101.brighteng.org/c/ubiquitous-language/

## yagni

**YAGNI** (development workflow). Avoid implementing capabilities before a current requirement justifies them.

- Use when: The proposed change adds extension points and configuration with no current consumer.
- What: YAGNI stands for You Aren't Gonna Need It. Build what the current requirement needs, including its validation and error handling, and leave hypothetical variations out.
- Why it matters with an agent: Generated abstractions can make a small feature harder to understand.
- Do: Separate required behavior from hypothetical future variation and implement the required part.
- Prompt: Apply YAGNI to this change. Remove speculative capabilities while preserving today’s requirements, validation, and failure handling.
- Avoid: Calling necessary error handling or access checks speculative work.
- Described as: over-engineered; too many abstractions; remove speculative code; you aren't gonna need it; agent overbuilds
- Related: deep-module, vertical-slice
- Page: https://vibe-coding-101.brighteng.org/c/yagni/

## contract-first

**contract-first design** (development workflow). Define an interface before implementing its producers and consumers.

- Use when: Frontend and backend implementations disagree on request or response formats.
- What: Both sides build against the same written interface, including data shapes, error responses, and what counts as a compatible change. Both sides check it.
- Why it matters with an agent: Two generated implementations can use plausible but incompatible schemas.
- Do: Agree on a small contract and run checks from both sides of the boundary.
- Prompt: Define this API contract before implementing either side. Validate requests, responses, and error cases against the same schema.
- Avoid: Changing the producer’s contract without checking existing consumers.
- Described as: contract-first; frontend backend disagree; API shape mismatch; define API before building; openapi schema first
- Related: dto, breaking-change
- Page: https://vibe-coding-101.brighteng.org/c/contract-first/

## partial-stage

**partial staging** (development workflow). Partial staging selects changes within a file for the next Git commit.

- Use when: A working directory contains an unrelated experiment beside a completed fix.
- What: Only the selected hunks go into the commit; the rest of the file stays as an uncommitted change. Review the staged diff on its own before committing.
- Why it matters with an agent: Staging the whole file can include unfinished work unintentionally.
- Do: Review the staged diff independently from the remaining working-tree diff.
- Prompt: Stage only this completed fix. Show the staged diff and remaining changes, and verify the staged version is coherent before committing.
- Avoid: Running a later blanket add that includes the previously excluded changes.
- Described as: stage only the bug fix; git add -p; hunk; commit part of a file; leave other changes uncommitted
- Related: git-worktree, diff-review
- Page: https://vibe-coding-101.brighteng.org/c/partial-stage/

## context-engineering

**context engineering** (agents and AI). Select and maintain the information an agent needs for the current task.

- Use when: The agent keeps overlooking repository rules or working from obsolete assumptions.
- What: You choose what the agent sees: the requirement, the relevant code, the exact error, and lasting decisions. Then you keep it current as the task changes, instead of pasting everything.
- Why it matters with an agent: More context can bury the evidence needed for the next decision.
- Do: Provide the requirement, relevant code, exact failure, and durable decisions; refresh them when context changes.
- Prompt: Prepare the context for this fix: requirement, relevant files, exact failure, and constraints. Identify missing evidence before editing.
- Avoid: Restricting context so tightly that a relevant caller is never inspected.
- Described as: token budget; compaction; agent forgets rules; what to put in context; too much context; agent lost track
- Related: agents-md, repro
- Page: https://vibe-coding-101.brighteng.org/c/context-engineering/

## tool-use

**tool calling** (agents and AI). Tool calling lets a model request a defined operation from an application.

- Use when: An assistant needs to query data or perform a bounded application action.
- What: The model asks for an operation by name with arguments. The application validates those arguments, checks permission, runs the operation, and returns the result.
- Why it matters with an agent: A fluent tool request can still contain invalid arguments or exceed the user’s authority.
- Do: Expose a narrow schema, validate on the host, and return explicit success or failure.
- Prompt: Expose this action as a tool with validated arguments and host-enforced permissions. Test malformed input and an unauthorized request.
- Avoid: Treating model-generated arguments as trusted application input.
- Described as: function calling; let the AI call our API; give the model actions; chatbot performs actions
- Related: mcp, sandbox
- Page: https://vibe-coding-101.brighteng.org/c/tool-use/

## human-in-the-loop

**human in the loop** (agents and AI). A person reviews a decision at a defined point in an automated workflow.

- Use when: An automated step needs human judgment before an external or irreversible action.
- What: The workflow stops at a defined point, shows a person the exact proposed change, and continues only on approval. Gates go before actions that are external or hard to undo.
- Why it matters with an agent: A general approval can be stretched to cover work the user never reviewed.
- Do: Place the gate immediately before the consequential action and show the concrete proposed change.
- Prompt: Add human review before publishing this result. Show the exact proposed content and verify that rejection leaves it unpublished.
- Avoid: Asking for so many low-value confirmations that meaningful approvals become automatic.
- Described as: plan then act; approval before action; ask before sending; confirm before irreversible step; review gate
- Related: diff-review, tool-use
- Page: https://vibe-coding-101.brighteng.org/c/human-in-the-loop/

## evals

**evals** (agents and AI). An evaluation measures an AI system on a defined set of tasks and criteria.

- Use when: A prompt improvement helps a demo but may regress other cases.
- What: Evals are a fixed set of tasks, with criteria, that you run before and after a prompt, model, or tool change to see what improved and what regressed.
- Why it matters with an agent: One convincing answer is weak evidence of repeatable performance.
- Do: Keep representative cases, failure cases, and held-out examples; compare under the same conditions.
- Prompt: Add an evaluation for this failure and run the representative suite before and after the change. Report regressions as well as improvements.
- Avoid: Tuning repeatedly to the same examples while calling them unseen evaluation.
- Described as: prompt regression; test the AI output; measure prompt quality; did my prompt change make it worse; LLM test suite
- Related: holdout, baseline
- Page: https://vibe-coding-101.brighteng.org/c/evals/

## guardrails

**guardrails** (agents and AI). Enforce explicit limits around automated actions.

- Use when: An agent can reach tools or data beyond the task’s intended scope.
- What: Guardrails are limits enforced in code around what an automated system may do: permissions, input validation, spending and rate budgets, and approval gates.
- Why it matters with an agent: Prompt instructions alone cannot enforce an application permission boundary.
- Do: Decide which operations are allowed and enforce those decisions outside the model.
- Prompt: Enforce these tool limits in the host application. Test a disallowed path, malformed arguments, and an action beyond the user’s permissions.
- Avoid: Describing a restriction in prose while leaving the underlying tool unrestricted.
- Described as: limit what the agent can do; agent did something it should not; enforce limits outside the prompt; AI safety checks in app
- Related: sandbox, least-privilege
- Page: https://vibe-coding-101.brighteng.org/c/guardrails/

## diff-review

**diff review** (agents and AI). Review the changes introduced by a patch, including tests and configuration.

- Use when: A change looks correct in the final file but may have removed safeguards.
- What: You read every added and deleted line, including tests and configuration, and check the callers the change affects, not just the final file.
- Why it matters with an agent: Generated edits can include unrelated changes or weakened assertions.
- Do: Inspect additions, deletions, affected callers, and the evidence for the intended behavior.
- Prompt: Review this diff for regressions, missing cases, and weakened checks. Trace affected callers and report concrete findings with file references.
- Avoid: Reviewing only additions and overlooking a deleted validation check.
- Described as: review my changes; check what changed; agent deleted a check; weakened tests; code review before merge; agent changed files I did not ask; unrelated changes in diff
- Related: verification, breaking-change
- Page: https://vibe-coding-101.brighteng.org/c/diff-review/

## few-shot

**few-shot prompting** (agents and AI). Few-shot prompting provides worked examples of the desired task behavior.

- Use when: A natural-language instruction leaves the expected output format ambiguous.
- What: The prompt includes a few worked input and output examples. They must be consistent and cover the distinctions the model needs, because the model copies the examples more than the instructions.
- Why it matters with an agent: Inconsistent examples can teach the wrong behavior more strongly than the instruction.
- Do: Use a small consistent set and evaluate on different inputs.
- Prompt: Add a few representative examples for this output contract. Evaluate on separate cases, including one that should be rejected.
- Avoid: Reusing the demonstrations as the entire evaluation set.
- Described as: few-shot; give the model examples; inconsistent AI output format; examples in prompt
- Related: evals, structured-output
- Page: https://vibe-coding-101.brighteng.org/c/few-shot/

## structured-output

**structured output** (agents and AI). Constrain model output to a defined structure and validate it at the boundary.

- Use when: Another program must consume the model’s output reliably.
- What: Use the provider's schema-constrained mode, then still validate the result. A response with the right shape can still contain wrong content.
- Why it matters with an agent: Asking for JSON does not ensure parsing, schema validity, or semantic correctness.
- Do: Use supported schema constraints, then validate structure and task-specific rules before consuming the result.
- Prompt: Return and validate output against this schema. Test missing fields, invalid values, and the provider’s refusal or incomplete-output case.
- Avoid: Treating schema-valid claims as verified facts.
- Described as: JSON mode; AI returns invalid JSON; parse model output; schema for LLM response; missing fields in AI response
- Related: dto, evals
- Page: https://vibe-coding-101.brighteng.org/c/structured-output/

## mcp

**MCP** (agents and AI). Model Context Protocol standardizes how applications expose tools and context to AI clients.

- Use when: An AI client needs a reusable integration with an existing service.
- What: MCP (Model Context Protocol) is an open protocol for exposing tools and data to AI clients such as Claude Code and Cursor. The server still decides who may call what.
- Why it matters with an agent: A discoverable tool is not automatically authorized for every user or task.
- Do: Expose a small integration surface and enforce identity, validation, and permissions at execution.
- Prompt: Implement this read-only MCP integration with validated arguments. Verify tool discovery, a successful read, and denial of unauthorized data access.
- Avoid: Assuming protocol compatibility provides the service’s authorization policy.
- Described as: Model Context Protocol; connect AI to our service; AI plugin standard; tool server for agents
- Related: tool-use, least-privilege
- Page: https://vibe-coding-101.brighteng.org/c/mcp/

## sandbox

**sandbox** (agents and AI). A sandbox restricts the resources a process can access.

- Use when: Untrusted code or an agent must run with limited access.
- What: The process can reach only the files, network hosts, and system calls its configuration allows. What it actually blocks depends on that configuration, so test both allowed and denied actions.
- Why it matters with an agent: Instructions cannot substitute for an enforced execution boundary.
- Do: Choose the allowed resources and verify both intended operations and blocked ones.
- Prompt: Run this workload in a sandbox with only its required files and network access. Verify normal execution and denial outside those boundaries.
- Avoid: Disabling the entire boundary to work around one missing permission.
- Described as: run untrusted code safely; agent deleted files; restrict file and network access; isolated environment
- Related: guardrails, least-privilege
- Page: https://vibe-coding-101.brighteng.org/c/sandbox/

## embedding

**embedding** (agents and AI). An embedding represents data as a numerical vector for a particular model and task.

- Use when: An application needs semantic retrieval or similarity matching.
- What: Embeddings let you find similar text by comparing vectors. Results depend on the embedding model, the preprocessing, and the distance measure, so only vectors from the same model can be compared.
- Why it matters with an agent: Nearby vectors are not necessarily relevant, accurate, or authorized for the caller.
- Do: Keep compatible vectors together and evaluate retrieval with permissions and real examples.
- Prompt: Add embeddings for this retrieval task. Verify model compatibility, tenant filtering, and relevance on representative positive and negative examples.
- Avoid: Mixing vectors from incompatible models in one similarity space.
- Described as: semantic search; search by meaning; vector search; similar documents
- Related: rag, evals
- Page: https://vibe-coding-101.brighteng.org/c/embedding/

## rag

**retrieval-augmented generation** (agents and AI). Retrieval-augmented generation supplies retrieved material to a model before it answers.

- Use when: An assistant must answer using private or changing application information.
- What: The application searches its own data, passes the matching passages to the model, and asks for an answer based on them. Retrieval and the grounding of the answer are checked separately.
- Why it matters with an agent: A plausible answer can cite a passage that does not support its claim.
- Do: Enforce retrieval access rules and evaluate both retrieved evidence and the resulting answer.
- Prompt: Build this grounded-answer flow. Test retrieval permissions, unsupported questions, and whether each answer claim is supported by its cited material.
- Avoid: Using prompt instructions as the only tenant filter.
- Described as: RAG; chatbot over our docs; AI makes things up about our data; answer from our documents; ground answers in sources
- Related: embedding, prompt-injection
- Page: https://vibe-coding-101.brighteng.org/c/rag/

## holdout

**holdout set** (agents and AI). A holdout set is reserved for evaluating behavior beyond the examples used for development.

- Use when: An AI change needs evidence of generalization beyond its demonstrations.
- What: Holdout examples are kept out of prompt tuning and are checked only occasionally. Inspecting and tuning against them repeatedly turns them into training examples.
- Why it matters with an agent: A score can reflect memorized examples or leaked related records.
- Do: Choose a split that matches deployment and protect it from iterative tuning.
- Prompt: Create a holdout for this evaluation, grouped by the relevant user or time boundary. Verify development examples cannot leak into it.
- Avoid: Calling a repeatedly inspected and optimized set an untouched holdout.
- Described as: test set; overfitting the prompt; unseen examples; train test split
- Related: evals, baseline
- Page: https://vibe-coding-101.brighteng.org/c/holdout/

## baseline

**baseline** (agents and AI). A baseline is a credible comparison under the same evaluation conditions.

- Use when: A new model or optimization reports a result with no useful comparator.
- What: Run the current or simplest alternative on the same cases with the same metrics, cost, and latency accounting, so you can tell whether the new approach is worth it.
- Why it matters with an agent: A high score can be less useful than a simple existing rule.
- Do: Run the current or simple alternative using the same cases, metrics, and resource accounting.
- Prompt: Establish a realistic baseline before this change. Compare quality, latency, and cost on the same evaluation cases and report the tradeoff.
- Avoid: Weakening the baseline so the proposed approach wins by construction.
- Described as: compared to what; simple rule beats model; before and after comparison; is the new approach better
- Related: evals, verification
- Page: https://vibe-coding-101.brighteng.org/c/baseline/

## quantization

**quantization** (agents and AI). Quantization represents model values with reduced numerical precision.

- Use when: A local model exceeds the available memory or latency budget.
- What: Weights are stored with fewer bits, which can cut memory and sometimes latency. The quality and speed effects depend on the model and runtime, so measure them on the target device.
- Why it matters with an agent: A smaller model file does not guarantee faster inference or acceptable task quality.
- Do: Compare supported representations on the target runtime with representative tasks.
- Prompt: Evaluate quantization for this model on the target device. Compare memory, latency, and task quality against the original representation.
- Avoid: Testing quality on a tiny calibration sample that misses important production inputs.
- Described as: model too big for memory; 4-bit model; GGUF; run model locally; shrink model
- Related: holdout, baseline
- Page: https://vibe-coding-101.brighteng.org/c/quantization/

## agents-md

**repository instructions** (agents and AI). Repository instructions document conventions and commands an agent should use.

- Use when: Every new coding session rediscovers the same setup and checks.
- What: AGENTS.md and CLAUDE.md files tell an agent the setup steps, check commands, and conventions for a repository. They guide the agent but do not enforce permissions.
- Why it matters with an agent: Stale instructions can send an agent through the wrong build or generated files.
- Do: Keep the instructions concise and verify the documented commands in the actual repository.
- Prompt: Update AGENTS.md with this repository’s verified setup, checks, and generated-file rules. Confirm a new session can follow them without undocumented steps.
- Avoid: Treating an instruction file as a system-enforced security boundary.
- Described as: AGENTS.md; CLAUDE.md; do not repeat the test command; agent forgets project setup; cursor rules; project instructions for AI
- Related: context-engineering, sandbox
- Page: https://vibe-coding-101.brighteng.org/c/agents-md/

## deep-module

**deep module** (code design). A small interface hides a substantial useful implementation.

- Use when: Callers must understand too many implementation details.
- What: A deep module provides useful behavior through an interface that is simpler than what it hides.
- Why it matters with an agent: Many generated wrappers add names without reducing what callers must know.
- Do: Compare the caller contract with the hidden work. Check whether a caller can complete a task with less knowledge.
- Prompt: Deepen this module: hide the coordination behind a small interface and test the behavior through that interface.
- Avoid: A one-line forwarding wrapper adds another interface to learn.
- Described as: too many wrappers; shallow modules; hide complexity; simple interface; pointless wrapper functions
- Related: seam, dependency-injection
- Page: https://vibe-coding-101.brighteng.org/c/deep-module/

## seam

**seam** (code design). A place where behavior can be replaced without editing its consumer.

- Use when: Tests need an alternative clock, storage system, or external service.
- What: A seam is a substitution point. Its location determines which behavior can vary independently.
- Why it matters with an agent: Hardwired dependencies make a small test require the entire environment.
- Do: Introduce the smallest useful substitution point. Check the same consumer with two implementations.
- Prompt: Introduce a seam for this dependency. Run the consumer with the real implementation and a controlled test implementation.
- Avoid: Adding an interface everywhere creates indirection without useful substitution.
- Described as: hard to test; replace dependency; test seam; cannot test without real service; swap implementation in tests
- Related: dependency-injection, test-double
- Page: https://vibe-coding-101.brighteng.org/c/seam/

## composition

**composition** (code design). Build a variation by assembling smaller parts.

- Use when: A component accumulates flags for every screen that uses it.
- What: Composition connects parts with explicit responsibilities. The caller chooses the arrangement.
- Why it matters with an agent: Adding another boolean mode can create combinations nobody intended.
- Do: Extract the shared parts and compose two real variants. Check that each arrangement remains understandable.
- Prompt: Use composition for these two variants. Share their common parts, make each layout explicit, and verify both preserve the intended behavior.
- Avoid: Tiny parts still depend on a single giant component full of mode checks.
- Described as: too many boolean props; isEditing isCompact; component modes; props keep growing; flags conflict
- Related: compound-components, component-variant
- Page: https://vibe-coding-101.brighteng.org/c/composition/

## compound-components

**compound components** (code design). Related components cooperate through a shared parent.

- Use when: Callers need different arrangements of tabs, menus, or editors.
- What: Compound components expose coordinated pieces such as a root, trigger, and panel while sharing their state.
- Why it matters with an agent: A growing list of layout props makes the component difficult to extend.
- Do: Define the parent contract and compose two layouts. Check coordination and accessible relationships in both.
- Prompt: Build these tabs as compound components with a shared root, triggers, and panels. Verify keyboard navigation in two different layouts.
- Avoid: Shared state works but the trigger and panel lose their accessible relationship.
- Described as: tabs root trigger panel; flexible component layout; Tabs.List Tabs.Panel; headless component parts
- Related: composition, lifting-state
- Page: https://vibe-coding-101.brighteng.org/c/compound-components/

## component-variant

**component variants** (code design). Name the supported forms of a component explicitly.

- Use when: Independent flags allow contradictory appearances or behaviors.
- What: A variant represents a deliberate component configuration, exposed through a named option or a composed component.
- Why it matters with an agent: An agent can keep adding flags until unsupported combinations become possible.
- Do: List valid configurations and encode them. Check that an invalid combination cannot be requested.
- Prompt: Replace these conflicting flags with explicit component variants. Preserve the supported appearances and reject unsupported combinations.
- Avoid: Every visual detail becomes a separate variant and the API grows again.
- Described as: conflicting props; button sizes and appearances; boolean combinations; variant prop; cva variants
- Related: composition, compound-components
- Page: https://vibe-coding-101.brighteng.org/c/component-variant/

## dependency-injection

**dependency injection** (code design). Supply a collaborator through a contract instead of constructing it inside.

- Use when: The same behavior needs local, remote, or test implementations.
- What: Dependency injection makes a consumer receive the implementation it uses. A function argument is often enough.
- Why it matters with an agent: A component coupled to one concrete store is hard to reuse or test.
- Do: Name the operations the consumer needs. Check it with two implementations of that contract.
- Prompt: Use dependency injection for this store. Keep the consumer on a small contract and verify it with real and in-memory implementations.
- Avoid: The interface copies every method of the underlying library.
- Described as: inject clock; swap store; fake dependency; pass dependencies in; hardcoded client inside class
- Related: seam, composition
- Page: https://vibe-coding-101.brighteng.org/c/dependency-injection/

## types-as-spec

**type-driven development** (code design). Type-driven development uses types to express a design before filling in its implementation.

- Use when: Invalid state combinations keep spreading through the code.
- What: You write the types for valid states first, so impossible combinations fail to compile, then implement against them. Data from outside the program still needs runtime validation.
- Why it matters with an agent: Optional fields and broad types can hide an incomplete model.
- Do: Model valid states and transitions, then implement against those contracts.
- Prompt: Use type-driven development for this request state. Make invalid combinations unrepresentable and test validation at the untrusted input boundary.
- Avoid: Assuming a type assertion validates data received at runtime.
- Described as: impossible states; make invalid states unrepresentable; discriminated union; types before code; optional fields everywhere
- Related: state-machine, structured-output
- Page: https://vibe-coding-101.brighteng.org/c/types-as-spec/

## separation-of-concerns

**separation of concerns** (code design). Separate responsibilities that change for different reasons.

- Use when: One handler mixes transport, business rules, and persistence details.
- What: Code that changes for different reasons, such as HTTP parsing, business rules, and database access, lives in different places so one can change without touching the others.
- Why it matters with an agent: A generated fix can duplicate a rule across unrelated entry points.
- Do: Extract the responsibility that has multiple callers or independent reasons to change.
- Prompt: Separate this business rule from HTTP parsing and persistence. Test the rule directly and verify both existing callers still use it.
- Avoid: Moving code into more folders without changing its dependencies.
- Described as: handler does everything; business logic in controller; duplicated rule in many places; mixed responsibilities; fat controller
- Related: service-layer, deep-module
- Page: https://vibe-coding-101.brighteng.org/c/separation-of-concerns/

## leaky-abstraction

**leaky abstraction** (code design). An abstraction exposes details callers still need to understand.

- Use when: Application code repeatedly handles vendor-specific details despite a wrapper.
- What: Every abstraction leaks somewhat. It becomes a problem when callers still have to handle the hidden system's types, errors, or quirks, so the boundary no longer protects them.
- Why it matters with an agent: A wrapper can add indirection while preserving all the coupling.
- Do: Identify the caller contract and translate the implementation detail at its boundary.
- Prompt: Reduce this abstraction leak. Keep vendor types and errors behind the adapter and verify the caller with two implementations.
- Avoid: Wrapping every method while returning the underlying client through an escape hatch.
- Described as: wrapper still exposes vendor types; vendor errors everywhere; abstraction does not hide details; SDK details leak into app
- Related: adapter, dependency-injection
- Page: https://vibe-coding-101.brighteng.org/c/leaky-abstraction/

## technical-debt

**technical debt** (code design). A design shortcut creates a continuing cost for future changes.

- Use when: A deliberate shortcut will make a known follow-up task harder.
- What: Technical debt is a shortcut that makes later changes cost more. Writing down the shortcut, its cost, and when to fix it lets you weigh repaying it against other work.
- Why it matters with an agent: A vague TODO can conceal the reason a compromise was accepted.
- Do: Name the shortcut, its concrete cost, and the condition that would justify changing it.
- Prompt: Document this technical debt with its current benefit, future cost, and repayment trigger. Keep the immediate implementation within the agreed scope.
- Avoid: Calling every stylistic disagreement debt without identifying a cost.
- Described as: shortcut to ship; write down what we skipped; TODO with no reason; cost of quick fix; tech debt
- Related: adr, yagni
- Page: https://vibe-coding-101.brighteng.org/c/technical-debt/

## semver

**semantic versioning** (code design). Semantic versioning communicates compatibility of a declared public API.

- Use when: A library release needs a version that reflects its effect on consumers.
- What: In major.minor.patch, the major number changes for incompatible API changes, the minor for compatible additions, and the patch for compatible fixes. The version only means something relative to a declared public API.
- Why it matters with an agent: A small code diff can still require a breaking release.
- Do: Identify the public contract and evaluate compatibility before choosing the version.
- Prompt: Review this release against its public API and choose the semantic version. Verify existing consumers and document any incompatible behavior.
- Avoid: Assuming version numbers prove compatibility without checking actual consumers.
- Described as: semantic versioning; semver; which version number; major minor patch; version bump
- Related: breaking-change, contract-first
- Page: https://vibe-coding-101.brighteng.org/c/semver/

## breaking-change

**breaking change** (code design). A change requires an existing consumer to adapt.

- Use when: An API, file format, or shared function is changing.
- What: A change is breaking if an existing consumer has to change, whether a name was removed, a default changed, validation became stricter, or an error looks different.
- Why it matters with an agent: An apparently stricter or cleaner implementation can reject inputs that previously worked.
- Do: Identify consumers, preserve compatibility where needed, and plan migration for intentional breaks.
- Prompt: Identify breaking changes in this patch. Test representative existing consumers and provide a migration path for each intentional incompatibility.
- Avoid: Checking only the exported function signatures.
- Described as: will this break clients; backwards compatible; API change broke app; stricter validation broke callers; migration path
- Related: schema-evolution, contract-first
- Page: https://vibe-coding-101.brighteng.org/c/breaking-change/

## observability

**observability** (code design). Expose evidence that helps explain a system’s behavior.

- Use when: Failures cannot be traced from a user action to the operation that caused them.
- What: Logs record events, metrics count and time them, and traces follow one request across services. Together they let you explain a failure without adding code after the fact.
- Why it matters with an agent: Unstructured print statements may omit identity, timing, or the actual failing boundary.
- Do: Choose a concrete diagnostic question and instrument only the evidence needed to answer it.
- Prompt: Add observability for this failing workflow. Correlate the request and downstream work, measure failures, and verify that logs omit secrets.
- Avoid: Collecting full sensitive payloads instead of the diagnostic fields needed.
- Described as: logs; metrics; traces; cannot debug production; no idea where it fails; add logging
- Related: tail-latency, build-id
- Page: https://vibe-coding-101.brighteng.org/c/observability/

## adr

**architecture decision record** (code design). An architecture decision record captures a consequential choice and its context.

- Use when: A design choice is likely to be revisited after its context is forgotten.
- What: An ADR is a short document recording a significant technical decision: the context, the choice, the alternatives considered, and the consequences. Future readers, including agents, can see why it was made.
- Why it matters with an agent: An agent may propose a discarded approach without seeing why it was rejected.
- Do: Record the decision when it is made and link it to the constraint or evidence behind it.
- Prompt: Write an ADR for this boundary: context, chosen approach, alternatives, and consequences. Check it against existing decisions before implementation.
- Avoid: Writing a retrospective justification that omits the real tradeoff.
- Described as: ADR; record why we chose; agent suggests rejected approach; design decision log; decision document; agent forgets decisions
- Related: deep-module, technical-debt
- Page: https://vibe-coding-101.brighteng.org/c/adr/

## invariant

**invariant** (code design). A condition must remain true across permitted operations.

- Use when: Several paths must preserve the same business rule.
- What: An invariant is a rule that every write must keep true, such as a balance never going negative. Enforce it where all writers pass through, ideally the database or one domain function.
- Why it matters with an agent: Repeated local checks may leave an unguarded write path.
- Do: State the rule precisely, identify all writers, and test attempts to violate it.
- Prompt: Enforce this invariant at the authoritative boundary. Test invalid input and concurrent writers, including paths that bypass the UI.
- Avoid: Writing the rule only in a comment or form validation.
- Described as: rule must always hold; balance went negative; data should never be in this state; enforce business rule everywhere
- Related: unique-constraint, state-machine
- Page: https://vibe-coding-101.brighteng.org/c/invariant/

## strategy

**strategy pattern** (code design). A strategy supplies interchangeable behavior behind a shared contract.

- Use when: The same workflow supports several algorithms or output formats.
- What: Each variant implements the same small contract, such as a function that writes one export format. The workflow calls the contract without checking which variant it has.
- Why it matters with an agent: Scattered mode checks make each new variant a change across many callers.
- Do: Extract the varying behavior and verify callers against more than one implementation.
- Prompt: Use interchangeable strategies for these export formats. Verify a third writer can be added without changing the workflow’s callers.
- Avoid: Building a class hierarchy when a small function parameter would express the variation.
- Described as: CSV and JSON export; interchangeable behavior; if else for each format; pluggable algorithm; switch on type everywhere
- Related: composition, dependency-injection
- Page: https://vibe-coding-101.brighteng.org/c/strategy/

## adapter

**adapter pattern** (code design). An adapter translates an existing interface into the interface its caller expects.

- Use when: An application must support another vendor or an incompatible external API.
- What: The adapter converts between the application's interface and an external API, including data shapes and errors, so the rest of the code never sees the vendor's types.
- Why it matters with an agent: SDK-specific response and error types can spread across business logic.
- Do: Define the application contract and translate external data and failures at the boundary.
- Prompt: Add an adapter for this provider behind the existing contract. Run the same behavior checks against both provider implementations.
- Avoid: Returning the raw vendor client to every caller for convenience.
- Described as: storage provider; vendor SDK; switch providers; wrap third-party API; translate external API
- Related: seam, dto
- Page: https://vibe-coding-101.brighteng.org/c/adapter/

## service-layer

**service layer** (code design). An application service coordinates a use case across entry points.

- Use when: HTTP endpoints and background jobs duplicate the same business workflow.
- What: A service function implements one use case, such as creating an order, and every entry point calls it: HTTP routes, jobs, and scripts. Parsing and presentation stay in the entry points.
- Why it matters with an agent: A fix applied to one entry point may leave another implementation inconsistent.
- Do: Extract the shared operation and keep its dependencies explicit.
- Prompt: Move this shared use case into an application service. Verify the HTTP endpoint and import job use it and preserve their existing behavior.
- Avoid: Introducing unrelated persistence abstractions merely because a service was extracted.
- Described as: thin controller; order creation; HTTP and import job; same logic in route and job; use case function
- Related: separation-of-concerns, dependency-injection
- Page: https://vibe-coding-101.brighteng.org/c/service-layer/

## repository

**repository pattern** (code design). A repository exposes persistence operations needed by the application.

- Use when: Domain code depends on storage details that must change independently.
- What: A repository offers the persistence operations the application needs, like findOrder or saveOrder, and hides the ORM behind them. Copying the whole ORM interface into it adds no value.
- Why it matters with an agent: A wrapper can add maintenance cost without removing any dependency.
- Do: Define a small application-facing contract and test its required behavior against the real persistence implementation.
- Prompt: Introduce a repository only for these application operations. Keep ORM details behind it and verify the real storage contract.
- Avoid: Re-exporting every query-builder method through another object.
- Described as: order persistence; do not wrap the whole ORM; data access layer; ORM calls everywhere
- Related: deep-module, seam
- Page: https://vibe-coding-101.brighteng.org/c/repository/

## feature-folder

**feature-based organization** (code design). Feature-based organization keeps related implementation close to the capability it serves.

- Use when: Changing one feature requires searching many unrelated global folders.
- What: A feature's components, state, API calls, and tests sit in one folder. Only code that several features really share goes in a shared folder.
- Why it matters with an agent: A generated directory structure can scatter code that changes together.
- Do: Identify the feature boundary and move related code without changing behavior or creating import cycles.
- Prompt: Organize this feature’s components, state, and tests together. Verify imports and behavior, and keep genuinely shared code outside the feature boundary.
- Avoid: Assuming every internal subfolder is wrong even when the feature remains cohesive.
- Described as: billing feature together; not global folders; folder structure by feature; colocate feature files; too many folders to change one thing
- Related: separation-of-concerns, refactoring
- Page: https://vibe-coding-101.brighteng.org/c/feature-folder/

## ownership

**ownership** (code design). Ownership defines which part of a program controls a value’s lifetime.

- Use when: A Rust change encounters ownership or lifetime errors.
- What: In Rust, each value has one owner that frees it when it goes out of scope. Other code borrows it with references, and the compiler checks that no borrow outlives the owner.
- Why it matters with an agent: Cloning or shared ownership can conceal the intended lifecycle and add cost.
- Do: Identify who should own the value and how long each borrower needs access.
- Prompt: Resolve this ownership error by making the intended lifetime explicit. Prefer borrowing where appropriate and verify behavior without adding unnecessary clones or unsafe code.
- Avoid: Using shared ownership to avoid deciding which component actually owns the resource.
- Described as: borrow checker; Rust lifetimes; does not live long enough; cannot move out of; too many clones
- Related: structured-concurrency, dependency-injection
- Page: https://vibe-coding-101.brighteng.org/c/ownership/

## state-machine

**state machine** (code design). A state machine describes states and permitted transitions driven by events.

- Use when: A workflow can become both saving and failed, or process an event in the wrong phase.
- What: You list the states, the events, and which events move which states where. Any event the table doesn't allow is handled on purpose instead of by accident.
- Why it matters with an agent: Independent booleans can admit combinations that no valid workflow should reach.
- Do: List states, events, and transition effects; decide how unexpected events are handled.
- Prompt: Model this workflow as a state machine. Test valid transitions, rejected events, failure, and retry without contradictory states.
- Avoid: Maintaining a second set of flags that can disagree with the machine’s state.
- Described as: impossible state; loading and error at the same time; too many booleans; status flow; wrong step allowed; workflow states
- Related: reducer, invariant
- Page: https://vibe-coding-101.brighteng.org/c/state-machine/

## lifting-state

**lifting state** (frontend and browser state). Move shared state to the nearest owner that can coordinate its users.

- Use when: Sibling controls must edit and display the same value.
- What: Lifting state gives cooperating components one owner and passes values or actions to their consumers.
- Why it matters with an agent: Duplicated local copies drift; unnecessary global state couples unrelated screens.
- Do: Find the smallest shared owner. Check that editing either control updates both views.
- Prompt: Lift this shared selection to the nearest common owner. Verify that both controls update together and unrelated panels remain independent.
- Avoid: Moving all state to the application root makes a local interaction global.
- Described as: sync sibling components; shared selection; single source of truth; two components out of sync; share state between components
- Related: derived-state, dependency-injection
- Page: https://vibe-coding-101.brighteng.org/c/lifting-state/

## derived-state

**derived state** (frontend and browser state). Calculate a value from state you already have.

- Use when: A total, filtered list, or count falls out of sync.
- What: Derived state is computed from existing inputs. In React, values needed for rendering can usually be calculated during render.
- Why it matters with an agent: Effects that copy computed values into another state variable create extra synchronization work.
- Do: Remove the redundant stored value. Check that one input change updates every dependent display.
- Prompt: Use derived state for the filtered list and count. Remove the synchronization effect and verify both update from the same inputs.
- Avoid: A stored duplicate survives under a different name.
- Described as: count out of sync; calculate total; duplicate state; useEffect to update state; value out of sync with list
- Related: lifting-state, memoization
- Page: https://vibe-coding-101.brighteng.org/c/derived-state/

## effect-deps

**effect dependencies** (frontend and browser state). The reactive inputs that determine when an effect must resynchronize.

- Use when: A subscription or request keeps using an old value.
- What: In React, an effect must track the reactive values it reads. Dependency identity determines when React reruns it.
- Why it matters with an agent: Omitting a dependency can make the page look correct until a prop changes.
- Do: Identify the external system and its inputs. Check cleanup and resubscription when an input changes.
- Prompt: Correct this effect’s dependencies. Keep the linter enabled and verify that changing the selected id cleans up the old subscription.
- Avoid: A new object on every render causes unnecessary resubscriptions.
- Described as: stale effect; missing dependency; effect reruns every render; useEffect dependency array; infinite loop useEffect; exhaustive-deps warning
- Related: event-cleanup, derived-state
- Page: https://vibe-coding-101.brighteng.org/c/effect-deps/

## functional-update

**functional state update** (frontend and browser state). Compute the next state from the previous state supplied by the framework.

- Use when: Rapid updates lose increments or append to an old list.
- What: React setter functions can receive an updater that operates on pending state rather than a captured render value.
- Why it matters with an agent: A callback can retain an older state value and overwrite intervening changes.
- Do: Use an updater when the next value depends on the previous one. Check several queued updates.
- Prompt: Use functional state updates for this increment. Verify that three queued increments increase the value by three.
- Avoid: The updater performs a side effect or mutates the previous object.
- Described as: lost increments; stale closure; setState previous value; fast clicks lose updates; setCount(c => c + 1)
- Related: derived-state, effect-deps
- Page: https://vibe-coding-101.brighteng.org/c/functional-update/

## request-waterfall

**request waterfall** (frontend and browser state). Requests form a sequence that adds their waiting times.

- Use when: A page loads several resources one after another.
- What: A waterfall is a dependency chain in request timing. Some dependencies are real; others come from avoidable sequential awaits.
- Why it matters with an agent: Correct-looking await statements can add their latencies together.
- Do: Map actual dependencies and start independent reads together. Check the network timeline and failure behavior.
- Prompt: Remove the request waterfall from this page. Run independent reads concurrently and show their overlap in the network timeline.
- Avoid: Requests that require an earlier result are parallelized incorrectly.
- Described as: sequential fetches; slow page loading; parallel requests; await one after another; Promise.all; requests wait for each other; bandwidth vs latency; bandwidth latency
- Related: request-deduplication, suspense
- Page: https://vibe-coding-101.brighteng.org/c/request-waterfall/

## request-deduplication

**request deduplication** (frontend and browser state). Share equivalent requests within a defined scope.

- Use when: Several components request the same data at the same time.
- What: Request deduplication lets callers reuse an in-flight operation or cached result identified by the same key.
- Why it matters with an agent: Repeated fetch code can quietly multiply traffic.
- Do: Include all result-changing inputs in the key. Check one request for equivalent callers and separate results for different users.
- Prompt: Deduplicate these equivalent requests through the existing query cache. Verify one network call and preserve user-specific cache keys.
- Avoid: An overly broad key shares data between different users or filters.
- Described as: duplicate requests; same fetch twice; dedupe; same API call many times; every component fetches the same data
- Related: request-waterfall, request-scope
- Page: https://vibe-coding-101.brighteng.org/c/request-deduplication/

### request deduplication: a worked example

Canonical page: https://vibe-coding-101.brighteng.org/c/request-deduplication/#before-and-after

#### The problem

Two components request the same profile at the same time. We want one underlying read while it is pending, but different users must never share a response and a failed read must be retryable.

#### Prompt to paste

Deduplicate these equivalent requests through the existing query cache. Verify one network call and preserve user-specific cache keys.

#### Before

Each caller invokes the loader independently. Equivalent concurrent reads start twice, even though both callers need the same result.

#### After

Keep a promise for each equivalent read within one owner. Include user identity and resource identity in the key. Return the existing pending promise, then remove it on either success or failure so later calls can refresh.

#### Run the check

Save the following code as request-deduplication.mjs and run `node --test request-deduplication.mjs` with Node.js 22.12 or later.

```js
import test from 'node:test';
import assert from 'node:assert/strict';

function before(load) {
  return (user, resource) => load(user, resource);
}

function after(load) {
  const pending = new Map();
  return (user, resource) => {
    const key = JSON.stringify([user, resource]);
    if (!pending.has(key)) {
      const request = Promise.resolve()
        .then(() => load(user, resource))
        .finally(() => pending.delete(key));
      pending.set(key, request);
    }
    return pending.get(key);
  };
}

test('equivalent callers start two reads without deduplication', async () => {
  let calls = 0;
  const read = before(async () => { calls++; return 'profile'; });
  await Promise.all([read('alice', 'profile'), read('alice', 'profile')]);
  assert.equal(calls, 2);
});

test('reads share only within scope and failures do not stick', async () => {
  let calls = 0;
  const read = after(async (user) => { calls++; return user; });
  const a = read('alice', 'profile');
  const b = read('alice', 'profile');
  assert.equal(a, b);
  assert.deepEqual(await Promise.all([a, b, read('bob', 'profile')]),
    ['alice', 'alice', 'bob']);
  assert.equal(calls, 2);
  await read('alice', 'profile');
  assert.equal(calls, 3);
  let attempts = 0;
  const retry = after(() => {
    if (++attempts === 1) throw new Error('offline');
    return 'recovered';
  });
  const failed = await Promise.allSettled([retry('alice', 'profile'), retry('alice', 'profile')]);
  assert.deepEqual(failed.map((item) => item.status), ['rejected', 'rejected']);
  assert.equal(attempts, 1);
  assert.equal(await retry('alice', 'profile'), 'recovered');
  assert.equal(attempts, 2);
});
```

#### Expected result

Two equivalent concurrent calls produce two loader calls before and one shared call afterward. Different users remain separate. Settled reads are removed, and a shared rejected read can be tried again.

#### Limits

This in-memory example shares pending reads in one owner only. It is not a persistent cache, a distributed lock, or an idempotency guarantee for writes. Include every result-changing input in the key; create the owner inside the correct account or request lifetime. Decide how cancellation works when several consumers share one promise. Prefer an existing query cache when it already provides the needed lifecycle.

#### Sources

- [MDN: Promise.prototype.finally](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally): Cleanup runs when a promise settles. The scoped map and behavior checks are original examples.

Sources checked: 2026-10-11. These are original illustrative examples with automated checks. Human editorial approval is not recorded. Policy: https://vibe-coding-101.brighteng.org/editorial/


## code-splitting

**code splitting** (frontend and browser state). Load a separate code bundle when a feature needs it.

- Use when: A rarely opened editor inflates the first page download.
- What: Code splitting divides the application into loadable chunks. Dynamic imports can defer a feature’s code until it is needed.
- Why it matters with an agent: An eager root import can pull an optional feature into every page.
- Do: Move the feature behind a loading boundary. Check the first-load bundle and opening the feature.
- Prompt: Code-split this optional editor. Verify its bundle is absent from the initial load and loads successfully when the editor opens.
- Avoid: A second eager import keeps the module in the initial bundle.
- Described as: large JavaScript bundle; lazy loading; dynamic import; React.lazy; bundle too big; slow first load
- Related: suspense, request-waterfall
- Page: https://vibe-coding-101.brighteng.org/c/code-splitting/

## suspense

**Suspense boundary** (frontend and browser state). Keep a useful shell visible while supported child content is waiting.

- Use when: One slow region blocks an otherwise useful React page.
- What: A Suspense boundary supplies a fallback for children that suspend through a supported framework or data source.
- Why it matters with an agent: Wrapping the whole page can replace usable navigation with a loading screen.
- Do: Place the boundary around the slow region. Check loading, successful content, and error handling separately.
- Prompt: Add a Suspense boundary around this slow region. Keep navigation visible and verify loading, success, and the separate error state.
- Avoid: An ordinary fetch in an effect is assumed to activate Suspense automatically.
- Described as: stream page sections; whole page loading; loading boundary; one slow part blocks the page; loading.tsx; spinner covers everything
- Related: code-splitting, request-waterfall
- Page: https://vibe-coding-101.brighteng.org/c/suspense/

## serialization

**serialization** (frontend and browser state). Encode state so it can cross a storage or process boundary.

- Use when: A draft must survive a restart or data must reach another process.
- What: Serialization converts values into an agreed format; deserialization reconstructs them. The format determines which values are supported.
- Why it matters with an agent: Saving an entire runtime object can include unsupported values or private fields.
- Do: Choose the fields and encoding deliberately. Check a round trip in a fresh instance.
- Prompt: Serialize this draft with an explicit data schema. Test that saving and loading in a fresh instance restores the same content.
- Avoid: A file is written successfully but cannot reconstruct the original state.
- Described as: save game; save draft; persist state; JSON stringify; dates become strings after save; save and load state
- Related: schema-evolution, request-scope
- Page: https://vibe-coding-101.brighteng.org/c/serialization/

## schema-evolution

**schema evolution** (frontend and browser state). Change a stored format while handling older data deliberately.

- Use when: An app update makes existing drafts or settings unreadable.
- What: Schema evolution defines how readers and writers handle multiple versions of a data format.
- Why it matters with an agent: New generated fields can silently change assumptions about files already on disk.
- Do: Version the format and define the old-data path. Check a previous-version fixture without losing the original.
- Prompt: Add schema evolution for this stored draft. Migrate a previous-version fixture and verify that its content survives the upgrade.
- Avoid: A failed migration overwrites the only copy of the old data.
- Described as: old save; old file no longer loads; versioned data; renamed field broke saved data; data migration on load; Schema evolution
- Related: serialization, migration, schema-registry, data-migration
- Sources checked: 2026-10-11 (not human editorial approval)
- [Confluent: Schema evolution and compatibility](https://docs.confluent.io/platform/current/schema-registry/fundamentals/schema-evolution.html): Schema Registry versions schemas and enforces configured compatibility modes; backward and forward compatibility differ.
- Page: https://vibe-coding-101.brighteng.org/c/schema-evolution/

## event-cleanup

**subscription cleanup** (frontend and browser state). Release listeners and subscriptions when their owner stops using them.

- Use when: Opening a screen repeatedly causes duplicate events or growing memory.
- What: A subscription has a lifetime. Cleanup detaches it when its owning component unmounts or its inputs change.
- Why it matters with an agent: Generated setup code can work on first mount while leaking on every later mount.
- Do: Pair each registration with cleanup using the same identity. Check repeated mount and unmount cycles.
- Prompt: Add subscription cleanup to this component. Mount and unmount it repeatedly and verify that each event invokes one active handler.
- Avoid: Removing a newly created callback leaves the original listener registered.
- Described as: duplicate listeners; memory leak; unsubscribe; remove event listener; handler fires multiple times; useEffect cleanup
- Related: effect-deps, test-isolation
- Page: https://vibe-coding-101.brighteng.org/c/event-cleanup/

## optimistic-ui

**optimistic UI** (frontend and browser state). Show an expected change before the server confirms it.

- Use when: A reversible interaction feels slow while waiting for the network.
- What: The interface applies the change immediately and marks it pending, then confirms it, rolls it back, or reconciles it when the server responds.
- Why it matters with an agent: A fast-looking UI can become permanently inconsistent after a rejected request.
- Do: Choose a reversible operation, track its pending state, and define rollback or reconciliation.
- Prompt: Make this toggle optimistic. Test success, rejection, and overlapping edits without losing the latest user intent.
- Avoid: Rolling back an old request overwrites a newer successful edit.
- Described as: instant UI update; update before server responds; feels slow waiting for save; rollback on error; useOptimistic
- Related: optimistic-lock, idempotency
- Page: https://vibe-coding-101.brighteng.org/c/optimistic-ui/

## ssr

**rendering strategy** (frontend and browser state). Rendering strategy determines when and where initial HTML is produced.

- Use when: A route’s initial content, indexing, or authenticated data needs a deliberate rendering choice.
- What: Server rendering builds HTML per request, static generation builds it at deploy time, and client rendering builds it in the browser. Each route can use a different one depending on freshness, privacy, and interactivity.
- Why it matters with an agent: A convenient starter can impose one rendering model on every route.
- Do: Classify public and personalized routes by freshness and interaction needs, then inspect their initial response.
- Prompt: Choose a rendering strategy for each route. Verify initial HTML, personalized-data isolation, and navigation rather than assuming every page needs client rendering.
- Avoid: Putting private user content into a shared static or cached response.
- Described as: SSR vs SSG vs CSR; server side rendering; static generation; SEO for pages; page empty without JavaScript
- Related: hydration, islands
- Page: https://vibe-coding-101.brighteng.org/c/ssr/

## hydration

**hydration** (frontend and browser state). Hydration connects client-side behavior to server-rendered HTML.

- Use when: A server-rendered page flashes different content or reports a hydration mismatch.
- What: After server-rendered HTML arrives, the framework attaches event handlers and state to it. The first client render must match the server HTML, or the framework reports a mismatch.
- Why it matters with an agent: Reading client-only state too early can produce a different initial tree.
- Do: Find the differing inputs and isolate genuinely client-only behavior.
- Prompt: Fix this hydration mismatch at its cause. Compare initial server and client output and verify the page before and after JavaScript loads.
- Avoid: Suppressing warnings while leaving incorrect event or state behavior.
- Described as: hydration mismatch; text content does not match server; flicker on load; window is not defined; content flashes then changes; dark mode flash on load; theme flicker
- Related: ssr, server-components
- Page: https://vibe-coding-101.brighteng.org/c/hydration/

## tree-shaking

**tree shaking** (frontend and browser state). Tree shaking removes unused code that a bundler can prove is unnecessary.

- Use when: A bundle contains a large dependency even though the app uses little of it.
- What: The bundler drops exports that no code uses, but only when it can prove removing them is safe. Module format and side effects decide what it can remove.
- Why it matters with an agent: Import syntax alone does not prove which bytes reach the browser.
- Do: Inspect the bundle graph and side-effect metadata before changing import structure.
- Prompt: Investigate tree shaking for this dependency. Compare the built bundle before and after the import change and verify required side effects still run.
- Avoid: Assuming every barrel export prevents tree shaking or marking real side effects as removable.
- Described as: unused code in bundle; whole library included; bundle size from one import; dead code elimination; sideEffects false
- Related: code-splitting, verification
- Page: https://vibe-coding-101.brighteng.org/c/tree-shaking/

## controlled-input

**controlled input** (frontend and browser state). A controlled input gets its current value from application state.

- Use when: A form’s displayed value and submitted value disagree.
- What: The input displays the value held in state, and every keystroke updates that state. One owner holds the draft, so the displayed and submitted values cannot differ.
- Why it matters with an agent: An agent may mix default values, state ownership, and delayed updates.
- Do: Choose an owner for the draft and test typing, reset, and submission.
- Prompt: Make this input consistently controlled by local draft state. Verify typing, reset, and submission without cursor jumps or lost edits.
- Avoid: Waiting for a server response before updating the local typing state.
- Described as: input value out of sync; cursor jumps to end; form submits old value; value and onChange; uncontrolled to controlled warning
- Related: lifting-state, autosave
- Page: https://vibe-coding-101.brighteng.org/c/controlled-input/

## progressive-enhancement

**progressive enhancement** (frontend and browser state). Provide a useful baseline and improve it when additional browser capabilities are available.

- Use when: A basic form or navigation action fails when its enhancement script does not load.
- What: The page works with plain HTML first, for example a form that posts and a link that navigates, and JavaScript adds a better experience on top when it loads.
- Why it matters with an agent: An event handler can accidentally remove a working HTML fallback.
- Do: Keep the baseline action meaningful and test both enhanced and fallback paths.
- Prompt: Progressively enhance this form. Verify a successful baseline submission and the enhanced experience, including a failed script or request.
- Avoid: Calling preventDefault without providing either a working replacement or recovery.
- Described as: works without JavaScript; form does nothing if JS fails; HTML fallback; no-JS baseline
- Related: a11y, ssr
- Page: https://vibe-coding-101.brighteng.org/c/progressive-enhancement/

## focus-management

**focus management** (frontend and browser state). Move and restore keyboard focus deliberately as interface context changes.

- Use when: Opening or closing a dialog leaves keyboard users in the wrong place.
- What: When a dialog opens, focus moves into it and stays there. When it closes, focus returns to the control that opened it, so keyboard and screen-reader users keep their place.
- Why it matters with an agent: A visual overlay can appear while focus remains in the page behind it.
- Do: Use the platform’s modal behavior where appropriate and test entry, navigation, exit, and restoration.
- Prompt: Fix this dialog’s focus management. Verify initial focus, Tab and Shift-Tab, Escape, and focus returning to the trigger.
- Avoid: Moving focus on every render and interrupting typing.
- Described as: focus trap; modal keyboard navigation; focus lost after closing dialog; tab goes behind modal; return focus to button
- Related: a11y, semantic-locator
- Page: https://vibe-coding-101.brighteng.org/c/focus-management/

## client-server-state

**client state vs server state** (frontend and browser state). Distinguish a local interaction draft from cached data owned by a server.

- Use when: Editing a form unintentionally changes other views before saving.
- What: Server state is a cached copy of data the server owns; client state is something like an unsaved draft that only the browser has. They refresh, update, and recover differently, so keep them in separate places.
- Why it matters with an agent: One shared object can blur unsaved input and confirmed data.
- Do: Give the draft a lifecycle and reconcile the server cache after the mutation resolves.
- Prompt: Separate this form’s draft from its server cache. Test cancel, failed save, and a successful response without mutating the cached record in place.
- Avoid: Overwriting an unsaved draft whenever background data refreshes.
- Described as: form edits change other views; draft vs saved data; cancel does not revert; background refetch overwrites form; server state vs UI state
- Related: optimistic-ui, query-invalidation
- Page: https://vibe-coding-101.brighteng.org/c/client-server-state/

## islands

**islands architecture** (frontend and browser state). Islands architecture adds interactive components to an otherwise server-rendered or static page.

- Use when: Only a small part of a content page needs JavaScript.
- What: The page is static HTML except for a few marked components that load JavaScript and hydrate on their own. Content that doesn't need JavaScript ships none.
- Why it matters with an agent: Making the whole page interactive can ship unnecessary code and data.
- Do: Keep static content outside client boundaries and hydrate only the widgets that need it.
- Prompt: Render this content page with an interactive island for the filter. Verify the article works before hydration and unrelated pages do not load the widget.
- Avoid: Passing the whole document into an island when it only needs a small input.
- Described as: partial hydration; only one widget interactive; Astro islands; too much JavaScript for static page; client:load
- Related: ssr, hydration
- Page: https://vibe-coding-101.brighteng.org/c/islands/

## rules-of-hooks

**rules of hooks** (frontend and browser state). React Hooks follow rules about where they can be called.

- Use when: A component calls useState or useEffect conditionally.
- What: React matches Hook state to calls by their order, so state and effect Hooks must run in the same order on every render: at the top level of a component or custom Hook, never inside a condition or loop.
- Why it matters with an agent: An added branch can change which Hook state corresponds to each call.
- Do: Keep stateful Hooks in components or custom Hooks at valid call sites and retain the lint checks.
- Prompt: Fix this component’s Hook call order. Keep the rules-of-hooks check enabled and test both sides of the conditional behavior.
- Avoid: Applying an oversimplified rule to APIs with documented exceptions instead of checking the API contract.
- Described as: React hooks; rendered more hooks than previous render; hook called conditionally; invalid hook call; useState inside if
- Related: custom-hook, effect-deps
- Page: https://vibe-coding-101.brighteng.org/c/rules-of-hooks/

## list-key

**list key** (frontend and browser state). A list key identifies an item across renders.

- Use when: Editing a row affects another row after sorting or inserting.
- What: React uses the key to match list items between renders. A stable key, such as a database id, keeps each item's state with that item when the list is sorted or changed.
- Why it matters with an agent: An index or random key can attach state to a position or recreate it unnecessarily.
- Do: Choose a stable identity that survives the item’s lifecycle and test reordering.
- Prompt: Use stable identity keys for this editable list. Verify drafts stay with their items after insertion, sorting, and filtering.
- Avoid: Changing an optimistic item’s key when the server assigns its permanent ID.
- Described as: reconciliation key; key prop warning; input jumps to another row; using index as key; list state mixed up after sort
- Related: controlled-input, optimistic-ui
- Page: https://vibe-coding-101.brighteng.org/c/list-key/

## stale-closure

**stale closure** (frontend and browser state). A callback retains values from the environment where it was created.

- Use when: A timer or listener repeatedly uses an old prop or state value.
- What: A function captures the variables in scope when it was created. A timer or listener created on an early render keeps seeing those old values after state changes.
- Why it matters with an agent: A callback can compile correctly while observing outdated input.
- Do: Decide which values should trigger resubscription and which should be read at execution time.
- Prompt: Fix this stale closure. Use the framework’s appropriate update or subscription pattern and test the callback after its inputs change.
- Avoid: Putting everything in refs merely to hide missing dependencies.
- Described as: stale props; stale state; setInterval old value; callback uses old state; listener sees outdated value
- Related: effect-deps, functional-update
- Page: https://vibe-coding-101.brighteng.org/c/stale-closure/

## css-specificity

**CSS specificity** (frontend and browser state). Specificity ranks competing selectors within the relevant cascade context.

- Use when: A style change works only after repeatedly increasing selector strength.
- What: When several rules set the same property, the winner depends on origin, !important, cascade layers, then specificity, then source order. Raising specificity only fixes one of those.
- Why it matters with an agent: An agent can add overrides while leaving the conflicting ownership unresolved.
- Do: Inspect the winning declaration and fix the cascade or component boundary intentionally.
- Prompt: Resolve this CSS conflict using the computed styles and cascade. Verify the intended variants without accumulating unexplained overrides.
- Avoid: Assuming a higher z-index or more specific selector can solve every visual layering problem.
- Described as: the cascade; cascade layers; style not applying; !important everywhere; CSS override not working
- Related: stacking-context, design-tokens
- Page: https://vibe-coding-101.brighteng.org/c/css-specificity/

## stacking-context

**stacking context** (frontend and browser state). A stacking context groups elements into a local stacking order.

- Use when: A menu appears behind another region despite a large z-index.
- What: Properties like transform, opacity, and position with z-index create a new stacking context. A child's z-index only orders it within that context, so it cannot rise above elements outside it.
- Why it matters with an agent: Increasing a number can leave the controlling ancestor unchanged.
- Do: Find the relevant contexts and choose the intended overlay boundary, portal, or top-layer primitive.
- Prompt: Fix this overlay’s stacking context. Verify its position, clipping, scrolling, and focus behavior without relying on arbitrarily large z-index values.
- Avoid: Moving an overlay into a portal without preserving its anchor or focus behavior.
- Described as: z-index; z-index not working; menu behind other element; dropdown hidden behind; overlay under content
- Related: focus-management, split-pane
- Page: https://vibe-coding-101.brighteng.org/c/stacking-context/

## server-components

**server components** (frontend and browser state). React Server Components run outside the client bundle and can prepare UI close to server data.

- Use when: A data-heavy page sends unnecessary code or sensitive data to the browser.
- What: Server Components render on the server and send UI to the client without their code. Components marked 'use client' handle browser interaction, and only serializable props cross between them.
- Why it matters with an agent: Marking a broad module boundary as client code can pull unintended dependencies into it.
- Do: Keep server-only dependencies protected and pass only the data allowed across the client boundary.
- Prompt: Keep this data read in a Server Component and isolate the interactive control. Inspect the client bundle and verify no server-only dependency or secret crosses the boundary.
- Avoid: Confusing the module dependency boundary with every visual descendant in the rendered tree.
- Described as: RSC; use client; server and client composition; server client; secret in client bundle; Next.js app router data fetching
- Related: suspense, data-access-layer
- Page: https://vibe-coding-101.brighteng.org/c/server-components/

## event-delegation

**event delegation** (frontend and browser state). A parent listener handles suitable events from descendants.

- Use when: A dynamic list needs shared handling for events from its rows.
- What: Events bubble up from the element clicked to its ancestors, so one listener on a stable container can handle clicks on rows that are added later.
- Why it matters with an agent: A listener attached only to initial children can miss rows inserted later.
- Do: Handle the relevant event at a stable ancestor and resolve the intended target within that boundary.
- Prompt: Delegate this list interaction to its stable container. Test nested click targets, newly inserted rows, and cleanup when the container is removed.
- Avoid: Assuming every event bubbles or trusting a target outside the intended container.
- Described as: bubbling; capturing; click not working on new elements; one listener for many items; dynamic elements events
- Related: event-cleanup, semantic-locator
- Page: https://vibe-coding-101.brighteng.org/c/event-delegation/

## service-worker

**service worker** (frontend and browser state). A service worker can intercept requests and manage offline behavior.

- Use when: An offline-capable site keeps serving outdated or incompatible assets.
- What: A service worker is a script that sits between the page and the network, so it can serve cached responses offline. A new version installs while old tabs still run the old one.
- Why it matters with an agent: A cache-first recipe can leave active pages using mixed application versions.
- Do: Define cache strategies by resource and test update transitions as well as the first installation.
- Prompt: Define this service worker’s caching and update policy. Verify offline loading and an upgrade with an older tab still open.
- Avoid: Activating new cached assets before existing pages can safely use them.
- Described as: service worker update; users stuck on old version; PWA cache; works offline; clear cache to see changes
- Related: http-cache, offline-first
- Page: https://vibe-coding-101.brighteng.org/c/service-worker/

## web-storage

**web storage** (frontend and browser state). Browser storage APIs offer different persistence and access models.

- Use when: Browser data must survive reload without blocking interactions or exposing credentials.
- What: localStorage is synchronous, holds strings only, and is limited to a few megabytes. IndexedDB is asynchronous and stores structured data. Any script on the same origin can read both.
- Why it matters with an agent: A convenient storage example can ignore size, corruption, quota, and same-origin script access.
- Do: Choose storage by data size and access pattern; validate stored values and handle failed writes.
- Prompt: Choose suitable browser storage for this non-secret draft. Test reload, malformed stored data, and quota failure without losing the current edit.
- Avoid: Treating browser storage as inaccessible to scripts running on the same origin.
- Described as: localStorage; sessionStorage; IndexedDB; token in localStorage; save data in browser; quota exceeded
- Related: serialization, schema-evolution
- Page: https://vibe-coding-101.brighteng.org/c/web-storage/

## structural-typing

**structural typing** (frontend and browser state). Structural typing compares the shape of types rather than only their declared names.

- Use when: Two values with similar shapes are being treated as interchangeable.
- What: TypeScript treats two types as compatible if their shapes match, whatever they are named. So a UserId and an OrderId that are both strings can be mixed up unless you brand them.
- Why it matters with an agent: A type assertion can conceal a wrong assumption about incoming data.
- Do: Use explicit boundary validation and strengthen domain types where similar shapes have different meanings.
- Prompt: Review this boundary’s structural types. Validate incoming data and prevent mixing these domain values without relying on an unchecked assertion.
- Avoid: Assuming naming two interfaces differently makes their values incompatible.
- Described as: duck typing; TypeScript excess property check; branded types; ids mixed up; types compatible by shape
- Related: types-as-spec, dto
- Page: https://vibe-coding-101.brighteng.org/c/structural-typing/

## shadow-dom

**shadow DOM** (frontend and browser state). Shadow DOM provides a component subtree with scoped DOM and styling behavior.

- Use when: A reusable web component needs predictable styling inside different pages.
- What: A shadow root gives a web component its own DOM tree and styles that page CSS does not reach. It is for style and DOM encapsulation, not security.
- Why it matters with an agent: Global styling assumptions can fail inside a shadow root.
- Do: Define the internal styles and supported customization surface, including inherited values and exposed parts.
- Prompt: Encapsulate this web component with Shadow DOM. Verify its styles and accessibility in two host pages and document its supported theme properties.
- Avoid: Using a closed root as protection for secrets or privileged operations.
- Described as: shadow root; web component; host page CSS breaks widget; style isolation; embeddable widget styling
- Related: design-tokens, a11y
- Page: https://vibe-coding-101.brighteng.org/c/shadow-dom/

## container-query

**container query** (frontend and browser state). A container query adapts styling to a containing context.

- Use when: The same component appears in a narrow sidebar and a wide content region.
- What: The component's styles respond to the width of its container rather than the viewport, so the same card can lay itself out differently in a sidebar and a main column.
- Why it matters with an agent: Viewport rules may choose the wrong layout for an embedded component.
- Do: Establish the query container and test the component at independently varying container sizes.
- Prompt: Use a container query for this card layout. Verify it in a sidebar and main panel while the viewport remains unchanged.
- Avoid: Querying the wrong ancestor and overlooking its effect on sizing.
- Described as: @container; responsive to parent width; media query wrong in sidebar; component responsive layout
- Related: adaptive-layout, split-pane
- Page: https://vibe-coding-101.brighteng.org/c/container-query/

## headless-ui

**headless UI** (frontend and browser state). Headless UI separates reusable interaction behavior from a particular visual presentation.

- Use when: Several screens need the same control behavior with different markup or styling.
- What: A headless library supplies the keyboard, focus, and state behavior of a control such as a combobox and leaves the markup and styles to you. The rendered markup still has to keep the accessibility attributes.
- Why it matters with an agent: Copying the behavior into each design creates divergent fixes and edge cases.
- Do: Share the behavior and render two concrete presentations against its contract.
- Prompt: Reuse this headless control behavior with our components. Verify both presentations preserve keyboard interaction, focus, and accessible relationships.
- Avoid: Replacing semantic controls with decorative elements while retaining only visual behavior.
- Described as: table sorting without our styles; behavior separate from markup; unstyled components; Radix; React Aria
- Related: compound-components, a11y
- Page: https://vibe-coding-101.brighteng.org/c/headless-ui/

## state-colocation

**state colocation** (frontend and browser state). Keep state near the components that own its lifecycle.

- Use when: Local temporary state is unnecessarily shared across independent panels.
- What: State lives in the lowest component that uses it, and moves up only when another component needs it too.
- Why it matters with an agent: A global store can couple interactions that should remain independent.
- Do: Identify readers, writers, and lifetime before choosing the state owner.
- Prompt: Colocate this temporary selection with its panel. Verify two panels remain independent and move ownership only where shared behavior requires it.
- Avoid: Duplicating a genuinely shared value and trying to synchronize the copies.
- Described as: keep this selection local; do not store it globally; everything in global store; local state vs global
- Related: lifting-state, derived-state
- Page: https://vibe-coding-101.brighteng.org/c/state-colocation/

## custom-hook

**custom Hook** (frontend and browser state). A React custom Hook extracts reusable stateful logic.

- Use when: Components repeat the same subscription, cleanup, or interaction logic.
- What: A custom Hook is a function starting with 'use' that wraps reusable stateful logic. Each component that calls it gets its own state unless the Hook subscribes to something shared.
- Why it matters with an agent: Extracting a Hook does not automatically create one shared state owner.
- Do: Define the Hook’s inputs and lifecycle, then test multiple consumers and cleanup.
- Prompt: Extract this upload logic into a custom Hook. Verify two independent uploads, cancellation, and cleanup after unmount.
- Avoid: Sharing mutable module state unintentionally between Hook consumers.
- Described as: useUpload; reusable stateful logic; each instance is separate; extract hook; duplicated useEffect logic
- Related: rules-of-hooks, event-cleanup
- Page: https://vibe-coding-101.brighteng.org/c/custom-hook/

## reducer

**reducer** (frontend and browser state). A reducer computes the next state from the current state and an action.

- Use when: Related state fields are updated inconsistently by separate event handlers.
- What: A reducer is a pure function from the current state and an action to the next state. All related transitions live in one place, where you can test them without the network.
- Why it matters with an agent: A generated handler can leave contradictory flags after an error.
- Do: Describe the allowed actions and test transition sequences independently of side effects.
- Prompt: Move these related state transitions into a reducer. Test save, failure, retry, and cancellation without performing network calls inside the reducer.
- Avoid: Using a reducer to centralize side effects instead of state transitions.
- Described as: open edit save failure transitions; useReducer; too many useState; related state updated separately; contradictory flags
- Related: state-machine, derived-state
- Page: https://vibe-coding-101.brighteng.org/c/reducer/

## composable

**composable** (frontend and browser state). A Vue composable encapsulates reusable stateful logic through the Composition API.

- Use when: Vue components repeat subscriptions or asynchronous behavior.
- What: A composable is a function that uses Vue's Composition API to package reactive state and lifecycle logic for reuse. It decides explicitly whether state is per caller or shared.
- Why it matters with an agent: Moving code into a function can leave listeners alive after its consumer disappears.
- Do: Define whether state is local or shared and use the appropriate lifecycle cleanup.
- Prompt: Extract this Vue behavior into a composable. Verify independent consumers and that subscriptions are removed when a consumer unmounts.
- Avoid: Translating a React Hook mechanically without checking Vue’s reactivity rules.
- Described as: Vue 3 useUpload; Composition API; reusable logic in Vue; Vue hook equivalent
- Related: event-cleanup, computed-vs-watch
- Page: https://vibe-coding-101.brighteng.org/c/composable/

## scoped-slot

**scoped slots** (frontend and browser state). A Vue scoped slot lets a child provide data to caller-supplied content.

- Use when: A reusable table needs different cell markup on different pages.
- What: The child component passes its data to a slot, and the parent decides how to render it, so the child keeps its behavior while each caller controls the markup.
- Why it matters with an agent: Copying the table to customize one cell duplicates sorting and selection behavior.
- Do: Expose the smallest useful slot data and verify multiple renderings of the same behavior.
- Prompt: Use scoped slots for these table cells. Verify two presentations share sorting and selection without mutating the table’s internal state through the slot.
- Avoid: Exposing unrestricted mutable internals as the customization API.
- Described as: Vue 3; customize table cells; renderless; slot props; render prop Vue
- Related: headless-ui, composition
- Page: https://vibe-coding-101.brighteng.org/c/scoped-slot/

## computed-vs-watch

**computed vs watch** (frontend and browser state). In Vue, computed values derive data while watchers respond with side effects.

- Use when: A watcher copies a total into another piece of state.
- What: A computed property derives a value from reactive state. A watcher runs code when state changes, for side effects such as a request or writing to storage.
- Why it matters with an agent: Synchronizing two representations can leave them temporarily inconsistent.
- Do: Derive pure values with computed and reserve watchers for the needed external synchronization.
- Prompt: Derive this total with computed and remove its copying watcher. Verify input changes update the total while the required external side effect remains separate.
- Avoid: Starting network requests inside a computed getter.
- Described as: Vue 3; calculate the total; watcher for a side effect; watch vs computed; Vue derived value
- Related: derived-state, composable
- Page: https://vibe-coding-101.brighteng.org/c/computed-vs-watch/

## query-key

**query keys** (frontend and browser state). A query key identifies cached data and the inputs that distinguish it.

- Use when: Changing a filter shows data from the previous selection.
- What: The key names a cached result and every input that changes it, such as resource, id, filters, and user. Equivalent reads share a key, and different data must never share one.
- Why it matters with an agent: The fetch function can close over an input omitted from the cache key.
- Do: Include the relevant resource identity and parameters, with deliberate authorization scoping.
- Prompt: Define query keys for this resource and its filters. Verify different inputs have separate cache entries and equivalent reads reuse one entry.
- Avoid: Omitting tenant or user context from a cache whose results depend on it.
- Described as: TanStack Query; React Query; project id in the key; shows previous data after switching; useQuery key
- Related: request-deduplication, cache-invalidation
- Page: https://vibe-coding-101.brighteng.org/c/query-key/

## query-freshness

**freshness and cache retention** (frontend and browser state). Freshness describes when cached data should be reconsidered; retention describes how long unused data remains available.

- Use when: A query refetches too often or unused cached results remain longer than intended.
- What: In TanStack Query, staleTime is how long data counts as fresh before a refetch, and gcTime is how long unused data stays in memory. They control different things.
- Why it matters with an agent: A cache duration can be mistaken for a polling interval.
- Do: Choose the permitted staleness and inactive retention separately and test the triggers that use them.
- Prompt: Configure this query’s freshness and inactive retention separately. Verify remount and invalidation behavior using the installed query library’s semantics.
- Avoid: Keeping data permanently fresh without updating or invalidating it after writes.
- Described as: TanStack Query; staleTime; gcTime; React Query; refetches too often; cacheTime
- Related: query-key, query-invalidation
- Page: https://vibe-coding-101.brighteng.org/c/query-freshness/

## query-invalidation

**mutation invalidation** (frontend and browser state). Query invalidation marks affected cached reads stale after a change.

- Use when: A successful mutation leaves detail or list screens displaying old data.
- What: After a write, you mark the cached reads it affected as stale so they refetch. Whether they refetch at once or on next use depends on the library and whether they are on screen.
- Why it matters with an agent: Updating the server does not automatically update every client cache entry.
- Do: Map the mutation to affected keys and verify active and inactive views.
- Prompt: Invalidate the queries affected by this mutation. Verify updated detail and list views while unrelated queries remain reusable.
- Avoid: Invalidating a plausible key that no actual reader uses.
- Described as: TanStack Query; after saving a project; React Query; list not updated after save; invalidateQueries; stale data after mutation
- Related: query-key, cache-invalidation
- Page: https://vibe-coding-101.brighteng.org/c/query-invalidation/

## route-loader

**route loader and query cache** (frontend and browser state). A route loader prepares data for navigation.

- Use when: A route and its component fetch the same resource independently.
- What: The loader starts fetching data during navigation, before the component renders. If the loader and the page use the same query definition, they share one cache entry and one request.
- Why it matters with an agent: Two similar loading paths can drift in keys, permissions, or error handling.
- Do: Share the data contract and define loading, error, and cancellation behavior across navigation.
- Prompt: Use one query definition in this route loader and page. Verify fresh-cache navigation avoids duplicate requests and cancelled navigation cannot publish obsolete state.
- Avoid: Inventing a separate loader cache that the component never reads.
- Described as: TanStack Router; TanStack Query; one shared query definition; loader and component fetch twice; prefetch on navigation
- Related: query-key, cancellation
- Page: https://vibe-coding-101.brighteng.org/c/route-loader/

## sticky

**sticky positioning** (frontend and browser state). Sticky positioning keeps an element in normal flow until it reaches an offset in its scrolling context.

- Use when: A section toolbar should remain visible only while its section is scrolling.
- What: A sticky element scrolls normally until it reaches its offset, then stays put until the end of its parent. An ancestor with overflow set changes which scroll container it sticks to.
- Why it matters with an agent: Fixed positioning can imitate one screenshot while ignoring the section boundary.
- Do: Identify the scroll container and set the intended offset and containment.
- Prompt: Make this toolbar sticky within its section. Verify scrolling, the section end, and narrow layouts without covering focused content.
- Avoid: Changing an ancestor’s overflow and silently changing the sticky behavior.
- Described as: keep the toolbar visible while scrolling; position sticky; sticky not working; sticky header; overflow hidden breaks sticky
- Related: stacking-context, a11y
- Page: https://vibe-coding-101.brighteng.org/c/sticky/

## autosave

**autosave** (frontend and browser state). Autosave persists edits without an explicit save command.

- Use when: A draft should survive navigation or interruption with minimal user effort.
- What: Edits save automatically after a pause or on a schedule. Writes must arrive in order, failures must be visible, and 'saved' must mean the server confirmed it.
- Why it matters with an agent: An older request can overwrite a newer edit even when the UI says saved.
- Do: Choose when edits persist, protect write ordering, and expose pending and failed states accurately.
- Prompt: Autosave this draft with versioned writes. Test an older delayed request, failed persistence, and restart without losing the newest edit.
- Avoid: Showing saved when a request was merely queued.
- Described as: save the draft without pressing save; saving saved failed; auto save as you type; lost edits; save on change
- Related: optimistic-lock, serialization
- Page: https://vibe-coding-101.brighteng.org/c/autosave/

## event-handler

**event handler** (frontend and browser state). Run interaction-triggered work in the code that handles that event.

- Use when: A form submission runs again when an unrelated theme or state value changes.
- What: An event handler responds to a specific interaction. In React, work caused by a click or submit often belongs there rather than in an effect that watches a flag.
- Why it matters with an agent: Modeling an action as a boolean plus an effect can repeat a side effect unexpectedly.
- Do: Identify the initiating event and move its action there. Keep effects for necessary synchronization.
- Prompt: Move this submit-triggered work into its event handler. Verify one submission per action and no resubmission after unrelated state changes.
- Avoid: Removing required ongoing synchronization together with the interaction-specific effect.
- Described as: submit runs twice; effect triggered by click; event vs effect; useEffect runs action again; side effect in effect instead of handler
- Related: effect-deps, derived-state
- Page: https://vibe-coding-101.brighteng.org/c/event-handler/

## query-plan

**query plan** (APIs and data). The operations a database chooses to answer a query.

- Use when: A query is slow and adding indexes would be guesswork.
- What: A query plan shows scans, joins, sorts, and estimated work. EXPLAIN ANALYZE also executes the query and measures it.
- Why it matters with an agent: A plausible index suggestion may optimize a query the application never runs.
- Do: Inspect a representative query and data set. Check actual rows, loops, and timing; use a safe environment for executing analysis.
- Prompt: Inspect this query plan on representative test data. Identify the costly operation and compare the plan after one targeted change.
- Avoid: EXPLAIN ANALYZE is run on a write under the assumption that it only explains.
- Described as: slow SQL; EXPLAIN ANALYZE; database performance; slow query; why is this query slow
- Related: db-index, n-plus-one, query-planner, cost-based-optimizer
- Page: https://vibe-coding-101.brighteng.org/c/query-plan/

## db-index

**database index** (APIs and data). A data structure that can make matching rows cheaper to find.

- Use when: A frequent selective query scans far more rows than it returns.
- What: An index supports particular access patterns. It also consumes storage and adds work to writes.
- Why it matters with an agent: Indexing every column can increase cost without improving the real query.
- Do: Start from the actual filter and ordering. Check the query plan before and after.
- Prompt: Add an index for this measured query bottleneck. Compare the query plan and account for the extra write cost.
- Avoid: The query’s expression or ordering does not match the proposed index.
- Described as: missing index; full table scan; slow lookup; add index; query slower as table grows; Indexing
- Related: query-plan, composite-index, partial-index, secondary-index, covering-index, b-tree
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Indexes](https://www.postgresql.org/docs/current/indexes.html): Indexes accelerate selected lookups while adding storage and write maintenance.
- Page: https://vibe-coding-101.brighteng.org/c/db-index/

## composite-index

**composite index** (APIs and data). One index covers an ordered combination of columns.

- Use when: A query repeatedly filters and sorts by several fields.
- What: A composite index stores multiple key columns. Their order affects the access patterns the database can use efficiently.
- Why it matters with an agent: Separate indexes on each field may not serve the combined query well.
- Do: Match key order to the measured filter and sort. Check the actual plan with representative values.
- Prompt: Evaluate a composite index for this filter and sort. Explain the column order and verify the plan on representative data.
- Avoid: Choosing column order from the table definition instead of the query.
- Described as: multi-column index; filter and sort; index column order; separate indexes not used; index on two columns; Composite index
- Related: db-index, query-plan, covering-index, b-tree
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Multicolumn indexes](https://www.postgresql.org/docs/current/indexes-multicolumn.html): Index key order affects which filters efficiently limit the scan; behavior varies by index access method.
- Page: https://vibe-coding-101.brighteng.org/c/composite-index/

## partial-index

**partial index** (APIs and data). Index only rows that satisfy a predicate.

- Use when: A frequently queried subset is small compared with the whole table.
- What: A partial index limits its contents to a condition, such as rows whose status is pending.
- Why it matters with an agent: A full-table index may do unnecessary maintenance for rows the query never needs.
- Do: Choose the subset and verify that the planner can match the query to its predicate.
- Prompt: Evaluate a partial index for pending jobs. Check that the actual query uses it and compare its size with a full index.
- Avoid: The query condition does not imply the index predicate, so the index is unusable.
- Described as: index active rows; index pending jobs; conditional index; index with WHERE
- Related: db-index, query-plan
- Page: https://vibe-coding-101.brighteng.org/c/partial-index/

## n-plus-one

**N+1 query** (APIs and data). One list query triggers another query for every result.

- Use when: A page becomes slower in proportion to the number of displayed rows.
- What: N+1 describes repeated per-record fetching after an initial query. Batching or suitable joins can reduce the round trips.
- Why it matters with an agent: A generated loop around an ORM call can hide the query count.
- Do: Trace database calls for a realistic list. Check that query count remains bounded as the list grows.
- Prompt: Fix the N+1 query on this list. Batch the related reads and show that doubling the rows does not double the query count.
- Avoid: One enormous join replaces the round trips but multiplies the result rows.
- Described as: query per item; ORM loop; too many database calls; n+1; one query per row; slow list page
- Related: query-plan, pagination
- Page: https://vibe-coding-101.brighteng.org/c/n-plus-one/

## pagination

**keyset pagination** (APIs and data). Continue a list after the last returned sort key.

- Use when: Deep offset pages are slow or inserts shift the page boundaries.
- What: Keyset pagination uses an ordered cursor, often a timestamp plus a unique id, to select the next range.
- Why it matters with an agent: A cursor missing a tie-breaker can skip records with equal timestamps.
- Do: Define a stable ordering and matching index. Check repeated sort values and inserts between page loads.
- Prompt: Use keyset pagination for this feed with a stable tie-breaker. Verify no duplicate or skipped rows when timestamps match.
- Avoid: A changing sort field invalidates assumptions about traversal. Random page jumps may need another approach.
- Described as: cursor pagination; slow deep pages; duplicate rows between pages; offset pagination slow; infinite scroll duplicates; load more
- Related: composite-index, db-index
- Page: https://vibe-coding-101.brighteng.org/c/pagination/

## connection-pool

**connection pool** (APIs and data). Reuse a bounded set of database connections.

- Use when: Traffic spikes exhaust the database’s connection limit.
- What: A connection pool lends connections to callers and reuses them after release. Its size must fit the deployment’s total capacity.
- Why it matters with an agent: A new pool per request defeats reuse and multiplies connection pressure.
- Do: Count pools across instances and define wait limits. Check concurrent load and cleanup after errors.
- Prompt: Use a bounded connection pool for this service. Account for all instances and verify connections are returned after failed requests.
- Avoid: A sensible per-instance limit exceeds database capacity when multiplied by replicas.
- Described as: too many connections; database connection limit; pool exhaustion; serverless database connections; remaining connection slots reserved; Connection pooling
- Related: transaction, request-scope, backpressure
- Sources checked: 2026-10-11 (not human editorial approval)
- [node-postgres: Pooling](https://node-postgres.com/features/pooling): Reusing a bounded connection pool, releasing clients, and keeping a transaction on one client.
- Page: https://vibe-coding-101.brighteng.org/c/connection-pool/

## prepared-statement

**parameterized query** (APIs and data). Keep SQL structure separate from input values.

- Use when: A database query includes values supplied by a user.
- What: A parameterized query binds values separately from SQL syntax. Dynamic identifiers still need a controlled selection strategy.
- Why it matters with an agent: String interpolation can turn an ordinary value into executable query syntax.
- Do: Bind values and allowlist variable identifiers. Check that hostile input is treated as data.
- Prompt: Parameterize this query. Bind every user-supplied value, allowlist dynamic column names, and test an input containing SQL syntax.
- Avoid: Parameters are incorrectly expected to substitute table or column names.
- Described as: SQL injection; prepared statement; bind parameters; string concatenation in SQL; user input in query; sql injection
- Related: rls, least-privilege
- Page: https://vibe-coding-101.brighteng.org/c/prepared-statement/

## transaction

**transaction** (APIs and data). Commit related database changes together or roll them back.

- Use when: A failed step leaves an object only partly saved.
- What: A transaction groups database operations into a commit unit. Its isolation level determines how concurrent work can interact.
- Why it matters with an agent: Sequential writes can each succeed independently and leave inconsistent state.
- Do: Keep the database unit short. Check failure between writes and concurrent access to shared records.
- Prompt: Wrap these related database writes in a transaction. Inject a failure between them and verify that none of the partial changes remain.
- Avoid: An external API call is assumed to roll back with the database.
- Described as: half saved order; all or nothing; partial database write; rollback on error; atomic save
- Related: unique-constraint, deadlock, acid, snapshot-isolation
- Page: https://vibe-coding-101.brighteng.org/c/transaction/

### transaction: a worked example

Canonical page: https://vibe-coding-101.brighteng.org/c/transaction/#before-and-after

#### The problem

Moving one seat from availability into a reservation needs two database writes. If saving the reservation fails after decrementing availability, the system should not silently lose the seat.

#### Prompt to paste

Wrap these related database writes in a transaction. Inject a failure between them and verify that none of the partial changes remain.

#### Before

Independent writes commit separately. An injected failure after the availability change leaves zero seats and no reservation.

#### After

Begin a transaction, execute both writes, and commit together. Roll back on an error and rethrow it. A failed reservation then leaves the original availability intact.

#### Run the check

Save the following code as transaction.mjs and run `node --experimental-sqlite --test transaction.mjs` with Node.js 22.12 or later. The SQLite examples use an experimental built-in API and the shown runtime flag.

```js
import test from 'node:test';
import assert from 'node:assert/strict';
import { DatabaseSync } from 'node:sqlite';

function before(db, fail = false) {
  db.exec('UPDATE inventory SET seats = seats - 1');
  if (fail) throw new Error('reservation failed');
  db.exec("INSERT INTO reservations VALUES ('r1')");
}

function after(db, fail = false) {
  db.exec('BEGIN');
  try {
    db.exec('UPDATE inventory SET seats = seats - 1');
    if (fail) throw new Error('reservation failed');
    db.exec("INSERT INTO reservations VALUES ('r1')");
    db.exec('COMMIT');
  } catch (error) {
    db.exec('ROLLBACK');
    throw error;
  }
}

function fixture() {
  const db = new DatabaseSync(':memory:');
  db.exec(`CREATE TABLE inventory (seats INTEGER NOT NULL CHECK (seats >= 0));
    INSERT INTO inventory VALUES (1);
    CREATE TABLE reservations (id TEXT NOT NULL UNIQUE);`);
  return db;
}
function state(db) {
  return [db.prepare('SELECT seats FROM inventory').get().seats,
    db.prepare('SELECT count(*) AS n FROM reservations').get().n];
}

test('a failure between independent writes loses a seat', () => {
  const db = fixture();
  try {
    assert.throws(() => before(db, true), /reservation failed/);
    assert.deepEqual(state(db), [0, 0]);
  } finally { db.close(); }
});

test('a transaction rolls back failure and commits success', () => {
  const db = fixture();
  try {
    assert.throws(() => after(db, true), /reservation failed/);
    assert.deepEqual(state(db), [1, 0]);
    after(db);
    assert.deepEqual(state(db), [0, 1]);
    assert.throws(() => after(db), /CHECK constraint failed/);
    assert.deepEqual(state(db), [0, 1]);
  } finally { db.close(); }
});
```

#### Expected result

The independent-write failure leaves [0 available seats, 0 reservations]. Rolling back leaves [1, 0], and a successful transaction leaves [0, 1]. A later attempt violating the nonnegative-seat constraint leaves the committed state unchanged.

#### Limits

This synchronous SQLite example assumes one inventory row and tests a failure between statements. It does not prove crash recovery, high-contention behavior, or a production booking design. Select isolation and conflict/retry handling for your database and workload. A database rollback cannot undo a completed payment, email, or other external API call. Keep such coordination explicit.

#### Sources

- [SQLite: Transactions](https://www.sqlite.org/lang_transaction.html): Explicit BEGIN, COMMIT, and ROLLBACK and SQLite transaction behavior.
- [Node.js 22: SQLite](https://nodejs.org/docs/latest-v22.x/api/sqlite.html): Executing the actual SQL in an in-memory database with DatabaseSync.

Sources checked: 2026-10-11. These are original illustrative examples with automated checks. Human editorial approval is not recorded. Policy: https://vibe-coding-101.brighteng.org/editorial/


## deadlock

**deadlock** (APIs and data). Operations wait on resources held by one another.

- Use when: Concurrent transactions sometimes block until the database aborts one.
- What: A deadlock forms a cycle of waits. Consistent lock ordering and short transactions reduce opportunities for those cycles.
- Why it matters with an agent: Two generated handlers can acquire the same records in opposite orders.
- Do: Inspect the competing operations and establish an order. Check the contention case and bounded retry handling.
- Prompt: Fix this deadlock by using a consistent lock order. Reproduce the competing transactions and verify bounded retries for aborted work.
- Avoid: Retrying forever hides the underlying cycle and increases load.
- Described as: transactions stuck; lock ordering; deadlock retry; deadlock detected; requests hang under load; Deadlock
- Related: transaction, query-plan, pessimistic-locking, lock-escalation
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Explicit locking](https://www.postgresql.org/docs/current/explicit-locking.html): Row and table locks, blocking, deadlocks, and consistent acquisition order.
- Page: https://vibe-coding-101.brighteng.org/c/deadlock/

## unique-constraint

**unique constraint** (APIs and data). The database rejects duplicate values for a declared key.

- Use when: Two simultaneous requests can create the same logical record.
- What: A unique constraint enforces a key’s uniqueness across writers, including writers outside the application.
- Why it matters with an agent: Checking for an existing row before inserting leaves a race window.
- Do: Choose the true business key, including tenant scope when needed. Check simultaneous conflicting inserts.
- Prompt: Enforce this uniqueness rule in the database. Test two concurrent inserts and return a useful conflict result to the losing caller.
- Avoid: The constraint omits tenant scope or conflicts with existing duplicate data.
- Described as: duplicate records; check then insert; unique key; duplicate email; double signup; retry creates duplicate records; two requests create the same row
- Related: upsert, transaction
- Page: https://vibe-coding-101.brighteng.org/c/unique-constraint/

### unique constraint: a worked example

Canonical page: https://vibe-coding-101.brighteng.org/c/unique-constraint/#before-and-after

#### The problem

An import must store an external event once per account. Two callers both inspect the table before either inserts. They both see no row. A uniqueness rule in application code alone cannot stop both planned inserts.

#### Prompt to paste

Enforce this uniqueness rule in the database. Test two concurrent inserts and return a useful conflict result to the losing caller.

#### Before

The table has no constraint. Model the overlapping schedule by preparing both callers after their existence checks, then executing their inserts. Two identical account/event rows remain.

#### After

Declare both key columns NOT NULL and enforce UNIQUE(account_id, event_id). Keep the preliminary check only as an optional convenience. The database rejects the second duplicate insert, including when a caller bypasses that check.

#### Run the check

Save the following code as unique-constraint.mjs and run `node --experimental-sqlite --test unique-constraint.mjs` with Node.js 22.12 or later. The SQLite examples use an experimental built-in API and the shown runtime flag.

```js
import test from 'node:test';
import assert from 'node:assert/strict';
import { DatabaseSync } from 'node:sqlite';

function before() {
  const db = new DatabaseSync(':memory:');
  db.exec('CREATE TABLE events (account_id TEXT, event_id TEXT)');
  return db;
}

function prepareInsert(db, account, event) {
  const exists = db.prepare(
    'SELECT 1 FROM events WHERE account_id = ? AND event_id = ?'
  ).get(account, event);
  return () => {
    if (!exists) db.prepare('INSERT INTO events VALUES (?, ?)').run(account, event);
  };
}

function after() {
  const db = new DatabaseSync(':memory:');
  db.exec(`CREATE TABLE events (
    account_id TEXT NOT NULL,
    event_id TEXT NOT NULL,
    UNIQUE (account_id, event_id)
  )`);
  return db;
}

test('both application checks pass before either insert', () => {
  const db = before();
  try {
    const first = prepareInsert(db, 'alice', 'event-1');
    const second = prepareInsert(db, 'alice', 'event-1');
    first(); second();
    assert.equal(db.prepare('SELECT count(*) AS n FROM events').get().n, 2);
  } finally { db.close(); }
});

test('the constraint rejects duplicates and preserves account scope', () => {
  const db = after();
  try {
    const first = prepareInsert(db, 'alice', 'event-1');
    const second = prepareInsert(db, 'alice', 'event-1');
    first();
    assert.throws(second, /UNIQUE constraint failed/);
    db.prepare('INSERT INTO events VALUES (?, ?)').run('bob', 'event-1');
    assert.throws(() => db.prepare('INSERT INTO events VALUES (?, ?)').run('alice', 'event-1'),
      /UNIQUE constraint failed/);
    assert.throws(() => db.prepare('INSERT INTO events VALUES (?, ?)').run('alice', null),
      /NOT NULL constraint failed/);
    assert.equal(db.prepare('SELECT count(*) AS n FROM events').get().n, 2);
  } finally { db.close(); }
});
```

#### Expected result

Without the constraint, two checks followed by two inserts store two duplicate rows. With the constraint, the second identical insert fails, while another account may use the same event ID. The check also rejects a missing event key.

#### Limits

The runnable file uses real SQLite statements with an explicitly controlled overlap schedule in one connection. It does not test simultaneous database connections or another database engine. Test your deployed engine with competing connections and handle its specific conflict code. SQLite treats NULLs as distinct for UNIQUE, so required key columns need NOT NULL. Existing duplicates need reconciliation before a migration. A unique row does not by itself ensure that an external side effect ran once.

#### Sources

- [SQLite: UNIQUE constraints](https://www.sqlite.org/lang_createtable.html#unique_constraints): Composite uniqueness and the treatment of NULL values.
- [SQLite: Constraint conflicts](https://www.sqlite.org/lang_conflict.html): The default ABORT behavior rejects a violating statement.
- [Node.js 22: SQLite](https://nodejs.org/docs/latest-v22.x/api/sqlite.html): The built-in DatabaseSync runtime; Node 22.12 requires the experimental SQLite flag.

Sources checked: 2026-10-11. These are original illustrative examples with automated checks. Human editorial approval is not recorded. Policy: https://vibe-coding-101.brighteng.org/editorial/


## upsert

**upsert** (APIs and data). Insert a row or update the row that conflicts with its key.

- Use when: Importing or saving a setting may encounter an existing record.
- What: An upsert combines insert-or-update behavior under a database conflict rule. It still needs a deliberate update policy.
- Why it matters with an agent: A separate existence check can race with another writer.
- Do: Choose the conflict key and allowed updates. Check new rows, existing rows, and simultaneous submissions.
- Prompt: Use an upsert for these settings with the correct unique key. Verify new and existing rows without a separate existence check.
- Avoid: A stale request overwrites newer data; upsert alone does not resolve version conflicts.
- Described as: insert or update; ON CONFLICT; import duplicates; create or update; INSERT ... ON DUPLICATE KEY
- Related: unique-constraint, transaction
- Page: https://vibe-coding-101.brighteng.org/c/upsert/

## migration

**database migration** (APIs and data). A recorded transition from one database schema to another.

- Use when: A schema change must preserve existing rows and deployed callers.
- What: A migration changes schema or data in a controlled sequence. Reversibility depends on the operation and recovery plan.
- Why it matters with an agent: Changing only the latest schema ignores the state users already have.
- Do: Exercise the migration on a representative older schema. Check data preservation and the recovery path.
- Prompt: Write a migration for this schema change. Test it against existing data and document how we recover if the rollout fails.
- Avoid: A destructive change is called reversible even though its discarded data cannot be reconstructed.
- Described as: change schema safely; existing data; database upgrade; rename column; alter table in production; prisma migrate
- Related: schema-evolution, unique-constraint, data-migration
- Page: https://vibe-coding-101.brighteng.org/c/migration/

## rls

**row-level security** (APIs and data). Database policies control which rows a role may access.

- Use when: Users or tenants share tables but must not access each other’s rows.
- What: Postgres RLS applies policies to row access. Roles that bypass RLS require separate care.
- Why it matters with an agent: A missing application filter can otherwise expose another user’s records.
- Do: Define read and write policies using trusted identity. Check them as the actual runtime role with two users.
- Prompt: Add row-level security for these tenant records. Test reads and writes as the runtime role, proving tenant B cannot access tenant A’s rows.
- Avoid: Tests use an administrative role that bypasses the policies.
- Described as: another user sees my data; tenant isolation; row permissions; Supabase policies; users can see other users data; RLS
- Related: least-privilege, unique-constraint
- Page: https://vibe-coding-101.brighteng.org/c/rls/

## least-privilege

**least privilege** (APIs and data). Give each runtime identity only the permissions its job needs.

- Use when: The application runs with an administrative database credential.
- What: Least privilege limits the operations available to a role, service, or token and reduces the impact of misuse.
- Why it matters with an agent: A convenient setup credential can become an unnecessarily powerful production credential.
- Do: List required operations and grant those. Check that ordinary work succeeds and administrative operations fail.
- Prompt: Apply least privilege to the runtime database role. Verify normal reads and writes succeed while schema changes and privilege grants fail.
- Avoid: A restricted role inherits broad permissions through another role.
- Described as: app uses admin; database permissions; restricted runtime role; API key has too much access; minimal permissions
- Related: rls, prepared-statement
- Page: https://vibe-coding-101.brighteng.org/c/least-privilege/

## webhook

**webhook** (APIs and data). A service sends an HTTP request when an event occurs.

- Use when: Your application must react to changes in an external service.
- What: The provider calls an endpoint in your app when something happens, such as a payment succeeding. You check its signature, store or queue it before acknowledging, and expect retries, duplicates, and out-of-order deliveries.
- Why it matters with an agent: A browser callback can be mistaken for authoritative evidence of a completed server operation.
- Do: Verify authenticity, persist or enqueue reliably, and handle duplicate or reordered deliveries.
- Prompt: Implement this webhook using the provider’s verification contract. Test an invalid signature, duplicate delivery, and reordered events.
- Avoid: Acknowledging an event before it is durably accepted, then losing it on a crash.
- Described as: Stripe callback; payment notification endpoint; verify signature; receive events from service; webhook called twice
- Related: idempotency, job-queue
- Page: https://vibe-coding-101.brighteng.org/c/webhook/

## rest

**REST** (APIs and data). REST is an architectural style for resource-oriented interactions through a uniform interface.

- Use when: An HTTP API needs predictable resource and operation behavior.
- What: REST models an API as resources with standard methods. GET only reads, PUT and DELETE are idempotent, and status codes describe what happened, so clients and caches can rely on that behavior.
- Why it matters with an agent: Generated endpoints may mutate data through safe methods or hide failures behind success responses.
- Do: Define resources and method semantics, then verify safety, idempotency, and error responses.
- Prompt: Design this resource API with explicit HTTP semantics. Verify that reads do not mutate state, retries behave as documented, and errors use appropriate responses.
- Avoid: Assuming every valid API operation must fit a simple CRUD endpoint.
- Described as: API design; HTTP methods; status codes; RESTful endpoints; everything returns 200
- Related: idempotency, contract-first
- Page: https://vibe-coding-101.brighteng.org/c/rest/

## rate-limit

**rate limit** (APIs and data). Limit how often a caller can perform an operation.

- Use when: A costly endpoint can be overwhelmed by repeated requests.
- What: Each caller, such as a user, API key, or IP address, gets a budget of requests per time window. The counter must be shared across all server instances or each instance allows the full rate.
- Why it matters with an agent: A process-local counter may multiply the allowed rate when more instances start.
- Do: Choose the caller identity and limit policy; test bursts and multiple instances.
- Prompt: Rate-limit this endpoint by its intended caller identity. Test the limit, reset behavior, and consistent enforcement across instances.
- Avoid: One global bucket lets a noisy caller block everyone else.
- Described as: too many requests; 429; throttle API; abuse protection; limit requests per user; Rate limiting
- Related: backpressure, least-privilege, throttling
- Sources checked: 2026-10-11 (not human editorial approval)
- [RFC 6585: 429 Too Many Requests](https://www.rfc-editor.org/rfc/rfc6585.html#section-4): HTTP 429 signals too many requests; Retry-After can communicate when to retry.
- [Microsoft: Rate limiting pattern](https://learn.microsoft.com/en-us/azure/architecture/patterns/rate-limiting-pattern): Rate policies and distributed coordination must match the scope of the resource or caller being limited.
- Page: https://vibe-coding-101.brighteng.org/c/rate-limit/

## cache-invalidation

**cache invalidation** (APIs and data). Mark cached data stale, remove it, or refresh it when its assumptions change.

- Use when: Users keep seeing old data after a successful edit.
- What: Each cached value depends on some data. When a write changes that data, the cache entries built from it must be removed or refreshed, using the same key the reader uses.
- Why it matters with an agent: Adding a cache without a write policy can make correct writes appear lost.
- Do: List cache keys, dependencies, and freshness expectations; connect relevant writes to their invalidation path.
- Prompt: Define invalidation for this cache. After a write, verify affected views become current and unrelated entries remain reusable.
- Avoid: A correct invalidation event uses a different key from the reader.
- Described as: tag-based revalidation; tag revalidation; stale cache after update; users see old data after edit; revalidatePath
- Related: query-key, query-invalidation
- Page: https://vibe-coding-101.brighteng.org/c/cache-invalidation/

## job-queue

**job queue** (APIs and data). A queue separates accepting work from processing it.

- Use when: Slow work should continue independently of the request that created it.
- What: The request records the work in a durable queue and returns. Separate workers process it with retries, and failures stay visible instead of disappearing with the request.
- Why it matters with an agent: An in-memory callback can disappear when the request or process ends.
- Do: Choose durable acceptance, bounded retry, and idempotent processing; make terminal failures visible.
- Prompt: Queue this background operation durably. Test a worker restart, duplicate delivery, and a terminal failure with a recoverable record.
- Avoid: Returning success before the work has been durably accepted.
- Described as: background job; request times out; run task in background; worker; BullMQ; task lost on restart
- Related: idempotency, dead-letter
- Page: https://vibe-coding-101.brighteng.org/c/job-queue/

## circuit-breaker

**circuit breaker** (APIs and data). Temporarily stop calls to a failing dependency and probe for recovery.

- Use when: Repeated upstream failures consume the application’s remaining capacity.
- What: After enough failures, calls to the dependency fail immediately for a while instead of waiting. A few trial calls then check whether it has recovered.
- Why it matters with an agent: Unbounded retries can amplify an outage.
- Do: Define which failures count, when calls are rejected, and how recovery is tested.
- Prompt: Add a circuit breaker around this dependency. Test closed, open, and recovery behavior, with bounded calls and explicit failure responses.
- Avoid: Counting every client validation error as evidence that the dependency is down.
- Described as: stop calling failing service; dependency outage slows everything; fail fast; retry storm; Circuit breaker
- Related: timeout-budget, graceful-degradation
- Sources checked: 2026-10-11 (not human editorial approval)
- [Microsoft: Circuit breaker pattern](https://learn.microsoft.com/en-us/azure/architecture/patterns/circuit-breaker): Closed, open, and half-open states stop repeated calls to a failing dependency and probe recovery.
- Page: https://vibe-coding-101.brighteng.org/c/circuit-breaker/

## graceful-shutdown

**graceful shutdown** (APIs and data). Stop accepting new work and finish or hand off existing work before exiting.

- Use when: Deployments interrupt active requests or background jobs.
- What: On a termination signal, the service stops taking new requests and jobs, finishes or hands off the ones in progress, closes connections, and exits before a deadline.
- Why it matters with an agent: Stopping the process immediately can lose acknowledged work.
- Do: Stop admission, drain or checkpoint work, close resources, and enforce an exit deadline.
- Prompt: Implement graceful shutdown for this service. Send the termination signal during active work and verify bounded exit without losing acknowledged work.
- Avoid: Waiting forever for one stuck task to complete.
- Described as: SIGTERM; deploy kills requests; jobs cut off on deploy; drain connections
- Related: job-queue, connection-pool
- Page: https://vibe-coding-101.brighteng.org/c/graceful-shutdown/

## minor-units

**minor units** (APIs and data). Represent money using integer minor units or an appropriate decimal representation with an explicit currency.

- Use when: Totals drift because prices are calculated with unsuitable arithmetic.
- What: Store amounts as integer minor units, such as cents, or as an exact decimal, always with the currency. Rounding happens at defined points, and currencies with zero or three decimal places are handled.
- Why it matters with an agent: A generated calculation may mix currencies or silently round at different stages.
- Do: Choose scale and rounding explicitly; verify sums, allocation, and currency-specific cases.
- Prompt: Represent these amounts with explicit currency and exact arithmetic. Test rounding, refunds, and totals without exceeding the numeric representation’s safe range.
- Avoid: Assuming every currency has two decimal places or every integer fits safely in a JavaScript number.
- Described as: cents; money integer; decimal scale; 0.1 + 0.2; price rounding error; floating point money
- Related: invariant, serialization
- Page: https://vibe-coding-101.brighteng.org/c/minor-units/

## utc-local

**UTC vs local time** (APIs and data). Distinguish an instant from a calendar date and a local scheduled time.

- Use when: Dates shift by a day or recurring times move unexpectedly around daylight-saving changes.
- What: An instant is an exact moment, stored in UTC. A calendar date, such as a birthday, has no time zone. A local schedule, such as 9am every Monday in Paris, needs a time-zone rule.
- Why it matters with an agent: One timestamp type cannot express every calendar meaning correctly.
- Do: Choose the value’s meaning first, then its storage format and conversion boundary.
- Prompt: Model these values as instants, dates, or zoned local schedules. Test daylight-saving gaps, overlaps, and users in different zones.
- Avoid: Turning a birthday into a UTC instant and later rendering it on another date.
- Described as: timezone; DST; civil date; date off by one day; daylight saving bug; store dates in UTC
- Related: schema-evolution, invariant
- Page: https://vibe-coding-101.brighteng.org/c/utc-local/

## optimistic-lock

**optimistic concurrency** (APIs and data). Accept an update only if the version being replaced still matches the version the caller read.

- Use when: Two editors can overwrite each other’s changes.
- What: Each record has a version. An update says 'only if the version is still N', and if someone else changed it first, the update is rejected with a conflict the user can resolve.
- Why it matters with an agent: Checking a version before a separate unconditional write still leaves a race.
- Do: Include the version condition in the atomic write and test competing writers.
- Prompt: Add optimistic concurrency control to this update. Race two edits from the same version and verify one succeeds while the other gets a recoverable conflict.
- Avoid: Incrementing the version without checking it in the write condition.
- Described as: version column; ETag; compare-and-swap; lost update; two people edit same record; concurrent edits overwrite; Optimistic locking
- Related: transaction, conflict, pessimistic-locking, write-skew
- Sources checked: 2026-10-11 (not human editorial approval)
- [Amazon DynamoDB: Optimistic locking](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking.html): Version-checked updates reject stale writes; guarantees depend on replication and conflict resolution.
- Page: https://vibe-coding-101.brighteng.org/c/optimistic-lock/

## partial-update

**partial update** (APIs and data). A partial update changes only the fields identified by its contract.

- Use when: Editing one field unexpectedly clears other stored values.
- What: The request changes only the fields it includes. Leaving a field out means 'keep it', and sending null means 'clear it', so the two must be told apart.
- Why it matters with an agent: Reusing a create-schema default can turn omitted fields into overwrites.
- Do: Define patch semantics and validate presence separately from value.
- Prompt: Implement this partial update with explicit missing and null behavior. Test an omitted field, a cleared field, and an unknown field.
- Avoid: Applying create-time defaults to every update request.
- Described as: PATCH; JSON Merge Patch; update clears other fields; fields wiped on update; null vs missing
- Related: dto, option-type
- Page: https://vibe-coding-101.brighteng.org/c/partial-update/

## isolation

**transaction isolation** (APIs and data). Transaction isolation defines how concurrent transactions may observe and affect one another.

- Use when: A transaction is atomic but still violates a rule under concurrent access.
- What: Isolation levels, such as read committed, repeatable read, and serializable, control what concurrent transactions see of each other. Stronger levels prevent more anomalies but can fail transactions that then need a full retry.
- Why it matters with an agent: Wrapping writes in a transaction does not automatically make every execution serializable.
- Do: Identify the required invariant, choose the isolation strategy, and test conflicting transactions.
- Prompt: Choose isolation for this invariant on our database. Test concurrent transactions and handle retryable failures with a bounded retry policy.
- Avoid: Retrying only the final statement after the database requires the whole transaction to restart.
- Described as: read committed; repeatable read; serializable; write skew; race condition in transaction
- Related: transaction, optimistic-lock
- Page: https://vibe-coding-101.brighteng.org/c/isolation/

## dto

**DTO** (APIs and data). A data transfer object defines the fields crossing an application boundary.

- Use when: An endpoint exposes private fields or accepts writable fields the caller should not control.
- What: Separate types for what an endpoint accepts and returns. Only fields you listed cross the boundary, so internal fields stay hidden and callers can't set fields like isAdmin.
- Why it matters with an agent: Returning the ORM object can leak fields added by a later migration.
- Do: Define explicit input and output contracts and map only the permitted fields.
- Prompt: Define input and output DTOs for this endpoint. Verify sensitive fields cannot be read or assigned through extra request properties.
- Avoid: Inheriting the full persistence model and calling it a restricted DTO.
- Described as: response model; mass assignment; password hash in API response; isAdmin in request body; API returns too many fields
- Related: contract-first, authn-authz
- Page: https://vibe-coding-101.brighteng.org/c/dto/

## websocket

**WebSocket** (APIs and data). A WebSocket provides a persistent bidirectional connection.

- Use when: The client and server must exchange ongoing updates in both directions.
- What: A WebSocket keeps one connection open so both sides can send messages at any time. Authentication, reconnection, message formats, and buffering are up to the application.
- Why it matters with an agent: A successful connection can still leak resources or duplicate work after reconnection.
- Do: Define message schemas, access checks, bounded buffers, and reconnect behavior.
- Prompt: Implement this WebSocket flow with validated messages and bounded buffering. Test reconnects, expired access, and a slow client.
- Avoid: Treating the connection’s initial authentication as permission for every future operation.
- Described as: socket; upgrade handshake; real-time updates; live updates without refresh; reconnect
- Related: backpressure, idempotency
- Page: https://vibe-coding-101.brighteng.org/c/websocket/

## error-as-value

**error as value** (APIs and data). Represent expected failures explicitly in a function’s result.

- Use when: Callers cannot tell not-found from validation failure or an unavailable dependency.
- What: Functions return expected failures, such as not found or invalid, as typed results the caller must handle. Exceptions are kept for the unexpected.
- Why it matters with an agent: A generic null or catch-all response hides the recovery decision.
- Do: Define a small result type and require callers to handle its relevant cases.
- Prompt: Return explicit result variants for these expected failures. Test each caller’s recovery behavior while preserving unexpected errors for diagnosis.
- Avoid: Converting every unexpected exception into an ordinary empty result.
- Described as: Result; Go error; return null on error; cannot tell why it failed; Result type TypeScript
- Related: option-type, observability
- Page: https://vibe-coding-101.brighteng.org/c/error-as-value/

## option-type

**option type** (APIs and data). An option type represents a value that may be absent.

- Use when: Missing data is represented by a misleading default value.
- What: A type that is either Some(value) or None, like Rust's Option or Haskell's Maybe. The compiler makes callers handle the missing case.
- Why it matters with an agent: Replacing absence with an empty string can erase a meaningful distinction.
- Do: Keep optionality at the boundary where it exists and handle it before requiring a value.
- Prompt: Represent this possibly missing value with an option type. Test present and absent cases, and model patch-field presence separately from a nullable value.
- Avoid: Assuming one optional value automatically represents absent, null, and empty as three distinct states.
- Described as: Option; Maybe; null vs undefined; empty string means missing; magic default values
- Related: partial-update, types-as-spec
- Page: https://vibe-coding-101.brighteng.org/c/option-type/

## dataloader

**DataLoader** (APIs and data). DataLoader batches related loads and can memoize results within a chosen scope.

- Use when: Related resolvers repeat loads for the same entities.
- What: DataLoader collects the keys requested during one tick and loads them in a single batch, returning results in the same order. One loader is created per request so caches don't leak between users.
- Why it matters with an agent: Creating a loader inside each resolver prevents useful batching.
- Do: Share a loader within the authorized request scope and handle missing keys explicitly.
- Prompt: Batch these resolver loads with a request-scoped DataLoader. Verify query count, key ordering, missing records, and isolation between users.
- Avoid: Sharing a loader cache across users without the required authorization boundaries.
- Described as: request-scoped batching; GraphQL n+1; batch resolver loads; too many queries GraphQL
- Related: n-plus-one, request-scope
- Page: https://vibe-coding-101.brighteng.org/c/dataloader/

## middleware-order

**middleware order** (APIs and data). Middleware ordering determines which request and response processing runs before another step.

- Use when: Authentication, parsing, or error handling runs too late or is skipped.
- What: Middleware runs in the order it is registered, so parsing, CORS, authentication, and error handling have to come in the right sequence for the framework.
- Why it matters with an agent: Copying an arbitrary ordered list may break a framework with different middleware semantics.
- Do: Trace the actual request and error paths, including short-circuits and preflight requests.
- Prompt: Verify this middleware chain on our framework. Test unauthorized requests, preflight, malformed bodies, and thrown errors without letting rejected requests reach the handler.
- Avoid: Sending an error response and then continuing to the protected handler.
- Described as: middleware pipeline; auth middleware not running; CORS preflight 401; body is undefined in handler; express middleware order
- Related: authn-authz, cors
- Page: https://vibe-coding-101.brighteng.org/c/middleware-order/

## data-access-layer

**data access layer** (APIs and data). A data access layer centralizes access rules and data retrieval at a boundary.

- Use when: Several server entry points duplicate sensitive reads and permission checks.
- What: Every sensitive read goes through a server-only module that gets the user from the session, checks access, and returns only the fields the caller may see.
- Why it matters with an agent: One forgotten filter can expose fields or records from another user.
- Do: Derive identity from trusted context, enforce access, and shape the allowed response.
- Prompt: Centralize this authorized data read on the server. Test two users and verify the response excludes fields the caller must not receive.
- Avoid: Trusting a caller-provided identity because the function lives in a server-only file.
- Described as: server-only profile reader; DAL; permission checks scattered; centralize authorization; Next.js data access
- Related: authn-authz, dto
- Page: https://vibe-coding-101.brighteng.org/c/data-access-layer/

## server-action

**server action** (APIs and data). A server action exposes a framework-supported server operation to the client.

- Use when: A form needs to invoke server work through the framework’s action mechanism.
- What: A server action is a server function the framework exposes as an endpoint so a form or button can call it. Anyone can call it directly, so it must check identity, permission, and input itself.
- Why it matters with an agent: A server function can look private in code while still being callable remotely.
- Do: Check identity and permission inside the operation and validate its arguments before mutation.
- Prompt: Implement this authenticated server action. Test direct signed-out calls, another user’s record, and invalid input before verifying the form.
- Avoid: Relying on a protected page or hidden button as the action’s authorization.
- Described as: use server; settings form versus webhook; server action security; form action Next.js; hidden button is not security
- Related: authn-authz, dto
- Page: https://vibe-coding-101.brighteng.org/c/server-action/

## etl

**ETL and ELT** (APIs and data). ETL transforms extracted data before loading it; ELT loads data before transformation.

- Use when: A report imports and transforms data from another system.
- What: ETL transforms data before loading it into the destination; ELT loads raw data first and transforms it there. Either way, a rerun must not lose or duplicate rows.
- Why it matters with an agent: An append-only import can duplicate rows every time a job retries.
- Do: Define source identity, transformation rules, and rerun behavior with representative fixtures.
- Prompt: Build this data import with explicit transformation and rerun rules. Verify a repeated batch and a mid-run failure do not lose or double-count records.
- Avoid: Transforming away source information needed to correct a later rule.
- Described as: data import job; nightly sync duplicates; data pipeline; import from another system
- Related: idempotency, backfill
- Page: https://vibe-coding-101.brighteng.org/c/etl/

## partitioning

**table partitioning** (APIs and data). Table partitioning divides a logical table into physical parts.

- Use when: A large table needs efficient bounded scans or lifecycle operations.
- What: The database stores one logical table as several physical tables split by a key, often a date range. Queries that filter on that key only read the matching partitions, and old ones can be dropped cheaply.
- Why it matters with an agent: Partitioning by an unrelated key can add complexity without reducing query work.
- Do: Check pruning and operational cost on representative queries before adopting the layout.
- Prompt: Evaluate partitioning for this table’s access and retention patterns. Verify query pruning and maintenance without creating excessive tiny partitions.
- Avoid: Assuming partitioning replaces indexes or guarantees every query is faster.
- Described as: huge table slow; split table by date; drop old data fast; table too big
- Related: query-plan, db-index, hash-partitioning, range-partitioning, time-series-partitioning
- Page: https://vibe-coding-101.brighteng.org/c/partitioning/

## backfill

**backfill** (APIs and data). A backfill populates or recomputes existing data after a rule or schema change.

- Use when: A new field works for new records but is missing from historical ones.
- What: A job that fills in or recomputes a value for existing rows in small, resumable batches, while the live app keeps writing.
- Why it matters with an agent: A single large update can block production traffic or restart from zero after failure.
- Do: Process bounded ranges, persist progress, and define how concurrent writes interact with the job.
- Prompt: Backfill this field in resumable batches. Test restart and concurrent edits, and verify live traffic stays within its performance budget.
- Avoid: Overwriting a newer live value with a value computed from an older snapshot.
- Described as: fill new column for old rows; update existing records; historical data missing; data migration script
- Related: migration, idempotency
- Page: https://vibe-coding-101.brighteng.org/c/backfill/

## denormalization

**denormalization** (APIs and data). Denormalization duplicates or precomputes data to serve a read pattern.

- Use when: A measured read bottleneck motivates storing a value near its consumer.
- What: You store a copy or precomputed value, such as a comment count on the post row, to make a read fast. Every copy needs a defined rule for when it is updated.
- Why it matters with an agent: A copied field can become an accidental second source of truth.
- Do: Choose whether the value is a historical snapshot or a maintained projection and test that policy.
- Prompt: Denormalize this measured read path with an explicit update policy. Verify source changes, retries, and rebuilds without inconsistent copies.
- Avoid: Maintaining the same copy through several independent update paths.
- Described as: store count on row; duplicate data for speed; precomputed column; counter cache; Denormalization
- Related: cache-invalidation, outbox, normalization, materialized-view
- Sources checked: 2026-10-11 (not human editorial approval)
- [MongoDB: Data modeling best practices](https://www.mongodb.com/docs/manual/data-modeling/best-practices/): Embedding and duplicating data trade simpler reads against update and consistency responsibilities.
- Page: https://vibe-coding-101.brighteng.org/c/denormalization/

## batch-stream

**batch vs stream** (APIs and data). Batch processing operates on bounded input; streaming processes ongoing input.

- Use when: A data workflow is acquiring a broker despite only needing periodic results.
- What: Batch jobs process a finished set of data on a schedule. Streaming processes events continuously as they arrive. The choice depends on how fresh the results must be.
- Why it matters with an agent: A more complex processing model can introduce unnecessary state and failure modes.
- Do: State the latency requirement and choose the simplest model that meets it.
- Prompt: Choose batch or streaming for this workload’s actual freshness requirement. Verify restart, duplicate handling, and the policy for late data.
- Avoid: Treating processing time as event time when late-arriving records change the result.
- Described as: do we need Kafka; real-time vs nightly; streaming vs cron job
- Related: job-queue, idempotency
- Page: https://vibe-coding-101.brighteng.org/c/batch-stream/

## runtime-validation

**runtime validation** (APIs and data). Check untrusted values when the program receives them.

- Use when: An API or file supplies data that TypeScript types merely assume is valid.
- What: Runtime validation checks whether actual input satisfies a contract. Compile-time types do not validate bytes received from a request, file, or model.
- Why it matters with an agent: A generated type assertion can silence the compiler while admitting invalid data.
- Do: Validate at the boundary, then pass the validated value inward. Check both malformed shapes and domain constraints.
- Prompt: Add runtime validation at this input boundary. Test malformed fields and invalid domain values before allowing side effects.
- Avoid: Validating the shape but trusting a caller-supplied identity or ownership claim.
- Described as: validate JSON; unchecked type assertion; schema validation; zod; TypeScript types do not check input; validate request body
- Related: dto, authn-authz
- Page: https://vibe-coding-101.brighteng.org/c/runtime-validation/

## clustered-storage

**physical row clustering** (APIs and data). Place related rows near each other to reduce scattered reads.

- Use when: A range query fetches related rows from many storage pages.
- What: Physical clustering groups stored rows using a key or index order. PostgreSQL CLUSTER rewrites a table once; later changes do not automatically preserve that ordering. This differs from a cluster of database nodes.
- Why it matters with an agent: An agent can confuse adding servers with reorganizing a table, or assume every engine maintains clustered order.
- Do: Measure page reads for the target range query. Check engine semantics, locking, and free disk before reorganizing. Recheck after representative updates.
- Prompt: Evaluate physical row clustering for this range query. Show page reads, rewrite locking, and maintenance costs.
- Avoid: A one-time rewrite can lose its benefit as rows change; clustered-index behavior varies by engine.
- Described as: clustering; clustered index; physical clustering; A range query fetches related rows from many storage pages; Clustering
- Related: database-cluster, b-tree, db-index, data-locality
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: CLUSTER](https://www.postgresql.org/docs/current/sql-cluster.html): Physical row reordering is a one-time operation in PostgreSQL and takes an exclusive table lock.
- Page: https://vibe-coding-101.brighteng.org/c/clustered-storage/

## normalization

**normalization** (APIs and data). Store facts according to their keys to reduce update anomalies.

- Use when: Changing a customer’s current address requires editing many inconsistent copies.
- What: Relational normalization organizes tables using keys and dependencies. Separating independent facts reduces insert, update, and delete anomalies; historical snapshots can be intentional copies.
- Why it matters with an agent: An agent can duplicate editable facts across tables because each screen needs them.
- Do: Identify each fact’s key, split independent entities, and add references and constraints. Check one update changes the current fact everywhere it is read.
- Prompt: Normalize these tables around their keys and dependencies. Test an update without inconsistent copies.
- Avoid: Splitting every value into a table without considering meaning or query cost is not a useful goal.
- Described as: database normalization; normal forms; update anomaly; Changing a customer’s current address requires editing many inconsistent copies; Normalization
- Related: denormalization, unique-constraint, transaction
- Sources checked: 2026-10-11 (not human editorial approval)
- [Microsoft: Database normalization](https://learn.microsoft.com/en-us/previous-versions/troubleshoot/microsoft-365/microsoft-365-apps/access/database-normalization-description): Normalization reduces redundant facts and update anomalies through keys and table relationships.
- Page: https://vibe-coding-101.brighteng.org/c/normalization/

## leader-follower-replication

**leader–follower replication** (APIs and data). Send writes through a leader and replicate them to followers.

- Use when: You need read capacity or a standby while keeping one write authority.
- What: A leader accepts writes and followers apply its changes. Acknowledgement policy determines whether a successful write has reached or been applied by followers; asynchronous followers may lag.
- Why it matters with an agent: An agent can route a read-after-write to a lagging follower or promote a stale copy.
- Do: Define write and read routes, acknowledgement guarantees, and promotion rules. Check replica lag and read-after-write behavior during a failover drill.
- Prompt: Document leader–follower replication, including acknowledgement policy, stale reads, and safe promotion checks.
- Avoid: One leader simplifies write ownership but does not eliminate data loss, lag, or split-brain risk.
- Described as: leader follower replication; primary secondary replication; primary standby; You need read capacity or a standby while keeping one write authority; Leader–Follower replication
- Related: read-replica, physical-replication, failover, split-brain
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Log-shipping standby servers](https://www.postgresql.org/docs/current/warm-standby.html): Primary/standby streaming replication, asynchronous lag, and synchronous acknowledgement configurations.
- [PostgreSQL: Failover](https://www.postgresql.org/docs/current/warm-standby-failover.html): Promotion, client routing, preventing the old primary from continuing as a writer, and restoring redundancy.
- Page: https://vibe-coding-101.brighteng.org/c/leader-follower-replication/

## multi-leader-replication

**multi-leader replication** (APIs and data). Allow multiple write authorities with explicit conflict handling.

- Use when: Disconnected sites or multiple regions need to accept writes.
- What: Multi-leader replication accepts writes at more than one leader and propagates changes between them. Products differ: some reconcile conflicts later, while coordinated multi-primary systems can reject conflicting transactions.
- Why it matters with an agent: An agent can assume two successful local writes will merge without losing a business decision.
- Do: Identify overlapping keys and constraints. Choose ownership or conflict rules. Test concurrent edits, retries, and recovery after disconnection for the selected product.
- Prompt: Evaluate multi-leader replication for these writers. Test conflicting updates and document the resolution rule.
- Avoid: Last-write-wins can discard valid work; extra writers do not guarantee linear write scaling.
- Described as: multi leader; multi-primary replication; active active replication; Disconnected sites or multiple regions need to accept writes; Multi-leader replication
- Related: leader-follower-replication, consensus, geo-replication, write-skew
- Sources checked: 2026-10-11 (not human editorial approval)
- [MySQL: Multi-primary mode](https://dev.mysql.com/doc/refman/8.0/en/group-replication-multi-primary-mode.html): Multiple writable members require conflict handling and have transaction and DDL restrictions.
- [Amazon DynamoDB: Global tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GlobalTables.html): Multi-region replication has explicit eventual and strong consistency modes with different constraints.
- Page: https://vibe-coding-101.brighteng.org/c/multi-leader-replication/

## base

**BASE** (APIs and data). Design for availability with temporary state and eventual convergence.

- Use when: A non-critical projection can stay usable while updates propagate.
- What: BASE expands to Basically Available, Soft state, and Eventually consistent. It describes a design approach that permits temporary differences and reconciliation, not one precise transaction isolation level.
- Why it matters with an agent: An agent can use the acronym to excuse permanent missing updates or broken payment invariants.
- Do: Name the data that may lag, how it converges, and what still requires atomic changes. Check delayed, duplicate, and failed updates against those rules.
- Prompt: Define the BASE behavior for this projection: acceptable staleness, convergence, and invariants that must stay atomic.
- Avoid: An eventually updated view can coexist with ACID transactions. Product categories do not establish exact guarantees.
- Described as: Basically Available Soft state Eventually consistent; BASE database; A non-critical projection can stay usable while updates propagate; BASE
- Related: eventual-consistency, acid, outbox
- Sources checked: 2026-10-11 (not human editorial approval)
- [AWS: ACID and BASE](https://aws.amazon.com/compare/the-difference-between-acid-and-base-database/): The BASE acronym and the use of eventual convergence. Product labels alone do not define transaction guarantees.
- [Amazon DynamoDB: Read consistency](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html): Strongly consistent reads reflect successful prior writes within the supported read scope; eventual reads may lag.
- Page: https://vibe-coding-101.brighteng.org/c/base/

## acid

**ACID** (APIs and data). Specify atomicity, consistency, isolation, and durability for transactions.

- Use when: A transfer or order must preserve invariants across several database changes.
- What: ACID describes transaction properties: all-or-nothing effects, preservation of defined invariants, controlled interaction with concurrent transactions, and persistence of acknowledged commits under the stated durability configuration.
- Why it matters with an agent: An agent can wrap code in a transaction while leaving a weak isolation level or an external side effect outside its guarantees.
- Do: Define constraints, isolation, and commit durability. Check rollback and competing transactions. Keep external side effects outside the claimed local atomic boundary.
- Prompt: State the ACID guarantees for this transaction. Test rollback, concurrent invariants, and the configured commit durability.
- Avoid: ACID consistency is invariant preservation, not CAP consistency. A local transaction cannot roll back an already sent email.
- Described as: Atomicity Consistency Isolation Durability; ACID transactions; A transfer or order must preserve invariants across several database changes; ACID
- Related: transaction, isolation, write-ahead-logging, two-phase-commit
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Transactions](https://www.postgresql.org/docs/current/tutorial-transactions.html): Atomic transaction boundaries, visibility of intermediate changes, commit, rollback, and persistence.
- [PostgreSQL: Transaction isolation](https://www.postgresql.org/docs/current/transaction-iso.html): Isolation-level behavior in PostgreSQL; snapshot isolation can still allow serialization anomalies.
- [PostgreSQL: Write-ahead logging](https://www.postgresql.org/docs/current/wal-intro.html): Log records reach durable storage before the corresponding data changes; redo supports crash recovery.
- Page: https://vibe-coding-101.brighteng.org/c/acid/

## strong-consistency

**strong consistency** (APIs and data). Make the exact freshness and ordering guarantee explicit.

- Use when: A permission revocation or inventory decision must not use an older acknowledged value.
- What: Strong consistency is an umbrella phrase; specify the required contract. A linearizable operation appears atomic between invocation and response and respects real-time order. Transaction serializability alone does not specify real-time ordering.
- Why it matters with an agent: An agent can choose a strong read endpoint while leaving an unsafe read-then-write race.
- Do: Identify the data scope and real-time ordering requirement. Use the supported consistent read or atomic conditional write. Check reads after acknowledged writes and overlapping updates.
- Prompt: Specify the required strong consistency contract and scope. Test read-after-write and use an atomic update for this invariant.
- Avoid: A fresh read alone does not make a later write atomic; caches and unsupported indexes can change the read path.
- Described as: linearizability; linearizable read; strongly consistent read; A permission revocation or inventory decision must not use an older acknowledged value; Strong consistency
- Related: eventual-consistency, optimistic-lock, consensus, cap-theorem
- Sources checked: 2026-10-11 (not human editorial approval)
- [Gilbert and Lynch: Brewer’s conjecture](https://groups.csail.mit.edu/tds/papers/Gilbert/Brewer2.pdf): Impossibility of providing atomic consistency and availability under partitions in the asynchronous model.
- [Amazon DynamoDB: Read consistency](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html): Strongly consistent reads reflect successful prior writes within the supported read scope; eventual reads may lag.
- [PostgreSQL: Transaction isolation](https://www.postgresql.org/docs/current/transaction-iso.html): Isolation-level behavior in PostgreSQL; snapshot isolation can still allow serialization anomalies.
- Page: https://vibe-coding-101.brighteng.org/c/strong-consistency/

## write-ahead-logging

**write-ahead logging (WAL)** (APIs and data). Persist the recovery log before the corresponding data pages.

- Use when: A database must recover committed changes after a crash without flushing every changed page at commit.
- What: WAL records changes before the affected data pages are written. Durable log records allow recovery to redo changes; the configured flush and acknowledgement policy determines what survives a failure.
- Why it matters with an agent: An agent can disable durable flushing for speed and still claim committed writes survive a crash.
- Do: Inspect log flush and commit settings. Run a crash-recovery drill on a disposable instance and reconcile acknowledged commits with recovered data.
- Prompt: Check WAL durability settings. Verify crash recovery against the writes that were acknowledged before the crash.
- Avoid: WAL is not a standalone backup. Losing required log segments or the underlying durable storage can prevent recovery.
- Described as: WAL; write ahead log; transaction log; A database must recover committed changes after a crash without flushing every changed page at commit; Write-ahead logging (WAL)
- Related: checkpointing, physical-replication, acid
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Write-ahead logging](https://www.postgresql.org/docs/current/wal-intro.html): Log records reach durable storage before the corresponding data changes; redo supports crash recovery.
- Page: https://vibe-coding-101.brighteng.org/c/write-ahead-logging/

## checkpointing

**checkpointing** (APIs and data). Record a recovery boundary after making the required state durable.

- Use when: Recovery replays too much log or periodic flushing causes latency spikes.
- What: A checkpoint establishes a recovery starting point. In PostgreSQL it coordinates writing dirty data pages and records the checkpoint in WAL, reducing how far crash recovery must replay. Stream processors use the word for different state snapshots.
- Why it matters with an agent: An agent can force frequent checkpoints without measuring the write and recovery tradeoff.
- Do: Check checkpoint duration, write load, and recovery time on representative data. Tune the interval and WAL budget together. Verify backups separately.
- Prompt: Measure checkpoint I/O and crash recovery time before changing checkpoint frequency or WAL limits.
- Avoid: A checkpoint does not replace backup retention or prove that a snapshot in another system is transactionally consistent.
- Described as: database checkpoint; checkpoint frequency; Recovery replays too much log or periodic flushing causes latency spikes; Checkpointing
- Related: write-ahead-logging, storage-compaction
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: WAL configuration](https://www.postgresql.org/docs/current/wal-configuration.html): Checkpoint work and the tradeoff between write activity, WAL volume, and recovery time.
- Page: https://vibe-coding-101.brighteng.org/c/checkpointing/

## storage-compaction

**storage compaction** (APIs and data). Merge storage runs and reclaim obsolete versions when safe.

- Use when: An LSM store accumulates files, tombstones, or background write pressure.
- What: LSM compaction merges sorted runs and may discard overwritten or deleted versions once retention and snapshot rules allow it. Policies trade read work, rewritten bytes, and temporary space.
- Why it matters with an agent: An agent can schedule full compaction without accounting for disk headroom or foreground latency.
- Do: Measure pending compaction bytes, read/write amplification, disk headroom, and latency. Check tombstone and snapshot retention before expecting space to return.
- Prompt: Diagnose compaction debt and amplification. Choose a policy and verify disk headroom and foreground latency.
- Avoid: Compaction consumes I/O and may need extra space before reclaiming any. It is different from a recovery checkpoint.
- Described as: LSM compaction; write amplification; tombstones; An LSM store accumulates files tombstones or background write pressure; Compaction
- Related: lsm-tree, checkpointing, mvcc
- Sources checked: 2026-10-11 (not human editorial approval)
- [RocksDB: Compaction](https://github.com/facebook/rocksdb/wiki/Compaction): Compaction merges sorted runs with different write, read, and space amplification tradeoffs.
- [RocksDB: Overview](https://github.com/facebook/rocksdb/wiki/RocksDB-Overview): Memtables, sorted table files, log recovery, and the organization of an LSM storage engine.
- Page: https://vibe-coding-101.brighteng.org/c/storage-compaction/

## data-locality

**data locality** (APIs and data). Place related data and computation close to reduce remote work.

- Use when: A request crosses regions or shards repeatedly to join related records.
- What: Data locality is the proximity of data to the work that uses it. Placement by tenant or region can reduce network hops, while replication and durability requirements may still require remote coordination.
- Why it matters with an agent: An agent can add a local read replica while writes and joins still cross the network.
- Do: Map request hops, key placement, and transaction participants. Compare local and remote paths under the chosen durability and failure policy.
- Prompt: Trace remote hops for this request. Improve data locality and verify latency without weakening the required durability.
- Avoid: Local reads do not imply local writes, regulatory compliance, or survival of a regional failure.
- Described as: regional data placement; colocation; data co-location; A request crosses regions or shards repeatedly to join related records; Data locality
- Related: geo-replication, clustered-storage, federation
- Sources checked: 2026-10-11 (not human editorial approval)
- [CockroachDB: Table localities](https://docs.cockroachlabs.com/docs/stable/table-localities): Regional placement changes where reads and writes incur network latency and how data survives regional failures.
- Page: https://vibe-coding-101.brighteng.org/c/data-locality/

## hot-partition

**hot partition** (APIs and data). One partition receives more work than its capacity can handle.

- Use when: One tenant or current-time bucket is throttled while the rest of the database is idle.
- What: A hot partition has disproportionate request load. Total database capacity can be sufficient while the partition or one heavily used key remains a bottleneck.
- Why it matters with an agent: An agent can raise global capacity without changing the key that concentrates every write.
- Do: Measure traffic and throttling per key or partition. Choose a better key or split hot-key work where semantics allow. Verify query fan-out and distribution afterward.
- Prompt: Find the hot partition. Propose a key or workload change and verify per-partition traffic and query costs.
- Avoid: More partitions do not divide a single key automatically. Balanced storage size does not guarantee balanced traffic.
- Described as: hot key; partition hotspot; hot shard; One tenant or current-time bucket is throttled while the rest of the database is idle; Hot partition
- Related: data-skew, hash-partitioning, range-partitioning, resharding
- Sources checked: 2026-10-11 (not human editorial approval)
- [Amazon DynamoDB: Partition key design](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-partition-key-design.html): Partition key choices determine traffic distribution; concentrated key activity can create hot partitions.
- [PostgreSQL: Table partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html): Range and hash partitioning, pruning, routing, and partition maintenance.
- Page: https://vibe-coding-101.brighteng.org/c/hot-partition/

## caching

**caching** (APIs and data). Reuse a stored result with explicit freshness and failure rules.

- Use when: Repeated requests recompute the same expensive result or reread the same data.
- What: A cache holds reusable data or computed results. Keys, expiration, invalidation, capacity, and misses determine whether reuse is correct; the authoritative data remains a separate responsibility.
- Why it matters with an agent: An agent can cache a user-specific result under a shared key or keep stale permissions indefinitely.
- Do: Define the key and acceptable staleness. Test hits, misses, invalidation, tenant separation, eviction, and a cache outage. Measure origin load as well as latency.
- Prompt: Cache this result with explicit keys and freshness. Test invalidation, tenant isolation, and cache-outage behavior.
- Avoid: A cache can amplify outages through miss storms. Fast stale data can still be wrong.
- Described as: cache; cache-aside; result cache; Repeated requests recompute the same expensive result or reread the same data; Caching
- Related: cache-invalidation, cache-stampede, http-cache, materialized-view
- Sources checked: 2026-10-11 (not human editorial approval)
- [Amazon Builders’ Library: Caching challenges](https://aws.amazon.com/builders-library/caching-challenges-and-strategies/): Cache freshness, capacity, failure behavior, and cache population are separate design concerns.
- Page: https://vibe-coding-101.brighteng.org/c/caching/

## materialized-view

**materialized view** (APIs and data). Persist a query result and define how it becomes current again.

- Use when: A dashboard repeats an expensive aggregate that can tolerate some lag.
- What: A materialized view stores the result of a query. In PostgreSQL, reading it uses stored rows and refreshing recomputes the result; other engines may support incremental maintenance.
- Why it matters with an agent: An agent can replace a query with a stored result without scheduling refreshes or showing its age.
- Do: Choose a freshness budget, refresh method, and failure handling. Change source data, verify the view’s documented lag, then verify the refreshed aggregate.
- Prompt: Evaluate a materialized view for this aggregate. Define refresh and freshness, then check results before and after a source change.
- Avoid: A normal view does not persist results. A materialized view can become stale and its refresh can be expensive.
- Described as: materialized views; persisted query result; refresh materialized view; A dashboard repeats an expensive aggregate that can tolerate some lag; Materialized views
- Related: denormalization, caching, query-plan
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Materialized views](https://www.postgresql.org/docs/current/rules-materializedviews.html): Persisting query results can speed reads while requiring a freshness and refresh policy.
- Page: https://vibe-coding-101.brighteng.org/c/materialized-view/

## secondary-index

**secondary index** (APIs and data). Provide another access path besides the table’s primary organization.

- Use when: Queries use an email or status rather than the primary lookup key.
- What: A secondary index maps indexed values to the records they identify. Storage engines differ: PostgreSQL indexes are separate from the heap, while some clustered engines use primary-key values in secondary indexes.
- Why it matters with an agent: An agent can assume every indexed lookup retrieves the full row without another access.
- Do: Choose an index for a real filter or ordering. Inspect the plan and table accesses, then measure write overhead and index size.
- Prompt: Evaluate a secondary index for this query. Show the access path, row fetches, and write maintenance cost.
- Avoid: Secondary indexes add work to writes and are not necessarily unique or covering.
- Described as: secondary indexes; nonclustered index; alternate access path; Queries use an email or status rather than the primary lookup key; Secondary indexes
- Related: db-index, covering-index, composite-index, clustered-storage
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Index-only scans and covering indexes](https://www.postgresql.org/docs/current/indexes-index-only-scans.html): Secondary indexes, payload columns, and visibility checks required for index-only scans.
- [PostgreSQL: Indexes](https://www.postgresql.org/docs/current/indexes.html): Indexes accelerate selected lookups while adding storage and write maintenance.
- Page: https://vibe-coding-101.brighteng.org/c/secondary-index/

## covering-index

**covering index** (APIs and data). Include the values a query needs so fewer table-row fetches may be necessary.

- Use when: An indexed query still spends time fetching columns from the table.
- What: A covering index contains the columns required by a particular query. PostgreSQL can use INCLUDE for payload columns, but MVCC visibility can still require heap checks in an index-only scan.
- Why it matters with an agent: An agent can add every column to an index or promise that coverage always eliminates heap reads.
- Do: Check filters, ordering, and selected columns. Compare index size, write overhead, and actual heap fetches on representative data and update rates.
- Prompt: Evaluate a covering index for this query. Verify index-only eligibility, heap fetches, index size, and write cost.
- Avoid: Coverage is relative to a query. Visibility, unsupported access methods, or changed projections can remove its benefit.
- Described as: covering indexes; INCLUDE columns; index-only scan; An indexed query still spends time fetching columns from the table; Covering index
- Related: secondary-index, composite-index, mvcc, query-plan
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Index-only scans and covering indexes](https://www.postgresql.org/docs/current/indexes-index-only-scans.html): Secondary indexes, payload columns, and visibility checks required for index-only scans.
- Page: https://vibe-coding-101.brighteng.org/c/covering-index/

## bloom-filter

**Bloom filter** (APIs and data). Reject definite misses cheaply while allowing possible false matches.

- Use when: Most lookups test keys absent from an expensive storage layer.
- What: A Bloom filter is a compact probabilistic membership structure. With correctly maintained membership it can say definitely absent or possibly present; a positive still needs the authoritative lookup.
- Why it matters with an agent: An agent can turn a possible match into a real match or lose new keys by updating the filter late.
- Do: Choose a false-positive budget and memory size. Check all inserted keys, measure false positives for absent keys, and define update and rebuild behavior.
- Prompt: Evaluate a Bloom filter before this lookup. Verify no inserted keys are rejected and measure false positives.
- Avoid: A standard Bloom filter cannot safely delete a key by clearing shared bits. A stale filter can reject valid new data.
- Described as: bloom filters; probabilistic membership; false positive filter; Most lookups test keys absent from an expensive storage layer; Bloom filter
- Related: lsm-tree, secondary-index, caching
- Sources checked: 2026-10-11 (not human editorial approval)
- [RocksDB: Bloom filters](https://github.com/facebook/rocksdb/wiki/RocksDB-Bloom-Filter): Probabilistic membership checks skip unnecessary reads but allow false positives.
- Page: https://vibe-coding-101.brighteng.org/c/bloom-filter/

## lsm-tree

**LSM tree** (APIs and data). Buffer writes and organize persisted data as sorted runs.

- Use when: You are choosing storage for sustained writes and ordered key reads.
- What: A Log-Structured Merge tree buffers updates in memory and flushes sorted runs to storage. Reads consult relevant versions and compaction merges runs; crash durability usually depends on a log and its configuration.
- Why it matters with an agent: An agent can call an LSM engine write-optimized without budgeting for compaction and read amplification.
- Do: Measure the actual mix of writes, point reads, range scans, and deletions. Inspect compaction debt, cache use, and disk headroom before tuning.
- Prompt: Evaluate this LSM engine with our workload. Measure read/write amplification, compaction debt, and durable-write latency.
- Avoid: Sequential ingestion does not mean every write is cheap; compaction rewrites data and can stall foreground work.
- Described as: Log-Structured Merge tree; log structured merge tree; SSTable; You are choosing storage for sustained writes and ordered key reads; LSM tree
- Related: b-tree, storage-compaction, bloom-filter, write-ahead-logging
- Sources checked: 2026-10-11 (not human editorial approval)
- [RocksDB: Overview](https://github.com/facebook/rocksdb/wiki/RocksDB-Overview): Memtables, sorted table files, log recovery, and the organization of an LSM storage engine.
- [RocksDB: Compaction](https://github.com/facebook/rocksdb/wiki/Compaction): Compaction merges sorted runs with different write, read, and space amplification tradeoffs.
- Page: https://vibe-coding-101.brighteng.org/c/lsm-tree/

## b-tree

**B-tree** (APIs and data). Keep keys ordered in a balanced tree for lookups and range scans.

- Use when: Queries filter by equality, compare ranges, or request indexed ordering.
- What: A B-tree stores ordered keys in balanced levels. Database implementations often use B+ tree variants; PostgreSQL’s B-tree indexes support equality and ordered comparisons.
- Why it matters with an agent: An agent can choose an index by name while its expressions or column order do not fit the query.
- Do: Match the operator and key order to real queries. Inspect plans for equality, range, and ordering cases and measure write cost.
- Prompt: Evaluate a B-tree index for these equality and range queries. Verify the plans and write overhead.
- Avoid: An index can be slower than a scan for a large result set; existence does not guarantee selection.
- Described as: B tree; B+ tree; balanced tree index; Queries filter by equality compare ranges or request indexed ordering; B-tree
- Related: lsm-tree, composite-index, query-planner
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Index types](https://www.postgresql.org/docs/current/indexes-types.html): B-tree supports equality and ordered range comparisons; suitability depends on the operator and query.
- Page: https://vibe-coding-101.brighteng.org/c/b-tree/

## query-planner

**query planner** (APIs and data). Choose an executable access path and join strategy for a query.

- Use when: A database picks a surprising scan or join even though an index exists.
- What: The query planner turns a query into an execution plan using available access paths, statistics, and optimization rules. The query plan is the chosen output; the planner is the component making the choice.
- Why it matters with an agent: An agent can force an index before checking estimates, query shape, or parameter behavior.
- Do: Compare estimated and actual row counts and inspect scans and joins. Refresh appropriate statistics before forcing a strategy. Use a safe environment for EXPLAIN ANALYZE, which executes the query.
- Prompt: Investigate the query planner’s choice. Compare estimates with actual rows and verify statistics before forcing an index.
- Avoid: A plan for one parameter or tiny fixture may not represent production. Planner costs are not elapsed milliseconds.
- Described as: SQL planner; execution planner; A database picks a surprising scan or join even though an index exists; Query planner
- Related: query-plan, cost-based-optimizer, db-index
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Using EXPLAIN](https://www.postgresql.org/docs/current/using-explain.html): Planner estimates, cost units, actual execution statistics, and the fact that ANALYZE executes the statement.
- Page: https://vibe-coding-101.brighteng.org/c/query-planner/

## cost-based-optimizer

**cost-based optimizer** (APIs and data). Choose among query plans using estimated resource costs.

- Use when: A join order performs badly because the database misestimates intermediate row counts.
- What: A cost-based optimizer estimates candidate plan costs from statistics and a cost model. It chooses among considered plans, without a guarantee of finding the globally fastest plan.
- Why it matters with an agent: An agent can tune random cost settings while the actual error is stale or unrepresentative statistics.
- Do: Find the largest estimate-versus-actual mismatch. Check statistics, data distribution, and cost assumptions. Compare candidate plans under the same representative workload.
- Prompt: Diagnose this cost-based optimizer estimate. Check statistics and skew, then compare plans on representative data.
- Avoid: Cost units are model units, not milliseconds. Correlated columns and changing workloads can defeat simple estimates.
- Described as: CBO; cost based optimization; cardinality estimate; A join order performs badly because the database misestimates intermediate row counts; Cost-based optimizer
- Related: query-planner, query-plan, data-skew
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Using EXPLAIN](https://www.postgresql.org/docs/current/using-explain.html): Planner estimates, cost units, actual execution statistics, and the fact that ANALYZE executes the statement.
- Page: https://vibe-coding-101.brighteng.org/c/cost-based-optimizer/

## data-skew

**data skew** (APIs and data). Uneven values or partition sizes make some units of work much larger than others.

- Use when: One join task runs long after every other task finishes.
- What: Data skew is an uneven distribution of values or records. It can distort cardinality estimates and create oversized partitions; a hot partition specifically concerns concentrated runtime traffic.
- Why it matters with an agent: An agent can add workers while the same oversized join key determines total completion time.
- Do: Inspect key frequencies, partition bytes, and task durations. Consider skew-aware joins or splitting heavy work. Check result correctness and the slowest task afterward.
- Prompt: Measure data skew for this join. Handle the heavy keys and verify results and tail task duration.
- Avoid: Hashing distributes different keys; it does not divide all rows with the same key unless the algorithm explicitly supports that split.
- Described as: skewed join; uneven data distribution; straggler partition; One join task runs long after every other task finishes; Data skew
- Related: hot-partition, cost-based-optimizer, hash-partitioning
- Sources checked: 2026-10-11 (not human editorial approval)
- [Apache Spark: SQL performance tuning](https://spark.apache.org/docs/latest/sql-performance-tuning.html): Skewed partitions can dominate query execution; adaptive skew handling splits selected work.
- Page: https://vibe-coding-101.brighteng.org/c/data-skew/

## change-data-capture

**change data capture (CDC)** (APIs and data). Publish source-data changes so downstream systems can follow them.

- Use when: A search index or warehouse must follow database updates without repeated full scans.
- What: CDC captures inserts, updates, and deletes and exposes change events, often from a database log. Snapshot initialization, offsets, ordering scope, and delivery semantics depend on the connector.
- Why it matters with an agent: An agent can process each event as unique and double-apply a change after a restart.
- Do: Define the snapshot-to-stream handoff and durable offsets. Test restart, duplicate delivery, deletes, schema changes, and reconciliation with the source.
- Prompt: Use CDC for this projection. Verify snapshot handoff, restart recovery, duplicate handling, and delete propagation.
- Avoid: CDC is not an automatic end-to-end exactly-once guarantee or an application business-event contract.
- Described as: CDC; Change Data Capture; database change stream; A search index or warehouse must follow database updates without repeated full scans; CDC (Change Data Capture)
- Related: logical-replication, outbox, idempotency, schema-evolution
- Sources checked: 2026-10-11 (not human editorial approval)
- [Debezium: Architecture](https://debezium.io/documentation/reference/stable/architecture.html): Connectors capture database changes and publish change events; consumers must account for delivery and recovery behavior.
- Page: https://vibe-coding-101.brighteng.org/c/change-data-capture/

## logical-replication

**logical replication** (APIs and data). Replicate logical table changes rather than a physical copy of storage.

- Use when: A reporting database needs selected tables or a migration crosses compatible database versions.
- What: Logical replication describes data changes independently of their physical block locations. PostgreSQL uses publications and subscriptions; supported operations and schema handling have specific restrictions.
- Why it matters with an agent: An agent can assume subscribing to table changes also migrates every schema object and DDL change.
- Do: Choose published data and row identity. Check initial synchronization, lag, updates, deletes, and schema compatibility before cutover.
- Prompt: Evaluate logical replication for these tables. Verify row identity, initial sync, deletes, lag, and schema handling.
- Avoid: Logical replication is not automatically multi-leader conflict resolution or a complete database clone.
- Described as: logical decoding; publication subscription; logical replica; A reporting database needs selected tables or a migration crosses compatible database versions; Logical replication
- Related: physical-replication, change-data-capture, data-migration
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Logical replication](https://www.postgresql.org/docs/current/logical-replication.html): Replication of logical data changes using publication and subscription rather than physical block identity.
- Page: https://vibe-coding-101.brighteng.org/c/logical-replication/

## physical-replication

**physical replication** (APIs and data). Keep a standby aligned with the primary’s physical database changes.

- Use when: You need a compatible whole-database standby for read offload or recovery.
- What: Physical replication transfers storage-level changes. PostgreSQL streaming replication sends WAL records for a compatible standby to replay; it differs from publishing selected logical table changes.
- Why it matters with an agent: An agent can assume any database version or subset of tables can use the same physical replay stream.
- Do: Check version and storage compatibility, base backup, retained WAL, and replay lag. Drill promotion and prevent the old primary from remaining writable.
- Prompt: Verify physical replication prerequisites, WAL retention, replay lag, and a fenced standby-promotion drill.
- Avoid: A lagging standby can lose acknowledged asynchronous writes on failover. Replication does not replace independently retained backups.
- Described as: physical replica; WAL streaming replication; You need a compatible whole-database standby for read offload or recovery; Physical replication
- Related: logical-replication, write-ahead-logging, leader-follower-replication
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Log-shipping standby servers](https://www.postgresql.org/docs/current/warm-standby.html): Primary/standby streaming replication, asynchronous lag, and synchronous acknowledgement configurations.
- [PostgreSQL: Failover](https://www.postgresql.org/docs/current/warm-standby-failover.html): Promotion, client routing, preventing the old primary from continuing as a writer, and restoring redundancy.
- Page: https://vibe-coding-101.brighteng.org/c/physical-replication/

## federation

**query federation** (APIs and data). Query independently managed data sources through a shared interface.

- Use when: A report joins local records with data owned by another database.
- What: Query federation exposes data across separate sources without first copying everything into one store. Foreign tables are one implementation; remote execution, credentials, and transaction boundaries remain relevant.
- Why it matters with an agent: An agent can write a convenient cross-source join that pulls millions of rows over the network.
- Do: Inspect pushdown and transferred rows. Restrict credentials and define remote failure handling. Check whether the required cross-source consistency is supported.
- Prompt: Evaluate query federation for this report. Inspect pushdown, transferred rows, permissions, and cross-source consistency.
- Avoid: One SQL statement across sources does not automatically provide a single global snapshot or atomic distributed writes.
- Described as: federation; federated query; foreign data wrapper; FDW; A report joins local records with data owned by another database; Federation
- Related: data-locality, materialized-view, data-warehouse
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: postgres_fdw](https://www.postgresql.org/docs/current/postgres-fdw.html): Foreign tables access remote PostgreSQL data; query pushdown, credentials, and remote transaction behavior matter.
- Page: https://vibe-coding-101.brighteng.org/c/federation/

## data-lake

**data lake** (APIs and data). Retain diverse data for later processing and analysis with governance.

- Use when: You need to preserve raw events and files for several future analytical uses.
- What: A data lake stores data in varied formats, often on object storage, so consumers can process it for different purposes. Catalogues, access control, quality, and retention determine whether the stored data is usable.
- Why it matters with an agent: An agent can dump files into buckets without a discoverable schema or deletion policy.
- Do: Define ownership, formats, metadata, partitions, permissions, and retention. Verify a consumer can discover, read, and reconcile a sample dataset.
- Prompt: Design this data lake’s layout, catalogue, access controls, and retention. Verify one consumer query against source records.
- Avoid: A lake is not inherently schema-free or transaction-free; table formats and lakehouse systems can add transaction semantics.
- Described as: raw data lake; lakehouse; analytical object storage; You need to preserve raw events and files for several future analytical uses; Data lake
- Related: data-warehouse, object-storage, columnar-storage, etl
- Sources checked: 2026-10-11 (not human editorial approval)
- [AWS: Data lakes](https://aws.amazon.com/what-is/data-lake/): A lake retains data in varied formats for later processing and analysis; governance and discoverability still matter.
- Page: https://vibe-coding-101.brighteng.org/c/data-lake/

## data-warehouse

**data warehouse** (APIs and data). Integrate and model data for reliable analytical queries and reporting.

- Use when: Reporting needs consistent business definitions across several operational systems.
- What: A data warehouse organizes integrated data for analysis, commonly with modeled tables and repeatable ingestion. It differs from the operational database serving individual user transactions.
- Why it matters with an agent: An agent can copy tables without defining grain, update cadence, or a shared meaning for revenue.
- Do: Define fact grain, dimensions, freshness, and reconciliation rules. Check one metric against source records and test late or corrected data.
- Prompt: Model this warehouse dataset with explicit grain and freshness. Reconcile the report and test late-arriving corrections.
- Avoid: A warehouse is not automatically current, correct, or cheaper; ingestion, modeling, and query costs still matter.
- Described as: analytical warehouse; fact table; dimension table; Reporting needs consistent business definitions across several operational systems; Data warehouse
- Related: data-lake, columnar-storage, etl, materialized-view
- Sources checked: 2026-10-11 (not human editorial approval)
- [AWS: Data warehouses](https://aws.amazon.com/what-is/data-warehouse/): Warehouses integrate data for analytical queries and reporting, with modeling and freshness responsibilities.
- Page: https://vibe-coding-101.brighteng.org/c/data-warehouse/

## columnar-storage

**columnar storage** (APIs and data). Store values by column to suit selective analytical scans.

- Use when: A report scans a few columns across many rows.
- What: Column-oriented storage groups values from the same column, supporting compression and scans that read only needed columns. Performance depends on filtering, encoding, updates, and the engine.
- Why it matters with an agent: An agent can select columnar storage for a point-update workload without checking its write behavior.
- Do: Benchmark the report and the actual insert/update mix. Measure scanned bytes, compression, latency, and maintenance work. Compare a row-oriented path for point access.
- Prompt: Evaluate columnar storage with our scan and update workload. Compare scanned bytes, latency, compression, and maintenance cost.
- Avoid: Columnar storage is not universally faster. Fetching many columns of one row or frequent small updates can favor other layouts.
- Described as: column store; column-oriented storage; columnstore; A report scans a few columns across many rows; Columnar storage
- Related: row-based-storage, data-warehouse, materialized-view
- Sources checked: 2026-10-11 (not human editorial approval)
- [Microsoft: Columnstore overview](https://learn.microsoft.com/en-us/sql/relational-databases/indexes/columnstore-indexes-overview?view=sql-server-ver17): Column-oriented storage suits many analytical scans; rowstore and columnstore can coexist for different workloads.
- Page: https://vibe-coding-101.brighteng.org/c/columnar-storage/

## row-based-storage

**row-based storage** (APIs and data). Keep a row’s fields together for record-oriented access.

- Use when: Requests frequently fetch or update complete individual records.
- What: Row-oriented storage groups fields of a record together. It commonly suits transactional point access, while wide analytical scans may read unused fields compared with columnar storage.
- Why it matters with an agent: An agent can assume every relational database has one fixed storage layout for every workload.
- Do: Measure point reads, updates, and analytical scans on realistic rows. Inspect indexes and bytes read; consider a separate analytical layout when needed.
- Prompt: Compare row-based and columnar storage for these point reads, updates, and scans using representative data.
- Avoid: Rowstore can still support efficient analytics with suitable indexes or mixed layouts. Storage orientation alone does not define transaction guarantees.
- Described as: row store; row-oriented storage; rowstore; Requests frequently fetch or update complete individual records; Row-based storage
- Related: columnar-storage, secondary-index, transaction
- Sources checked: 2026-10-11 (not human editorial approval)
- [Microsoft: Columnstore overview](https://learn.microsoft.com/en-us/sql/relational-databases/indexes/columnstore-indexes-overview?view=sql-server-ver17): Column-oriented storage suits many analytical scans; rowstore and columnstore can coexist for different workloads.
- Page: https://vibe-coding-101.brighteng.org/c/row-based-storage/

## time-series-partitioning

**time-series partitioning** (APIs and data). Partition timestamped records into explicit time intervals.

- Use when: Retention cleanup or bounded-time queries scan a growing events table.
- What: Time-series partitioning commonly uses ranges on an event or ingestion timestamp. Queries can prune irrelevant intervals and retention can detach or drop old partitions, depending on engine support.
- Why it matters with an agent: An agent can create daily partitions without handling late events, time zones, or the newest hot interval.
- Do: Choose the timestamp, UTC boundaries, interval, and late-data policy. Check boundary routing, pruning, retention, and traffic concentrated in the current partition.
- Prompt: Partition these events by time. Test UTC boundaries, late arrivals, query pruning, and safe retention cleanup.
- Avoid: Partitioning by time does not automatically distribute current writes across machines or accelerate queries missing the time filter.
- Described as: time series partitioning; time-based partitioning; time buckets; Retention cleanup or bounded-time queries scan a growing events table; Time-series partitioning
- Related: range-partitioning, hot-partition, partitioning
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Table partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html): Range and hash partitioning, pruning, routing, and partition maintenance.
- Page: https://vibe-coding-101.brighteng.org/c/time-series-partitioning/

## hash-partitioning

**hash partitioning** (APIs and data). Use a hash of the partition key to assign records to buckets.

- Use when: Independent keys should spread across partitions without maintaining range boundaries.
- What: Hash partitioning computes a hash and maps it to a partition. It can spread distinct keys, while range queries may need to contact many partitions and a single dominant key stays together.
- Why it matters with an agent: An agent can change the bucket count and silently route existing keys to the wrong location.
- Do: Choose the key and mapping. Check distribution with real key frequencies, query fan-out, and the migration procedure for changing the layout.
- Prompt: Evaluate hash partitioning for this key. Verify skew, query fan-out, and remapping during a partition-count change.
- Avoid: Uniform hashing does not remove skew caused by one heavily used key. Table partitions are not necessarily separate server shards.
- Described as: hash partitions; hash buckets; hash sharding; Independent keys should spread across partitions without maintaining range boundaries; Hash partitioning
- Related: range-partitioning, consistent-hashing, hot-partition, resharding
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Table partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html): Range and hash partitioning, pruning, routing, and partition maintenance.
- Page: https://vibe-coding-101.brighteng.org/c/hash-partitioning/

## range-partitioning

**range partitioning** (APIs and data). Assign rows to partitions by ordered key intervals.

- Use when: Queries and retention operations target a bounded date or key range.
- What: Range partitioning groups records by non-overlapping key intervals. It supports pruning and range-oriented maintenance, but an increasing key can concentrate new writes in the newest interval.
- Why it matters with an agent: An agent can leave a boundary gap or assume the database prunes partitions for every query expression.
- Do: Define lower and upper bounds and a missing-partition policy. Test boundary values, pruning for actual queries, and distribution of current writes.
- Prompt: Evaluate range partitioning. Test interval boundaries, missing ranges, query pruning, and concentrated writes.
- Avoid: Partitioning does not replace useful indexes, and a range layout can create a hot partition.
- Described as: range partitions; range sharding; partition pruning; Queries and retention operations target a bounded date or key range; Range partitioning
- Related: hash-partitioning, time-series-partitioning, partitioning
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Table partitioning](https://www.postgresql.org/docs/current/ddl-partitioning.html): Range and hash partitioning, pruning, routing, and partition maintenance.
- Page: https://vibe-coding-101.brighteng.org/c/range-partitioning/

## consistent-hashing

**consistent hashing** (APIs and data). Limit key reassignment when the set of storage nodes changes.

- Use when: Adding a cache or storage node should not remap nearly every key.
- What: Consistent hashing assigns keys and nodes in a stable hash space. Adding or removing nodes moves a subset of assignments; virtual nodes can improve distribution. It differs from taking a hash modulo a changing node count.
- Why it matters with an agent: An agent can call modulo-based routing consistent hashing and trigger a near-total cache miss storm on resize.
- Do: Compare key assignments before and after a node change. Measure moved keys, per-node load, and replica placement, and plan any state transfer.
- Prompt: Evaluate consistent hashing for this routing layer. Measure key movement, load balance, and replica placement on node changes.
- Avoid: Fewer moved keys does not mean zero migration, balanced hot-key traffic, or safe membership changes.
- Described as: hash ring; virtual nodes; rendezvous hashing; Adding a cache or storage node should not remap nearly every key; Consistent hashing
- Related: hash-partitioning, rebalancing, hot-partition, quorum
- Sources checked: 2026-10-11 (not human editorial approval)
- [DeCandia et al.: Dynamo](https://www.allthingsdistributed.com/files/amazon-dynamo-sosp2007.pdf): Consistent hashing, virtual nodes, replica quorums, version reconciliation, and eventual consistency.
- Page: https://vibe-coding-101.brighteng.org/c/consistent-hashing/

## data-migration

**data migration** (APIs and data). Move or transform existing records with validation and a controlled cutover.

- Use when: An application must move from one database or data layout to another.
- What: Data migration transfers or transforms records between locations or representations. A schema migration changes structure; a data migration must also reconcile the records, ongoing writes, and the moment readers switch.
- Why it matters with an agent: An agent can finish a bulk copy while updates made during the copy never reach the target.
- Do: Define snapshot, change capture or write pause, mappings, reconciliation, cutover, and rollback. Check counts, sampled values, deletes, and critical invariants before routing traffic.
- Prompt: Plan this data migration with concurrent-write handling, reconciliation, cutover, and rollback. Verify critical records and invariants.
- Avoid: Matching row counts alone does not establish equivalent data. A rollback after new target-only writes needs a recovery strategy.
- Described as: move database records; database cutover; data migration; An application must move from one database or data layout to another; Data migration
- Related: migration, schema-evolution, change-data-capture, backfill
- Sources checked: 2026-10-11 (not human editorial approval)
- [AWS DMS: Terminology and concepts](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Introduction.html): Migration tasks can use full load and ongoing change capture; cutover and validation remain explicit steps.
- Page: https://vibe-coding-101.brighteng.org/c/data-migration/

## schema-registry

**schema registry** (APIs and data). Version message schemas and enforce a chosen compatibility policy.

- Use when: Producers and consumers deploy separately and disagree on event fields.
- What: A schema registry stores schema versions and can validate compatibility when a new version is registered. Producers and consumers use the associated schema or identifier to encode and interpret data.
- Why it matters with an agent: An agent can rename a field and assume registration proves every deployed consumer will work.
- Do: Choose the format and backward, forward, or full compatibility policy. Test old/new producer-consumer combinations and retained messages with the actual serializers.
- Prompt: Define the schema registry compatibility policy. Test old and new producers, consumers, and retained messages before rollout.
- Avoid: Compatibility rules depend on format and mode. A registry does not migrate existing records or prove semantic compatibility.
- Described as: schema registry; Avro schema compatibility; Protobuf schema versions; Producers and consumers deploy separately and disagree on event fields; Schema registry
- Related: schema-evolution, change-data-capture, runtime-validation
- Sources checked: 2026-10-11 (not human editorial approval)
- [Confluent: Schema evolution and compatibility](https://docs.confluent.io/platform/current/schema-registry/fundamentals/schema-evolution.html): Schema Registry versions schemas and enforces configured compatibility modes; backward and forward compatibility differ.
- Page: https://vibe-coding-101.brighteng.org/c/schema-registry/

## memoization

**memoization** (performance). Reuse a computed result while its inputs are unchanged.

- Use when: Profiling shows repeated expensive computation during rendering.
- What: Memoization trades memory and input comparisons for less repeated work. Its benefit depends on cost and stable inputs.
- Why it matters with an agent: Adding caches everywhere can hide dependencies and make simple code harder to understand.
- Do: Measure the expensive operation first. Check both correctness after input changes and actual work avoided.
- Prompt: Memoize this measured expensive calculation. Include all inputs and compare render cost before and after the change.
- Avoid: A cache with incomplete dependencies displays a stale result.
- Described as: expensive recalculation; useMemo; unnecessary rerenders; slow on every keystroke; cache computed value; React.memo; re-renders too much; too many re-renders
- Related: derived-state, query-plan
- Page: https://vibe-coding-101.brighteng.org/c/memoization/

## reflow

**layout thrashing** (performance). Alternating DOM reads and writes forces the browser to recalculate layout repeatedly.

- Use when: An interaction stalls while repeatedly measuring and resizing elements.
- What: Reading geometry such as offsetHeight after changing styles forces the browser to compute layout immediately. Doing it in a loop repeats that work every iteration. Painting is a separate, later step.
- Why it matters with an agent: An apparently small DOM loop can trigger repeated layout calculations.
- Do: Measure the interaction, group compatible reads and writes, and recheck after content changes.
- Prompt: Reduce forced layout in this interaction. Use a performance trace to compare before and after, and verify measurements after fonts and content load.
- Avoid: Caching geometry that becomes stale when the layout changes.
- Described as: forced reflow; forced synchronous layout; page freezes when resizing; offsetHeight in loop; layout and paint; getBoundingClientRect slow
- Related: layout-shift, frame-budget
- Page: https://vibe-coding-101.brighteng.org/c/reflow/

## critical-path

**critical rendering path** (performance). The critical rendering path is the work needed before the browser can render content.

- Use when: A page waits for unrelated resources before showing useful content.
- What: These are the HTML, CSS, fonts, and scripts the browser must fetch and process before it can show the first screen. Anything else on that path delays first paint.
- Why it matters with an agent: Loading every resource early can compete with the resources the first screen actually needs.
- Do: Trace the initial load and remove or defer work that does not support the initial content.
- Prompt: Identify this page’s critical rendering path. Compare loading traces after deferring nonessential work and verify the first screen remains complete.
- Avoid: Preloading everything and reducing the relative priority of important resources.
- Described as: blank page while loading; render blocking resources; slow first paint; LCP; defer scripts
- Related: request-waterfall, code-splitting
- Page: https://vibe-coding-101.brighteng.org/c/critical-path/

## tail-latency

**tail latency** (performance). Tail latency describes the slow end of a response-time distribution.

- Use when: Average latency looks healthy while some users wait much longer.
- What: Percentiles such as p95 and p99 describe the slowest requests. A healthy average can hide the one-in-a-hundred user who waits ten seconds.
- Why it matters with an agent: A benchmark of a few successful requests may hide queueing or dependency stalls.
- Do: Measure a representative distribution and trace the operations behind slow requests.
- Prompt: Measure this endpoint’s tail latency under representative load. Trace the slow cases and compare percentiles after one targeted change.
- Avoid: Reporting p99 from too few samples to support a useful estimate.
- Described as: p99; p95; some requests very slow; average looks fine but users complain; latency percentiles
- Related: observability, timeout-budget
- Page: https://vibe-coding-101.brighteng.org/c/tail-latency/

## cold-start

**cold start** (performance). A cold start includes initialization work before a new instance can serve its first operation.

- Use when: Initial requests are much slower than requests to an already-running instance.
- What: A new instance, such as a serverless function or a scaled-up container, has to boot and initialize before its first request, so that request is much slower than later ones.
- Why it matters with an agent: Initialization can accidentally repeat on every request or load unnecessary resources.
- Do: Measure cold and warm paths separately and move only safe reusable initialization into the appropriate lifecycle.
- Prompt: Measure this route’s cold start. Remove unnecessary initialization and compare cold and warm latency without sharing user-specific state.
- Avoid: Optimizing a warm benchmark and reporting it as cold-start improvement.
- Described as: first request slow; serverless slow start; lambda cold start; slow after idle
- Related: request-scope, code-splitting
- Page: https://vibe-coding-101.brighteng.org/c/cold-start/

## list-virtualization

**list virtualization** (performance). Render a window of list items instead of every item at once.

- Use when: A long list spends too much time or memory rendering off-screen rows.
- What: Only the rows near the visible area are rendered, and they are reused as the user scrolls. Rows keep stable identities, and the data still loads in pages.
- Why it matters with an agent: Virtualizing the DOM does not stop loading an entire dataset into memory.
- Do: Measure the list, preserve stable identity, and test scrolling, focus, and variable content.
- Prompt: Virtualize this measured slow list. Verify scrolling, row identity, keyboard access, and bounded data loading with a large fixture.
- Avoid: Recycling a row without resetting state that belongs to a different item.
- Described as: long list slow; render only visible rows; react-window; FlatList performance; infinite scroll laggy; windowing
- Related: list-key, pagination
- Page: https://vibe-coding-101.brighteng.org/c/list-virtualization/

## memory-leak

**memory leak** (performance). A memory leak retains memory beyond its useful lifetime.

- Use when: Memory grows after repeatedly opening and closing a feature.
- What: Memory that is no longer needed stays reachable, through an old listener, a timer, a cache, or a closure, so the garbage collector can't free it and usage keeps growing.
- Why it matters with an agent: A feature can appear closed while listeners, tasks, or caches still retain its data.
- Do: Reproduce the lifecycle repeatedly and compare retained objects or allocations.
- Prompt: Investigate this memory growth with repeated open/close cycles. Identify retained owners and verify memory stabilizes after the fix.
- Avoid: Declaring a leak fixed because garbage collection temporarily lowered one sample.
- Described as: memory keeps growing; app gets slower over time; out of memory; heap snapshot; detached DOM nodes
- Related: event-cleanup, cancellation
- Page: https://vibe-coding-101.brighteng.org/c/memory-leak/

## lock-contention

**lock contention** (performance). Lock contention occurs when operations wait to acquire the same synchronization boundary.

- Use when: Many independent operations queue behind one protected section.
- What: Many operations wait on the same lock, so throughput stops growing as you add load even though each operation is fast once it gets the lock.
- Why it matters with an agent: Removing a lock can improve a benchmark while introducing incorrect shared state.
- Do: Measure hold and wait time, then reduce unnecessary shared work without losing the invariant.
- Prompt: Reduce this measured lock contention. Preserve the protected invariant and compare correctness and throughput under concurrent load.
- Avoid: Creating a per-key lock map that grows forever.
- Described as: threads waiting on lock; more threads not faster; global lock bottleneck; lock hot spot
- Related: mutex, invariant
- Page: https://vibe-coding-101.brighteng.org/c/lock-contention/

## game-loop

**game loop** (performance). A game loop coordinates repeated input, simulation, and rendering.

- Use when: Gameplay updates are spread across unrelated timers.
- What: Each frame, the loop reads input, advances the simulation, and draws. Keeping state changes in the update step and out of the draw step keeps the game consistent.
- Why it matters with an agent: Independent update paths can process the same frame inconsistently.
- Do: Choose the engine’s supported update phases and keep state changes separate from drawing.
- Prompt: Organize this simulation around the engine’s update loop. Verify update order, pause behavior, and rendering without advancing the simulation twice.
- Avoid: Adding another timer that mutates the same simulation state outside its update phase.
- Described as: setInterval game; requestAnimationFrame loop; update and render; game objects out of sync
- Related: delta-time, state-machine
- Page: https://vibe-coding-101.brighteng.org/c/game-loop/

## delta-time

**delta time** (performance). Delta time is elapsed time between updates.

- Use when: Movement speed changes when frame rate changes.
- What: Delta time is the time since the last frame. Multiplying speeds by it keeps movement consistent at any frame rate. Physics usually needs a fixed timestep on top of that.
- Why it matters with an agent: Multiplying by elapsed time helps motion but does not guarantee stable physics.
- Do: Express rates consistently and choose a bounded fixed or variable timestep strategy.
- Prompt: Make this movement independent of render frame rate. Test low and high rates, a long frame, and pause using the chosen timestep policy.
- Avoid: Allowing one unusually long timestep to cross obstacles or destabilize the simulation.
- Described as: speed depends on frame rate; fixed timestep; movement too fast on high refresh rate; frame rate independent
- Related: game-loop, frame-budget
- Page: https://vibe-coding-101.brighteng.org/c/delta-time/

## object-pool

**object pool** (performance). An object pool reuses instances instead of creating a new one for each use.

- Use when: Profiling shows frequent allocations or expensive resource creation causing pauses.
- What: Instead of creating and discarding objects such as bullets or particles, the program keeps a set and reuses them, resetting each one before reuse. Use it only when profiling shows allocation is the problem.
- Why it matters with an agent: Reused instances can retain state from their previous owner.
- Do: Measure the allocation cost, define exhaustion behavior, and reset all reusable state.
- Prompt: Pool these measured costly objects. Test reuse, exhaustion, and complete state reset, and compare allocation pressure before and after.
- Avoid: Adding pooling where normal allocation was inexpensive and the extra retained memory is larger.
- Described as: garbage collection stutter; reuse objects; too many allocations; GC pauses
- Related: frame-budget, memory-leak
- Page: https://vibe-coding-101.brighteng.org/c/object-pool/

## frame-budget

**frame budget** (performance). A frame budget allocates the time available for responsive rendering at a target cadence.

- Use when: An interaction drops frames during updates or rendering.
- What: At 60 frames per second, each frame has about 16.7 ms for input, logic, layout, and painting. One frame that runs over shows up as a stutter even if the average is fine.
- Why it matters with an agent: A feature can look smooth on small fixtures while expensive frames grow with content.
- Do: Trace representative frames and identify the work exceeding the chosen target.
- Prompt: Profile this interaction against its target frame budget. Reduce the measured bottleneck and compare slow frames on a representative device and dataset.
- Avoid: Moving work off the main thread but waiting synchronously for its result each frame.
- Described as: janky scrolling; dropped frames; 60fps; stutter on slow devices; long tasks
- Related: reflow, list-virtualization
- Page: https://vibe-coding-101.brighteng.org/c/frame-budget/

## authn-authz

**authentication and authorization** (security). Authentication establishes identity; authorization decides whether that identity may perform an operation.

- Use when: Signed-in users can request records belonging to other users.
- What: Authentication answers 'who is this?' and authorization answers 'may they do this, to this record?'. Being signed in only settles the first question.
- Why it matters with an agent: A page-level login check can leave direct API calls unprotected.
- Do: Derive identity from trusted authentication and check the requested action at the authoritative boundary.
- Prompt: Separate authentication from authorization on this endpoint. Test signed-out access, another user’s object, and the permitted owner’s request.
- Avoid: Trusting an owner or role field supplied in the request body.
- Described as: authentication vs authorization; logged in user can edit others data; auth vs permissions; role check; who can do what
- Related: rls, idor
- Page: https://vibe-coding-101.brighteng.org/c/authn-authz/

## xss

**cross-site scripting** (security). Cross-site scripting lets untrusted content execute in another user’s browser.

- Use when: User-provided text or rich content is rendered on a page.
- What: Untrusted text is inserted into a page as HTML, an attribute, a URL, or script, and the browser runs it. Each of those places needs its own encoding or sanitization.
- Why it matters with an agent: Generated string templates can cross from displaying text into executing markup.
- Do: Keep text escaped; sanitize deliberately allowed markup and validate URL contexts.
- Prompt: Review this rendering path for XSS. Keep text escaped, sanitize allowed rich content, and test malicious markup and URL inputs.
- Avoid: Applying one hand-written escaping rule to HTML, attributes, URLs, and JavaScript.
- Described as: XSS; dangerouslySetInnerHTML; script in user content; sanitize HTML; innerHTML user input
- Related: csp, structured-output
- Page: https://vibe-coding-101.brighteng.org/c/xss/

## csrf

**cross-site request forgery** (security). Cross-site request forgery induces an authenticated browser to send an unwanted request.

- Use when: A browser automatically sends cookies to state-changing endpoints.
- What: Another site makes the user's browser send a request to your app, and the browser attaches the user's cookies. The defense depends on how credentials are sent: SameSite cookies, tokens, or origin checks.
- Why it matters with an agent: A login check alone cannot prove that the user intended this request.
- Do: Use the framework’s CSRF protection and trusted-origin policy; verify state-changing requests from another origin.
- Prompt: Protect these cookie-authenticated actions against CSRF. Test cross-origin requests and legitimate submissions without disabling the framework’s checks.
- Avoid: Assuming CORS prevents every cross-origin request from being sent.
- Described as: CSRF; cross-site form submission; SameSite cookie; CSRF token; forged request from other site
- Related: session-cookie, cors
- Page: https://vibe-coding-101.brighteng.org/c/csrf/

## ssrf

**server-side request forgery** (security). Server-side request forgery causes a server to contact an unintended destination.

- Use when: A server downloads content from URLs supplied by users.
- What: A feature that fetches a user-supplied URL, such as a link preview or import, can be pointed at internal addresses like 169.254.169.254 or localhost, directly or through redirects.
- Why it matters with an agent: A URL-shaped string can target internal services or redirect to them.
- Do: Constrain destinations and protocols, validate redirect targets, and enforce network-level egress restrictions where possible.
- Prompt: Restrict this URL-fetching feature to its intended destinations. Test internal addresses, redirects, and DNS changes without allowing arbitrary internal access.
- Avoid: Checking only the submitted hostname while the eventual connection reaches another address.
- Described as: SSRF; user supplied URL fetch; link preview security; cloud metadata endpoint; fetch any URL
- Related: least-privilege, threat-model
- Page: https://vibe-coding-101.brighteng.org/c/ssrf/

## idor

**insecure direct object reference** (security). An insecure direct object reference exposes an object without checking access to it.

- Use when: A request contains the ID of an object to read, edit, or delete.
- What: The endpoint loads a record by the id in the URL or body without checking that the caller may access it, so changing the id exposes someone else's data.
- Why it matters with an agent: An agent may check ownership on one endpoint and omit it on another.
- Do: Apply the resource authorization rule to every operation and test with two users.
- Prompt: Check object authorization on all operations for this resource. Verify another user cannot read, update, or delete it by changing the ID.
- Avoid: Treating an unpredictable identifier as an access-control mechanism.
- Described as: IDOR; change id in URL see other data; access other users records; missing ownership check; BOLA
- Related: authn-authz, rls
- Page: https://vibe-coding-101.brighteng.org/c/idor/

## password-hashing

**password hashing** (security). Store a salted password hash using a purpose-built password hashing function.

- Use when: A service must support password authentication.
- What: Store a slow, salted hash made by bcrypt, scrypt, or Argon2, never the password and never a fast hash like SHA-256. Login hashes the attempt and compares.
- Why it matters with an agent: A fast general-purpose hash makes offline guessing cheaper after a database leak.
- Do: Use the maintained authentication library’s password storage and upgrade path; keep raw passwords out of logs.
- Prompt: Use the authentication library’s password hashing and verification. Test login and hash upgrades, and verify raw passwords never enter storage or logs.
- Avoid: Replacing a password hash with reversible encryption as the primary storage mechanism.
- Described as: store passwords; bcrypt; argon2; SHA-256 passwords; password storage
- Related: session-cookie, env-secrets
- Page: https://vibe-coding-101.brighteng.org/c/password-hashing/

## oauth

**OAuth and OpenID Connect** (security). OAuth delegates access to resources; OpenID Connect adds identity information for login.

- Use when: An application integrates a third-party account or delegated API access.
- What: OAuth gives an app an access token to call an API for the user. OpenID Connect adds an ID token saying who the user is. Each token has a specific audience and must be validated for its job.
- Why it matters with an agent: A token’s presence alone does not establish the claimed identity or permissions.
- Do: Use the provider-supported flow and maintained client; verify redirect, request binding, token validation, and expiry handling.
- Prompt: Implement this provider’s supported authorization flow. Test redirect validation, request binding, expired credentials, and the permissions actually granted.
- Avoid: Treating an access token as proof of identity without the provider’s identity contract.
- Described as: sign in with Google; social login; OIDC; access token vs ID token; OAuth redirect
- Related: authn-authz, secure-storage
- Page: https://vibe-coding-101.brighteng.org/c/oauth/

## csp

**content security policy** (security). Content Security Policy restricts resources and execution in the browser.

- Use when: A site needs to limit script execution and external resource access.
- What: A Content-Security-Policy header tells the browser which scripts, styles, and connections a page may use. It limits the damage from injected scripts but does not prevent the injection.
- Why it matters with an agent: A policy can be weakened to silence errors without understanding what it permits.
- Do: Inventory required resources, use appropriate nonces or hashes, and test before enforcing the policy.
- Prompt: Add a CSP suited to this application. Verify legitimate interactions and blocked injected scripts without broadly allowing unsafe execution.
- Avoid: Mistaking report-only monitoring for an enforced policy.
- Described as: CSP; Content-Security-Policy header; security headers; unsafe-inline; nonce
- Related: xss, threat-model
- Page: https://vibe-coding-101.brighteng.org/c/csp/

## cors

**CORS** (security). Cross-Origin Resource Sharing controls which cross-origin responses browser scripts may read.

- Use when: A browser frontend calls an API on another origin.
- What: The browser lets a page read a response from another origin only if that server's CORS headers allow it. CORS does not stop the request from being sent and does not authenticate anyone.
- Why it matters with an agent: Reflecting any Origin can unintentionally grant response access.
- Do: Allow only intended origins and credential behavior; test preflight and actual requests.
- Prompt: Configure CORS for these frontend origins. Verify allowed and disallowed origins, credential handling, and preflight responses.
- Avoid: Testing only with a command-line client that does not enforce browser CORS.
- Described as: blocked by CORS policy; Access-Control-Allow-Origin; preflight request fails; cross origin request blocked
- Related: csrf, authn-authz
- Page: https://vibe-coding-101.brighteng.org/c/cors/

## threat-model

**threat model** (security). Identify assets, adversaries, entry points, and plausible failure paths.

- Use when: A new feature changes who can access valuable data or operations.
- What: List what is valuable, who might misuse it, including other signed-in customers, how they could reach it, and what controls and tests block each path.
- Why it matters with an agent: Generic security middleware may miss the actual trust boundary.
- Do: Describe the sensitive operation and the least-privileged caller who could misuse it.
- Prompt: Threat-model this feature’s trust boundaries. Identify concrete misuse paths, choose controls, and turn the highest-risk paths into tests.
- Avoid: Listing only anonymous attackers while ignoring another authenticated customer.
- Described as: how could this be abused; security review of feature; attack scenarios; what could go wrong security
- Related: least-privilege, prompt-injection
- Page: https://vibe-coding-101.brighteng.org/c/threat-model/

## supply-chain

**software supply-chain security** (security). Software supply-chain security addresses risks in dependencies, build inputs, and distribution.

- Use when: A patch adds a package, build plugin, or downloaded executable.
- What: Every dependency, build plugin, and downloaded binary runs with your code's privileges. Check that the package is the one you meant, review its install scripts, and keep the lockfile.
- Why it matters with an agent: A plausible package name or install script can introduce unintended code execution.
- Do: Verify the package identity, review installation behavior, and preserve reproducible dependency resolution.
- Prompt: Review this new dependency’s identity, install scripts, and required privileges. Verify the lockfile and document why the existing dependencies are insufficient.
- Avoid: Assuming a pinned version is necessarily safe because it is reproducible.
- Described as: new npm package safe; typosquatting; hallucinated package name; slopsquatting; malicious dependency; postinstall script; AI made up a package; package does not exist
- Related: least-privilege, continuous-integration
- Page: https://vibe-coding-101.brighteng.org/c/supply-chain/

## session-cookie

**session cookie** (security). A session cookie carries a session credential in browser requests.

- Use when: A web application maintains a signed-in browser session.
- What: The browser sends the session cookie with every request. Secure, HttpOnly, and SameSite limit how it travels, and the server limits how long it lasts and revokes it on logout.
- Why it matters with an agent: A working login can leave stolen or logged-out sessions usable.
- Do: Use appropriate Secure, HttpOnly, and SameSite settings; define expiry, rotation, and invalidation.
- Prompt: Harden this session cookie and lifecycle. Test login rotation, expiry, logout invalidation, and the intended cross-site behavior.
- Avoid: Believing HttpOnly prevents an injected script from acting through the victim’s session.
- Described as: HttpOnly; SameSite; logout does not invalidate session; cookie settings; session expiry; keep user logged in; stay logged in
- Related: csrf, authn-authz
- Page: https://vibe-coding-101.brighteng.org/c/session-cookie/

## prompt-injection

**prompt injection** (security). Untrusted content attempts to redirect an AI system’s instructions or actions.

- Use when: An agent reads content supplied by another user, page, or external service.
- What: Text the model reads, such as a web page, email, document, or tool result, contains instructions, and the model treats them as if they came from you. Only permission checks in the host application stop the resulting actions.
- Why it matters with an agent: Content that looks authoritative can be mistaken for authorization to act.
- Do: Keep trusted instructions separate, constrain available actions, and require host-side permission checks.
- Prompt: Test this agent against instructions embedded in retrieved content. Verify that untrusted text cannot expand tool permissions or trigger unauthorized actions.
- Avoid: Relying on one prompt sentence as the entire security boundary.
- Described as: indirect prompt injection; ignore previous instructions; AI follows instructions in content; jailbreak via document; agent tricked by web page
- Related: guardrails, tool-use
- Page: https://vibe-coding-101.brighteng.org/c/prompt-injection/

## e2e

**end-to-end test** (testing). Check a user journey through the running application.

- Use when: Unit tests pass but users cannot finish a real workflow.
- What: An end-to-end test drives a complete flow across the application’s relevant boundaries.
- Why it matters with an agent: Generated pieces can each look correct while their integration fails.
- Do: Choose one critical journey, use realistic data, and assert the user-visible outcome. State which external services are substituted.
- Prompt: Add an end-to-end test for this user journey. Run the application, complete the workflow, and verify its persisted result.
- Avoid: Mocking the entire backend removes the integration the test claims to cover.
- Described as: whole app test; user journey; integration breaks; Playwright test; Cypress test; test like a real user
- Related: test-isolation, test-double
- Page: https://vibe-coding-101.brighteng.org/c/e2e/

## test-isolation

**test isolation** (testing). Each test controls its own state and can run independently.

- Use when: A test passes alone but fails in the full suite or in parallel.
- What: Isolated tests do not rely on another test’s execution order, browser session, or mutable records.
- Why it matters with an agent: An agent may reuse an account or a fixture that competing tests modify.
- Do: Give each test independent state and cleanup. Run the affected tests alone, together, and in parallel.
- Prompt: Isolate these tests with independent sessions and records. Verify they pass alone and together in parallel.
- Avoid: A fresh browser still points at database records shared by every test.
- Described as: passes alone fails together; parallel tests fail; shared test data; test order dependency; tests affect each other; tests pass individually but fail together; tests only fail when run together
- Related: test-fixture, e2e
- Page: https://vibe-coding-101.brighteng.org/c/test-isolation/

### test isolation: a worked example

Canonical page: https://vibe-coding-101.brighteng.org/c/test-isolation/#before-and-after

#### The problem

One test adds a cart item. Another expects a fresh empty cart. Both pass with a fresh process, but the empty-cart check fails after the first test mutates the shared fixture.

#### Prompt to paste

Isolate these tests with independent sessions and records. Verify they pass alone and together in parallel.

#### Before

A fixture factory always returns the same cart. One test leaves state for the next; changing their order changes the outcome.

#### After

Create a new cart for each test rather than sharing the mutable object. Test independence in both orders. In an application, apply the same ownership rule to sessions, records, files, and other mutable resources.

#### Run the check

Save the following code as test-isolation.mjs and run `node --test test-isolation.mjs` with Node.js 22.12 or later.

```js
import test from 'node:test';
import assert from 'node:assert/strict';

function before() {
  const shared = { items: [] };
  return () => shared;
}

function after() {
  return () => ({ items: [] });
}

function addItem(makeCart) {
  const cart = makeCart();
  cart.items.push('book');
  assert.equal(cart.items.length, 1);
}
function startsEmpty(makeCart) {
  assert.deepEqual(makeCart().items, []);
}

test('checks pass alone but interfere when sharing the fixture', () => {
  addItem(before());
  startsEmpty(before());
  const shared = before();
  addItem(shared);
  assert.throws(() => startsEmpty(shared), { code: 'ERR_ASSERTION' });
});

test('independent fixtures pass in both orders and overlapping owners', () => {
  for (const order of [[addItem, startsEmpty], [startsEmpty, addItem]]) {
    const fixture = after();
    for (const check of order) check(fixture);
  }
  const fixture = after();
  const first = fixture(), second = fixture();
  first.items.push('book');
  assert.deepEqual(second.items, []);
});
```

#### Expected result

The shared-fixture example reproduces the exact alone-versus-together mismatch. Independent fixtures pass in both orders and retain separate mutable state when two owners exist at once.

#### Limits

Fresh objects isolate this memory-only example. Separate objects do not isolate a shared database row, account, port, or filesystem path. Give parallel tests unique resources or a safe reset boundary, close resources, and restore mocks and clocks. These checks do not run multiple OS processes or measure suite flakiness; verify the actual suite under its real parallel settings.

#### Sources

- [Playwright: Test isolation](https://playwright.dev/docs/best-practices#make-tests-as-isolated-as-possible): Independent tests should own their storage, session, cookies, and data. The cart example is an original memory-only illustration.

Sources checked: 2026-10-11. These are original illustrative examples with automated checks. Human editorial approval is not recorded. Policy: https://vibe-coding-101.brighteng.org/editorial/


## test-fixture

**test fixture** (testing). Reusable setup gives a test a known starting state and owns cleanup.

- Use when: Tests repeat setup or leave records behind after a failure.
- What: A fixture supplies test resources with an explicit lifetime, such as a signed-in page or seeded record.
- Why it matters with an agent: Copied setup tends to drift and cleanup often disappears from failure paths.
- Do: Extract the repeated resource lifecycle. Pick its scope deliberately and ensure teardown runs after failures.
- Prompt: Create a test fixture for this resource with explicit scope and teardown. Verify a failing test still cleans it up.
- Avoid: A suite-wide fixture shares mutable state that should belong to one test.
- Described as: test setup; test cleanup; seed test data; beforeEach duplication; leftover test data
- Related: test-isolation, test-double
- Page: https://vibe-coding-101.brighteng.org/c/test-fixture/

## auto-waiting

**auto-waiting** (testing). Wait for an observable condition instead of a fixed delay.

- Use when: A browser test needs sleeps to pass on slower machines.
- What: Playwright actions wait for relevant actionability checks; retrying assertions wait for the expected state within a timeout.
- Why it matters with an agent: Adding a longer sleep can hide a timing bug without making the test reliable.
- Do: Replace fixed sleeps with locators and assertions for the state that makes the next step valid.
- Prompt: Remove fixed sleeps from this test. Use Playwright auto-waiting and retrying assertions for the actual ready and completed states.
- Avoid: A visible button is not proof that the preceding save has completed.
- Described as: flaky test; wait for page; fixed sleep; slow CI; waitForTimeout; test fails on CI only
- Related: semantic-locator, e2e
- Page: https://vibe-coding-101.brighteng.org/c/auto-waiting/

## semantic-locator

**semantic locator** (testing). Find an element by its role, label, or other user-facing meaning.

- Use when: A small markup change breaks many browser tests.
- What: A semantic locator identifies an interface element through meaning, such as a button’s accessible name, rather than DOM position.
- Why it matters with an agent: Generated selectors often depend on CSS classes and element order.
- Do: Use role and accessible name first, scope to the relevant region, and require an unambiguous match.
- Prompt: Replace brittle selectors with semantic locators. Use role and accessible name, check that each match is unique, and rerun the affected tests.
- Avoid: Using the first match hides ambiguous or duplicated controls.
- Described as: brittle selector; nth child; find button; accessible name; getByRole; tests break on markup change
- Related: auto-waiting, e2e
- Page: https://vibe-coding-101.brighteng.org/c/semantic-locator/

## test-double

**test double** (testing). A controlled substitute makes a dependency predictable in a test.

- Use when: You need to exercise a timeout or rejection that is hard to trigger reliably.
- What: Test double is the umbrella term for substitutes such as stubs, fakes, and mocks, which serve different testing purposes.
- Why it matters with an agent: An agent can over-mock a test until it only confirms its own assumptions.
- Do: Substitute the smallest boundary needed for the scenario. Keep separate coverage of the real integration.
- Prompt: Use a test double at the external service boundary to simulate a timeout. Assert recovery, and keep a separate test of the real integration.
- Avoid: The substitute returns a response the real service would never produce.
- Described as: fake service; mock API; simulate timeout; stub response; mock vs stub; test without calling real API
- Related: seam, e2e
- Page: https://vibe-coding-101.brighteng.org/c/test-double/

### test double: a worked example

Canonical page: https://vibe-coding-101.brighteng.org/c/test-double/#before-and-after

#### The problem

A product screen loads a price from an external service. You need to check its timeout state without waiting for the real service to become unavailable. Keep the screen logic real and substitute only the price-loading boundary.

#### Prompt to paste

Use a test double at the external service boundary to simulate a timeout. Assert recovery, and keep a separate test of the real integration.

#### Before

The happy path returns a price, but a rejected dependency escapes without a defined screen state. A happy-path check alone leaves that missing behavior undiscovered.

#### After

Use a controlled loader that rejects with TimeoutError to expose the failure. Handle that specified error as an unavailable state, preserve the success path, and let unexpected errors propagate instead of hiding them.

#### Run the check

Save the following code as test-double.mjs and run `node --test test-double.mjs` with Node.js 22.12 or later.

```js
import test from 'node:test';
import assert from 'node:assert/strict';

async function before(loadPrice) {
  return { status: 'ready', price: await loadPrice() };
}

async function after(loadPrice) {
  try {
    return { status: 'ready', price: await loadPrice() };
  } catch (error) {
    if (error.name !== 'TimeoutError') throw error;
    return { status: 'unavailable', message: 'Price unavailable. Try again.' };
  }
}

const timeout = async () => {
  throw new DOMException('Price service timed out', 'TimeoutError');
};

test('a controlled timeout exposes missing recovery', async () => {
  assert.deepEqual(await before(async () => 100), { status: 'ready', price: 100 });
  await assert.rejects(before(timeout), { name: 'TimeoutError' });
});

test('the real handler recovers and still handles success and unexpected errors', async () => {
  let calls = 0;
  const unavailable = await after(async () => { calls++; return timeout(); });
  assert.deepEqual(unavailable,
    { status: 'unavailable', message: 'Price unavailable. Try again.' });
  assert.equal(calls, 1);
  assert.deepEqual(await after(async () => 100), { status: 'ready', price: 100 });
  await assert.rejects(after(async () => { throw new Error('invalid response'); }),
    /invalid response/);
});
```

#### Expected result

The controlled timeout makes the initial handler reject. The revised handler returns the specified unavailable state, still returns a real price from the success stub, and propagates an unexpected failure. The test double replaces the loader, not the handler being checked.

#### Limits

A test double is a substitute used in a test; it does not make the application resilient by itself. This stub assumes the boundary uses TimeoutError. Match the real client contract and keep separate integration checks for request shape, decoding, authentication, and actual error types. A stub that returns the desired final screen state without running the handler would not test recovery.

#### Sources

- [Martin Fowler: Test Double](https://martinfowler.com/bliki/TestDouble.html): Test double as the umbrella term and stubs as controlled canned responses.
- [MDN: AbortSignal timeout](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal#static_methods): TimeoutError is used by AbortSignal.timeout; the example assumes that explicit boundary contract.

Sources checked: 2026-10-11. These are original illustrative examples with automated checks. Human editorial approval is not recorded. Policy: https://vibe-coding-101.brighteng.org/editorial/


## visual-regression

**visual regression test** (testing). Compare rendered output with an intentionally reviewed baseline.

- Use when: Behavioral tests pass while spacing, clipping, or typography breaks.
- What: A visual regression test detects image differences under a controlled rendering environment.
- Why it matters with an agent: An agent can change CSS globally while only checking the component it edited.
- Do: Fix viewport, fonts, and data; capture important states; inspect differences before accepting a new baseline.
- Prompt: Add visual regression coverage for these screens and states. Stabilize fonts and data, then review every baseline difference.
- Avoid: Automatically accepting new snapshots turns regressions into expected output.
- Described as: screenshot diff; CSS regression; visual snapshot; layout broke unnoticed; screenshot testing
- Related: e2e, layout-shift
- Page: https://vibe-coding-101.brighteng.org/c/visual-regression/

## linter-loop

**static analysis** (testing). Static analysis inspects code without exercising the application.

- Use when: A generated patch contains type errors or suspicious patterns.
- What: Linters and type checkers read the code without running it and catch different kinds of mistakes. A suppression comment hides the warning but leaves the defect.
- Why it matters with an agent: Suppressions can hide a defect instead of resolving it.
- Do: Run the relevant analyzer, understand its diagnostic, and check the affected behavior after fixing it.
- Prompt: Resolve these static-analysis diagnostics at their cause. Keep the rules enabled and rerun the analyzer plus the relevant behavior checks.
- Avoid: Treating a clean analyzer result as proof that the application works.
- Described as: type errors; lint errors; ts-ignore; eslint-disable; tsc errors; fix warnings properly
- Related: verification, tdd
- Page: https://vibe-coding-101.brighteng.org/c/linter-loop/

## snapshot-test

**snapshot test** (testing). Compare serialized output with a reviewed expected snapshot.

- Use when: Stable structured output is easier to review as a whole than through many individual assertions.
- What: The test saves the serialized output once, someone reviews it, and later runs fail on any difference. Each difference has to be reviewed, not accepted automatically.
- Why it matters with an agent: An agent can accept a changed snapshot without checking whether it represents a regression.
- Do: Keep snapshots focused and deterministic; pair them with assertions for essential behavior.
- Prompt: Add a focused snapshot for this output. Stabilize volatile fields and demonstrate that an unintended output change fails the test.
- Avoid: Updating every baseline to make a failing suite green.
- Described as: toMatchSnapshot; update snapshots; snapshot keeps changing; golden file
- Related: characterization-test, visual-regression
- Page: https://vibe-coding-101.brighteng.org/c/snapshot-test/

## property-based

**property-based testing** (testing). Generate inputs to test a general property rather than only handpicked examples.

- Use when: A parser or transformation has many combinations and boundary cases.
- What: Instead of a few hand-picked inputs, the framework generates many and checks a rule that must always hold, such as 'parse(format(x)) equals x'. It then shrinks any failure to a small example.
- Why it matters with an agent: A few generated examples may miss the exact condition that breaks an invariant.
- Do: Define a useful invariant, generate representative inputs, and keep discovered regressions.
- Prompt: Add property-based tests for this round trip. Generate edge cases and preserve any failing counterexample as a regression test.
- Avoid: Choosing a property so weak that a broken implementation satisfies it.
- Described as: fast-check; hypothesis; fuzz inputs; generated test cases; edge cases I did not think of
- Related: invariant, serialization
- Page: https://vibe-coding-101.brighteng.org/c/property-based/

## flaky-test

**flaky test** (testing). A test produces inconsistent outcomes without an intentional relevant change.

- Use when: A check intermittently fails under the same expected conditions.
- What: A test passes and fails on the same code. The cause may be timing, shared state, the test infrastructure, or a real race condition in the product.
- Why it matters with an agent: Retries can hide both test defects and intermittent application failures.
- Do: Capture the failure conditions, control suspected inputs, and verify the underlying cause before changing expectations.
- Prompt: Investigate this flaky test using its failure evidence. Isolate timing or shared state and verify the fix under the conditions that previously failed.
- Avoid: Deleting the assertion or increasing retries while leaving the cause unexplained.
- Described as: test fails randomly; intermittent failure; passes on retry; nondeterministic test; flaky CI
- Related: test-isolation, auto-waiting
- Page: https://vibe-coding-101.brighteng.org/c/flaky-test/

## network-panel

**network panel** (testing). The browser network panel shows requests and responses made by the page.

- Use when: Clicking Save appears to do nothing and the failing boundary is unknown.
- What: The Network tab in browser devtools lists every request the page makes, with status, timing, headers, and bodies. It shows whether a request was sent and where it failed.
- Why it matters with an agent: Changing server code cannot fix an event that never sends a request.
- Do: Reproduce the action and inspect the relevant request, status, timing, and safely redacted data.
- Prompt: Inspect the network activity for this failing action. Report whether a request occurred and identify its failing boundary without exposing credentials or private payloads.
- Avoid: Filtering out fetch requests and concluding that the page sent nothing.
- Described as: did Save send a request; request and response; devtools network; button does nothing; check API call in browser
- Related: repro, request-waterfall
- Page: https://vibe-coding-101.brighteng.org/c/network-panel/

## structured-concurrency

**structured concurrency** (concurrency). Child tasks finish within the lifetime of their enclosing operation.

- Use when: Background work survives the screen or request that started it.
- What: Structured concurrency ties child-task lifetimes to a scope, with defined rules for waiting, cancellation, and errors.
- Why it matters with an agent: Launching untracked tasks makes completion and cleanup hard to reason about.
- Do: Use scoped child tasks for related work. Define failure behavior and verify that cancellation reaches the children.
- Prompt: Use structured concurrency for these related tasks. Define failure handling and verify parent cancellation reaches all child work.
- Avoid: An unstructured task created inside a function is assumed to share its lifetime.
- Described as: orphan task; untracked task; task group; async let; background task keeps running; fire and forget
- Related: cancellation, actor-isolation
- Page: https://vibe-coding-101.brighteng.org/c/structured-concurrency/

## cancellation

**cooperative cancellation** (concurrency). Work must observe cancellation and stop safely.

- Use when: An old search or upload keeps running after the user leaves.
- What: In cooperative cancellation, a cancellation request signals intent; the running operation must check it or use cancellation-aware APIs.
- Why it matters with an agent: Calling cancel alone does not guarantee that obsolete work stops or cannot publish a result.
- Do: Propagate cancellation, check it between work units, and prevent obsolete completions from updating current state.
- Prompt: Make this operation cooperatively cancellable. Propagate cancellation and verify cancelled or obsolete work cannot update the UI.
- Avoid: A catch-all handler swallows cancellation and continues the operation.
- Described as: cancel request; stale response; old search result; stop background task; AbortController; results for previous query
- Related: structured-concurrency, debounce
- Page: https://vibe-coding-101.brighteng.org/c/cancellation/

### cooperative cancellation: a worked example

Canonical page: https://vibe-coding-101.brighteng.org/c/cancellation/#before-and-after

#### The problem

A user leaves a search screen while its request is in flight. Cancelling the owner should prevent a late completion from updating the abandoned screen, including when a dependency ignores the signal.

#### Prompt to paste

Make this operation cooperatively cancellable. Propagate cancellation and verify cancelled or obsolete work cannot update the UI.

#### Before

The owner creates an AbortController but never passes its signal to the dependency or checks it before publishing. Calling abort changes the signal, while the pending work can still update the view.

#### After

Pass the signal through the supported boundary, check before starting, and check again after awaiting the result. The second check prevents publishing a late result even if that particular dependency did not cooperate.

#### Run the check

Save the following code as cancellation.mjs and run `node --test cancellation.mjs` with Node.js 22.12 or later.

```js
import test from 'node:test';
import assert from 'node:assert/strict';

async function before(load, signal, publish) {
  const result = await load();
  publish(result);
}

async function after(load, signal, publish) {
  signal.throwIfAborted();
  const result = await load({ signal });
  signal.throwIfAborted();
  publish(result);
}

test('aborting an unused signal does not prevent publication', async () => {
  const controller = new AbortController();
  const shown = [];
  let finish;
  const task = before(() => new Promise((resolve) => { finish = resolve; }),
    controller.signal, (value) => shown.push(value));
  controller.abort();
  finish('obsolete');
  await task;
  assert.deepEqual(shown, ['obsolete']);
});

test('cancellation is propagated and late publication is blocked', async () => {
  const controller = new AbortController();
  const shown = [];
  let finish, received;
  const task = after(({ signal }) => {
    received = signal;
    return new Promise((resolve) => { finish = resolve; });
  }, controller.signal, (value) => shown.push(value));
  assert.equal(received, controller.signal);
  controller.abort();
  finish('obsolete');
  await assert.rejects(task, { name: 'AbortError' });
  assert.deepEqual(shown, []);
  let calls = 0;
  await assert.rejects(after(() => { calls++; }, controller.signal, () => {}),
    { name: 'AbortError' });
  assert.equal(calls, 0);
  const active = new AbortController();
  await after(async () => 'current', active.signal, (value) => shown.push(value));
  assert.deepEqual(shown, ['current']);
});
```

#### Expected result

Calling abort alone leaves the unguarded publication intact. The revised version passes the exact signal, rejects with AbortError after a cancelled late completion, does not start already-cancelled work, and still publishes an active result.

#### Limits

Cancellation is cooperative: a dependency that ignores the signal can continue using resources. A signal does not undo a completed server write. Use a fresh controller for new work, handle cancellation separately from current errors, and release listeners you add yourself. A generation guard still helps when several active operations share a view.

#### Sources

- [MDN: AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal): Signal propagation, throwIfAborted, one-use signals, and cooperative APIs.
- [MDN: AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController): Aborting supported requests is distinct from clearing a timer.

Sources checked: 2026-10-11. These are original illustrative examples with automated checks. Human editorial approval is not recorded. Policy: https://vibe-coding-101.brighteng.org/editorial/


## actor-isolation

**actor isolation** (concurrency). An actor protects its mutable state through an isolation boundary.

- Use when: Concurrent Swift tasks read and write the same mutable object.
- What: Actor-isolated state is accessed according to the actor’s executor and isolation rules, preventing unsynchronized access to that state.
- Why it matters with an agent: Adding async does not by itself make shared mutable state safe.
- Do: Give the state one isolation owner and expose operations through it. Check assumptions across suspension points.
- Prompt: Put this shared mutable state behind actor isolation. Remove unsynchronized access and review invariants across every await.
- Avoid: Assuming actor isolation makes a multi-step operation atomic across await.
- Described as: Swift data race; shared mutable state; actor state; Sendable warning; Swift 6 concurrency errors; actor model; actor
- Related: actor-reentrancy, structured-concurrency
- Page: https://vibe-coding-101.brighteng.org/c/actor-isolation/

## actor-reentrancy

**actor reentrancy** (concurrency). Other work can change actor state while an operation is suspended.

- Use when: An actor checks a condition, awaits a request, then acts on a stale assumption.
- What: Actor reentrancy allows other work to run on the actor during suspension. State observed before await may differ afterward.
- Why it matters with an agent: The compiler can protect memory access while the business invariant still breaks.
- Do: Recheck assumptions after await or reserve the operation before suspending. Test overlapping calls deliberately.
- Prompt: Review this actor for reentrancy across await. Preserve the invariant and test two overlapping calls with controlled completion order.
- Avoid: The test runs calls sequentially and never exercises the suspension window.
- Described as: actor race after await; stale state after await; overlapping async calls; actor state changed during await; double refresh
- Related: actor-isolation, cancellation
- Page: https://vibe-coding-101.brighteng.org/c/actor-reentrancy/

## debounce

**debounce** (concurrency). Wait for a quiet interval before acting on repeated input.

- Use when: A search field sends a request on every keystroke.
- What: Debouncing postpones work until input has stopped for a chosen interval. It differs from throttling, which limits execution frequency.
- Why it matters with an agent: Delaying every event independently still runs every request.
- Do: Replace the pending action on new input. Handle cancellation and obsolete responses separately from the delay.
- Prompt: Debounce this search input. Replace pending work on each edit and verify an older response cannot overwrite the latest results.
- Avoid: Debouncing input is treated as protection against out-of-order responses.
- Described as: search on every keystroke; too many search requests; delay input; wait until user stops typing; throttle vs debounce; fires on every keypress; fires too often
- Related: cancellation, request-deduplication
- Page: https://vibe-coding-101.brighteng.org/c/debounce/

### debounce: a worked example

Canonical page: https://vibe-coding-101.brighteng.org/c/debounce/#before-and-after

#### The problem

A search field receives 'c', 'ca', and 'cat' at 100 ms intervals. We want to submit only the latest value after 300 ms without another edit. The interval is a choice for this illustration, not a recommended setting for every product.

#### Prompt to paste

Debounce this search input. Replace pending work on each edit and verify an older response cannot overwrite the latest results.

#### Before

Starting an independent timeout on every edit delays each call but retains all of them. The three inputs still cause three submissions.

#### After

Keep one pending timeout and clear it on each edit. The latest value replaces the earlier pending values, so this burst submits only 'cat'. Provide a way to cancel pending work when the field is removed.

#### Run the check

Save the following code as debounce.mjs and run `node --test debounce.mjs` with Node.js 22.12 or later.

```js
import test from 'node:test';
import assert from 'node:assert/strict';

function before(submit, wait) {
  return (value) => {
    setTimeout(() => submit(value), wait);
  };
}

function after(submit, wait) {
  let timer;
  const input = (value) => {
    clearTimeout(timer);
    timer = setTimeout(() => submit(value), wait);
  };
  input.cancel = () => clearTimeout(timer);
  return input;
}

test('a delay still submits every value', (t) => {
  t.mock.timers.enable({ apis: ['setTimeout'] });
  const calls = [];
  const input = before((value) => calls.push(value), 300);
  input('c');
  t.mock.timers.tick(100);
  input('ca');
  t.mock.timers.tick(100);
  input('cat');
  t.mock.timers.tick(300);
  assert.deepEqual(calls, ['c', 'ca', 'cat']);
});

test('debounce submits only after the last quiet interval', (t) => {
  t.mock.timers.enable({ apis: ['setTimeout'] });
  const calls = [];
  const input = after((value) => calls.push(value), 300);
  input('c');
  t.mock.timers.tick(100);
  input('ca');
  t.mock.timers.tick(100);
  input('cat');
  t.mock.timers.tick(299);
  assert.deepEqual(calls, []);
  t.mock.timers.tick(1);
  assert.deepEqual(calls, ['cat']);
  input('cats');
  input.cancel();
  t.mock.timers.tick(300);
  assert.deepEqual(calls, ['cat']);
});
```

#### Expected result

The timer-controlled example records three submissions before and one after, with no submission before the final 300 ms quiet interval. It also checks cancellation of pending work. These counts describe this input sequence only; they are not a production performance benchmark.

#### Limits

Debounce controls when work starts. It cannot stop a request that has already started or stop an older response from arriving last. Use cancellation-aware requests and guard which response may update the UI. Continuous input can postpone trailing-edge work indefinitely. If intermediate updates are necessary, consider a throttle or an explicit maximum wait instead. Clear pending timers on teardown.

#### Sources

- [MDN: Debounce](https://developer.mozilla.org/en-US/docs/Glossary/Debounce): Quiet-interval behavior and the distinction from throttling.
- [MDN: AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController): Aborting supported web requests is a separate mechanism from a debounce timer.
- [Node.js test runner: MockTimers](https://nodejs.org/api/test.html#class-mocktimers): Advancing time deterministically in the downloadable test.

Sources checked: 2026-10-11. These are original illustrative examples with automated checks. Human editorial approval is not recorded. Policy: https://vibe-coding-101.brighteng.org/editorial/


## backpressure

**backpressure** (concurrency). Let consumer capacity constrain how fast producers send work.

- Use when: An event queue grows faster than the application can process it.
- What: Backpressure coordinates production with consumption so pending work does not grow without a deliberate bound.
- Why it matters with an agent: An unbounded queue can look responsive initially while memory and latency keep growing.
- Do: Select a bounded buffer and decide whether producers wait, reject, or drop specified work when it is full.
- Prompt: Add backpressure to this pipeline. Bound queued work, define the full-buffer policy, and test with a deliberately slow consumer.
- Avoid: Dropping events silently when every event is required.
- Described as: queue keeps growing; slow consumer; unbounded buffer; producer faster than consumer; out of memory under load; Backpressure
- Related: streaming, structured-concurrency
- Sources checked: 2026-10-11 (not human editorial approval)
- [Node.js: Backpressuring in streams](https://nodejs.org/learn/modules/backpressuring-in-streams): A producer must respect downstream capacity to avoid unbounded buffering.
- Page: https://vibe-coding-101.brighteng.org/c/backpressure/

## race-condition

**race condition** (concurrency). An outcome depends on the timing of concurrent operations.

- Use when: Two overlapping operations can update the same state.
- What: Two operations overlap, such as a check followed by a write, and the result depends on which finishes first. Each step can be correct on its own while the combination is wrong.
- Why it matters with an agent: A sequential test can miss an unsafe check-then-write sequence.
- Do: Identify the shared invariant and exercise competing operations with controlled ordering.
- Prompt: Reproduce this race with overlapping operations. Protect the shared invariant and verify both completion orders, including a failed operation.
- Avoid: Fixing the visible order while leaving the underlying write unprotected.
- Described as: only happens sometimes; two requests at once; timing bug; check then act; intermittent wrong data; search results arrive out of order; old search results overwrite new ones
- Related: optimistic-lock, cancellation
- Page: https://vibe-coding-101.brighteng.org/c/race-condition/

### race condition: a worked example

Canonical page: https://vibe-coding-101.brighteng.org/c/race-condition/#before-and-after

#### The problem

You search for 'ca', then 'cat'. The cat request finishes first, but the slower ca request arrives afterward. The rule is that only the latest requested search may update the results, even when a query is repeated.

#### Prompt to paste

Reproduce this race with overlapping operations. Protect the shared invariant and verify both completion orders, including a failed operation.

#### Before

Every completion writes to the same display. The network completion order decides what the reader sees, so an obsolete response can overwrite the current result.

#### After

Assign an increasing generation to each requested search. Publish a completion only if its generation is still current. This comparison registers each requested search immediately. In a debounced UI, invalidate the previous generation on each input change, before waiting to send the next request.

#### Run the check

Save the following code as race-condition.mjs and run `node --test race-condition.mjs` with Node.js 22.12 or later.

```js
import test from 'node:test';
import assert from 'node:assert/strict';

function before(publish) {
  return (request) => request.then(publish);
}

function after(publish) {
  let generation = 0;
  return async (request) => {
    const mine = ++generation;
    const result = await request;
    if (mine === generation) publish(result);
  };
}

test('an older completion overwrites current results', async () => {
  const shown = [];
  let finishOld;
  const old = new Promise((resolve) => { finishOld = resolve; });
  const search = before((value) => shown.push(value));
  const first = search(old);
  await search(Promise.resolve('cat'));
  finishOld('ca');
  await first;
  assert.deepEqual(shown, ['cat', 'ca']);
});

test('the current generation wins in both orders, including a failure', async () => {
  for (const oldFirst of [true, false]) {
    const shown = [];
    let finishOld, finishNew;
    const old = new Promise((resolve) => { finishOld = resolve; });
    const latest = new Promise((resolve) => { finishNew = resolve; });
    const search = after((value) => shown.push(value));
    const first = search(old);
    const second = search(latest);
    if (oldFirst) { finishOld('ca'); await first; finishNew('cat'); }
    else { finishNew('cat'); await second; finishOld('ca'); }
    await Promise.all([first, second]);
    assert.deepEqual(shown, ['cat']);
  }
  const shown = [];
  const search = after((value) => shown.push(value));
  let finishOld;
  const first = search(new Promise((resolve) => { finishOld = resolve; }));
  await assert.rejects(search(Promise.reject(new Error('offline'))), /offline/);
  finishOld('obsolete');
  await first;
  assert.deepEqual(shown, []);
});
```

#### Expected result

The unguarded version displays cat and then ca. The guarded version publishes only cat in either completion order. If the latest request fails, an older success still cannot become current; the caller receives the error and must show the current query's error state.

#### Limits

This guard protects one display owner; it does not stop network work, make database writes atomic, or make side effects safe to retry. Handle errors for the current generation and invalidate it when leaving the view. Comparing query strings alone is insufficient when the same query is requested twice. The interactive example compares two already-started requests; connecting this guard to an actual input is a separate integration step.

#### Sources

- [React: Fetching data in Effects](https://react.dev/reference/react/useEffect#fetching-data-with-effects): Documents responses arriving in a different order and ignoring obsolete completions. The generation example here is framework-independent and original.

Sources checked: 2026-10-11. These are original illustrative examples with automated checks. Human editorial approval is not recorded. Policy: https://vibe-coding-101.brighteng.org/editorial/


## event-loop

**event loop** (concurrency). An event loop schedules work and callbacks around the runtime’s execution model.

- Use when: One expensive request freezes unrelated interactions or requests.
- What: Node.js and browsers run JavaScript on one thread that takes tasks from a queue. A long synchronous computation blocks every other task until it finishes, even inside an async function.
- Why it matters with an agent: An async function can still execute blocking CPU work before or between awaits.
- Do: Profile the blocking segment and move or divide it according to the workload.
- Prompt: Find what blocks this event loop. Move appropriate CPU work to bounded workers and verify other requests stay responsive under load.
- Avoid: Replacing synchronous syntax with async syntax while keeping the same blocking computation.
- Described as: microtask; macrotask; Node event loop; server freezes during heavy task; blocking the event loop; CPU heavy work in Node
- Related: thread-pool, async-parallel
- Page: https://vibe-coding-101.brighteng.org/c/event-loop/

## mutex

**mutex** (concurrency). A mutex provides mutually exclusive access to a protected critical section.

- Use when: Concurrent operations must update shared memory without interleaving.
- What: A mutex lets only one thread or task at a time run a protected section of code. An in-process mutex does nothing to coordinate separate processes or servers.
- Why it matters with an agent: A boolean flag does not supply a mutex’s synchronization guarantees.
- Do: Choose the appropriate synchronization primitive and release it on every path.
- Prompt: Protect this shared critical section with the appropriate mutex. Test concurrent access and failure paths without holding the lock during unrelated slow work.
- Avoid: Assuming an in-process mutex coordinates independent servers.
- Described as: lock; only one at a time; critical section; shared counter wrong with threads; synchronized
- Related: race-condition, deadlock
- Page: https://vibe-coding-101.brighteng.org/c/mutex/

## async-parallel

**async vs parallel** (concurrency). Asynchronous work can yield while waiting; parallel work executes simultaneously.

- Use when: I/O waits and CPU work need different execution strategies.
- What: Async code overlaps waiting, such as on network or disk. Parallel code runs computation on several cores at once. CPU-heavy work needs workers or threads, not just async.
- Why it matters with an agent: Adding async syntax cannot make blocking computation stop occupying its executor.
- Do: Classify the workload and choose bounded overlap or worker execution as appropriate.
- Prompt: Separate the I/O-bound and CPU-bound work here. Use bounded concurrency and verify responsiveness and throughput under representative load.
- Avoid: Starting an unbounded task for every item and exhausting a downstream resource.
- Described as: Promise.all too many; async does not make it faster; CPU vs IO bound; limit concurrency; p-limit
- Related: request-waterfall, thread-pool
- Page: https://vibe-coding-101.brighteng.org/c/async-parallel/

## thread-pool

**thread pool** (concurrency). A thread pool reuses worker threads to execute submitted work.

- Use when: Blocking or CPU-heavy work must run without unbounded thread creation.
- What: A fixed set of worker threads takes jobs from a queue, so the app doesn't create a thread per task. Both the worker count and the queue length need limits.
- Why it matters with an agent: A bounded worker count can still hide an unbounded queue.
- Do: Size workers for the workload and dependencies, then define overload behavior.
- Prompt: Use a bounded worker pool for this task. Test queue saturation, cancellation, and shutdown without exceeding the downstream capacity.
- Avoid: Blocking pool workers on tasks that need the same exhausted pool to finish.
- Described as: worker pool; too many threads; limit workers; executor; worker threads
- Related: backpressure, event-loop
- Page: https://vibe-coding-101.brighteng.org/c/thread-pool/

## atomic

**atomic operation** (concurrency). An atomic operation takes effect indivisibly with respect to the relevant observers.

- Use when: Concurrent read-modify-write operations lose updates.
- What: An atomic operation, such as an atomic increment, compare-and-swap, or a single SQL UPDATE, happens all at once, so no other writer can see or change a half-finished state.
- Why it matters with an agent: Two individually safe statements may still expose an unsafe intermediate state.
- Do: Choose the atomic primitive or database operation that protects the complete required update.
- Prompt: Make this update atomic at the shared-state boundary. Test competing writers and verify the invariant across the entire operation.
- Avoid: Assuming atomicity also supplies every required memory-ordering or transaction-isolation guarantee.
- Described as: read modify write; lost update; increment safely; oversell inventory; UPDATE stock = stock - 1
- Related: transaction, mutex
- Page: https://vibe-coding-101.brighteng.org/c/atomic/

## goroutine

**goroutine** (concurrency). A goroutine is a lightweight unit of concurrent execution in Go.

- Use when: Go background work survives its request or becomes stuck on a channel.
- What: Starting a goroutine takes only the go keyword, but something must still stop it, wait for it, and collect its error. Otherwise it leaks or blocks forever on a channel.
- Why it matters with an agent: Starting work is easy while observing its completion and cancellation is easy to omit.
- Do: Define who starts, stops, and waits for the goroutine, including blocked sends and receives.
- Prompt: Tie this goroutine to an explicit lifecycle. Test cancellation while blocked, bounded concurrency, and delivery of its result or error.
- Avoid: Checking cancellation only after a channel operation that can block forever.
- Described as: Go channel; goroutine leak; context cancellation Go; errgroup; goroutine count keeps growing
- Related: cancellation, backpressure
- Page: https://vibe-coding-101.brighteng.org/c/goroutine/

## quorum

**quorum** (concurrency). Require a defined set of replicas or voters before accepting an operation.

- Use when: An operation must continue after some nodes fail without accepting conflicting decisions.
- What: A quorum is a sufficient voting or acknowledgement set under a protocol. Read/write quorum intersection can make reads contact an updated replica, but version selection, concurrency, membership, and repair still determine correctness.
- Why it matters with an agent: An agent can treat R + W > N as a complete proof of linearizable reads.
- Do: State membership, read/write counts, version rules, and failure assumptions. Check quorum loss and overlapping operations; distinguish acknowledgement counts from consensus.
- Prompt: Specify this quorum protocol’s membership and read/write rules. Test concurrent writes and loss of quorum.
- Avoid: A majority is common, but not every quorum is a majority and intersection alone is not consensus.
- Described as: read quorum; write quorum; R W N; An operation must continue after some nodes fail without accepting conflicting decisions; Quorum
- Related: consensus, strong-consistency, eventual-consistency
- Sources checked: 2026-10-11 (not human editorial approval)
- [DeCandia et al.: Dynamo](https://www.allthingsdistributed.com/files/amazon-dynamo-sosp2007.pdf): Consistent hashing, virtual nodes, replica quorums, version reconciliation, and eventual consistency.
- [Ongaro and Ousterhout: Raft](https://raft.github.io/raft.pdf): Replicated-log consensus, majority voting, safe membership changes, and timing requirements for progress.
- Page: https://vibe-coding-101.brighteng.org/c/quorum/

## consensus

**consensus** (concurrency). Make participating nodes agree on decisions despite specified failures.

- Use when: Nodes must agree on a leader or committed log instead of inventing competing histories.
- What: Consensus protocols establish agreement under a stated failure model. Raft manages a replicated log with elections and majority rules; progress needs enough reachable nodes and suitable communication timing.
- Why it matters with an agent: An agent can mistake broadcasting a value or counting responses for a safe consensus protocol.
- Do: Use a proven implementation. Define crash versus Byzantine assumptions, membership changes, and commit rules. Check leader loss, partitions, and rejoining nodes.
- Prompt: Use the platform’s consensus mechanism. Explain its commit rule and verify behavior on leader loss and quorum loss.
- Avoid: Safety and progress are different properties. A safe system can stop accepting writes when it cannot decide.
- Described as: Raft; Paxos; distributed consensus; Nodes must agree on a leader or committed log instead of inventing competing histories; Consensus
- Related: quorum, split-brain, leader-follower-replication, cap-theorem
- Sources checked: 2026-10-11 (not human editorial approval)
- [Ongaro and Ousterhout: Raft](https://raft.github.io/raft.pdf): Replicated-log consensus, majority voting, safe membership changes, and timing requirements for progress.
- Page: https://vibe-coding-101.brighteng.org/c/consensus/

## cap-theorem

**CAP theorem** (concurrency). During a network partition, atomic consistency and availability cannot both be guaranteed.

- Use when: You must decide what isolated replicas do when they cannot communicate.
- What: CAP concerns atomic consistency, usually described as linearizability, and availability of every request to a non-failing node in a partitionable asynchronous system. It describes a failure-time constraint, rather than a menu of three independent features.
- Why it matters with an agent: An agent can label a database AP or CP without specifying the operation or partition behavior.
- Do: Describe one partitioned read/write scenario. Choose whether to reject or delay an operation or allow potentially divergent results. Test that policy.
- Prompt: Apply CAP to this partition scenario. State which operations stop and which consistency guarantees remain.
- Avoid: CAP availability differs from a monthly uptime percentage. ACID consistency means something else again.
- Described as: CAP; consistency availability partition tolerance; You must decide what isolated replicas do when they cannot communicate; CAP theorem
- Related: strong-consistency, eventual-consistency, high-availability, acid
- Sources checked: 2026-10-11 (not human editorial approval)
- [Gilbert and Lynch: Brewer’s conjecture](https://groups.csail.mit.edu/tds/papers/Gilbert/Brewer2.pdf): Impossibility of providing atomic consistency and availability under partitions in the asynchronous model.
- Page: https://vibe-coding-101.brighteng.org/c/cap-theorem/

## snapshot-isolation

**snapshot isolation** (concurrency). Read a stable transaction snapshot while detecting conflicting writes.

- Use when: A multi-query report mixes values from different committed moments.
- What: Snapshot isolation reads from a transaction snapshot and prevents certain concurrent write conflicts. It can still permit write skew when transactions update different rows after reading the same invariant.
- Why it matters with an agent: An agent can call a stable snapshot serializable and miss a cross-row constraint violation.
- Do: Check the database’s snapshot boundary and conflict behavior. Test a stable report and a two-writer invariant. Use serializable execution or explicit coordination when required.
- Prompt: Use snapshot isolation for this report. Verify a stable snapshot and demonstrate whether write skew remains possible.
- Avoid: Isolation names vary by product. PostgreSQL Repeatable Read uses snapshot isolation, with stronger phantom protection than the SQL minimum.
- Described as: transaction snapshot; snapshot isolation level; A multi-query report mixes values from different committed moments; Snapshot isolation
- Related: mvcc, read-skew, write-skew, isolation
- Sources checked: 2026-10-11 (not human editorial approval)
- [Berenson et al.: A Critique of ANSI SQL Isolation Levels](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-95-51.pdf): Definitions of read skew and write skew, and the distinction between snapshot isolation and serializability.
- [PostgreSQL: Transaction isolation](https://www.postgresql.org/docs/current/transaction-iso.html): Isolation-level behavior in PostgreSQL; snapshot isolation can still allow serialization anomalies.
- Page: https://vibe-coding-101.brighteng.org/c/snapshot-isolation/

## mvcc

**MVCC** (concurrency). Keep multiple row versions so reads can use a consistent snapshot.

- Use when: Readers and writers need concurrency without ordinary reads waiting on every write.
- What: Multi-Version Concurrency Control retains versions and uses visibility rules to select what a transaction sees. The chosen isolation level still determines snapshot scope and permitted anomalies.
- Why it matters with an agent: An agent can assume versioned storage eliminates locks or makes all transactions serializable.
- Do: Document snapshot visibility and version cleanup. Check concurrent reads and writes, long-running transactions, and retained-version growth.
- Prompt: Explain this database’s MVCC visibility and cleanup. Check concurrent updates and long-lived snapshots.
- Avoid: Explicit locks still exist; old snapshots can delay cleanup and increase storage use.
- Described as: Multi-Version Concurrency Control; multi version concurrency control; Readers and writers need concurrency without ordinary reads waiting on every write; MVCC (Multi-Version Concurrency Control)
- Related: snapshot-isolation, isolation, pessimistic-locking, storage-compaction
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Concurrency control](https://www.postgresql.org/docs/current/mvcc-intro.html): MVCC uses data versions and snapshots; ordinary reads and writes generally do not block each other.
- [PostgreSQL: Transaction isolation](https://www.postgresql.org/docs/current/transaction-iso.html): Isolation-level behavior in PostgreSQL; snapshot isolation can still allow serialization anomalies.
- [PostgreSQL: Routine vacuuming](https://www.postgresql.org/docs/current/routine-vacuuming.html): Old row versions require cleanup, and long-running transactions can prevent vacuum from removing versions they may still need.
- Page: https://vibe-coding-101.brighteng.org/c/mvcc/

## two-phase-commit

**two-phase commit (2PC)** (concurrency). Coordinate prepare and commit decisions across transaction participants.

- Use when: One transaction must commit or abort across multiple supporting resource managers.
- What: In 2PC, participants first prepare, then resolve the coordinator’s commit or abort decision. A prepared participant has promised it can commit and may retain locks while the outcome is unknown.
- Why it matters with an agent: An agent can treat two sequential API calls as an atomic distributed transaction.
- Do: Verify native participant support and a durable coordinator. Check crash recovery with a prepared participant and confirm unresolved transactions are monitored and resolved.
- Prompt: Evaluate native 2PC support here. Test coordinator failure after prepare and document recovery of in-doubt transactions.
- Avoid: A coordinator failure can leave participants blocked. Arbitrary HTTP services are not automatically 2PC participants.
- Described as: 2PC; two phase commit; distributed atomic commit; One transaction must commit or abort across multiple supporting resource managers; Two-phase commit (2PC)
- Related: transaction, three-phase-commit, saga, outbox
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: PREPARE TRANSACTION](https://www.postgresql.org/docs/current/sql-prepare-transaction.html): Durable prepared transactions for external coordinators retain locks until resolved.
- [Bernstein, Hadzilacos and Goodman: Distributed Recovery](https://www.cs.cornell.edu/courses/cs5414/2017fa/papers/AtomicCommit.pdf): Section 7.5 derives three-phase commit under failure assumptions and discusses blocking with partitions.
- Page: https://vibe-coding-101.brighteng.org/c/two-phase-commit/

## three-phase-commit

**three-phase commit (3PC)** (concurrency). Add a pre-commit phase to reduce blocking under restricted failure assumptions.

- Use when: You are comparing atomic commit protocols and their failure models.
- What: Classic 3PC separates voting, pre-commit, and commit so surviving participants can resolve some coordinator failures. Its nonblocking argument relies on timing and failure assumptions; arbitrary network partitions require different treatment.
- Why it matters with an agent: An agent can recommend an extra message round as a universal cure for 2PC blocking.
- Do: Compare protocol states and assumptions using the cited recovery model. Analyze coordinator failure and a partition separately before selecting a supported implementation.
- Prompt: Compare 3PC with 2PC for this failure model. Explain pre-commit and where the nonblocking assumptions fail.
- Avoid: Classic 3PC does not make arbitrary partitions safe simply by adding timeouts. It is not a substitute for proven consensus-based coordination.
- Described as: 3PC; three phase commit; pre-commit phase; You are comparing atomic commit protocols and their failure models; Three-phase commit (3PC)
- Related: two-phase-commit, consensus, cap-theorem
- Sources checked: 2026-10-11 (not human editorial approval)
- [Bernstein, Hadzilacos and Goodman: Distributed Recovery](https://www.cs.cornell.edu/courses/cs5414/2017fa/papers/AtomicCommit.pdf): Section 7.5 derives three-phase commit under failure assumptions and discusses blocking with partitions.
- Page: https://vibe-coding-101.brighteng.org/c/three-phase-commit/

## lock-escalation

**lock escalation** (concurrency). Replace many fine-grained locks with a coarser lock in engines that support it.

- Use when: A large SQL Server update unexpectedly blocks unrelated rows in the same table.
- What: Lock escalation changes many row or page locks into a coarser lock to reduce lock-management overhead. SQL Server may escalate to a table lock based on lock counts and memory pressure; this is engine-specific.
- Why it matters with an agent: An agent can attribute any table lock to escalation or disable it without considering lock memory.
- Do: Capture the lock-escalation event and blocking chain. Reduce the scan or batch size where appropriate, then verify lock footprint and transaction semantics.
- Prompt: Confirm SQL Server lock escalation with events. Reduce the lock footprint and verify blocking and transaction correctness.
- Avoid: A table lock can have other causes. Batching changes atomicity; do not split an all-or-nothing operation casually.
- Described as: lock promotion; table lock escalation; A large SQL Server update unexpectedly blocks unrelated rows in the same table; Lock escalation
- Related: deadlock, pessimistic-locking, transaction
- Sources checked: 2026-10-11 (not human editorial approval)
- [Microsoft: Lock escalation](https://learn.microsoft.com/en-us/troubleshoot/sql/database-engine/performance/resolve-blocking-problems-caused-lock-escalation): SQL Server can escalate fine-grained locks to a table lock based on thresholds and memory pressure.
- Page: https://vibe-coding-101.brighteng.org/c/lock-escalation/

## pessimistic-locking

**pessimistic locking** (concurrency). Lock the protected rows before making a competing update.

- Use when: Several workers try to claim the same job or modify the same inventory row.
- What: Pessimistic concurrency uses locks to prevent conflicting operations while a transaction makes its decision. In PostgreSQL, SELECT FOR UPDATE locks selected rows until the transaction ends.
- Why it matters with an agent: An agent can read a value, release the transaction, and then perform the supposedly protected write.
- Do: Keep read, decision, and write inside one transaction. Lock the necessary rows in consistent order. Test two competing sessions and lock timeouts.
- Prompt: Use pessimistic row locking for this update. Keep the decision in one transaction and test two concurrent writers.
- Avoid: Locking existing rows does not automatically protect every predicate or a missing row; constraints or stronger isolation may be needed.
- Described as: pessimistic lock; SELECT FOR UPDATE; row locking; Several workers try to claim the same job or modify the same inventory row; Pessimistic locking
- Related: optimistic-lock, deadlock, isolation, write-skew
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Explicit locking](https://www.postgresql.org/docs/current/explicit-locking.html): Row and table locks, blocking, deadlocks, and consistent acquisition order.
- Page: https://vibe-coding-101.brighteng.org/c/pessimistic-locking/

## dirty-read

**dirty read** (concurrency). Read a value another transaction has written but not committed.

- Use when: A report might include an update that is later rolled back.
- What: A dirty read exposes uncommitted data from another transaction. Whether it is possible depends on the engine and isolation configuration; PostgreSQL treats Read Uncommitted as Read Committed and prevents it.
- Why it matters with an agent: An agent can lower isolation for speed without checking whether transient values become user-visible.
- Do: Use two sessions: pause an uncommitted update, read from the other session, then roll back. Verify the behavior under the actual engine and isolation level.
- Prompt: Test whether this isolation level allows a dirty read using an uncommitted update followed by rollback.
- Avoid: Dirty reads differ from stale committed reads on a replica and from read skew across separate committed moments.
- Described as: uncommitted read; dirty reads; A report might include an update that is later rolled back; Dirty read
- Related: isolation, read-skew, read-replica
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Transaction isolation](https://www.postgresql.org/docs/current/transaction-iso.html): Isolation-level behavior in PostgreSQL; snapshot isolation can still allow serialization anomalies.
- Page: https://vibe-coding-101.brighteng.org/c/dirty-read/

## phantom-read

**phantom read** (concurrency). Repeat a predicate query and observe a changed set of matching rows.

- Use when: Two counts inside one transaction disagree after another transaction inserts a matching row.
- What: A phantom involves the result set of a repeated predicate query changing because another transaction commits a relevant change. Protection differs by isolation implementation; PostgreSQL Repeatable Read prevents phantoms.
- Why it matters with an agent: An agent can lock the current rows and assume no new matching row can appear.
- Do: Coordinate two sessions around the predicate read and competing insert. Check the chosen isolation level, then protect the invariant with constraints or appropriate transaction coordination.
- Prompt: Test this predicate for phantom reads with two sessions. Protect the invariant using the database’s actual isolation behavior.
- Avoid: An empty result locks no ordinary rows. Preventing phantoms alone does not establish serializability.
- Described as: phantom reads; predicate query anomaly; Two counts inside one transaction disagree after another transaction inserts a matching row; Phantom read
- Related: snapshot-isolation, pessimistic-locking, write-skew
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Transaction isolation](https://www.postgresql.org/docs/current/transaction-iso.html): Isolation-level behavior in PostgreSQL; snapshot isolation can still allow serialization anomalies.
- Page: https://vibe-coding-101.brighteng.org/c/phantom-read/

## read-skew

**read skew** (concurrency). Read related facts from different committed moments and combine an inconsistent view.

- Use when: A report reads an account before a transfer and the other account after it.
- What: Read skew mixes related values that were individually committed but do not form one coherent snapshot. For example, separate reads can double-count or miss a transfer between accounts.
- Why it matters with an agent: An agent can use a transaction while its isolation level still takes a fresh snapshot for each statement.
- Do: Interleave a transfer between the report’s two reads. Use a suitable transaction snapshot or one consistent query, then verify the reported invariant.
- Prompt: Reproduce read skew across these reads. Use a consistent snapshot and verify the combined total during a transfer.
- Avoid: Read skew does not require a dirty read. Stable reads still do not prevent write skew in other transactions.
- Described as: read skew anomaly; inconsistent analysis; A report reads an account before a transfer and the other account after it; Read skew
- Related: snapshot-isolation, dirty-read, write-skew
- Sources checked: 2026-10-11 (not human editorial approval)
- [Berenson et al.: A Critique of ANSI SQL Isolation Levels](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-95-51.pdf): Definitions of read skew and write skew, and the distinction between snapshot isolation and serializability.
- [PostgreSQL: Transaction isolation](https://www.postgresql.org/docs/current/transaction-iso.html): Isolation-level behavior in PostgreSQL; snapshot isolation can still allow serialization anomalies.
- Page: https://vibe-coding-101.brighteng.org/c/read-skew/

## write-skew

**write skew** (concurrency). Concurrent decisions update different rows and jointly violate an invariant.

- Use when: Two on-call doctors each see the other available and both go off duty.
- What: Write skew occurs when transactions read a shared condition and write different records so that their combined result violates the condition. Snapshot isolation can allow it even without a same-row write conflict.
- Why it matters with an agent: An agent can add row-version checks to separate rows and still leave the cross-row rule unprotected.
- Do: Synchronize two decisions in a test. Use serializable execution with retries, a suitable constraint, or a shared lock boundary. Verify the invariant survives both attempted changes.
- Prompt: Reproduce write skew for this cross-row invariant. Protect it and test two concurrent decisions, including required retries.
- Avoid: No lost update on a single row does not mean the transaction set is serializable.
- Described as: write skew anomaly; cross-row invariant; Two on-call doctors each see the other available and both go off duty; Write skew
- Related: snapshot-isolation, pessimistic-locking, optimistic-lock, isolation
- Sources checked: 2026-10-11 (not human editorial approval)
- [Berenson et al.: A Critique of ANSI SQL Isolation Levels](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/tr-95-51.pdf): Definitions of read skew and write skew, and the distinction between snapshot isolation and serializability.
- [PostgreSQL: Transaction isolation](https://www.postgresql.org/docs/current/transaction-iso.html): Isolation-level behavior in PostgreSQL; snapshot isolation can still allow serialization anomalies.
- Page: https://vibe-coding-101.brighteng.org/c/write-skew/

## throttling

**throttling** (concurrency). Bound how often work runs while events continue arriving.

- Use when: Continuous scroll events trigger expensive work faster than the UI needs it.
- What: Throttling caps an execution rate. In event handlers, it can keep periodic updates flowing while debounce waits for a quiet period. API providers also use throttling to describe quota enforcement, so specify the behavior.
- Why it matters with an agent: An agent can replace a throttle with debounce and make feedback disappear during continuous input.
- Do: Choose leading and trailing behavior and a maximum rate. Check continuous events, the final value, and teardown using a controlled clock.
- Prompt: Throttle this handler at the required rate. Specify leading/trailing behavior and test continuous input and teardown.
- Avoid: A client-side throttle does not enforce a server quota. Dropping intermediate work is unsafe when every event must be processed.
- Described as: throttle; throttle vs debounce; execution rate; Continuous scroll events trigger expensive work faster than the UI needs it; Throttling
- Related: debounce, rate-limit, backpressure
- Sources checked: 2026-10-11 (not human editorial approval)
- [MDN: Throttle](https://developer.mozilla.org/en-US/docs/Glossary/Throttle): Throttling bounds invocation rate during continuous events; debouncing waits for a pause.
- Page: https://vibe-coding-101.brighteng.org/c/throttling/

## offline-first

**offline-first** (native apps). Design a useful local workflow that tolerates missing connectivity.

- Use when: Users need to keep reading or editing while disconnected.
- What: The app reads and writes local data first and syncs with the server when it can, so it stays usable offline. Pending changes, conflicts, and server rejections each need a defined outcome.
- Why it matters with an agent: Caching the last response alone does not preserve offline edits.
- Do: Persist local intent, show pending state, and reconcile with the authoritative service when available.
- Prompt: Make this draft workflow work offline. Test restart before sync, reconnection, conflicting edits, and a rejected server write without losing user input.
- Avoid: Calling local data universally authoritative when the server must still enforce access or business rules.
- Described as: works without internet; app crashes when offline; sync when back online; offline mode; local first
- Related: conflict, idempotency
- Page: https://vibe-coding-101.brighteng.org/c/offline-first/

## deep-link

**deep link** (native apps). A deep link addresses a particular location or action in an application.

- Use when: A shared link should open a specific record or screen.
- What: A URL that opens a specific screen or record in the app. It has to work when the app is already running and when the link launches it, and survive a sign-in in between.
- Why it matters with an agent: A handler tested only while the app is running may drop the cold-start target.
- Do: Parse and validate the target, preserve it across sign-in, and test app lifecycle states.
- Prompt: Implement this deep link. Verify cold start, an already-running app, required sign-in, and an invalid or unauthorized target.
- Avoid: Using a link’s parameters as trusted commands or access permission.
- Described as: protocol handler; link opens app home screen; open specific screen from link; custom URL scheme; link not working on cold start
- Related: app-link, authn-authz
- Page: https://vibe-coding-101.brighteng.org/c/deep-link/

## safe-area

**safe area** (native apps). Safe-area insets describe regions where important content can remain unobscured by system UI or display features.

- Use when: Controls overlap the home indicator, cutout, or system bars.
- What: The system reports insets for the notch, status bar, and home indicator. Content is padded by those insets, once, at the right container.
- Why it matters with an agent: Hardcoded padding can fail with orientation, window size, or device changes.
- Do: Use the platform’s current inset information at the appropriate layout boundary.
- Prompt: Respect safe-area insets for these controls. Test rotation, system bars, and changing window sizes without applying the same inset twice.
- Avoid: Padding every nested container and creating unnecessary empty space.
- Described as: notch; home indicator overlap; content under status bar; SafeAreaView; env(safe-area-inset-bottom)
- Related: adaptive-layout, dynamic-type
- Page: https://vibe-coding-101.brighteng.org/c/safe-area/

## navigation-stack

**navigation stack** (native apps). A navigation stack records a sequence of destinations.

- Use when: A multi-screen workflow loses its place when navigating back.
- What: Screens are pushed onto a stack as the user moves forward, and back pops them off. Each tab can keep its own stack.
- Why it matters with an agent: Boolean screen switches can omit route identity, history, and restoration.
- Do: Model destinations and state ownership explicitly, including tab and modal boundaries.
- Prompt: Use the platform navigation stack for this workflow. Verify back navigation, per-tab history, and a deep link into a nested destination.
- Avoid: Resetting navigation state on an unrelated view update.
- Described as: back button goes to wrong screen; lose place when switching tabs; React Navigation stack; NavigationStack SwiftUI
- Related: deep-link, app-lifecycle
- Page: https://vibe-coding-101.brighteng.org/c/navigation-stack/

## push-notification

**push notification** (native apps). A push notification delivers an external event through a platform notification service.

- Use when: An app must notify users when it is not actively displaying the relevant screen.
- What: Your server sends a message through Apple's or Google's push service to a device token. Tokens change, users can revoke permission, and tapping the notification must open the right screen.
- Why it matters with an agent: A visible notification test may miss token renewal or cold-start routing.
- Do: Handle token changes, permission states, and payload validation; test notification entry paths.
- Prompt: Implement this notification flow. Test permission denial, token replacement, multiple devices, and opening the target from a cold start.
- Avoid: Treating one device token as a permanent user identifier.
- Described as: notify users when app closed; APNs; FCM; notification tap opens wrong screen; device token
- Related: deep-link, os-permission
- Page: https://vibe-coding-101.brighteng.org/c/push-notification/

## app-lifecycle

**app lifecycle** (native apps). Applications move between active, inactive, background, and terminated states according to their platform.

- Use when: Returning to an app loses a draft or leaves stale work running.
- What: The operating system moves an app between foreground, background, suspended, and terminated without asking. Anything important is saved early, because there may be no warning before termination.
- Why it matters with an agent: An in-memory timer or callback may never run after suspension or termination.
- Do: Persist important intent promptly and define resume reconciliation without resetting unrelated UI state.
- Prompt: Handle lifecycle changes for this draft. Test backgrounding, process termination, and resume while preserving the edit and reconciling stale requests.
- Avoid: Depending on a final shutdown callback to save the only copy of user data.
- Described as: app loses data when backgrounded; state lost after switching apps; app killed in background; resume from background
- Related: background-execution, autosave
- Page: https://vibe-coding-101.brighteng.org/c/app-lifecycle/

## os-permission

**OS permission** (native apps). Operating-system permissions mediate access to protected capabilities.

- Use when: A feature needs camera, location, files, or another protected resource.
- What: Camera, location, photos, and notifications each have permission states: not asked, granted, denied, or restricted, and the user can change them in Settings at any time.
- Why it matters with an agent: A generated flow may assume that requesting permission guarantees access.
- Do: Ask in context, explain the feature need, and provide usable denied and restricted states.
- Prompt: Implement the permission flow for this action. Test granted, denied, restricted, and changed-in-settings states on the target platform.
- Avoid: Looping the request when the OS will no longer show another prompt.
- Described as: background location; camera permission denied; permission prompt not showing again; location access; ask for permission
- Related: app-lifecycle, least-privilege
- Page: https://vibe-coding-101.brighteng.org/c/os-permission/

## ota-update

**OTA update** (native apps). An over-the-air update replaces supported application assets or code without a full binary install.

- Use when: A deployed mobile app needs a compatible code or asset update.
- What: OTA updates ship new JavaScript and assets to an installed app without an app store release. Changes that need new native code still need a full store release.
- Why it matters with an agent: A JavaScript change can still require native capabilities absent from the installed binary.
- Do: Identify compatible runtimes and use a staged update with a recovery path.
- Prompt: Prepare this OTA update for its compatible runtime. Verify a preview installation, a rejected incompatible runtime, and recovery to the previous update.
- Avoid: Treating every source change as eligible for an OTA release.
- Described as: over-the-air; Expo updates; CodePush; update app without app store; hotfix mobile app
- Related: build-variant, rollback
- Page: https://vibe-coding-101.brighteng.org/c/ota-update/

## main-process

**main process vs renderer** (native apps). Desktop shells such as Electron separate privileged application work from the renderer.

- Use when: A desktop UI needs filesystem or operating-system access.
- What: Electron's main process has Node and operating-system access. Renderer processes show web pages and should ask the main process for privileged work through narrow messages.
- Why it matters with an agent: Importing privileged APIs into page code widens the impact of a renderer compromise.
- Do: Keep privileged operations behind narrow validated messages and trusted process boundaries.
- Prompt: Keep this privileged operation in the desktop main process. Expose a narrow IPC method and test rejection of invalid or unauthorized arguments.
- Avoid: Exposing the entire filesystem or shell API through a convenience bridge.
- Described as: Electron main; Tauri core; nodeIntegration; read files from Electron page; renderer process
- Related: ipc, context-isolation
- Page: https://vibe-coding-101.brighteng.org/c/main-process/

## ipc

**IPC** (native apps). Inter-process communication exchanges data or requests between processes.

- Use when: A renderer or worker must request work from another process.
- What: Processes cannot share memory, so they send messages. Each message type is a contract: the receiver checks who sent it and validates its arguments.
- Why it matters with an agent: A generic run-command channel can turn a small feature into unrestricted control.
- Do: Expose specific operations, validate inputs at the receiving side, and preserve structured errors.
- Prompt: Define a narrow IPC contract for this action. Validate the sender and arguments, then test malformed messages and out-of-scope requests.
- Avoid: Assuming messages are trusted because both processes are part of the same application.
- Described as: inter-process communication; contextBridge; ipcRenderer; send message between processes
- Related: dto, least-privilege
- Page: https://vibe-coding-101.brighteng.org/c/ipc/

## context-isolation

**context isolation** (native apps). Electron context isolation separates the page’s JavaScript environment from privileged preload code.

- Use when: An Electron renderer needs a small amount of privileged integration.
- What: Electron runs the page's JavaScript and the preload script in separate contexts. The page only sees the functions the preload exposes through contextBridge.
- Why it matters with an agent: A broad preload bridge can bypass the isolation that the configuration enables.
- Do: Keep isolation enabled and expose only specific validated operations through the supported bridge.
- Prompt: Verify context isolation for this Electron window. Keep Node access out of page code and test the limited bridge with untrusted arguments.
- Avoid: Assuming context isolation alone supplies every sandbox or authorization property.
- Described as: nodeIntegration off; contextBridge; Electron security warning; preload script
- Related: ipc, webview
- Page: https://vibe-coding-101.brighteng.org/c/context-isolation/

## single-instance

**single instance** (native apps). Single-instance behavior routes subsequent launches to an existing application instance.

- Use when: Launching an app twice starts competing windows or local services.
- What: The second launch of the app hands its arguments, such as a file to open or a link, to the window already running, then exits.
- Why it matters with an agent: A second process can lose the user’s requested file while handing off control.
- Do: Acquire the instance boundary early and handle subsequent activation messages explicitly.
- Prompt: Enforce this app’s single-instance behavior. Test simultaneous launches and forwarding a file or deep link to the existing instance.
- Avoid: Focusing the old window but discarding the new launch payload.
- Described as: single instance lock; app opens twice; second window launches; open file in existing window
- Related: deep-link, ipc
- Page: https://vibe-coding-101.brighteng.org/c/single-instance/

## code-signing

**code signing** (native apps). Code signing binds an artifact to a signing identity and detects covered modifications.

- Use when: A native release must establish its publisher and artifact integrity.
- What: The release is signed with your developer certificate, and on macOS notarized by Apple, so the operating system can verify who published it and that it hasn't changed.
- Why it matters with an agent: A successful build does not prove that the distributed package passes platform checks.
- Do: Use the target platform’s release signing workflow and verify the final packaged artifact on that platform.
- Prompt: Sign this release through the supported platform workflow. Verify the distributed artifact, nested executable components, and required platform validation steps.
- Avoid: Checking a locally signed build while distributing a different unsigned package.
- Described as: notarization; Gatekeeper; Authenticode; app is damaged warning; unidentified developer; SmartScreen
- Related: desktop-update, verification
- Page: https://vibe-coding-101.brighteng.org/c/code-signing/

## desktop-update

**desktop auto-update** (native apps). Desktop auto-update retrieves and installs a new application release through a defined trust and lifecycle process.

- Use when: A shipped desktop app must update safely on user machines.
- What: The app checks a release feed, downloads the new version, verifies its signature, and installs it at a safe moment, with a way back if the update fails.
- Why it matters with an agent: Downloading the correct URL does not prove the downloaded artifact is trusted.
- Do: Use the framework’s supported updater and verify authenticity, failure handling, and user-data compatibility.
- Prompt: Implement this desktop update with the supported updater. Test authenticity checks, interrupted download, installation timing, and recovery without losing user data.
- Avoid: Letting untrusted renderer content choose the update source.
- Described as: Sparkle; Squirrel; electron-updater; auto update desktop app; users on old version
- Related: code-signing, schema-evolution
- Page: https://vibe-coding-101.brighteng.org/c/desktop-update/

## app-sandbox

**app sandbox** (native apps). An application sandbox restricts access to system resources.

- Use when: A native app needs protected resources without unrestricted system access.
- What: The app runs with only the capabilities its entitlements grant, and reaches user files only through the system's file picker or saved bookmarks.
- Why it matters with an agent: Disabling the sandbox can conceal missing entitlement or access-grant handling.
- Do: Identify the smallest required access and test real signed builds with allowed and denied operations.
- Prompt: Keep this application sandboxed while enabling its required file workflow. Verify user-granted access, relaunch behavior, and denial outside the granted scope.
- Avoid: Assuming a remembered path always retains the operating system’s access grant.
- Described as: entitlements; App Sandbox; security-scoped bookmark; sandbox blocks file access
- Related: os-permission, secure-storage
- Page: https://vibe-coding-101.brighteng.org/c/app-sandbox/

## webview

**webview** (native apps). A WebView embeds web content in a native application.

- Use when: A native app displays remote content alongside privileged local features.
- What: An embedded browser view inside a native app. Remote pages and your own trusted pages need different permissions, and any bridge to native code has to check where messages come from.
- Why it matters with an agent: A shared bridge can expose local capabilities to an untrusted page.
- Do: Separate trusted application content from remote content and validate navigation and message origins.
- Prompt: Constrain this WebView to its intended content and bridge. Test unexpected navigation and messages from untrusted origins.
- Avoid: Disabling web security to fix a request without understanding the boundary removed.
- Described as: WKWebView; WebView2; react-native-webview; JavaScript bridge native
- Related: ipc, context-isolation
- Page: https://vibe-coding-101.brighteng.org/c/webview/

## secure-storage

**secure storage** (native apps). Use the platform’s protected storage for suitable credentials or keys.

- Use when: An application must retain a credential between launches.
- What: Keychain on Apple platforms and Keystore on Android store small secrets such as tokens encrypted, tied to the device, with rules for backup and lock state.
- Why it matters with an agent: A convenience preferences store may expose the credential more widely than intended.
- Do: Choose the protected storage API and lifecycle policy, then test access and deletion.
- Prompt: Store this credential in the platform’s protected storage. Verify relaunch, logout deletion, and the intended device-lock or backup behavior.
- Avoid: Keeping a second plaintext copy in preferences, diagnostics, or a migration file.
- Described as: Keychain; Keystore; AsyncStorage token; store token on phone; expo-secure-store
- Related: env-secrets, biometric
- Page: https://vibe-coding-101.brighteng.org/c/secure-storage/

## app-link

**app link** (native apps). A verified app link associates an HTTPS domain with an application through platform verification.

- Use when: Shared web URLs should open an installed app when the platform permits.
- What: A file hosted on your domain proves you own it, so the operating system opens matching https links directly in your app, and falls back to the website when the app isn't installed.
- Why it matters with an agent: A custom URL scheme does not establish the same domain association.
- Do: Configure the association and test platform verification, installed and uninstalled behavior, and cold start.
- Prompt: Implement verified app links for these paths. Check domain association, cold-start routing, and the fallback when the app is unavailable.
- Avoid: Testing only an in-app URL handler while the OS association file is unreachable.
- Described as: universal link; Android App Link; apple-app-site-association; open website link in app
- Related: deep-link, authn-authz
- Page: https://vibe-coding-101.brighteng.org/c/app-link/

## background-execution

**background execution** (native apps). Background execution uses the operating system’s supported scheduling or execution model.

- Use when: Work needs to resume or complete despite application suspension.
- What: Apps can't run freely in the background. The operating system offers specific mechanisms, such as background tasks, uploads, and foreground services, with time limits and no guaranteed start time.
- Why it matters with an agent: A timer can stop running as soon as the process loses foreground privileges.
- Do: Choose the platform mechanism and checkpoint work so it tolerates interruption.
- Prompt: Use the supported background mechanism for this operation. Test expiration, termination, and resumption without duplicate effects or lost progress.
- Avoid: Assuming a background scheduling request guarantees an exact start time.
- Described as: BGTask; foreground service; background upload stops; WorkManager; run task when app closed
- Related: app-lifecycle, idempotency
- Page: https://vibe-coding-101.brighteng.org/c/background-execution/

## adaptive-layout

**adaptive layout** (native apps). An adaptive layout responds to available space and presentation context.

- Use when: A phone layout becomes unusable in a tablet pane or resized window.
- What: The screen's structure changes with the available width, for example one column on a phone and side-by-side panes on a tablet or wide window, without losing navigation state.
- Why it matters with an agent: Device-name checks can miss split-screen and resizable contexts.
- Do: Use current layout constraints and test transitions between narrow and wide presentations.
- Prompt: Adapt this screen to changing available width. Verify resizing, rotation, and large text without losing navigation or the current draft.
- Avoid: Measuring size once at launch and treating it as permanent.
- Described as: size class; window size class; iPad layout; tablet layout; split screen
- Related: container-query, safe-area
- Page: https://vibe-coding-101.brighteng.org/c/adaptive-layout/

## in-app-purchase

**in-app purchase** (native apps). In-app purchases exchange a store transaction for a defined entitlement.

- Use when: An application unlocks paid content or a subscription.
- What: The store processes payment, and your app verifies the transaction with the store, ideally on a server, then grants an entitlement that also handles restore, renewal, expiry, and refunds.
- Why it matters with an agent: A successful client callback can be mistaken for durable entitlement state.
- Do: Follow the store’s supported verification path and handle restore, renewal, expiry, and revocation.
- Prompt: Implement this purchase entitlement using the store’s supported verification. Test purchase, restore, expiry, and revocation with the store’s test environment.
- Avoid: Granting permanent access from an unverified local premium flag.
- Described as: StoreKit; Play Billing; RevenueCat; subscription unlock; receipt validation
- Related: idempotency, secure-storage
- Page: https://vibe-coding-101.brighteng.org/c/in-app-purchase/

## build-variant

**build variant** (native apps). A build variant selects a deliberate combination of configuration and packaging.

- Use when: Testing must use different services or identity without changing the production app.
- What: Separate build configurations, such as dev, staging, and release, each with its own bundle id, app name, API endpoint, and signing, so they install side by side and dev settings never ship.
- Why it matters with an agent: Runtime switches can leave development endpoints or secrets in a release artifact.
- Do: Define variant-specific identity, configuration, and signing, then inspect the produced artifacts.
- Prompt: Create a development build variant with its own identity and backend. Verify side-by-side installation and that the release artifact excludes development configuration.
- Avoid: Assuming different display names alone create separate installed applications.
- Described as: scheme; product flavor; bundle id; dev and prod app side by side; app.config environments
- Related: env-secrets, preview-deploy
- Page: https://vibe-coding-101.brighteng.org/c/build-variant/

## dynamic-type

**dynamic type** (native apps). Dynamic Type adapts text to the user’s preferred size on Apple platforms.

- Use when: A native screen clips text at accessibility sizes.
- What: On Apple platforms, text styles scale with the user's chosen text size. Layouts must let rows grow and wrap, or large sizes clip text and hide buttons.
- Why it matters with an agent: A fixed row height can undo the benefit of a scalable font.
- Do: Use supported text styles and flexible layout, then test the largest relevant sizes.
- Prompt: Support Dynamic Type on this screen. Verify large accessibility sizes keep labels readable and the primary action reachable.
- Avoid: Disabling font scaling to preserve a screenshot’s original layout.
- Described as: Dynamic Type; font scale; large text cut off; accessibility text size
- Related: adaptive-layout, a11y
- Page: https://vibe-coding-101.brighteng.org/c/dynamic-type/

## biometric

**biometric authentication** (native apps). Biometric authentication can authorize a local operation through the operating system.

- Use when: A sensitive local action needs device-user verification.
- What: Face ID, Touch ID, or a fingerprint confirms the person holding the device. Use it to unlock a key stored in secure storage. On its own it says nothing to your server about the account.
- Why it matters with an agent: A successful local prompt can be mistaken for server-side account authorization.
- Do: Use the platform authentication and key-access policy with explicit fallback and invalidation behavior.
- Prompt: Gate this local credential use with the platform’s biometric policy. Test cancellation, fallback, and changed enrollment without treating the result as remote account authorization.
- Avoid: Showing a biometric prompt while the protected key remains accessible without it.
- Described as: Face ID; BiometricPrompt; biometric; Touch ID; fingerprint login
- Related: secure-storage, authn-authz
- Page: https://vibe-coding-101.brighteng.org/c/biometric/

## conflict

**sync conflict** (native apps). A synchronization conflict occurs when changes cannot be combined safely under the chosen policy.

- Use when: Two offline or concurrent editors change the same record.
- What: Two devices or people changed the same record without seeing each other's change. You detect it from versions, then merge, reject, or ask the user, without discarding either version first.
- Why it matters with an agent: Last-arriving data can overwrite an edit that was never observed by its author.
- Do: Track versions or the required causal information and choose merge, rejection, or user resolution.
- Prompt: Detect conflicts for this synchronized record. Test competing edits and preserve both versions until the chosen resolution policy succeeds.
- Avoid: Showing a conflict message after one version has already been discarded.
- Described as: two people edit same record; offline edits conflict; last write wins; merge changes; sync overwrote my edit
- Related: optimistic-lock, offline-first
- Page: https://vibe-coding-101.brighteng.org/c/conflict/

## continuous-integration

**continuous integration** (delivery and operations). Run repeatable checks when code changes are integrated.

- Use when: Changes pass locally but break the shared branch.
- What: Continuous integration combines frequent integration with automated checks in a reproducible environment.
- Why it matters with an agent: An agent’s local result is incomplete evidence if the shared build uses different dependencies or configuration.
- Do: Use a clean install, required checks, and retained failure artifacts. Confirm the checks run on the actual proposed revision.
- Prompt: Add continuous integration for the required build and tests. Use a clean install, retain failure reports, and verify a failing test produces a failed check.
- Avoid: A successful check belongs to an older revision of the change.
- Described as: CI pipeline; checks on pull requests; works on my machine; GitHub Actions; tests run automatically; broken main branch; CI as judge; ci as judge
- Related: verification, git-worktree
- Page: https://vibe-coding-101.brighteng.org/c/continuous-integration/

## request-scope

**request-scoped state** (delivery and operations). Keep user-specific mutable state within the request that owns it.

- Use when: A warm server process reuses variables across different users.
- What: Request-scoped state belongs to one request. Module-level mutable data can outlive that request and be shared with later work.
- Why it matters with an agent: A convenient global variable can leak identity or results between requests.
- Do: Pass request context explicitly. Share only safe reusable resources, and test interleaved requests for different users.
- Prompt: Make identity and user-specific state request-scoped. Test interleaved requests from two users for cross-request leakage.
- Avoid: A shared cache key omits the user or tenant even after globals are removed.
- Described as: global user variable; cross request leak; server global state; user sees another users data on server; module level variable shared
- Related: rls, request-deduplication
- Page: https://vibe-coding-101.brighteng.org/c/request-scope/

## streaming

**streaming** (delivery and operations). Process or forward data incrementally as it arrives.

- Use when: A download buffers the entire response before sending any bytes.
- What: Streaming handles data in chunks instead of requiring the complete body in memory first.
- Why it matters with an agent: Convenient whole-body helpers can erase streaming behavior and exhaust memory on large inputs.
- Do: Keep the path incremental, respect backpressure, and test cancellation and errors after output has begun.
- Prompt: Stream this response without buffering the full body. Verify bounded memory, slow-consumer handling, and cancellation.
- Avoid: A later transformation reads the whole stream into a string.
- Described as: large response memory; download buffers; incremental response; stream LLM response; out of memory on big export; send data in chunks
- Related: backpressure, cancellation
- Page: https://vibe-coding-101.brighteng.org/c/streaming/

## idempotency

**idempotency** (delivery and operations). Repeating an operation has the same intended effect as doing it once.

- Use when: A retried request or duplicate message repeats a side effect.
- What: An idempotent operation tolerates repetition. At-least-once message delivery makes duplicate handling part of normal operation.
- Why it matters with an agent: A successful happy-path test does not cover retries arriving concurrently or after a crash.
- Do: Choose a stable operation key and durable duplicate handling. Coordinate the recorded result with the side effect; use provider support for external effects.
- Prompt: Make this handler idempotent. Use a stable operation key and test duplicate, concurrent, and crash-retried deliveries.
- Avoid: Recording completion separately from the side effect leaves a crash window.
- Described as: duplicate webhook; retry duplicates; same event twice; double charge; clicked pay twice; idempotency key; double submit; button clicked twice; idempotent pipeline; Idempotency
- Related: unique-constraint, transaction
- Page: https://vibe-coding-101.brighteng.org/c/idempotency/

### idempotency: a worked example

Canonical page: https://vibe-coding-101.brighteng.org/c/idempotency/#before-and-after

#### The problem

A user wants notification emails disabled. The same request may be submitted twice. Compare a toggle with an explicit assignment to see why the operation's meaning matters before choosing a retry strategy.

#### Prompt to paste

Make this handler idempotent. Use a stable operation key and test duplicate, concurrent, and crash-retried deliveries.

#### Before

Toggling a preference expresses a change relative to the current state. Starting from true, one call turns emails off and the second call turns them back on.

#### After

Assigning false expresses the desired state directly. Starting from true, both one call and two calls leave emails disabled. The same operation has the same intended effect when repeated.

#### Run the check

Save the following code as idempotency.mjs and run `node --test idempotency.mjs` with Node.js 22.12 or later.

```js
import test from 'node:test';
import assert from 'node:assert/strict';

function before(state) {
  state.emailEnabled = !state.emailEnabled;
}

function after(state) {
  state.emailEnabled = false;
}

test('repeating the toggle reverses the requested change', () => {
  const state = { emailEnabled: true };
  before(state);
  assert.equal(state.emailEnabled, false);
  before(state);
  assert.equal(state.emailEnabled, true);
});

test('repeating the assignment preserves the desired state', () => {
  const state = { emailEnabled: true };
  after(state);
  assert.equal(state.emailEnabled, false);
  after(state);
  assert.equal(state.emailEnabled, false);
});
```

#### Expected result

Two toggle calls finish with emailEnabled equal to true; two disable calls finish with it equal to false. This is a deterministic state comparison. It makes no claim about request latency, payment safety, or production duplicate rates.

#### Limits

A payment cannot usually become idempotent through assignment alone. A handler may need a stable operation key, durable storage, and coordination between the side effect and its recorded result. Test simultaneous duplicates, restarts, payload mismatches, and failures at that boundary. A database transaction cannot undo a completed external API call. Use the external provider's documented duplicate-handling mechanism where available. Idempotency does not require identical response bodies or forbid logging each request.

#### Sources

- [RFC 9110, section 9.2.2: Idempotent Methods](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.2.2): Idempotency concerns the intended effect of repeated requests, rather than identical responses.
- [Stripe: Idempotent requests](https://docs.stripe.com/api/idempotent_requests): A concrete provider-specific operation key and replay contract; not a universal implementation recipe.

Sources checked: 2026-10-09. These are original illustrative examples with automated checks. Human editorial approval is not recorded. Policy: https://vibe-coding-101.brighteng.org/editorial/


## env-secrets

**secret management** (delivery and operations). Supply credentials through an appropriate secret store or runtime configuration.

- Use when: An integration needs a credential in development and deployment.
- What: API keys and passwords come from environment variables or a secret manager at runtime. They never appear in the repository, the client bundle, or the logs.
- Why it matters with an agent: An agent can accidentally embed a real value in an example or error report.
- Do: Document variable names, inject values at runtime, and inspect release output for accidental exposure.
- Prompt: Move this credential to runtime secret configuration. Validate missing configuration and verify the value is absent from source, logs, and client output.
- Avoid: Rotating the environment value while an older leaked credential remains valid.
- Described as: env and secrets; API key in code; secret committed to git; .env file; API key exposed in frontend; NEXT_PUBLIC secret
- Related: least-privilege, build-variant
- Page: https://vibe-coding-101.brighteng.org/c/env-secrets/

## feature-flag

**feature flag** (delivery and operations). A switch controls whether a behavior is enabled.

- Use when: A new behavior needs a staged rollout or a quick way to disable it.
- What: The new code ships turned off and is enabled per user, percentage, or environment from configuration. Turning it off doesn't need a deploy.
- Why it matters with an agent: A flag can hide the UI while leaving unintended side effects active.
- Do: Define the flag’s scope, default, owner, and removal condition; exercise both branches.
- Prompt: Put this behavior behind a feature flag. Verify enabled and disabled paths, including side effects, and document when the flag can be removed.
- Avoid: Treating a rollout switch as an authorization check.
- Described as: turn feature on for some users; kill switch; release toggle; hide unfinished feature; gradual rollout
- Related: canary, rollback
- Page: https://vibe-coding-101.brighteng.org/c/feature-flag/

## rollback

**rollback** (delivery and operations). Return to an earlier working release or state after a failed change.

- Use when: A deployment needs a tested recovery path.
- What: Redeploy a known working release. If the failed release changed the data, the old code may not be able to read it, so that case needs a forward fix.
- Why it matters with an agent: Restoring an old binary may fail against newly changed data.
- Do: Identify a known working artifact and verify its compatibility with the state left by the new release.
- Prompt: Prepare and test rollback for this release. Check the previous artifact against the updated data and identify changes requiring forward recovery.
- Avoid: Claiming a destructive data rewrite can be undone by redeploying old code.
- Described as: undo deploy; revert release; go back to previous version; deploy broke production; roll back migration
- Related: migration, blue-green
- Page: https://vibe-coding-101.brighteng.org/c/rollback/

## load-balancer

**load balancer** (delivery and operations). A load balancer routes requests among service instances.

- Use when: A service runs on multiple instances that must share traffic safely.
- What: A load balancer distributes incoming traffic across configured targets. Routing and health-check settings determine which targets receive work; application readiness and failure behavior need separate verification.
- Why it matters with an agent: Adding instances may expose state or connection assumptions hidden in one process.
- Do: Define readiness and state ownership, then test routing when an instance fails.
- Prompt: Verify this service behind its load balancer. Remove one instance during traffic and check session behavior, readiness, and in-flight requests.
- Avoid: Sending traffic to a process that has started but is not ready.
- Described as: multiple servers; traffic split between instances; sticky sessions; random logouts with two servers; Load balancing
- Related: liveness-readiness, horizontal-scaling
- Sources checked: 2026-10-11 (not human editorial approval)
- [AWS: Elastic Load Balancing](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html): Distributing incoming traffic across targets and configured health checks.
- Page: https://vibe-coding-101.brighteng.org/c/load-balancer/

## horizontal-scaling

**horizontal scaling** (delivery and operations). Increase capacity by running more service instances.

- Use when: One instance cannot handle the measured workload.
- What: Horizontal scaling adds instances to share work. Stateless request handling is easier to distribute; stateful systems need deliberate partitioning, replication, or shared storage and coordination.
- Why it matters with an agent: Duplicating a process can duplicate scheduled jobs or exceed connection limits.
- Do: Find the bottleneck and account for shared resources before adding replicas.
- Prompt: Evaluate horizontal scaling for this workload. Test two instances, shared state, and downstream limits, and compare capacity with the single-instance baseline.
- Avoid: Adding instances while a shared database, hot key, or serialized operation remains the bottleneck.
- Described as: scale out; not up; run more instances; add more servers; cron runs twice with replicas; Horizontal scaling
- Related: connection-pool, load-balancer, vertical-scaling, resharding
- Sources checked: 2026-10-11 (not human editorial approval)
- [Microsoft: Scaling and partitioning](https://learn.microsoft.com/en-us/azure/well-architected/performance-efficiency/scale-partition): Vertical resource increases, horizontal instance increases, bottlenecks, and state distribution.
- Page: https://vibe-coding-101.brighteng.org/c/horizontal-scaling/

## cdn

**CDN** (delivery and operations). A content delivery network serves content through distributed edge locations.

- Use when: Public assets or pages need lower latency for geographically distributed users.
- What: Edge servers around the world keep copies of your static files and public pages, so users download from somewhere nearby. Only responses that are the same for everyone may be cached.
- Why it matters with an agent: Incorrect edge caching can mix personalized responses.
- Do: Classify public and private responses and test cache keys, freshness, and invalidation.
- Prompt: Configure CDN caching for these public resources. Verify cache hits, publication updates, and isolation of personalized responses.
- Avoid: Caching authenticated content under a key that omits its authorization context.
- Described as: slow for faraway users; edge caching; Cloudflare cache; serve static files faster
- Related: http-cache, cache-invalidation
- Page: https://vibe-coding-101.brighteng.org/c/cdn/

## read-replica

**read replica** (delivery and operations). A read replica serves a copy of database data.

- Use when: Read-heavy work competes with writes on the primary database.
- What: A read replica serves queries from replicated data rather than handling the primary write workload. Asynchronous replicas can lag behind, sometimes substantially; acknowledgement and read guarantees depend on the selected replication mode.
- Why it matters with an agent: A recent write can appear missing when its next read reaches a lagging replica.
- Do: Classify reads by consistency requirements and observe replication lag.
- Prompt: Route only suitable reads to this replica. Test lag after a write and preserve the consistency required by user-facing confirmations.
- Avoid: Sending a read-after-write to a lagging replica and treating missing data as a failed write. Replicas do not replace backups.
- Described as: database read copy; reads slow down writes; replication lag; user cannot see what they just saved; Read replicas
- Related: eventual-consistency, query-plan, leader-follower-replication, strong-consistency
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Log-shipping standby servers](https://www.postgresql.org/docs/current/warm-standby.html): Primary/standby streaming replication, asynchronous lag, and synchronous acknowledgement configurations.
- Page: https://vibe-coding-101.brighteng.org/c/read-replica/

## eventual-consistency

**eventual consistency** (delivery and operations). Replicas or projections converge when updates stop and propagation succeeds.

- Use when: A view updates asynchronously after the authoritative write.
- What: Copies of the data, such as replicas, caches, and search indexes, catch up after a write instead of updating at the same moment. The product has to decide what users see in between.
- Why it matters with an agent: A temporary stale view can be mistaken for a lost write or treated as current authority.
- Do: Define which views may lag, how pending work appears, and how failed propagation is detected.
- Prompt: Handle this eventually consistent view explicitly. Test delayed propagation and convergence, and keep authoritative decisions on the correct data path.
- Avoid: Calling permanently missing updates eventual consistency.
- Described as: data appears after delay; search index lag; eventually consistent; update shows up later; Eventual consistency
- Related: outbox, read-replica, strong-consistency, base, quorum
- Sources checked: 2026-10-11 (not human editorial approval)
- [Amazon DynamoDB: Read consistency](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html): Strongly consistent reads reflect successful prior writes within the supported read scope; eventual reads may lag.
- [DeCandia et al.: Dynamo](https://www.allthingsdistributed.com/files/amazon-dynamo-sosp2007.pdf): Consistent hashing, virtual nodes, replica quorums, version reconciliation, and eventual consistency.
- Page: https://vibe-coding-101.brighteng.org/c/eventual-consistency/

## saga

**saga** (delivery and operations). A saga coordinates a multi-step operation through local commits and explicit recovery actions.

- Use when: A business operation spans systems that cannot share one transaction.
- What: Each step commits on its own, such as charging a card, reserving stock, and booking shipping. If a later step fails, earlier ones get compensating actions such as a refund, and progress is saved so recovery can resume.
- Why it matters with an agent: A happy-path orchestration can leave partial results after a later step fails.
- Do: Persist progress and define retries, compensation, and manual recovery for each step.
- Prompt: Model this cross-service workflow as a saga. Test a failure at each step, repeated delivery, and failed compensation without losing recovery state.
- Avoid: Assuming every external effect has an exact inverse.
- Described as: multi-step across services; undo earlier steps on failure; distributed transaction; compensating action
- Related: outbox, idempotency
- Page: https://vibe-coding-101.brighteng.org/c/saga/

## outbox

**transactional outbox** (delivery and operations). A transactional outbox records an event alongside the business change in one database transaction.

- Use when: A database write and event publication must not drift apart.
- What: The business change and the event are written to the database in one transaction. A separate process reads the event table and publishes, retrying until it succeeds.
- Why it matters with an agent: A crash between committing data and sending a message can lose the event.
- Do: Commit the business record and outbox record together, then publish with retry and duplicate handling.
- Prompt: Use a transactional outbox for this event. Test crashes around commit and publication, with idempotent consumers for repeated delivery.
- Avoid: Deleting the outbox record before publication has been safely acknowledged.
- Described as: message lost after save; save and publish event; dual write problem; event not sent after crash
- Related: transaction, idempotency
- Page: https://vibe-coding-101.brighteng.org/c/outbox/

## cache-stampede

**cache stampede** (delivery and operations). Many callers rebuild the same missing or expired cache entry at once.

- Use when: A popular key’s expiration causes a burst of expensive work.
- What: A popular cache entry expires and hundreds of requests all try to rebuild it at once, overloading the database. The fix is one rebuild with others waiting or getting slightly stale data.
- Why it matters with an agent: A correct cache miss path can still overload its dependency under concurrency.
- Do: Choose refresh coordination and a bounded wait or stale-response policy.
- Prompt: Prevent a stampede on this cache entry. Test simultaneous misses and a failed refresher without leaving readers blocked indefinitely.
- Avoid: Using an in-process lock while every instance independently rebuilds the same value.
- Described as: thundering herd; cache expiry spike; everyone rebuilds cache; database spike on cache miss
- Related: cache-invalidation, timeout-budget
- Page: https://vibe-coding-101.brighteng.org/c/cache-stampede/

## dead-letter

**dead-letter queue** (delivery and operations). A dead-letter destination retains work that exhausted normal processing or retry policy.

- Use when: Repeatedly failing jobs block progress or disappear from view.
- What: After a job has failed its allowed retries, it moves to a separate queue with its error, where someone can inspect it, fix the cause, and replay it.
- Why it matters with an agent: A retry loop can consume resources without making the failure actionable.
- Do: Keep the error context and stable identity; define ownership, retention, and replay behavior.
- Prompt: Add dead-letter handling for this job. Verify exhausted retries preserve diagnostic context and that replay does not duplicate completed side effects.
- Avoid: Collecting failed jobs without a way to inspect or recover them.
- Described as: DLQ; failed jobs disappear; job retries forever; poison message
- Related: job-queue, idempotency
- Page: https://vibe-coding-101.brighteng.org/c/dead-letter/

## liveness-readiness

**liveness and readiness** (delivery and operations). Liveness asks whether a process should be restarted; readiness asks whether it should receive work.

- Use when: Deployments send traffic too soon or restart healthy processes during dependency failures.
- What: A liveness check failing means 'restart me'. A readiness check failing means 'send me no traffic for now'. Database outages belong in readiness, or every instance restarts at once.
- Why it matters with an agent: Using one deep health check for every purpose can create restart storms.
- Do: Define separate probes and test startup, dependency loss, and recovery.
- Prompt: Separate liveness and readiness for this service. Verify an unavailable dependency stops unsafe traffic without causing unnecessary process restarts.
- Avoid: A probe depends on the same congested path whose health it should diagnose.
- Described as: health check; Kubernetes probes; restart loop; traffic before app is ready; readiness probe
- Related: load-balancer, graceful-shutdown
- Page: https://vibe-coding-101.brighteng.org/c/liveness-readiness/

## canary

**canary deploy** (delivery and operations). A canary release exposes a new version to a limited portion of traffic first.

- Use when: A release needs production evidence before a full rollout.
- What: The new version gets a small share of real traffic first. Its error rate and latency are compared with the old version before the share grows.
- Why it matters with an agent: Successful deployment does not prove the new behavior is healthy.
- Do: Choose representative traffic and measurable failure thresholds while keeping versions compatible.
- Prompt: Prepare a canary rollout with explicit success and rollback criteria. Verify version identification, error comparison, and compatibility during overlap.
- Avoid: Comparing unequal workloads and calling the difference a release regression.
- Described as: release to small percentage; gradual rollout; test in production safely; partial release
- Related: feature-flag, build-id
- Page: https://vibe-coding-101.brighteng.org/c/canary/

## failover

**failover** (delivery and operations). Failover transfers responsibility from an unavailable component to another.

- Use when: A primary service or datastore has a standby that must take over.
- What: When the primary fails, a standby takes over and clients reconnect to it. The old primary must not keep accepting writes.
- Why it matters with an agent: A standby’s existence does not prove clients can safely use it after failure.
- Do: Use the platform’s supported mechanism and rehearse its failure and recovery boundaries.
- Prompt: Verify the supported failover path for this service. Check client reconnection, acknowledged data, and prevention of conflicting writers.
- Avoid: Promoting a new writer while an old writer still accepts conflicting work.
- Described as: backup server takes over; database goes down; high availability; switch to standby; Failover
- Related: liveness-readiness, read-replica, split-brain, high-availability
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Failover](https://www.postgresql.org/docs/current/warm-standby-failover.html): Promotion, client routing, preventing the old primary from continuing as a writer, and restoring redundancy.
- Page: https://vibe-coding-101.brighteng.org/c/failover/

## pub-sub

**pub/sub** (delivery and operations). Publish/subscribe distributes events to interested subscribers.

- Use when: Several independent consumers need to react to the same event.
- What: Publishers send events to a topic, and every subscriber gets its own copy. Whether a disconnected subscriber misses events, and whether duplicates arrive, depends on the system.
- Why it matters with an agent: A broadcast channel may lose events while a subscriber is disconnected.
- Do: Define which consumers require durable delivery and how they handle repeated events.
- Prompt: Choose pub/sub delivery semantics for this event. Test a disconnected subscriber, reconnect, and duplicates against the required retention policy.
- Avoid: Assuming pub/sub or a work queue guarantees exactly-once side effects.
- Described as: broadcast event to services; event bus; multiple listeners; topic subscribers
- Related: job-queue, idempotency
- Page: https://vibe-coding-101.brighteng.org/c/pub-sub/

## timeout-budget

**timeout budget** (delivery and operations). An operation’s total deadline must account for downstream calls, retries, and cleanup.

- Use when: A user-facing request takes far longer than its intended maximum.
- What: The whole request gets one deadline, and each downstream call uses only what's left, retries included, so a 3-second request can't quietly take 30.
- Why it matters with an agent: Each generated client wrapper may introduce its own full timeout and retry cycle.
- Do: Propagate a remaining deadline and define safe cancellation and retry behavior.
- Prompt: Apply one timeout budget to this workflow. Test a slow dependency and bounded retries, ensuring leftover work is cancelled or safely handed off.
- Avoid: Retrying a timed-out write without knowing whether its side effect already happened.
- Described as: request hangs; deadline; timeouts add up; retries make it slower; set timeout on API call
- Related: cancellation, idempotency
- Page: https://vibe-coding-101.brighteng.org/c/timeout-budget/

## graceful-degradation

**graceful degradation** (delivery and operations). Keep essential behavior useful when an optional dependency or capability is unavailable.

- Use when: An optional widget failure takes down an otherwise useful page.
- What: When an optional dependency such as recommendations or reviews fails, the page shows the core content with a clear note, instead of failing entirely.
- Why it matters with an agent: A broad error path can fail the whole workflow or fabricate a success.
- Do: Separate essential dependencies from optional ones and test the declared fallback.
- Prompt: Degrade gracefully when this optional service fails. Verify the core task still works and the UI clearly reflects missing or stale information.
- Avoid: Replacing a failed dependency with a more expensive fallback that overloads the system.
- Described as: page breaks when one service down; optional feature fails; fallback content; partial outage
- Related: circuit-breaker, empty-state
- Page: https://vibe-coding-101.brighteng.org/c/graceful-degradation/

## bff

**backend for frontend** (delivery and operations). A backend for frontend adapts backend capabilities to a client’s needs.

- Use when: A client assembles one screen from many internal service calls.
- What: A backend endpoint built for one client screen collects data from several services and returns exactly what that screen needs. Shared business rules stay in their own services.
- Why it matters with an agent: Client-side orchestration can multiply round trips and expose internal contracts.
- Do: Define a screen-oriented response and keep shared rules in their authoritative location.
- Prompt: Add a backend-for-frontend endpoint for this screen. Verify the response contract, authorization, and partial dependency failures.
- Avoid: Copying pricing or access rules into a client-specific layer.
- Described as: BFF; too many API calls for one screen; aggregate endpoint; screen-specific API
- Related: request-waterfall, dto
- Page: https://vibe-coding-101.brighteng.org/c/bff/

## iac

**infrastructure as code** (delivery and operations). Infrastructure as code describes infrastructure in reviewable files.

- Use when: Environments depend on undocumented manual configuration.
- What: Servers, databases, and DNS are defined in files such as Terraform or Pulumi. A plan step shows what will change before anything is applied.
- Why it matters with an agent: An agent can propose a small edit that replaces a stateful resource.
- Do: Inspect the plan, protect state, and verify how existing resources are adopted.
- Prompt: Describe this infrastructure change as code. Show the plan, identify replacements, and verify secret values stay outside the repository.
- Avoid: Applying a replacement plan without accounting for the resource’s stored data.
- Described as: IaC; Terraform; Pulumi; clicked in console; reproducible infrastructure
- Related: config-drift, env-secrets
- Page: https://vibe-coding-101.brighteng.org/c/iac/

## container

**container** (delivery and operations). A container runs a process with a packaged filesystem and configured isolation.

- Use when: A service starts differently across development and deployment environments.
- What: A container image packages the app with its dependencies and filesystem, so it runs the same everywhere. Configuration and persistent data are supplied from outside.
- Why it matters with an agent: A successful local image can still depend on unrecorded host files.
- Do: Build a reproducible image and test startup, shutdown, configuration, and persistent storage explicitly.
- Prompt: Containerize this service with pinned build inputs and a non-root runtime where supported. Verify startup and shutdown without undeclared host dependencies.
- Avoid: Assuming a container alone supplies durable storage or a complete security boundary.
- Described as: Docker; Dockerfile; works on my machine; same environment everywhere
- Related: bind-mount, env-secrets
- Page: https://vibe-coding-101.brighteng.org/c/container/

## multi-tenancy

**multi-tenancy** (delivery and operations). A multi-tenant application serves distinct customers through shared infrastructure.

- Use when: Several customer organizations share the same application.
- What: Many customer organizations share the same app and database. Every query, cache key, file, and job has to carry the right tenant and check that the caller belongs to it.
- Why it matters with an agent: A tenant filter in one query does not isolate all the other paths.
- Do: Derive tenant context from trusted membership and trace it through every shared resource.
- Prompt: Verify tenant isolation across this workflow’s queries, caches, and jobs. Test two tenants and direct requests that bypass the UI.
- Avoid: Accepting a tenant ID without checking the caller’s membership.
- Described as: multiple companies same database; organization data separation; tenant id; SaaS data isolation
- Related: rls, query-key
- Page: https://vibe-coding-101.brighteng.org/c/multi-tenancy/

## object-storage

**object storage** (delivery and operations). Object storage stores data as objects addressed by keys.

- Use when: Uploaded files must outlive an application instance.
- What: Services like S3 and R2 store files by key, outside your servers. The database records which object belongs to whom, and access goes through checks or short-lived signed URLs.
- Why it matters with an agent: A local path or public bucket can be mistaken for a durable private file service.
- Do: Choose ownership and access policy, index object references, and handle incomplete uploads and deletion.
- Prompt: Store these uploads in object storage with explicit ownership. Test private access, failed uploads, and cleanup of orphaned objects.
- Avoid: Assuming an unguessable object key provides authorization.
- Described as: S3; R2; file uploads; signed URL; uploads lost on deploy
- Related: authn-authz, serialization
- Page: https://vibe-coding-101.brighteng.org/c/object-storage/

## blue-green

**blue-green deploy** (delivery and operations). Blue-green deployment keeps old and new environments available during a traffic switch.

- Use when: A release needs a quick traffic switch with an available previous version.
- What: Two complete environments run side by side. Traffic switches from the old one to the new one at once, and switching back is just as quick, as long as both can use the same data.
- Why it matters with an agent: A working new environment can still make the previous one unusable through a data change.
- Do: Verify the new environment before switching and test the route back with shared state.
- Prompt: Prepare this blue-green release. Verify both versions against shared data and test traffic switching and recovery before retiring the old environment.
- Avoid: Calling a traffic switch a rollback when the previous application can no longer read the database.
- Described as: zero downtime deploy; switch traffic between versions; instant switch back
- Related: rollback, migration
- Page: https://vibe-coding-101.brighteng.org/c/blue-green/

## config-drift

**configuration drift** (delivery and operations). Configuration drift is a difference between intended and running configuration.

- Use when: An environment behaves differently despite using the expected application build.
- What: The configuration actually running has changed from what's written down, through a manual hotfix or a forgotten setting, so environments behave differently.
- Why it matters with an agent: Applying a configuration blindly can remove an active mitigation.
- Do: Compare authoritative configuration with observed state and explain each meaningful difference.
- Prompt: Identify configuration drift in this environment. Show the differences and their effects before proposing how to reconcile them.
- Avoid: Automatically overwriting an emergency change without understanding why it exists.
- Described as: staging and production differ; manual change on server; environments behave differently; settings out of sync
- Related: iac, build-id
- Page: https://vibe-coding-101.brighteng.org/c/config-drift/

## tls

**TLS** (delivery and operations). TLS protects communication and authenticates peers according to the configured trust model.

- Use when: An application connects to a service over an untrusted network.
- What: TLS encrypts traffic and checks the server's certificate, so you know you're talking to the right server. Turning verification off keeps the encryption but drops that check.
- Why it matters with an agent: Disabling certificate verification can make an integration appear fixed while removing identity checks.
- Do: Use supported TLS clients and inspect the entire path, including proxies and trust configuration.
- Prompt: Verify TLS for this connection. Test valid and invalid certificates and identify where encrypted transport ends without disabling verification.
- Avoid: Assuming an encrypted connection is authentic when certificate validation is bypassed.
- Described as: TLS termination; certificate verify failed; HTTPS; SSL error; self-signed certificate; tls termination
- Related: reverse-proxy, env-secrets
- Page: https://vibe-coding-101.brighteng.org/c/tls/

## http-cache

**HTTP caching** (delivery and operations). HTTP caching controls when clients and intermediaries can reuse a response.

- Use when: A response is unexpectedly stale or reused for the wrong user.
- What: Cache-Control and related headers tell browsers and shared caches whether they may store a response, for how long, and how to check it is still valid. Private data must never land in a shared cache.
- Why it matters with an agent: One cache header copied everywhere can be incorrect for both assets and private data.
- Do: Classify responses, define validation and variants, and test the actual browser or shared cache.
- Prompt: Set deliberate HTTP caching for these responses. Verify public-asset reuse, private-data isolation, and revalidation after changes.
- Avoid: Reading no-cache as a prohibition on storage; it requires validation before reuse.
- Described as: Cache-Control; users get old version after deploy; browser caching; no-cache vs no-store; ETag
- Related: cdn, cache-invalidation
- Page: https://vibe-coding-101.brighteng.org/c/http-cache/

## reverse-proxy

**reverse proxy** (delivery and operations). A reverse proxy accepts client traffic and forwards it to application services.

- Use when: An application sits behind a gateway that handles TLS, routing, or limits.
- What: A server such as nginx or a cloud gateway receives client requests and forwards them to your app. Headers like X-Forwarded-For are only trustworthy if they came from that proxy.
- Why it matters with an agent: Blindly trusting forwarded headers lets callers spoof connection or client information.
- Do: Define trusted proxies and align path, timeout, body-size, and scheme handling.
- Prompt: Configure this reverse-proxy boundary. Verify forwarded headers, URL generation, request limits, and behavior when the upstream is unavailable.
- Avoid: Trusting client-supplied forwarding headers from connections that bypass the proxy.
- Described as: nginx; X-Forwarded-For; real client IP; redirects to http behind proxy
- Related: tls, timeout-budget
- Page: https://vibe-coding-101.brighteng.org/c/reverse-proxy/

## port-mapping

**port mapping** (delivery and operations). Port mapping publishes a service port through another network boundary.

- Use when: A container runs but the browser cannot reach its service.
- What: A container listens on its own port, and Docker publishes that port on the host, for example 8080 on the host to 3000 in the container. 'localhost' inside a container means the container itself.
- Why it matters with an agent: Using localhost from the wrong network namespace can point back at the caller.
- Do: Trace the listener, published port, bind address, and each caller’s network context.
- Prompt: Map this container service to the intended local host port. Verify access from the browser and a sibling container using their correct addresses.
- Avoid: Publishing the wrong internal port or unintentionally binding a private service publicly.
- Described as: localhost:8080; publish a container port; docker publish; cannot reach container; connection refused docker
- Related: container, reverse-proxy
- Page: https://vibe-coding-101.brighteng.org/c/port-mapping/

## bind-mount

**bind mount vs volume** (delivery and operations). A bind mount exposes a host path to a container; a managed volume has a separate storage lifecycle.

- Use when: Container replacement loses a database or development edits are not visible.
- What: A bind mount puts a folder from your machine inside the container, so code edits show up live. A named volume is storage Docker manages that survives the container being replaced.
- Why it matters with an agent: The container’s writable layer can be mistaken for durable application storage.
- Do: Choose the appropriate mount for source and data, then test replacement and cleanup.
- Prompt: Use suitable mounts for this source tree and database. Verify edits appear and data survives container replacement; document which cleanup deletes stored data.
- Avoid: Calling a mounted directory durable without checking its actual host lifecycle.
- Described as: keep database data; docker volume; mount the source; data lost when container restarts; hot reload in docker
- Related: container, serialization
- Page: https://vibe-coding-101.brighteng.org/c/bind-mount/

## preview-deploy

**preview deployment** (delivery and operations). A preview deployment exposes a particular proposed revision for review.

- Use when: Reviewers need to exercise a change outside the developer’s machine.
- What: Each pull request gets its own temporary deployment and URL, built from that exact commit and connected to non-production data.
- Why it matters with an agent: A preview URL can still connect to production services unintentionally.
- Do: Identify the built revision and verify the environment before testing the feature.
- Prompt: Deploy this revision to its preview environment. Verify the build ID, required configuration, and isolation from production writes.
- Avoid: Testing the wrong revision because the preview address points at an older artifact.
- Described as: review URL; do not change production; deploy per pull request; Vercel preview; staging link per branch
- Related: build-id, env-secrets
- Page: https://vibe-coding-101.brighteng.org/c/preview-deploy/

## build-id

**build ID** (delivery and operations). A build ID identifies the artifact running in an environment.

- Use when: A fix is deployed but users may still be running an older release.
- What: Each build records an identifier, such as the git commit, and the running app can report it, so you can check exactly which code is live.
- Why it matters with an agent: A build log alone does not prove which artifact is serving traffic.
- Do: Embed a stable build identity and expose it through an appropriate diagnostic surface.
- Prompt: Expose this artifact’s build ID and source revision. Read them from the running app and compare them with the intended release.
- Avoid: Using request time as a build ID so every response appears to be a new version.
- Described as: which version is running; source commit; is my fix deployed; version endpoint
- Related: verification, canary
- Page: https://vibe-coding-101.brighteng.org/c/build-id/

## database-cluster

**database clustering** (delivery and operations). Coordinate database nodes with explicit storage, replication, and routing roles.

- Use when: A single database node cannot meet your availability or capacity target.
- What: Database clustering makes several nodes cooperate as a database system. Depending on the product, nodes may replicate data, share storage, or own different shards. Physical row clustering is a separate meaning.
- Why it matters with an agent: An agent can add nodes without defining which node owns a write or how clients recover.
- Do: Draw the node roles and failure domains. Define write routing, replication, and failover. Check a node-loss drill and verify acknowledged writes.
- Prompt: Describe this database cluster’s node roles, write routing, and failure behavior. Verify a node-loss drill.
- Avoid: A cluster is not automatically highly available, strongly consistent, or faster for every workload.
- Described as: clustering; database cluster; database nodes; A single database node cannot meet your availability or capacity target; Clustering
- Related: leader-follower-replication, partitioning, high-availability, clustered-storage
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Log-shipping standby servers](https://www.postgresql.org/docs/current/warm-standby.html): Primary/standby streaming replication, asynchronous lag, and synchronous acknowledgement configurations.
- [PostgreSQL: Failover](https://www.postgresql.org/docs/current/warm-standby-failover.html): Promotion, client routing, preventing the old primary from continuing as a writer, and restoring redundancy.
- Page: https://vibe-coding-101.brighteng.org/c/database-cluster/

## rebalancing

**rebalancing** (delivery and operations). Move existing partitions or replicas to improve their placement.

- Use when: A newly added shard is idle while older shards carry most data.
- What: Rebalancing changes where existing data ranges or replicas live, subject to capacity and placement rules. It need not change the key that assigns records to partitions.
- Why it matters with an agent: An agent can add a node and expect old data and traffic to move automatically.
- Do: Inspect bytes, traffic, and replica constraints per node. Move data gradually, then verify placement and request latency. Distinguish balancing bytes from balancing hot keys.
- Prompt: Rebalance existing partitions across these nodes. Verify placement constraints, migration load, and per-node traffic.
- Avoid: Moving an indivisible hot key to another node can merely move the bottleneck.
- Described as: shard rebalancing; partition rebalance; A newly added shard is idle while older shards carry most data; Rebalancing
- Related: resharding, hot-partition, data-locality
- Sources checked: 2026-10-11 (not human editorial approval)
- [MongoDB: Sharded cluster balancer](https://www.mongodb.com/docs/manual/core/sharding-balancer-administration/): The balancer migrates data ranges between shards subject to placement constraints.
- [MongoDB: Reshard a collection](https://www.mongodb.com/docs/manual/core/sharding-reshard-a-collection/): Resharding can change the shard key or force redistribution; it has resource and write-blocking requirements.
- Page: https://vibe-coding-101.brighteng.org/c/rebalancing/

## resharding

**resharding** (delivery and operations). Change the shard layout or assignment used to distribute data.

- Use when: The existing shard key or partition layout cannot spread the workload.
- What: Resharding redistributes records using a changed shard layout, key, or mapping. Some products also use the term for rebuilding distribution with the same key. Rebalancing usually moves existing units between nodes.
- Why it matters with an agent: An agent can change a routing hash without migrating the records already stored under the old mapping.
- Do: Plan copy, change capture, routing transition, and rollback. Check row reconciliation, writes during migration, and queries using the old key.
- Prompt: Plan resharding with data reconciliation, concurrent-write handling, routing cutover, and rollback checks.
- Avoid: Online resharding still needs resources and can block writes briefly; product behavior and limits vary.
- Described as: reshard; change shard key; shard count; The existing shard key or partition layout cannot spread the workload; Resharding
- Related: rebalancing, hash-partitioning, range-partitioning, data-migration
- Sources checked: 2026-10-11 (not human editorial approval)
- [MongoDB: Reshard a collection](https://www.mongodb.com/docs/manual/core/sharding-reshard-a-collection/): Resharding can change the shard key or force redistribution; it has resource and write-blocking requirements.
- Page: https://vibe-coding-101.brighteng.org/c/resharding/

## split-brain

**split-brain** (delivery and operations). Competing nodes act as the same write authority after losing coordination.

- Use when: An old primary resumes writes after a standby has been promoted.
- What: Split-brain occurs when separated nodes both believe they may own an exclusive role. Conflicting histories can result if both accept writes without the required coordination.
- Why it matters with an agent: An agent can implement promotion on a missed heartbeat without disabling the old writer.
- Do: Use the platform’s election and fencing mechanisms. In a disposable drill, isolate the primary and verify the old authority cannot write after promotion.
- Prompt: Verify failover fencing: isolate the primary, promote safely, and prove the former primary cannot accept writes.
- Avoid: A timeout shows that a node is unreachable, not that it is dead. Deliberate multi-leader replication has a different conflict contract.
- Described as: split brain; fencing; dual primary; An old primary resumes writes after a standby has been promoted; Split-brain
- Related: failover, consensus, multi-leader-replication
- Sources checked: 2026-10-11 (not human editorial approval)
- [PostgreSQL: Failover](https://www.postgresql.org/docs/current/warm-standby-failover.html): Promotion, client routing, preventing the old primary from continuing as a writer, and restoring redundancy.
- [Ongaro and Ousterhout: Raft](https://raft.github.io/raft.pdf): Replicated-log consensus, majority voting, safe membership changes, and timing requirements for progress.
- Page: https://vibe-coding-101.brighteng.org/c/split-brain/

## high-availability

**high availability (HA)** (delivery and operations). Keep the service usable through specified failures and recovery procedures.

- Use when: A single machine or zone failure must not exceed the service’s outage budget.
- What: High availability combines redundancy, failure detection, routing, and recovery to meet an availability target. The target needs a defined user operation, measurement window, and failure scope.
- Why it matters with an agent: An agent can count replicas while ignoring a shared power source, failed routing, or exhausted connections.
- Do: Define the availability objective and failure domains. Drill node and zone loss. Measure successful user operations and recovery duration, then restore redundancy.
- Prompt: Define the HA target and failure scope. Verify a failover drill using successful user requests and recovery time.
- Avoid: An HA setup is not a backup strategy or a promise of zero downtime and zero data loss.
- Described as: HA; high availability; availability target; A single machine or zone failure must not exceed the service’s outage budget; High availability (HA)
- Related: failover, database-cluster, load-balancer
- Sources checked: 2026-10-11 (not human editorial approval)
- [Microsoft: Reliability targets](https://learn.microsoft.com/en-us/azure/well-architected/reliability/metrics): Availability targets must define a measurement scope, time window, and failure/recovery objectives.
- [PostgreSQL: Failover](https://www.postgresql.org/docs/current/warm-standby-failover.html): Promotion, client routing, preventing the old primary from continuing as a writer, and restoring redundancy.
- Page: https://vibe-coding-101.brighteng.org/c/high-availability/

## vertical-scaling

**vertical scaling** (delivery and operations). Give one instance more CPU, memory, or I/O capacity.

- Use when: One database instance is constrained by a measured resource bottleneck.
- What: Vertical scaling increases the resources of an instance. It can postpone distribution work, but hardware ceilings, resize procedures, and single-instance failure exposure still matter.
- Why it matters with an agent: An agent can recommend a larger machine when the real delay is lock contention or a slow query.
- Do: Identify the constrained resource, compare a larger instance under the same workload, and check resizing downtime, cost, and remaining headroom.
- Prompt: Evaluate vertical scaling for the measured bottleneck. Compare throughput, latency, cost, and resize downtime.
- Avoid: More CPU does not repair a serialized critical section, missing index, or remote dependency bottleneck.
- Described as: scale up; scale down; larger database instance; One database instance is constrained by a measured resource bottleneck; Vertical scaling
- Related: horizontal-scaling, query-plan, connection-pool
- Sources checked: 2026-10-11 (not human editorial approval)
- [Microsoft: Scaling and partitioning](https://learn.microsoft.com/en-us/azure/well-architected/performance-efficiency/scale-partition): Vertical resource increases, horizontal instance increases, bottlenecks, and state distribution.
- Page: https://vibe-coding-101.brighteng.org/c/vertical-scaling/

## geo-replication

**geo-replication** (delivery and operations). Replicate data across geographic regions with an explicit consistency policy.

- Use when: A regional outage or distant users require copies beyond one region.
- What: Geo-replication places replicas in multiple regions. It can be asynchronous or coordinated; write latency, conflict handling, failover, and supported read guarantees depend on the selected mode.
- Why it matters with an agent: An agent can call a multi-region system eventually consistent when the product now offers several modes.
- Do: Choose regions and consistency mode. Measure cross-region writes and lag, then drill regional loss and reconnection. Verify data residency requirements separately.
- Prompt: Specify geo-replication mode and region roles. Test regional failure, recovery, and the promised read/write consistency.
- Avoid: A remote copy is not proof of zero data loss, local write latency, or residency compliance.
- Described as: geo replication; cross-region replication; multi-region replication; A regional outage or distant users require copies beyond one region; Geo-replication
- Related: data-locality, multi-leader-replication, high-availability
- Sources checked: 2026-10-11 (not human editorial approval)
- [Amazon DynamoDB: Global tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GlobalTables.html): Multi-region replication has explicit eventual and strong consistency modes with different constraints.
- Page: https://vibe-coding-101.brighteng.org/c/geo-replication/

## url-state

**URL state** (web interface). Put shareable navigation state in the URL.

- Use when: Reloading or sharing a filtered page loses the selected view.
- What: URL state encodes choices such as filters and pagination so navigation can restore them.
- Why it matters with an agent: Local component state can make a useful view impossible to bookmark.
- Do: Define supported parameters and defaults. Check reload, shared links, and browser back navigation.
- Prompt: Make these filters URL state. Validate parameters and verify reload, sharing, and back navigation restore the same view.
- Avoid: Private or sensitive values are exposed in URLs and history.
- Described as: share filter; bookmark search; back button loses filter; filters lost on refresh; query params; search params state
- Related: lifting-state, pagination
- Page: https://vibe-coding-101.brighteng.org/c/url-state/

## reduced-motion

**reduced motion** (web interface). Respect the user’s preference for less interface animation.

- Use when: A transition uses large motion or persistent animation.
- What: Reduced-motion support replaces or removes nonessential movement when the user requests it through system preferences.
- Why it matters with an agent: Generated animation may overlook people who find motion uncomfortable.
- Do: Offer a restrained alternative while preserving state changes and feedback. Test with the preference enabled.
- Prompt: Respect prefers-reduced-motion for this interaction. Keep the outcome clear without nonessential movement and test both settings.
- Avoid: Removing an animation also removes the only indication that an action completed.
- Described as: disable animation; motion sensitivity; prefers reduced motion; animations make users dizzy
- Related: visual-regression, url-state
- Page: https://vibe-coding-101.brighteng.org/c/reduced-motion/

## layout-shift

**layout shift** (web interface). Visible content moves unexpectedly as the page loads or updates.

- Use when: Text or buttons jump when images, fonts, or embeds arrive.
- What: Layout shifts occur when existing elements change position. Cumulative Layout Shift measures qualifying unexpected shifts over defined windows.
- Why it matters with an agent: Generated layouts often omit reserved space for content that loads later.
- Do: Trace the moving elements, reserve appropriate space, and compare before and after under delayed loading.
- Prompt: Find and fix the cause of these layout shifts. Reserve space for late content and compare a before-and-after loading trace.
- Avoid: A fixed placeholder height clips content on a smaller viewport.
- Described as: page jumps; image moves content; CLS; font shifts; content jumps on load; clicked wrong button because page moved
- Related: visual-regression, code-splitting
- Page: https://vibe-coding-101.brighteng.org/c/layout-shift/

## a11y

**accessibility** (web interface). Accessibility makes an interface usable by people with varied abilities and assistive tools.

- Use when: A feature works with a mouse but is difficult to use otherwise.
- What: Accessibility covers semantic markup, keyboard operation, visible focus, labels for screen readers, contrast, zoom, and error feedback, so people using assistive tools can finish the same tasks.
- Why it matters with an agent: Generated custom controls can omit the behavior supplied by native elements.
- Do: Use semantic controls and verify the complete task with keyboard and assistive technology.
- Prompt: Check this workflow for accessibility. Verify names, keyboard operation, visible focus, zoom, and error feedback; fix barriers to completing the task.
- Avoid: Passing an automated scan while the main workflow remains unusable by keyboard.
- Described as: a11y; screen reader; keyboard only; WCAG; aria labels; accessible form
- Related: focus-management, semantic-locator
- Page: https://vibe-coding-101.brighteng.org/c/a11y/

## empty-state

**empty state** (web interface). An empty state explains why expected content is absent and what action is available.

- Use when: A list appears blank and users cannot tell what happened.
- What: Distinct screens for 'nothing here yet', 'no results for this filter', 'still loading', and 'failed to load', each with a useful next action.
- Why it matters with an agent: A single empty branch can conceal a failed request or an active filter.
- Do: Model the relevant states separately and keep the next useful action clear.
- Prompt: Implement distinct first-use, no-results, loading, and error states for this list. Verify each state and its available recovery action.
- Avoid: Displaying no records as if a failed request completed successfully.
- Described as: blank page no data; no results message; first use screen; nothing to show
- Related: error-copy, skeleton
- Page: https://vibe-coding-101.brighteng.org/c/empty-state/

## progressive-disclosure

**progressive disclosure** (web interface). Reveal secondary choices when they become relevant.

- Use when: A form overwhelms users with rarely used options.
- What: The common path shows only what most people need. Advanced options appear on demand or when they become relevant, and stay easy to find.
- Why it matters with an agent: Hiding controls can simplify appearance while making the task impossible to complete.
- Do: Separate required choices from optional detail and test the basic path without opening every section.
- Prompt: Use progressive disclosure for these advanced options. Verify the basic task completes with required fields visible and hidden settings remain discoverable.
- Avoid: Hiding a required decision until after submission fails.
- Described as: too many options; advanced settings; simplify form; hide rarely used options
- Related: a11y, empty-state
- Page: https://vibe-coding-101.brighteng.org/c/progressive-disclosure/

## destructive-action

**destructive action** (web interface). A destructive action removes or invalidates user value.

- Use when: A delete or revoke action can affect the wrong object or cannot be reversed.
- What: Deleting, revoking, or overwriting something the user values. The confirmation names exactly what will be lost, permissions are checked on the server, and recovery is offered where possible.
- Why it matters with an agent: A generic confirmation can obscure exactly what will be lost.
- Do: Name the affected object and distinguish reversible actions from irreversible ones.
- Prompt: Make this destructive action explicit. Verify the target, required permission, and confirmation or recovery path before applying it.
- Avoid: Showing an undo option when the underlying state cannot actually be restored.
- Described as: delete confirmation; accidental delete; are you sure dialog; type name to confirm
- Related: undo, authn-authz
- Page: https://vibe-coding-101.brighteng.org/c/destructive-action/

## undo

**undo** (web interface). Undo reverses a supported action according to a defined history and lifetime.

- Use when: A user needs to recover from an accidental reversible edit.
- What: The app keeps enough history to reverse an action for a defined time, so 'undo' really restores the previous state instead of just hiding a message.
- Why it matters with an agent: A temporary message can promise recovery that persistence no longer supports.
- Do: Define which actions are reversible and test recovery across the supported lifecycle.
- Prompt: Implement undo for this action with an explicit lifetime. Verify the original state returns and repeated or expired undo requests behave correctly.
- Avoid: Overwriting the only undo record when a second action happens.
- Described as: undo button; restore after delete; soft delete; undo toast
- Related: destructive-action, state-machine
- Page: https://vibe-coding-101.brighteng.org/c/undo/

## skeleton

**skeleton screen** (web interface). A skeleton screen reserves the shape of content while it loads.

- Use when: A loading region appears blank or shifts substantially when content arrives.
- What: Grey placeholder shapes the size of the coming content hold the layout while it loads, then give way to the content, an empty state, or an error.
- Why it matters with an agent: A polished placeholder can hide a missing error path.
- Do: Match the content’s layout and test slow, empty, and failed loads.
- Prompt: Add a skeleton for this loading region. Verify a stable layout and transitions to success, empty, and error states, including reduced motion.
- Avoid: Animating an indefinite placeholder after the request has already failed.
- Described as: loading placeholder; shimmer; content placeholder; gray boxes while loading
- Related: layout-shift, reduced-motion
- Page: https://vibe-coding-101.brighteng.org/c/skeleton/

## error-copy

**error copy** (web interface). Error copy explains a failure in terms useful to the user.

- Use when: Users receive raw exceptions or the same message for unrelated failures.
- What: Error messages say what went wrong in the user's terms and what they can do next. Stack traces and internal details go to the logs, not the screen.
- Why it matters with an agent: A generic message can make a recoverable problem look permanent.
- Do: Map known failures to actionable messages and keep diagnostic detail in the appropriate logs.
- Prompt: Write error messages for validation, offline, and service failure here. Verify the next action works and sensitive diagnostics stay out of the UI.
- Avoid: Offering retry for an operation that will repeat a successful side effect.
- Described as: error messages; user friendly errors; raw exception shown to user; something went wrong message
- Related: idempotency, observability
- Page: https://vibe-coding-101.brighteng.org/c/error-copy/

## design-tokens

**design tokens** (web interface). Design tokens name reusable visual decisions such as spacing and colors.

- Use when: The same visual role has many slightly different hardcoded values.
- What: Named values for colors, spacing, type, and radii, such as color-surface or space-4, that components use instead of raw hex codes and pixel values.
- Why it matters with an agent: An agent can add a second palette rather than reuse existing design decisions.
- Do: Define a small semantic set and replace the values for the targeted components.
- Prompt: Consolidate these repeated visual values into design tokens. Verify one token change updates the intended components without altering unrelated roles.
- Avoid: Creating tokens but continuing to use raw values at the call sites.
- Described as: shared colors and spacing; one surface color; inconsistent colors; CSS variables theme; hardcoded hex values
- Related: component-variant, visual-regression
- Page: https://vibe-coding-101.brighteng.org/c/design-tokens/

## split-pane

**split pane** (web interface). A split pane divides a workspace with an adjustable separator.

- Use when: Users need to resize a sidebar and primary work area.
- What: Two panels separated by a draggable divider, with minimum sizes, keyboard resizing, and a fallback layout for narrow windows.
- Why it matters with an agent: A mouse-only drag handle can make the layout unusable for keyboard users.
- Do: Define size constraints, keyboard behavior, and narrow-window fallback.
- Prompt: Build this resizable split pane. Verify pointer and keyboard resizing, minimum widths, and the layout when the window becomes too narrow.
- Avoid: Allowing a pane to collapse until its recovery control is unreachable.
- Described as: resize the sidebar; resizable panel; drag the divider; resizable layout
- Related: adaptive-layout, a11y
- Page: https://vibe-coding-101.brighteng.org/c/split-pane/
