Mental models for software engineering with AI GitHub →
Interactive Evaluation
Deconstruct Architecture
"Evaluate our user auth microservice strategy. What assumptions are we relying on regarding team scale, network latency, and deployment boundaries?"
Status: ● Live Simulation
Reasoning Trace
1. Question assumption: Is microservice isolation required for 4 devs?
2. Decompose to fundamentals: Auth needs 1) Verify ID, 2) Session state.
3. Reconstruct: Modular monolith reduces dev loop overhead by 4.2x.
01 / OVERVIEW

Timeless engineering principles for AI-built software.

AI tools can generate code at machine speed, but human engineers must hold the frame. These mental models provide compressed judgment to evaluate architecture, cut premature complexity, and prevent silent outages.

🧠
Why Mental Models?
AI tools generate plausible code based on common training patterns. Mental models give you the lenses to question assumptions, expose hidden flaws, and make intentional architectural choices before writing code.
📖
How to Use This Library
Read each deep dive for foundational principles, inspect real-world worked case studies, practice with interactive checkpoints, and copy Socratic prompt templates directly into your AI workflow.
The Published Frameworks
Currently featuring First Principles Thinking, Occam's Razor, Chesterton's Fence, Conway's Law, Inversion, and Hyrum's Law — each accompanied by an interactive hero simulator trace, worked incident study, and quiz.
02 / MODEL 01

First Principles Thinking

Stop copying patterns you don't understand. Reason from the ground up — and use AI as a thinking partner, not a vending machine.

Foundation

Reasoning from Irreducible Truths

First principles thinking is the practice of actively questioning every assumption you take for granted, breaking down a complex problem into its basic components, and building a solution from scratch.

"Reasoning by first principles is the practice of actively questioning every assumption you think you know about a given problem, and then creating new knowledge and solutions from scratch."
PRINCIPLE 01
Question Every Assumption
Don't accept "we've always done it this way" as technical justification. Test if historical constraints still apply.
Software Example

Assumption: "We need microservices." Question: Do we have team scaling problems or deployment independence needs? For a 3-person team, a modular monolith is fundamentally better.

AI Application

When AI suggests a pattern, prompt it: "What assumptions does this solution make about my scale, team, and constraints? What would change if those assumptions were false?"

PRINCIPLE 02
Decompose to Fundamentals
Break the problem down until you hit atoms — things that are undeniably true. These are your true requirements.
Software Example

"Build user authentication." Fundamentals: (1) Verify identity, (2) Persist session, (3) Protect resources. From these atoms, choose OAuth, JWT, or cookies based on your context.

AI Application

Ask AI: "Help me decompose this feature into its fundamental requirements — what does it absolutely need to do, ignoring implementation?"

PRINCIPLE 03
Reconstruct from Truth
Build your solution up from fundamentals, not down from convention. Know why every piece exists.
Software Example

Fundamental: "Process 10 events/sec with guaranteed delivery." Reconstruct: Redis streams, RabbitMQ, or DB queues become conscious choices rather than cargo culting.

AI Application

After decomposing, prompt AI: "Given these 4 fundamental constraints, generate 3 different architectures and explain which assumptions each makes."

PRINCIPLE 04
Separate Problem from Solution
Most "technical problems" are actually solution-framing problems. Optimize the outcome, not the implementation.
Software Example

"Optimize SQL query" anchors to a solution. The actual problem: "Users wait 4s." That might be solved via caching, pagination, or async loading without touching SQL.

AI Application

Tell AI the pain outcome, not your assumed solution: "Users complain about slowness" vs "optimize my query." The first framing unlocks first-principles thinking.

PRINCIPLE 05
Validate Against Reality
First principles logic must be tested, not just trusted. Build feedback loops early to measure production reality.
Software Example

You reasoned in-memory caching eliminates DB bottleneck. Test it. Maybe network latency was the real bottleneck. Production reality overrules elegant theory.

AI Application

Prompt AI to steelman your design: "Here is my architecture. What are 5 ways this could fail in production that I haven't considered?"

Practical Method

The First Principles AI Workflow

A 5-step process for using AI as a Socratic thinking partner — not a code vending machine.

STEP 01 State the Real Problem

Describe the problem in terms of human or business outcomes — not technical systems. No solutions allowed yet.

"I have a problem where [user/business pain]. The current situation is [what is happening now]. The constraint is [time/team/budget]. Help me decompose this to fundamental requirements without suggesting solutions yet."
STEP 02 Expose Hidden Assumptions

