system-design
- Run by agents
- spec-writer
- Reached from commands
- /builder-os:bos-shape
At a glance
Mode. Standalone returns the architecture, the failure plan, the scale defaults and the threat model for the supplied product or feature, in the requested format. In the lifecycle it runs in phase 4 after domain-model and the stack (the entities and the chosen layers are its inputs) and before the acceptance criteria are final; it writes SPEC.md → ## Architecture and ## Threat model and the criteria they cite, gates 4.18 and 4.19 check them, and phase 5 reviews the diff against the threat model (5.13) and measures the performance budget (5.14). Both per operating modes. Read the system method for the templates, the failure defaults, the scale defaults with their reasons, the threat catalogue and a worked example.
- 1Read the inputs
- 2Set the scope of the design
- 3Draw the components
- 4Write the contracts
- 5Plan every external call for failure
- 6Apply the scale defaults
- 7Model the threats
- 8Put the trade-offs to the person
- 9Record
The skill
Two modes. Stack chooses what the product is built with, a card per open layer in plain language and ADRs for the hard-to-reverse ones: follow stack decisions, with its own marker. Architecture, the procedure below, decides how it fits together, how it fails, how it grows and who could break it. Left to the build, the architecture is whatever the first slice needed, every external call waits as long as its library's default, and another customer's data is one missing filter away. A tier-1 engineer writes this down before the code, on a page the next engineer reads in five minutes.
Mode. Standalone returns the architecture, the failure plan, the scale defaults and the threat model for the supplied product or feature, in the requested format. In the lifecycle it runs in phase 4 after domain-model and the stack (the entities and the chosen layers are its inputs) and before the acceptance criteria are final; it writes SPEC.md → ## Architecture and ## Threat model and the criteria they cite, gates 4.18 and 4.19 check them, and phase 5 reviews the diff against the threat model (5.13) and measures the performance budget (5.14). Both per operating modes. Read the system method for the templates, the failure defaults, the scale defaults with their reasons, the threat catalogue and a worked example.
Procedure
- Read the inputs. The domain model and data sketch in
SPEC.md→ Design, the spec's## Stackand flows,TECH.md(Stack, Map, Technical constraints, Operations),PRODUCT.md→## Businessfor the stage and the expected users, and the code whererepo.readresolved: routes, schema, indexes, middleware, how secrets are read. Done when you can say what exists, what this work adds, and how many users and records the stage expects. - Set the scope of the design. Work with no server, no stored data and no input written by other people (copy, a static page, a style change) writes
**Architecture:** not applicable, {reason}and**Threat model:** not applicable, {reason}and stops here. A feature on an existing system designs what it adds or strains and names the rest as inherited. Done when what is designed and what is inherited are both named. - Draw the components. Each component this work creates or changes (a service, a worker, a scheduled job, a database, a queue, a third-party service): its responsibility, the entities it owns, what it talks to and by which mechanism (a call, an event, a shared table). Each entity has one owning component. State lives in the database or a cache, so any server can answer any request. Work slower than the latency budget (an export, a batch of emails, a third-party call per row) runs as a background job whose status the user can see. Done when every entity in the domain model has one owner and every arrow names its mechanism.
- Write the contracts. Every interface this work exposes or another party calls (an endpoint, a webhook, an event, an export): input and output shapes, errors in one format with a code the client can act on and no internal detail, a page size and cursor on every list, and a version once a customer or another team consumes it. Done when each contract has shapes, errors and, for a list, its paging.
- Plan every external call for failure. Every call that leaves the process (a third-party API, the model provider, email, payments, another service): a timeout in seconds; retries with backoff only where repeating is safe; an idempotency key on every write that can be retried (a charge, an order, a message); what the user sees when it fails. Done when every external call has its timeout, retry rule, idempotency and failure behavior.
- Apply the scale defaults. Six choices that cost little now and a rewrite later, each written as how this design does it or why it does not apply: an owner key on every row and in every query; paginated lists; an index behind every query the flows run; idempotent writes wherever a retry can happen; slow work off the request; reversible migrations (expand, migrate, contract). They hold at every stage and are not scale work: gate 4.15 rejects building for load nobody has, and these keep the door open without building it. Then
**Capacity:**: the expected load at this stage from## Business(users, peak requests per minute, rows after a year), tagged, and the design target at ten times that. Done when all six defaults have a how or a reason and the capacity has numbers. - Model the threats. Name the trust boundaries (browser to server, webhooks and uploads coming in, server to database, admin tools, the model's inputs). Per boundary, the threats from the method's catalogue that apply, each with a mitigation and the acceptance criterion that tests it. Four always get a row: another user's or customer's data, tested by a request for a record the caller may not see, which fails; untrusted input, validated at the boundary with parameterized queries and encoded output; abuse, with rate limits on sign-in, sign-up and every expensive or paid endpoint; secrets, kept in the host's secret store, read on the server, with how they rotate. With model output, the injection surfaces from
agent-designare this table's model boundary, referenced by name. Done when every row has a mitigation and a criterion that exists, or the reason it does not apply. - Put the trade-offs to the person. A choice with a real cost on both sides (synchronous or background, one database or two, a rate limit that could block a real customer, where the data lives) is a
pressure-testinground question with a recommendation in plain words: what it costs, what it protects, what undoing it takes. A choice with one sound answer is written, not asked. Done when every trade-off has the person's answer. - Record. Write
## Architectureand## Threat modelinSPEC.mdper the method's template; add the criteria they cite to## Acceptance criteria, where phase 5 maps a test to each; make sure the performance row of## Quality barcarries a budget with a number for the primary action, which gate 5.14 measures; add one line per decided trade-off to## What we chose. At ship, components and contracts that outlive the initiative go intoTECH.md→ Map. Done when gates 4.18 and 4.19 pass on the file.
Watch for
| Do | Instead of |
|---|---|
| One owner per entity, a mechanism on every arrow | Boxes joined by unlabeled lines |
| A timeout and a failure behavior on every external call | The library default, which may wait for minutes |
| An idempotency key on every retried write | A double charge on the first network blip |
| The scale defaults now, the load test after PMF | Sharding for ten users, or a table with no owner key |
| Every access rule tested by a request that has to fail | "Users only see their own data" with no test behind it |
| Rate limits on sign-in, sign-up and every paid call | Learning about abuse from the invoice |
| Secrets in the host's secret store, read on the server | A key in the client bundle or the repository |
Capabilities
| Capability | Used for | Floor if absent |
|---|---|---|
repo.read | Current components, routes, schema, indexes, middleware, secrets handling | Ask the person; mark the architecture as designed without code access |
db.query | Real table sizes, slow queries, missing indexes, rows with no owner key | Estimate from ## Business, tagged as an estimate |
logs.query | Current latency, error rates and traffic peaks | Set the budget and capacity from the stage, marked unmeasured |
web.search | Provider limits, default timeouts, security advisories | State them as unverified with the page to check |
files.read / files.write | The spec, SPEC.md → Design, TECH.md | Inline answers need no write; lifecycle writes require it |
Output Contract
## SYSTEM DESIGNED with the components and what each owns, the contracts, every external call with its timeout, retry, idempotency and failure behavior, the six scale defaults, the capacity, the trust boundaries with every threat's mitigation and criterion, and the trade-offs the person decided. The lifecycle artifact is SPEC.md → ## Architecture and ## Threat model; gates 4.18 and 4.19 parse their subsections, tables and bold labels.
References
Read only when a step needs them, so they cost no context until then.
Stack Decisionsreferences/stack-decisions.md
The stack is a product decision with technical consequences: what the product costs to run, how fast it ships, who can maintain it, what changing course costs. An agent that picks it silently while building has made the person's most durable decision without them. This mode turns every open layer into a choice the person makes knowingly, as an informed owner rather than a tech lead: what we pick, why, what it costs, the alternatives, and what would make us switch.
Mode. Standalone answers the stack question for the supplied product or feature with the same decision cards. In the lifecycle it runs inside phase 4 after the flows and before the acceptance criteria, writes TECH.md → Stack, the spec's ## Stack and an ADR per hard-to-reverse choice, and gate 4.8 checks the result. Both per operating modes. Read the stack method for the layer catalogue, the decision card, the plain-language rules and worked examples.
Procedure
- Read the inputs.
PRODUCT.mdconstraints (budget, team, regulation, distribution),TECH.md, the bet's primary action, the flows and the data sketch inSPEC.md→ Design (the shape of the data drives the data layer), and the repository whererepo.readresolved: a manifest is a fact, a memory of the stack is a guess. On the build track also readBRIEF.md→ Bet →## Feature map: every feature chosen as integrate or buy is a service this stack must call, its candidates already compared; a layer card weighs real alternatives too, never only the first tool suggested. Done when you can say what exists and what this work asks of it. - List the layers this work touches from the catalogue, each inherited (exists, and nothing in this work strains it), open (missing, or strained by this work) or not needed (with the reason); a product for sale always needs payments and tax (gate 4.14). An inherited layer stays unless a driver breaks it, and reopening one is itself an open question. Done when every catalogue layer this work could touch has a status.
- Name the decision drivers before any option: three to five properties of this product that decide between technologies, in plain words, each traced to
PRODUCT.md,TECH.md, the spec or the person ("one person maintains it", "data stays in the EU", "under €50 a month until 100 customers", "the pilot ships in two weeks"). A driver nothing supports goes in the first round. Done when every driver has its source. - Write a decision card per open layer. Two to four real options, the boring default always among them and, where credible, the managed service, the do-it-later and the reuse-what-we-have. Per option: what it is in one plain sentence; what it gives this product; what it costs (money, tagged or flagged unverified; time; operational load); lock-in, meaning what leaving later would take; what would make us switch. Then the recommendation and the driver that decides it. Volatile facts (prices, limits, licences, deprecations) come from
web.searchwith a tag, or stay flagged. Done when every open layer has a card judged against the drivers. - Speak to the owner. Every technical term gets a one-line gloss the first time ("a managed Postgres: a database someone else runs and backs up"); every consequence is stated in product terms: money, speed, who can maintain it, what breaks if it was the wrong call, how hard it is to undo. Done when the person could defend each option's trade-off to someone else.
- Decide in rounds per
pressure-testing. Layers that constrain others go first (usually backend and data, then hosting and auth, then the rest); a dependent question waits for the next round. The design kit depends on the frontend and is asked byux-architecture(direction) once that is settled. A load-bearing unknown (can this provider meet the latency, does this library support the auth flow) becomes a timeboxed spike with its cost in hours, or a recorded risk. Done when every open layer has the person's choice. - Record. Each decided layer goes into
TECH.md→ Stack (Layer, Choice, Why, Decision). A choice that is hard to reverse, surprising without context and a real trade-off (data store, backend runtime, hosting, auth, model provider, usually) gets an ADR indecisions/with the options, the drivers and aRevisit when. In the lifecycle write the spec's## Stackper the Output Contract.TECH.md→ Verified moves only after a check against the repository. Done when the table,TECH.mdand every ADR agree. - Summarize for acceptance. Each decided layer gets a line in the spec's
## What we chose: what, why, the alternative set aside, the cost, what would make us change it. Done when every decided layer has its line. - Hand off. The build plan reads the decided stack and adds nothing at the level of a layer. A structural addition found mid-build (a framework, a database, a hosted service, a paid API, a runtime) pauses the slice and returns here as a card; plan and
TECH.mdare updated before it resumes. A utility library is the build's call, listed in the review with its reason. Done when the build plan names the stack it uses.
Watch for
| Do | Instead of |
|---|---|
| Decide open layers here, before the plan | Picking the stack while scaffolding the first slice |
| Two to four options, the boring default among them | One option with a paragraph of praise |
| Judge against the named drivers | Comparing features and popularity |
| Search a price with a tag, or flag it with the page to check | A price or free-tier limit from memory |
| Gloss every term; consequences in money, speed, maintenance and undo cost | Jargon the owner cannot repeat |
| Keep inherited layers unless a driver breaks them | Reopening every layer, turning a feature into a rewrite |
Capabilities
| Capability | Used for | Floor if absent |
|---|---|---|
repo.read | What already exists: manifests, lockfiles, config, deploy files | Ask the person what exists; mark every inherited layer unverified |
web.search / web.fetch | Current pricing, free-tier limits, licensing, regional hosting, maintenance status of each option | State each such fact as [assumption:unvalidated] with the page that would settle it and the date to check by; a price from memory is a guess, labeled so |
docs.search | Earlier ADRs, team conventions, the person's past stack choices | Ask |
subagent.dispatch | A timeboxed technical spike on a load-bearing unknown | Run the spike inline, or defer it as a named test |
files.read / files.write | TECH.md, PRODUCT.md, the spec, ADRs | Inline answers need no write; lifecycle writes require it |
No capability beyond files is required. Without search the cards still compare options on structure (lock-in, operational load, fit to the drivers); only the volatile facts become stated gaps.
Output Contract
## STACK DECIDED with the layer table (inherited, decided, not needed), the drivers, who decided each open layer, the ADRs written and any spike or deferred risk.
Lifecycle: TECH.md → Stack updated, ADRs in .builderos/decisions/, and in SPEC.md:
## Stack
**Drivers:** {three to five, each with its source}
| Layer | Choice | Status | Decided by | ADR |
|-------|--------|--------|------------|-----|
| {layer} | {choice} | inherited / decided / not needed | {person, or "-" when inherited or not needed} | {decisions/ADR-NNN-slug.md, or "-"} |Gate 4.8 parses this table: every row has a status, every decided row names who decided it, every ADR it links exists, and ## What we chose is present. Standalone output is the decision cards and the recommendation, in the requested format.
Stack Methodreferences/stack-method.md
The catalogue, the card and the example behind system-design (stack). Read the section the current step needs. Every product name below is an example of a kind of option, never a default or a requirement.
Layer Catalogue
List only the layers this work touches. A small feature on an existing product usually touches one or two; a new product touches most of the first six.
| Layer | The question it answers | What usually drives it | Typical option kinds (examples only) |
|---|---|---|---|
| Interface | Where the user meets the product: web app, mobile, desktop, chat channel, API only | Where the ICP already works; offline needs; distribution | Server-rendered web (Next.js, Rails views), single-page app, native or cross-platform mobile, a messaging channel, no UI |
| Backend / API | Where the logic runs and in what language | Who maintains it; existing team skills; latency; long-running work | Full-stack framework in one repo, a separate API service, backend-as-a-service (Supabase, Firebase), serverless functions |
| Data | Where state lives and how it is queried | Shape of the data (relational, documents, files, vectors); consistency; residency | Managed relational database, document store, object storage, vector index, a spreadsheet for a concierge pilot |
| Auth | Who the user is and what they may see | B2B vs B2C; SSO demands; tenancy; compliance | Built into the backend service, a dedicated identity provider, magic links, none for an internal pilot |
| Hosting / runtime | Where it runs and who keeps it up; whether it gives every change a preview link | Operational load the team can carry; region; cost curve; previews per pull request (release-ops (production) uses them for gate 5.17) | Platform-as-a-service (Vercel, Render, Fly), a cloud provider directly, the user's own servers |
| Background work | Jobs, schedules, queues, retries | Anything slower than a request, anything scheduled | Cron on the host, a managed queue, a workflow engine, a database-backed job table |
| Model / AI | Which model provider and how it is called | Quality on the eval set; latency; cost per call; data handling terms | A hosted model API, an open model on managed inference, no model (rules first) |
| Integrations | Email, payments, messaging, the ICP's existing tools | What the flows send or receive (SPEC.md → Design → Messages); business messaging channels need approved templates | Transactional email service, payment processor, the tool's own API, a manual export for the pilot |
| Payments and tax | How the product takes money, and who issues invoices and handles VAT | Product for sale (PRODUCT.md → Revenue model); where customers are; who does the admin. Gate 4.14 wants this row on a product for sale | A merchant of record (sells on your behalf, handles VAT and invoices in every country, higher fee per sale); a payment processor plus your own invoicing (lower fee; in Italy, e-invoices through SdI for Italian customers, and VAT where an EU consumer lives through OSS, usually with an accountant); manual invoices for the first ten customers. Tax facts are verified with an accountant, never decided from the card |
| Analytics | How the phase 2 metric gets measured | The tracking plan; references/analytics-contract.md | An existing provider, events in the product database, none until the pilot |
| Design kit | The component library and tokens | Decided by ux-architecture (direction), after the interface and frontend are settled | : |
Not needed is an answer. A pilot that a person runs by hand needs no queue. Write the reason, so nobody adds one "for later".
Decision Drivers
A driver is a property of this product that would make one option right and another wrong. Good drivers are specific and checkable; "scalable" and "modern" are not drivers.
| Weak | Driver |
|---|---|
| Scalable | 200 customers in year one [doc:…]; nothing here needs more than one database |
| Cheap | Under €50 a month until revenue, from the budget in PRODUCT.md |
| Fast to build | The pilot ships by {date}; one person builds it |
| Secure | Customer call recordings: EU residency and deletion on request [doc:…] |
| Easy to maintain | Mario maintains it alone, in TypeScript, with an agent |
Three to five drivers. If two options tie on every driver, the more reversible one wins, and the card says so.
The Decision Card
One card per open layer, written for the owner:
❓ **Q{n} · {Layer}**: {the question in plain words}
Drivers that decide it: {the two or three that matter here}.
- **A. {option}** ({one-line gloss}): gives {what it gives this product}. Costs {money with tag or "unverified, check {page} by {date}"}, {time}, {operational load}. Leaving it later: {what that would take}. We'd switch if {condition}.
- **B. {option}** (…): …
- **C. {option}** (…): …
➡️ **{X}**: {the deciding driver, with its source}.Rules for the card:
- The boring default is always an option. The most common, best-documented choice for this kind of product is the baseline every other option has to beat.
- Consequences in product terms. Money per month at the expected scale, days to the first slice, who can fix it at 2 a.m., what it takes to undo.
- Gloss every term once. "Serverless functions: code that runs only when called, so you pay per request and there is no server to keep up." If the gloss takes more than a line, the option is probably wrong for an owner who is not an engineer.
- Lock-in is a number or a sentence, not a feeling. "Leaving means rewriting the 12 database queries and the auth flow, about a week" beats "some lock-in".
- Volatile facts carry a tag or a flag. Prices, free-tier limits, rate limits, licences and maintenance status change; search them, or say they are unverified.
Worked Example
A solo builder, a B2B tool for agencies, phase 4 of a new product; the pilot is five agencies for four weeks; PRODUCT.md says EU customers and a budget of a few hundred euros a month until revenue.
Drivers: one person maintains it in TypeScript [doc:user-2026-10-20-team]; EU data residency [doc:user-2026-10-20-customers]; pilot live in three weeks [doc:…].
Round 1 (backend and data constrain everything else, so they go first):
❓ **Q1 · Backend and data**: where does the logic run and where does the data live?
Drivers that decide it: one maintainer, EU residency, three weeks.
- **A. Full-stack web framework + managed Postgres** (one codebase for pages and API; a database someone else runs and backs up): one repo, one language, the most documented path. Costs a small monthly fee for the database, unverified, check the provider's EU pricing page before acceptance. Leaving later: move the database with a dump; the framework stays. We'd switch if background jobs grow past what the host allows.
- **B. Backend-as-a-service** (database, auth and storage as one hosted product): the fastest first slice; auth comes included. Costs a free tier then a monthly plan, unverified. Leaving later: auth and storage are its own, so about a week to rewrite them. We'd switch if pricing or residency change.
- **C. Separate API service + database** (the backend as its own program): clean separation, more to run. Costs a second deployment and twice the setup. Leaving later: easy. Only worth it if another client (mobile, partners) will call the API this year, which nothing in PRODUCT.md says.
➡️ **B**: it covers data and auth in one EU-hosted service and the three-week driver dominates; A is the fallback if its residency option is not confirmed.Round 2 then asks hosting, background work and the model provider, which depend on the answer; the design kit goes to ux-architecture (direction) once the interface layer is settled.
Recorded: TECH.md → Stack gains the rows; decisions/ADR-004-backend-and-data.md holds the card, the drivers, "chosen by Mario, 2026-10-20" and Revisit when: the pilot ends, or monthly cost passes €200; SPEC.md → Stack lists every layer with its status.
Spikes
A spike is a timeboxed proof that answers one load-bearing unknown before a layer is chosen: "can the voice provider return a first token under 500 ms from the EU", "does the backend service support SAML for the two enterprise pilots". It has a question, a timebox in hours, a pass condition and a throwaway location. Its result goes into the card as a tagged fact. A spike that grows past its timebox becomes the answer "unknown", recorded as a risk with an owner.
Feature Track
On an existing product almost every layer is inherited. Read them from the repository, write them as inherited, and ask only about what this feature adds: a new integration, a queue, a model provider. A feature that strains an inherited layer (the database cannot hold the new volume, the host has no scheduled jobs) reopens that layer with a card, and the reason is a driver, not a preference.
System Methodreferences/system-method.md
The templates, defaults and catalogue behind system-design. Product and vendor names are examples of a kind of option, never defaults.
Components
A component is something that runs or stores on its own: a web server, a worker, a scheduled job, a database, a cache, a queue, a third-party service. A module inside one process is a seam (delivery-discipline), not a component.
- One owner per entity. The component that owns an entity is the only one that writes it. Another component that needs it asks the owner or reads a copy it is told about; two writers to one table is a race waiting for traffic.
- The mechanism on every arrow. A synchronous call (the caller waits, so it shares the caller's latency budget and its failures), an event or a queue (the caller moves on, so the work needs a status and a retry), or a shared table (the cheapest and the most coupled; acceptable inside one service).
- No state in a server's memory. Sessions, carts, progress and caches live in the database or a shared cache, so a second server, a restart or a deploy loses nothing.
- Slow work off the request. Anything that can exceed the latency budget runs as a job: the request records it and returns, the user sees its status, a failure is retried by the job runner and lands somewhere a person sees after the last retry.
Contracts
- Errors. One shape across the product (
{ "error": { "code": "report_not_found", "message": "…" } }), a code the client can branch on, a status that matches, and no stack trace, query or internal identifier in the body. - Lists. Every list endpoint takes a page size with a ceiling and returns a cursor. An unpaginated list works with ten rows and times out with ten thousand.
- Validation. Input is checked against a schema at the boundary; unknown fields are rejected or dropped by rule, not by accident.
- Versions. Once a customer, a mobile app or another team consumes a contract, a breaking change ships as a new version beside the old one, with the date the old one goes away (gate 4.11, contracts).
External Calls
| Property | Default to start from |
|---|---|
| Timeout | Set explicitly on every call: a few seconds for an interactive call, longer for a job; the library default is often unbounded |
| Retry | Only where repeating is safe (reads, idempotent writes), with exponential backoff and jitter, at most 3 attempts in a request, more in a job |
| Idempotency | A key per logical operation (the order id, a client-generated request id) sent to providers that accept one, and stored so a repeated request returns the first result |
| Failure | What the user sees and what is kept: an error with a retry, a queued job with its status, or the product working without that part |
| Circuit | After repeated failures, stop calling for a while and serve the degraded behavior, so a provider outage does not become yours |
Scale Defaults
Each is cheap on day one and expensive to retrofit. They are what keeps a product able to grow; building for load nobody has (sharding, a cache layer, a second region, microservices) waits for PMF and a load test that says it is needed.
| Default | How | Why it is cheap now and expensive later |
|---|---|---|
| Owner key on every row | Every row carries the tenant, workspace or user it belongs to, and every query filters on it from the session, never from the request body | Adding it later means backfilling every table and auditing every query; missing it once is a data leak |
| Paginated lists | Cursor and page size on every list, in the API and the interface | Clients built on a full list break when the list is paginated |
| Indexed queries | An index for every filter and sort the flows run, checked against the query plan on realistic data | A missing index is invisible at 100 rows and an outage at 1 million |
| Idempotent writes | An idempotency key on every write a client, a job or a webhook can repeat | Duplicate charges, emails and records are expensive to clean up and to explain |
| Slow work off the request | A job runner for anything that can exceed the budget | Moving work to a job later changes the contract and the interface |
| Reversible migrations | Expand (add the new shape), migrate (backfill, dual write), contract (remove the old) as separate releases; each step can be rolled back | A destructive migration in one step leaves no way back when it goes wrong |
Capacity. Expected load at the current stage, from PRODUCT.md → ## Business or the logs: users, peak requests per minute on the primary action, rows in the largest table after a year. The design target is ten times that. A choice that only breaks above ten times is fine for now and recorded as such; a choice that breaks below it is redesigned. After PMF, gate 6.10 asks for **Load tested:** at that target.
Threat Catalogue
Per trust boundary, the threats that usually apply. The first four rows are always written; the rest where the product has the surface.
| Threat | Mitigation | Criterion that tests it |
|---|---|---|
| Another user's or customer's data (broken access control, the most common serious web flaw) | Authorization on the server for every read and write, from the session, scoped by the owner key; identifiers that cannot be enumerated where exposure matters | A request for a record of another workspace returns not-found, for every endpoint that takes an id |
| Untrusted input (injection, cross-site scripting, oversized or malformed payloads) | Schema validation at the boundary, parameterized queries, output encoding by the framework, upload type and size limits, a content security policy | A payload with markup or a query fragment is stored and shown as text; an upload over the limit is refused with a message |
| Abuse (credential stuffing, sign-up spam, scraping, running up paid calls) | Rate limits per account and per address on sign-in, sign-up, password reset and every endpoint that costs money; a spending cap on paid providers | The sixth failed sign-in in a minute is refused and logged |
| Secrets (keys in the client, in the repository, in logs) | The host's secret store, read on the server only; the secret scan in the guardrail (gate 5.10); rotation written down | The client bundle contains no provider key; the secret scan runs on every change |
| Session theft | Secure, http-only, same-site cookies; short sessions with refresh; re-authentication for sensitive changes | Changing the email asks for the password |
| Forged requests from another site | Same-site cookies plus a token on state-changing requests where cookies authenticate | A state-changing request from another origin is refused |
| Webhooks and callbacks | Signature verification, timestamp window, idempotent handling | An unsigned or replayed webhook is refused |
| Server-side requests to user-supplied URLs | An allow-list of hosts, no internal addresses | A URL pointing at an internal address is refused |
| Data exposure in errors and logs | Personal data and secrets redacted from logs and error bodies | The error for a failed payment shows no card data |
| Admin and support tools | Separate roles, every action logged with who | A support agent's view of a customer is recorded |
| Model inputs | The injection surfaces of agent-design (gate 4.16) | Their must-pass eval cases |
Mitigations that a machine can check go into the guardrail: the dependency audit, the secret scan and static analysis (gate 5.10). What a machine cannot check is a criterion with a test, and the security review in phase 5 (gate 5.13) reads the diff against this table.
Templates
## Architecture
### Components
| Component | Responsibility | Owns | Talks to |
|-----------|----------------|------|----------|
| {name} | {one line} | {entities} | {component: call / event / shared table} |
### Contracts
| Contract | Shapes | Errors | Lists |
|----------|--------|--------|-------|
| {endpoint, webhook, event, export} | {input → output} | {codes} | {page size and cursor, or "not a list"} |
### External calls
| Call | Timeout | Retry | Idempotency | When it fails |
|------|---------|-------|-------------|---------------|
| {provider: operation} | {seconds} | {attempts with backoff, or "none: not safe to repeat"} | {the key, or "read only"} | {what the user sees} |
{or one line: "none: nothing leaves the process"}
### Scale defaults
| Default | How | Not applicable because |
|---------|-----|------------------------|
| Owner key on every row | {} | {} |
| Paginated lists | {} | {} |
| Indexed queries | {} | {} |
| Idempotent writes | {} | {} |
| Slow work off the request | {} | {} |
| Reversible migrations | {} | {} |
**Capacity:** {expected load at this stage, tagged} · designed for {ten times that}
## Threat model
**Boundaries:** {each trust boundary, in one line}
| Boundary | Threat | Mitigation | Criterion |
|----------|--------|------------|-----------|
| {boundary} | {threat} | {mitigation} | {acceptance criterion number, or "not applicable, {reason}"} |Gate 4.18 checks the four subsections, a timeout with a number on every external call, all six defaults and a capacity with numbers. Gate 4.19 checks the boundaries, a row for each of the four standing threats, a mitigation on every row and a criterion that exists. Either section can be **Architecture:** not applicable, {reason} or **Threat model:** not applicable, {reason} when there is no server, no stored data and no input written by other people.
Worked Example
A B2B reporting tool: workspaces import ad-spend CSVs and share weekly reports. Stage pre-PMF, 40 workspaces expected this quarter.
## Architecture
### Components
| Component | Responsibility | Owns | Talks to |
|-----------|----------------|------|----------|
| Web app | Pages, sign-in, the report editor |: | API: call |
| API | Every read and write, authorization | Workspace, Report, Import | Postgres: shared table; Job runner: event |
| Job runner | Parses imports, renders PDFs, sends the weekly email | ImportRow | Postgres: shared table; Email provider: call |
| Postgres (managed) | All data, EU region |: |: |
### Contracts
| Contract | Shapes | Errors | Lists |
|----------|--------|--------|-------|
| GET /reports | workspace from session → reports | 401 unauthenticated | 50 per page, cursor |
| POST /imports | CSV up to 20 MB → import id and status | 413 too_large, 422 bad_columns | not a list |
### External calls
| Call | Timeout | Retry | Idempotency | When it fails |
|------|---------|-------|-------------|---------------|
| Email provider: send weekly report | 10 s | 5 attempts with backoff, in the job | report id + week | the report shows "email not sent, retry" |
### Scale defaults
| Default | How | Not applicable because |
|---------|-----|------------------------|
| Owner key on every row | workspace_id on every table, set from the session; a query helper adds the filter | |
| Paginated lists | cursor on /reports and /imports | |
| Indexed queries | (workspace_id, created_at) on reports and imports | |
| Idempotent writes | import keyed by file hash per workspace; email keyed by report and week | |
| Slow work off the request | parsing, PDF and email in the job runner; the import shows its progress | |
| Reversible migrations | expand and contract in separate releases | |
**Capacity:** 40 workspaces, 2 imports a week each, 300k rows a year `[doc:business-plan]` · designed for 400 workspaces and 3M rows
## Threat model
**Boundaries:** browser → API; CSV upload → job runner; API → Postgres; job runner → email provider
| Boundary | Threat | Mitigation | Criterion |
|----------|--------|------------|-----------|
| browser → API | another workspace's report requested by id | workspace_id from the session on every query; 404 for other workspaces | 14 |
| CSV upload → job runner | malformed or hostile input: formulas, markup, 2 GB files | 20 MB limit, cells stored as text, formulas neutralized on export | 15, 16 |
| browser → API | abuse: credential stuffing, mass sign-ups | 5 sign-ins a minute per account and address; sign-up rate limit | 17 |
| API → email provider | secrets: the provider key | host secret store, server only; secret scan in CI; rotated yearly | 18 |skills/system-design/SKILL.mdView on GitHub