Ask AI to surface what you take for granted regarding scale, team, technology, and user behavior.

"Here are requirements: [paste]. What assumptions am I making about scale, team capabilities, technology constraints, and user behavior? Which assumptions, if wrong, would change the right solution?"
STEP 03 Generate Solution Space

Explore multiple architectural paths with explicit trade-offs instead of jumping to the first plausible code snippet.

"Given these verified fundamentals: [constraints]. Generate 3 different approaches. For each, tell me: what assumptions it optimizes for, where it breaks down, and what must be true for it to be the right choice."
STEP 04 Steelman & Challenge

Once chosen, force AI to act as a skeptical senior engineer finding blind spots before building.

"I decided on [approach]. Act as a skeptical senior engineer. Give me your strongest argument against this design. What would break it in production? What hidden costs am I missing?"
STEP 05 Build, Measure, Revise

Define lead indicators and instrumentation metrics to verify first-principles hypotheses in production.

"Help me define success metrics for [feature]. What should I measure to know if my first-principles reasoning was correct? What leading indicators tell me early if I need to revise?"
Comparison Matrix

First Principles vs. Cargo Culting

Scenario ❌ Analogy Thinking ✅ First Principles
Choosing a database "Everyone uses Postgres, so we use Postgres" Define read/write ratio, query patterns, scale needs — then choose
Using AI for code Copy-paste AI output without understanding Ask AI to explain trade-offs; verify against actual constraints
Architecture "Netflix uses microservices, so should we" Evaluate team size, deployment frequency, and boundary isolation
Performance issues Add caching everywhere as default fix Profile first. Identify the actual bottleneck. Solve that.
Tech stack choice "React is popular, Kubernetes is mature" What problems am I solving? What is the team's learning curve cost?
AI prompting "Write me a user auth system" "My constraints are X. What are fundamental auth requirements for my case?"
Worked Case Study

Designing a Notification System

"We need to build a notification system for our app."

Most engineers jump straight to Firebase push notifications or message queues. First principles says: stop. Decompose first.

Step 1 → Decompose to Fundamental Truths
1
FUNDAMENTAL TRUTH 1: A notification is information delivered to a user at a time when they can act on it.
2
FUNDAMENTAL TRUTH 2: Delivery has two axes: channel (email, push, SMS, in-app) and timing (real-time, batched, scheduled).
3
FUNDAMENTAL TRUTH 3: Reliability requirements vary by notification type ("Your payment failed" ≠ "Weekly digest").
4
FUNDAMENTAL TRUTH 4: Users have preferences. Delivery that ignores preferences becomes spam.
Step 2 → Reconstruct Based on Your Constraints
IF: Small scale, single channel, low latency tolerance → Simple DB-polling worker. No queue needed. Dead simple to operate and debug.
IF: High reliability required, multi-channel → Outbox pattern + dedicated delivery workers per channel with retry logic.
IF: Millions of users, complex preferences → Message queue, fan-out architecture, and preference service are now justified.
CHECKPOINT 01 Question 1 of 3 • Score: 0/3
INTERACTIVE EVALUATION
First Principles Scenario
Loading question...
Status: ● Live Evaluation
SELECT ANSWER
03 / MODEL 02

Occam's Razor

The simplest solution that works is usually correct. Cut unnecessary abstractions and avoid architecting for hypothetical futures.

Foundation

Entities Must Not Be Multiplied Beyond Necessity

Occam's Razor states that among competing hypotheses, the one with the fewest assumptions should be selected. In software: every layer, interface, or service must earn its place.

"Entities must not be multiplied beyond necessity. When two explanations fit the facts equally well, prefer the simpler one." — William of Ockham, 14th century philosopher
PRINCIPLE 01
Prefer the Simpler Explanation
Don't multiply abstractions beyond what the problem demands. Every extra layer adds cognitive load.
Software Example

"We need Kafka for notifications." Why? Current load: 50 events/day. A simple database table with a background job does the job with 90% less operational complexity.

AI Application

Ask AI: "What is the simplest solution that meets ONLY stated requirements? Give me that first, then tell me what changes if scale increased 100x."

PRINCIPLE 02
Measure Cognitive Load
Complexity lives in the reader's head, not line count. Minimize new concepts, not character count.
Software Example

A clever 1-liner with reduce & flatMap replaces a 20-line loop. It wins on line count, but loses on debuggability and reading clarity during a 2am incident.

AI Application

Tell AI: "Write this for a junior engineer joining tomorrow. Optimize for clarity over cleverness. If using advanced syntax, explain if a simpler form works."

PRINCIPLE 03
Eliminate Unnecessary Layers
Every wrapper and interface has a cost. If removing a layer breaks nothing, delete it.
Software Example

Repository pattern over an ORM over a DB driver is 3 layers to query 1 table. Ask: does each layer represent a genuinely separate concern?

AI Application

Ask AI: "For each layer in your proposed design, tell me: what specifically would be harder to change if this layer didn't exist?"

PRINCIPLE 04
Don't Architect for Hypotheticals
Solve today's requirements. Speculative extensibility is almost always wrong when the future arrives.
Software Example

An API designed to support "any payment provider" when you have exactly one provider and no plans to change. YAGNI: You Aren't Gonna Need It.

AI Application

Prompt AI: "What are actual requirements I need this week? Build exactly that, and tell me what changes if requirement X appears in 6 months."

PRINCIPLE 05
Simple ≠ Simplistic
True simplicity takes more thought, not less. Omitting error handling or security is incomplete, not simple.
Software Example

A simple REST endpoint that handles input validation, error codes, and timeouts takes work. Simplicity in design (few moving parts) ≠ lazy effort.

AI Application

Ask AI: "Is this solution actually simple, or just incomplete? What necessary complexity am I dropping, and what is the minimum needed for safety?"

Practical Method

The Occam's Razor AI Workflow

A 5-step method for applying the razor before, during, and after generating code with AI.

STEP 01 State Only What You Need Now

Strip qualifiers like "someday" and "in case we." Only what you need to ship this week counts.

"My current requirements are: [list present requirements]. Explicitly NOT in scope: [tempting future items]. Design the simplest solution meeting only in-scope items."
STEP 02 Challenge Every Component

For every proposed component, ask what specific requirement it serves. Flag anything without a direct mapping.

"For each component in your proposed solution, answer: what specific requirement from my list does this serve? Flag anything without a direct mapping and suggest what to remove."
STEP 03 Ask for the Simpler Version

AI defaults to comprehensive. Always explicitly request a minimal, stripped-down version.

"Now give me a version that is1 meaningfully simpler. Drop any pattern or layer not strictly required. What are concrete trade-offs vs the previous version?"
STEP 04 Evaluate What You'd Lose

Distinguish between essential safety (error handling, security) and premature flexibility.

"Between simpler and complex versions, separate what is missing into: 1) Essential things to add back (security/errors), 2) Speculative flexibility I only thought I needed."
STEP 05 Ship & Set a Complexity Budget

Write a 1-paragraph decision record capturing why complexity was cut so future devs don't re-add it.

"Help me write a 1-paragraph decision record: 1) What we chose & why, 2) What we explicitly decided NOT to build, 3) What specific signal tells us to add complexity later."
Comparison Matrix

When Engineers Violate the Razor

Scenario ❌ Over-Engineered ✅ Occam's Approach
Auth for 3-person internal tool OAuth2 + ID provider + refresh tokens + RBAC matrix HTTP Basic Auth or shared secret. Add OAuth when compliance demands it.
Config per environment Feature flag dashboard + SDK + percentage rollouts + A/B tracking Environment variables. A .env file. Change value to change behavior.
Storing 500 static records Redis cache + Postgres + invalidation events + TTL tuning Query database. Add cache only when profiling proves it slow.
Daily background job Celery / BullMQ + worker autoscaling + DLQ + dashboard Cron job checking a SQL table row with run_at timestamp.
API for 1 internal frontend Versioned REST API + OpenAPI spec + SDK generator Unversioned endpoints. Change both sides together.
Sharing code between 2 services Private npm package repo + CI/CD + semver + update bot Copy the code. Refactor to a shared package when duplication hurts.
Case Study

The 6-Week vs. 1-Day Notification System

A team was asked to send email notifications for nightly reports (~200 users).

❌ Over-Engineered (6 Weeks)
  • Kafka event bus for domain events
  • Dedicated microservice & separate DB
  • Handlebars dynamic template editor
  • User preference matrix center
✅ Occam's Razor (1 Day)
  • Cron job running at 6am checking SQL
  • Direct SendGrid API call with text template
  • Single stdout log line for observability
  • Shipped before standup
CHECKPOINT 02 Question 1 of 3 • Score: 0/3
INTERACTIVE EVALUATION
Occam's Razor Scenario
Loading question...
Status: ● Live Evaluation
SELECT ANSWER
04 / MODEL 03

Chesterton's Fence

Never remove code you don't understand. The guard or delay you can't explain is the one most likely to hurt you in production.

Incident Report

"An AI cleaned up the codebase on Tuesday. By Thursday, 3% of payments silently failed."

An AI assistant flagged await sleep(500); as dead code. An engineer merged the cleanup PR. Without that delay, a vendor SDK race condition surfaced under load, failing transactions silently for 6 hours.

PRINCIPLE 01
Never Remove What You Can't Explain
If you can't state why it's safe to delete, your investigation is incomplete. "It looks unused" is not an explanation.
Software Example

A finally block releasing a DB connection looks redundant when try has cleanup logic. Remove it, and you create a connection leak under heavy load.

AI Application

Tell AI: "Before proposing removals, explain what each piece does, when it executes, and what happens if absent. I will verify against git history."

PRINCIPLE 02
"Weird" Code Is Defensive Code
Counterintuitive null checks or delays are scars. They encode memory of past production outages.
Software Example

Checking if (userId !== undefined && userId !== null && userId !== '') is defensive — written because a client sent empty strings causing data corruption.

AI Application

When AI calls code "overly verbose": "Check git history for commits touching this line. Is there an incident explaining why naive code failed?"

PRINCIPLE 03
History Is Part of the Code
git blame and PR descriptions are primary sources. A file without its history is an unlabelled fence.
Software Example

git log -p -- src/payments/processor.js takes 30s. The 3-year-old commit message says: "fix: compensate for SDK race condition JIRA-4821."

AI Application

Paste git history into prompt: "Here is commit history: [paste]. What is the purpose of this guard, and what risk does removing it introduce?"

PRINCIPLE 04
AI Sees the Fence, Not the Cattle
AI sees syntax, not institutional history. It doesn't know what incident a guard was written to defend against.
Software Example

A feature flag set to false might be an ops killswitch triggered during outages. AI sees dead code. Ops sees a circuit breaker.

AI Application

Treat AI's "safe to remove" as hypotheses, not verdicts. Supply operational context, then ask: "Given this incident history, is it still safe?"

PRINCIPLE 05
Burden of Proof Is on Removal
Keeping code costs almost nothing; deleting code without context risks outages. Prove safety before deleting.
Software Example

A 2019 data migration script ran once and is idempotent. Safe to remove because you can state date, completion status, and no-op guarantee.

AI Application

Require AI to write a 1-paragraph removal justification detailing what it did, when it ran, why added, and why safe to remove now.

Practical Method

The Archaeology Protocol

A two-phase method: investigate before touching code, then prompt with context AI can't see.

STEP 01 Read the Stratigraphy

Run git log to inspect every commit touching this code. A commit message with "fix: compensate for SDK bug" is crucial context.

git log -p --follow -- <path/to/file> && git blame <path/to/file>
STEP 02 Find the Incident Layer

Search history for ticket IDs, bug numbers, and phrases like "workaround", "hotfix", or "compensate".

git log --all --grep="JIRA-ID" --oneline && git log --all -S "functionName"
STEP 03 Ask AI to Explain, Not Change

Ask AI to describe what the code does and why it might exist before requesting any refactoring.

"Do not suggest changes yet. First: explain what this code does, when it runs, and what you hypothesize it was written to protect against."
STEP 04 Load the Archaeology Context

Supply AI with commit messages and PR descriptions so it can reason with institutional memory.

"Here is git history and PR description: [paste]. Given this context, re-evaluate whether the code flagged is safe to remove."
Comparison Matrix

Violations vs. The Archaeology Protocol

Scenario ❌ Violation ✅ Protocol
"This looks unused" Delete based on visual inspection Trace all call sites including dynamic & config-driven invocations first.
"AI said safe to remove" Trust AI without supplying history AI lacks incident history; supply git blame & PR context first.
"Old code is bad code" Assume 3-year-old code is obsolete Old fences guard old wounds (e.g. vendor SDK bugs without upstream fix).
"No unit test coverage" Delete because 0% test coverage Defensive error-path code is often untested because failure is hard to mock.
"Don't understand it" Delete what looks confusing Lack of understanding is the reason to investigate, not to delete.
"Cleanup sprint" Skip protocol for refactoring PRs Apply Archaeology Protocol regardless of sprint framing.
Incident Breakdown

The 500ms That Brought Down Payments

An AI assistant flagged await sleep(500); in processor.js as dead code. An engineer merged the cleanup PR.

Git Archaeology Trace:
$ git log -p --follow -- payment/processor.js | grep -B2 -A4 "sleep"
commit a3f9c2d (3 years ago) marcus.chen@company.com
"fix: add delay before processor.init() call"
+ await sleep(500); // SDK fires PAYMENT_READY before internal state ready. JIRA-2847
What Happened: Without the delay, 3% of payment transactions attempted to charge before the SDK token cache warmed up. The SDK silently accepted the call and failed downstream for 6 hours under load.
The Resolution: Restored the sleep, documented vendor ticket JIRA-2847 in code, and wrote an async SDK initialization mock test.
CHECKPOINT 03 Question 1 of 3 • Score: 0/3
INTERACTIVE EVALUATION
Chesterton's Fence Scenario
Loading question...
Status: ● Live Evaluation
SELECT ANSWER
05 / MODEL 04

Conway's Law

Your system architecture will mirror your organization's communication structures. Design your teams to produce the architecture you want.

Org Mirror

Architecture Follows Communication

Melvin Conway observed in 1967: organizations which design systems are constrained to produce designs which are copies of their communication structures. The Inverse Conway Maneuver flips this: structure teams first, then let architecture follow.

PRINCIPLE 01
Portrait of Your Org
Module boundaries follow team boundaries. You can't fix architectural coupling without fixing org communication.
Software Example

A monolith co-owned by 3 teams ends up with 3 tightly coupled modules mirroring the 3 team leaders' weekly sync meetings.

AI Application

Ask AI: "Given our 3 team boundaries [list], analyze where code coupling will naturally form if we generate microservices without re-assigning ownership."

PRINCIPLE 02
Seams Follow Ownership
Shared ownership between teams creates fragile, over-specified APIs. Ambiguous ownership causes architectural debt.
Software Example

Two teams both maintain the Payments service because "it's too big for one team." Every schema change requires cross-team sprint alignment.

AI Application

Prompt AI: "Identify all files in this repository where commits originate from more than one team. Suggest domain split boundaries."

PRINCIPLE 03
The Inverse Conway Maneuver
Organize autonomous teams around intended domain boundaries first. Service isolation follows naturally.
Software Example

Assign Team A to own Payments end-to-end (schema, API, deploys, on-call). Team B treats Payments as an external API dependency.

AI Application

Ask AI: "We want to move to architecture X. How should we restructure team ownership of domains BEFORE we refactor code?"

PRINCIPLE 04
AI Accelerates Existing Patterns
AI tools amplify whoever holds the keyboard. Misaligned teams + AI acceleration = architectural debt at 10x speed.
Software Example

Deploying AI org-wide in siloed teams accelerates local hacks and cross-service dependencies at machine speed.

AI Application

Scope AI prompt contexts per team domain: "You work strictly within the Payments team domain. Do not generate direct calls to Fulfillment internals."

PRINCIPLE 05
Team Interfaces Are APIs
Every sync meeting is a tight coupling. Independent deploy pipelines reflect clean team interface boundaries.
Software Example

A platform team running on tickets creates synchronous bottlenecks. A platform providing self-service APIs decouples team velocity.

AI Application

Tell AI: "Design this platform capability as a self-service SDK with clear SLAs so consuming product teams require zero ticket coordination."

Practical Method

The Inverse Conway AI Workflow

A 4-step workflow to align team structure before generating modular code with AI.

STEP 01 Map the Org Mirror

Overlay your actual team communication map onto code repositories to expose hidden shared ownership.

"Here are our team structures: [teams]. Analyze our service list [services] and map where shared ownership causes deploy coordination."
STEP 02 Reshape Ownership First

Assign single-team ownership to each business domain before writing or splitting a single line of code.

"We are reassigning domain [NAME] to Team [X] end-to-end. What API contracts must Team [X] publish for other teams to consume asynchronously?"
STEP 03 Enforce API Seams

Treat internal cross-team calls with the same rigor as external 3rd-party vendor APIs.

"Generate an API contract for domain [NAME]. Ensure no internal DB schemas or private state leaks across team boundaries."
STEP 04 Apply the AI Maneuver

Scope AI prompt execution context per team domain to reinforce clean architecture boundaries.

"You are working within Team [NAME] domain. Owned services: [list]. External allowed APIs: [list]. Generate code respecting these boundaries."
Comparison Matrix

How Teams Fight Conway's Law

Scenario ❌ Anti-Pattern ✅ Conway-Aware Approach
Microservices Migration Design architecture diagram first; force existing teams to own slices Structure autonomous teams around business domains first; service boundaries follow.
Shared Service Ownership Two teams maintain 1 monolith because "it's too big for one team" Single team owns domain end-to-end (schema, API, deploy, on-call).
AI Rollout Strategy Deploy AI org-wide without restructuring; accelerates siloed coupling Restructure teams first, then scope AI prompt context per team domain.
Platform Team Model Central platform team running on a ticket queue Platform team provides self-service products with documented SLAs and APIs.
Case Study

The Checkout Rewrite That Wasn't

3 teams (Payments, Fulfillment, UI) co-owned a checkout monolith. A 6-month microservice rewrite failed because communication patterns never changed.

The Diagnosis: Teams drew service boundaries on whiteboards without changing ownership. Payments still consulted Fulfillment before changing state logic.
The Maneuver: Eng director paused code split and split ownership: Payments owns payment intent end-to-end; Fulfillment owns order lifecycle; Checkout owns UI orchestration.
The Result: Over 1 quarter, independent teams naturally produced clean API boundaries. AI assistants scoped per team domain accelerated velocity without cross-coupling.
CHECKPOINT 04 Question 1 of 3 • Score: 0/3
INTERACTIVE EVALUATION
Conway's Law Scenario
Loading question...
Status: ● Live Evaluation
SELECT ANSWER
06 / MODEL 05

Inversion Thinking

Solve hard problems by thinking backward. Instead of asking how to achieve success, figure out how to cause catastrophic failure — and systematically eliminate those failure modes.

Backward Reasoning

Invert, Always Invert

Inversion is the practice of solving problems by reversing the direction of your thinking. Popularized by mathematician Carl Jacobi ("Invert, immer invertieren") and investor Charlie Munger, inversion forces you to ask: "What would make this system fail horribly?" before asking how to make it succeed.

"Invert, always invert: Turn a problem upside down. Think about what you want to avoid, not just what you want to achieve." — Carl Jacobi & Charlie Munger
PRINCIPLE 01
Invert, Always Invert
Reframe every engineering goal into its opposite failure mode. Prevent the worst outcome before chasing the best.
Software Example

Instead of asking "How do we scale write throughput?", ask "What conditions will crash our database during peak write traffic?"

AI Application

Ask AI: "List 5 ways this architecture could catastrophically fail under heavy concurrency or network partition before offering solutions."

PRINCIPLE 02
Run Premortem Analyses
Assume your feature has failed 6 months in the future. Work backward to uncover hidden assumptions and risks while they are cheap to fix.
Software Example

Before launching a microservice migration, assume high latency and data out-of-sync outages occurred. Map out why.

AI Application

Prompt AI: "Act as a postmortem lead for a major outage 6 months from now. What subtle bug or resource exhaustion broke this system?"

PRINCIPLE 03
Define Anti-Goals & Non-Requirements
Explicitly state what the system must never do before specifying what it should do.
Software Example

"Anti-goal: The background billing worker must NEVER process the same charge event twice, even if the message queue redelivers."

AI Application

Provide AI with explicit guardrails: "Requirement: Process webhook. Anti-Goal: Never block the main web thread or leak raw API keys in logs."

PRINCIPLE 04
Negative Space Testing
Test for unintended side effects, resource leaks, and invalid state transitions rather than just happy-path inputs.
Software Example

Unit test what happens when a database connection drops mid-transaction or when payload keys are missing.

AI Application

Ask AI: "Generate edge-case tests specifically targeting negative space: null pointers, rate-limit hits, and unexpected connection drops."

PRINCIPLE 05
AI Red-Teaming & Adversarial Prompting
Use AI as an aggressive adversary to poke holes in your specs, security assumptions, and concurrency models.
Software Example

Feed your draft architecture spec to AI and ask it to play the role of an attacker or Chaos Engineering agent.

AI Application

Prompt: "Roleplay as a malicious caller or chaotic network condition trying to break this service. Where are my blind spots?"

Practical Method

The Premortem & Inversion AI Workflow

A 4-step workflow to uncover critical failure modes before generating implementation code.

STEP 01 Frame the Premortem

Assume the feature has failed catastrophically in production and prompt AI to diagnose the top causes.

"Assume this feature failed in production 6 months from now. List the top 5 technical failure modes that caused the outage."
STEP 02 Extract Non-Negotiable Anti-Goals

Define explicit negative constraints that the implementation must never violate under any circumstances.

"Define 3 non-negotiable anti-goals for this system: what state or behavior must this code NEVER allow, even under network failure?"
STEP 03 Red-Team System Assumptions

Ask AI to play an adversarial chaos engineer to exploit race conditions and resource leaks.

"Act as a chaos engineer. Expose 5 edge cases or race conditions where this state transition model breaks."
STEP 04 Build Inverted Safety Guards

Generate defensive guards, rate limiters, circuit breakers, and fallback mechanisms first.

"Generate defensive guards and circuit breakers for each identified failure mode before writing main domain logic."
Comparison Matrix

Forward-Only vs. Inversion Thinking

Scenario ❌ Forward-Only Thinking ✅ Inversion Thinking
Feature Launch Focus only on happy-path user flows and expected load targets Run a premortem to identify silent failure modes and data corruption risks beforehand.
Background Queue Optimize for processing speed and batch size Design dead-letter queues, idempotent retry guards, and backpressure limits first.
Security & Auth Add basic token verification and consider it done Actively red-team the flow: token replay, clock skew, and expired session race conditions.
AI Code Generation Ask AI for the optimal implementation immediately Ask AI to list 5 ways its proposed code will break under extreme edge cases first.
Case Study

The Silent Queue Outage Avoided

A high-growth team designed a background processing worker. An unexpected upstream API outage triggered an infinite retry loop that crashed primary database connections.

The Diagnosis: Forward-only planning focused on batch processing throughput, ignoring what happens when worker retries pile up indefinitely.
The Maneuver: Eng lead ran an Inversion Audit. They defined the anti-goal: "Queue failures must NEVER cascade into the primary application database."
The Result: Added exponential backoff, dead-letter queues, and isolated pool limits. When the upstream API failed next, background jobs safely paused without taking down the web app.
CHECKPOINT 05 Question 1 of 3 • Score: 0/3
INTERACTIVE EVALUATION
Inversion Thinking Scenario
Loading question...
Status: ● Live Evaluation
SELECT ANSWER
07 / MODEL 06

Hyrum's Law

Every observable behavior of your system will be depended on by somebody. API contracts are defined by real-world behavior, not written documentation.

API Evolution

Implicit Contracts Rule Production

Formulated by Google engineer Hyrum Wright: "With a sufficient number of users of an API, it does not matter what you specify on the contract: all observable behaviors of your system will be depended on by somebody." Response ordering, timing, error message text, and side effects become de facto APIs.

"With a sufficient number of users of an API, it does not matter what you specify on the contract: all observable behaviors of your system will be depended on by somebody." — Hyrum Wright, Software Engineer
PRINCIPLE 01
Observable Behavior Is the Real Contract
Users don't just read your API docs; they inspect network payloads, measure latency, and rely on accidental side effects.
Software Example

Callers rely on a database query returning items in insertion order, even though ORDER BY was omitted in the SQL query.

AI Application

Ask AI: "What implicit behaviors (key order, default sorts, execution timing) does this endpoint expose that callers might depend on?"

PRINCIPLE 02
Scale Multiplies Implicit Dependencies
The larger your caller base, the higher the probability someone relies on undocumented behavior.
Software Example

A minor internal change (sorting JSON keys alphabetically) breaks 12 downstream client apps that regex-parsed raw HTTP response bodies.

AI Application

Prompt AI: "Analyze this proposed API refactor for breaking changes against both explicit contracts AND implicit caller assumptions."

PRINCIPLE 03
AI Callers Maximize Hyrum Risk
AI agents and generated scripts often parse APIs non-standardly (e.g. scraping raw response strings or inferring status code order).
Software Example

AI-generated client code parses exact error message strings instead of checking standard HTTP status or error code fields.

AI Application

Instruct AI callers: "Rely ONLY on explicit schema properties. Do not parse error message strings or rely on key ordering."

PRINCIPLE 04
Defend Against Implicit Dependencies
Actively scramble non-deterministic outputs in dev/test to prevent callers from coupling to internal implementation details.
Software Example

Shuffle JSON key ordering or randomize array return order when no explicit sort key was requested by the caller.

AI Application

Ask AI: "How can we introduce intentional variability in dev/test environments to prevent callers from relying on implementation quirks?"

PRINCIPLE 05
Manage Breaking Changes Realistically
True backwards compatibility requires managing observable behavior changes through deprecation cycles and telemetry.
Software Example

Log telemetry on client user-agent patterns and request payload shapes before removing deprecated fields or changing response formats.

AI Application

Ask AI: "Design a backwards-compatible migration plan for updating endpoint X without breaking legacy callers."

Practical Method

The Hyrum Risk Audit AI Workflow

A 4-step workflow to audit API dependencies and prevent fragile client coupling.

STEP 01 Audit Implicit Behaviors

Identify non-contract behaviors (key order, error text, response timing) exposed by your API endpoints.

"Identify all non-contract observable behaviors (ordering, timing, un-documented fields) exposed by endpoint [URL]."
STEP 02 Detect Brittle Client Parsing

Scan client code or AI-generated callers for regex matching, string scraping, or implicit sort assumptions.

"Scan caller repository [REPO] for brittle API usage: regex parsing of JSON, string matching on error text, or missing sort parameters."
STEP 03 Introduce Chaos Validation

Add dev/staging middleware that randomizes unpromised ordering and key positions to catch implicit reliance early.

"Generate a dev/staging middleware that scrambles JSON key ordering and array results when explicit sorting is not requested."
STEP 04 Version & Deprecate Safely

Use versioning wrappers and deprecation telemetry when updating observable system behavior.

"Generate a versioning wrapper for API [NAME] that preserves legacy observable behavior while exposing clean v2 contracts."
Comparison Matrix

Naive Assumptions vs. Hyrum-Aware API Design

Scenario ❌ Naive Contract Assumption ✅ Hyrum-Aware API Design
Changing JSON Field Order "JSON specs say key order is undefined, so changing it is completely safe" Recognize callers may parse raw text; scramble key order in dev early to enforce real JSON parsing.
Database Query Refactor "I didn't change schema fields, only the underlying SQL execution plan" Un-ordered SQL returns non-deterministic rows; add explicit ORDER BY to guarantee contract stability.
Error Response Formatting Change error string formatting assuming clients check standard HTTP status code Preserve machine-readable error codes; document exact error schemas and telemetry.
AI API Integration Assume LLM clients parse APIs strictly according to OpenAPI schema specs Fuzz endpoints and validate against brittle regex/string parsing patterns common in LLM scripts.
Case Study

The Hash Order Incident

An infra team upgraded their backend runtime, which randomized hash map key iteration order. 14 microservices crashed because client apps assumed deterministic JSON key ordering.

The Diagnosis: Downstream callers parsed HTTP response text directly with regular expressions, depending on accidental key ordering.
The Maneuver: The team recognized Hyrum's Law. Instead of freezing runtime upgrades, they enforced explicit key sorting in API encoders and added key-shuffling in staging.
The Result: Staging environments now surface implicit key-order dependencies before production release. Zero breaking API deployments since.
CHECKPOINT 06 Question 1 of 3 • Score: 0/3
INTERACTIVE EVALUATION
Hyrum's Law Scenario
Loading question...
Status: ● Live Evaluation
SELECT ANSWER
08 / PRACTICE & EVALUATION

Interactive Model Checkpoints

Test your engineering judgment directly within each model section or jump straight to a specific checkpoint below.

09 / REFERENCE

Socratic Prompt Cheatsheets

Copy-pasteable Socratic prompt templates to apply these models with AI assistants.

First Principles Prompt
Decompose requirements without assuming stack
"Decompose [FEATURE] into fundamental requirements. List 3 assumptions I'm making about scale, team, or stack, and what would change if they were false."
Occam's Razor Prompt
Strip speculative abstractions
"Give me the simplest architecture that meets ONLY today's requirements. What layers can we remove, and under what conditions would it break?"
Chesterton's Fence Prompt
Investigate defensive code before refactoring
"Here is git history for this file: [paste]. Before proposing changes, explain what this guard protects against and write a removal justification."
Inverse Conway Prompt
Align service boundaries with team ownership
"We are structuring around team [NAME] owning services [LIST]. Generate code that respects these ownership boundaries without cross-team coupling."
Inversion & Premortem Prompt
Uncover subtle failure modes before building
"Assume [FEATURE/SYSTEM] failed catastrophically in production 6 months from now. List the top 5 technical root causes and define 3 anti-goals to prevent them."
Hyrum Risk Audit Prompt
Audit APIs for implicit behavioral dependencies
"Analyze API endpoint [ENDPOINT/SCHEMA] for non-contract observable behaviors (key ordering, error text format, response timing) that caller SDKs or AI clients might rely on."
Interactive Challenge

Model Quiz

Question 1 of 3 • Score: 0
Question text goes here...