From 27088a2e34d61819cd55df86df0c850723ba38f0 Mon Sep 17 00:00:00 2001 From: alexengrig Date: Sat, 31 Oct 2026 00:35:03 +0300 Subject: [PATCH] feat: add the framework article Add the Framework page: the whole system design interview, step by step, on one running example, a notification service. It covers how the interview runs, defending a decision, the opening, functional and non-functional requirements, estimates in two passes, API and entities with the data and control planes, data flow, high-level design, the key part and choosing technologies, resources, cost, and operations as optional steps, deep dives, and the wrap-up. Each step says when to take it, what to ask, what stays on the board, and how long it takes. The page is published while still in work: the sidebar marks it WIP. Add board diagrams, which show the design as a candidate draws it on a whiteboard. The board-diagrams skill in `.agents/skills/board-diagrams/` renders a scene from `src/diagrams/board/.mjs` to a static SVG with rough.js (vendored, MIT) and checks the layout. The high-level design grows one scenario at a time in steps; the key part and the design after the deep dive show the whole board with what matters in focus. The steps before the design leave board text in the board font. The skill's DECISIONS.md records the rules and why; WRITING.md gets a first Board diagrams section. Add glossary entries for the data plane and the control plane, and mark the page written in the article map. Validation: - `bun run build` passes (18 pages). - Every view of all 13 diagrams checked in light and dark themes, at desktop and phone widths. The skill's checks pass: no overlaps, no line through a shape or a text, nothing outside the board. - The WIP badge checked in the sidebar in both themes and on a phone. Open: the raw Markdown export drops diagrams, so board text is missing there (recorded in the skill's DECISIONS.md). Co-Authored-By: Claude Opus 5.5 Signed-off-by: alexengrig --- .agents/skills/board-diagrams/DECISIONS.md | 246 ++++++++++ .agents/skills/board-diagrams/SKILL.md | 65 +++ .../skills/board-diagrams/scripts/build.mjs | 46 ++ .../skills/board-diagrams/scripts/render.mjs | 446 ++++++++++++++++++ .../scripts/vendor/roughjs/LICENSE | 21 + .../scripts/vendor/roughjs/SOURCE | 1 + .../scripts/vendor/roughjs/rough.esm.js | 1 + ARTICLES.md | 2 +- WRITING.md | 16 +- astro.config.mjs | 2 +- board-diagrams.json | 6 + src/content/docs/framework.md | 330 +++++++++++++ src/data/glossary.mjs | 23 + src/diagrams/board/framework.mjs | 260 ++++++++++ src/diagrams/framework-api.svg | 5 + src/diagrams/framework-cost.svg | 5 + src/diagrams/framework-data-flow.svg | 5 + src/diagrams/framework-deep-dive-design.svg | 33 ++ src/diagrams/framework-deep-dive.svg | 16 + src/diagrams/framework-estimates.svg | 5 + src/diagrams/framework-functional.svg | 5 + src/diagrams/framework-hld.svg | 33 ++ src/diagrams/framework-key-part.svg | 34 ++ src/diagrams/framework-non-functional.svg | 5 + src/diagrams/framework-opening.svg | 5 + src/diagrams/framework-operations.svg | 5 + src/diagrams/framework-resources.svg | 5 + 27 files changed, 1622 insertions(+), 4 deletions(-) create mode 100644 .agents/skills/board-diagrams/DECISIONS.md create mode 100644 .agents/skills/board-diagrams/SKILL.md create mode 100644 .agents/skills/board-diagrams/scripts/build.mjs create mode 100644 .agents/skills/board-diagrams/scripts/render.mjs create mode 100644 .agents/skills/board-diagrams/scripts/vendor/roughjs/LICENSE create mode 100644 .agents/skills/board-diagrams/scripts/vendor/roughjs/SOURCE create mode 100644 .agents/skills/board-diagrams/scripts/vendor/roughjs/rough.esm.js create mode 100644 board-diagrams.json create mode 100644 src/content/docs/framework.md create mode 100644 src/diagrams/board/framework.mjs create mode 100644 src/diagrams/framework-api.svg create mode 100644 src/diagrams/framework-cost.svg create mode 100644 src/diagrams/framework-data-flow.svg create mode 100644 src/diagrams/framework-deep-dive-design.svg create mode 100644 src/diagrams/framework-deep-dive.svg create mode 100644 src/diagrams/framework-estimates.svg create mode 100644 src/diagrams/framework-functional.svg create mode 100644 src/diagrams/framework-hld.svg create mode 100644 src/diagrams/framework-key-part.svg create mode 100644 src/diagrams/framework-non-functional.svg create mode 100644 src/diagrams/framework-opening.svg create mode 100644 src/diagrams/framework-operations.svg create mode 100644 src/diagrams/framework-resources.svg diff --git a/.agents/skills/board-diagrams/DECISIONS.md b/.agents/skills/board-diagrams/DECISIONS.md new file mode 100644 index 0000000..63c1c82 --- /dev/null +++ b/.agents/skills/board-diagrams/DECISIONS.md @@ -0,0 +1,246 @@ +# Board diagrams: decisions + +The record of what was decided for board diagrams, and why. Add each new +decision here when it is made. The skill is SKILL.md and `scripts/` (written +2026-10-30 from a prototype, now kept out of git in +`.agents/board-diagrams-proto/`). + +The skill is built to be moved out of this repository later and installed +with Skills CLI. So decisions are split: the skill section is general, the +project section is this site's settings and must not leak into the skill. + +## Skill (general) + +### Purpose + +- Board diagrams look as if drawn by hand on a whiteboard during a design + interview. Use them for a system being designed (high-level design, its + steps, the key part). Explaining diagrams that teach one idea stay crisp and + do not use this style. + +### Drawing + +- rough.js (MIT), roughness 1. Output is deterministic: the seed comes from the + element id. +- Font: Comic Shanns Mono (MIT). Every glyph is 0.5465 em wide (1119 of 2048 + units; the prototype used 0.55), so the script measures text without a + browser. Browsers round the width down a little at small sizes. +- Two text sizes: + - medium: names inside shapes, the technology in brackets, board text of + the steps (Functional, Non-functional, API, ...); + - small: arrow labels and notes. +- Grid unit 32. Every class has one shape, from the few shapes a person draws + on a board (no cylinders, buckets or stacks): + + | Class | Shape | Units (w x h) | + | --- | --- | --- | + | client | circle | 2 x 2 | + | service | rectangle | 3 x 2 | + | database | vertical rectangle | 2 x 3 | + | files | same as database | 2 x 3 | + | cache | square | 2 x 2 | + | queue | long horizontal rectangle | 5 x 1 | + | API, load balancer | long vertical bar, text turned | 1 x 5 | + +- External system: the shape of its class, dashed. +- Many instances: two shapes, one behind the other (offset +8, -8). +- Lines: solid = sync call, dashed = async (through a queue, replication, events). +- No accent color. Everything is drawn in the theme's text colors. + +### Text fit + +- The name keeps the medium size. When it does not fit, the shape grows around + its center by exactly what is needed, without keeping proportions. A circle + and a square grow on both sides and stay round or square. + (Rejected: shrinking the font. At hard names it went down to 6.5 px.) +- The technology goes inside the shape, in brackets, as the last line: + `Message store (Cassandra)`. (Rejected: small text at the bottom inside, + and text below the shape.) +- A line break in a name is the writer's choice, as on a board. +- The script limits the growth to half the base size; past the limit it fails + and asks for a shorter name. + +### Steps (slides) + +- A high-level design grows one scenario at a time, like slides. After the + last step comes the final view with everything. +- Each view has a caption that says what the diagram shows ("The team reads + the message status"), without the word "step" or a number: the controls + show the position. The final view's caption names the whole design. + (Rejected: "Step 2 of 4 · Status".) +- The caption sits between the diagram and the controls, centered. + (Rejected: above the diagram, under the controls.) +- Elements of earlier steps fade to 32% opacity; elements of the current step + are drawn normally; later steps are hidden. The final view shows everything + normally. (Rejected: accent color for the new step, gray instead of fade.) +- The key part is one frame: the whole design with the key components and + their edges in focus and the rest faded, the technologies written on the + key components, and a strong note with the reason. +- Controls are outside the scrolled diagram: on a narrow screen the diagram + scrolls sideways, the controls stay centered under it. +- The reader can go back and forward, jump to the first step, to the final + view, or to any step. The final view counts as the place after the last + step. Arrows are disabled at the ends (back on step 1, forward on the final + view). +- Controls follow the project's own control style. Rejected: names on the + buttons (wraps on a phone), classic first/prev/next/last with "2/4" + (heavy), and bordered numbered buttons with a filled current one (good + idea, but stands out from the site). +- Control layout: `‹ 1 2 3 4 All ›` — prev arrow, one number per step, `All` + for the final view, next arrow, all in one row and centered. The current + number is the accent and bold. (Chosen 2026-10-30. Rejected in the site + style: dots with a square final, dots with `All`, bar segments.) +- Each number's accessible name is the caption of its view; the caption + under the diagram is a polite live region. Keys on the focused diagram: + left / right, Home (step 1), End (final view). +- The slides open on step 1, because they tell a story. Without JavaScript + the SVG shows the final view. +- The canvas has the final size from step 1. Hidden elements keep their + place, so nothing jumps between steps; early steps leave empty space below, + as on a real board. + +### Layout + +How a person draws on a board, so the final view has few crossings and shows +at a glance what is ours and what is not. + +- Zones, left to right: + 1. outside: users, client apps, external systems (both those that call us + and those we call); + 2. the API gateway or load balancer, a long vertical bar: the border between + outside and ours. It stretches to cover every client that enters through + it (the one exception to the 1 x 5 size); + 3. services; a queue sits between the services it connects; + 4. stores: databases, caches, files; + 5. internal users (support, admins, operators), on the far right. +- Steps go from the top down: step 1 is the top row, each next scenario adds a + row below. The board is drawn from the top left corner. +- The main flow in a row goes left to right. To go back to the left (call an + external system, retry into a queue), make a loop: leave the row up or + down, go left along a free lane between rows, then enter the target. +- Shapes linked in a row share a center line, so their arrows are straight. + The gap between linked shapes is at least 1.5 units for a short label + (pub, set) and 3 units for a long one (write status). +- A lane between rows carries one line and keeps clear of shapes and labels. +- Avoid crossings. When one cannot be avoided, cross at a right angle and + never through a shape or a label. +- An arrow starts at the one who acts (calls, writes, reads, publishes, + consumes), not where the data goes. A producer and a consumer both point at + the queue. The label on the arrow is the action: pub, sub, read, write. +- The script fails on shapes and texts that overlap (closer than 4 px), a + line through a shape or a text, and content outside the board. It reports + the crossings, so the writer sees each one. + +### Board text + +Text written on the board next to the design, in the board font (agreed +2026-10-30 for the framework page; the form of each shape may still be tuned). + +- Data next to a store, so that the form shows the shape with no label: + - table: the name, a line, the columns; `(key)`, and `(sort)` for a column + that orders the rows of one key; + - key-value: `settings:{user_id} -> {channels}`; + - cache: a key-value pair plus `TTL 1 min, LRU`; + - document: nesting in braces, `order {id, items: [{sku, qty}]}`; + - files: the path, `media/{user_id}/{file_id}.jpg`; + - queue: `key user_id, kept 3 days`. + Placeholders in braces, as in API paths. A type only when not obvious + (`status: queued|sent|failed`). +- API: auth once above the calls; a header only when it changes the call; a + status code only when not obvious; a long call breaks before `->`. A + long-lived connection: the connection once, then one line per kind of + message, `client:` or `server:` first. +- A data note goes next to its store, placed by the writer (`near`, `side`, + `align`), and the checks keep it clear of shapes and lines. A note of + several lines is a left-aligned block, also when it is centered on a point or + ends at one. A table is its name, `---` (three short dashes, as written on a + board), then its columns. (2026-10-30: the drawn line under the name was + replaced by `---`.) A store's note says how long the data is kept, so the + key part's numbers have a source on the board. +- Each step before the design leaves board text: one diagram per step, text + only, no frame, a heading and lines in the medium size. No bold: a + candidate does not write bold on a board (2026-10-30). Columns line + up as in the monospaced source: browsers collapse runs of spaces in inline + SVG, so each run of two or more spaces starts a new span at its column. +- The alt text of board text is the text itself. +- Not every step leaves board text. The wrap-up is spoken while pointing at + the board, so it has no diagram; its example is a quote in the prose. +- A list on the board has one item per line, with its problems right under + the item, indented (data flow: one stage per line, the slow and failing + places under the stage). The problems are not a second column: it made the + line wider than a phone (2026-10-31). +- A data flow is a pipeline, so it is written as a chain: what enters first, + then `-> stage: what it passes on` per line (`request`, `-> accept: + message`, ...). Each thing is written once and the order needs no numbers + (the author's idea, 2026-10-31; rejected: `1. accept request -> message`, + which wrote every thing twice). +- No marks that say nothing: when every scenario above `Out:` is designed, + the scenarios get no stars. +- A deep dive draws the part of the design the problem lives in, larger, with + the steps numbered, and marks where it breaks. Step 1 is the problem with + the options as board text below; step 2 adds the choice. Then the whole + design follows, with what the choice changed in focus, as on the key part. +- Notes stay one tone lighter than arrow labels (gray-3 vs gray-2). The author + saw it and kept it (2026-10-30). + +### Configuration + +- The project keeps its settings in a file at its root (planned name + `board-diagrams.json`): text sizes, fade, roughness, where scenes and SVGs + live, how a diagram is embedded in a page, how colors are applied. Without + the file the skill uses its defaults. +- The skill renders a scene to a static SVG with documented classes and + `data-step` attributes. Showing it (theme colors, the step controls) is the + project's job; the skill ships a reference CSS and JS for projects that have + none. +- rough.js and the font are copied into the skill, so it does not depend on + the project's `node_modules`. + +## Project: sysdes + +These move to the project's settings file and WRITING.md when the skill is +moved out. + +- Board diagrams are used on the framework page and in systems/* articles. +- Text sizes 16 / 14 (about 15 / 13 px on screen at the 672 px content + column). Chosen 2026-10-30: 14 / 12, the sizes of the site's other + diagrams, read too small for board text. A board line holds at most 78 + characters, so a 720 px board is not scaled down. +- Settings: `board-diagrams.json` in the project root. Scenes are + `src/diagrams/board/.mjs`, SVGs go to `src/diagrams/-.svg` + and are embedded with `::diagram{name="..."}`. Render with + `bun .agents/skills/board-diagrams/scripts/build.mjs`. +- The framework page (2026-10-30): every step's code block became a board + diagram. The design: the read-status lane runs above the first row (the API + bar starts above the queue's data note), so the message table fits under the + message store; the failure note sits by the retry loop; one crossing is + left (deliver x read status). The key part is the same board with the queue + and the message store in focus and the key-part text below it. With the + 16 / 14 sizes the queue is 4 x 1 (5 x 1 left no room for the write-status + label once the key part writes Cassandra in the store), and the queue's + data note wraps into three lines. +- Open (to come back to): the raw Markdown export of a page drops diagrams, + so an agent that reads it does not see the board. Idea (2026-10-31): the + skill also writes a text form of each scene, a Mermaid flowchart for a + design (nodes, edges with labels, notes) and the plain lines for board + text, and the shared package puts it into the raw Markdown in place of the + `::diagram`. Where the text form lives (in the SVG or next to it) and how + steps and focus show in it are not decided. +- Colors come from Starlight theme variables through `sk-*` classes, so the + diagrams follow the light and dark theme. +- The `sk-*` styles and the step controls live in `@tech0ver/starlight`, the + shared package of tech0ver sites. Shipped in 0.8.0 (2026-10-30), with a + 576 px minimum width for `.sk-svg` (no needless scroll on desktop). What the + skill must emit for it: + - root ``; the font is the package's + `Comic Shanns Mono`, so the SVG does not embed one; + - stepped diagram: `data-steps` (JSON array of captions, one per step) and + `data-final` (the final caption) on the root; `::diagram` fails the build + when a caption is empty; + - key part: `data-focus-mode` on the root and `data-focus` on the elements + in focus. +- Step controls match the site's controls: 2rem targets, no border, no + plaque, gray-2; text accent on hover and for the current view (bold for a + number); the arrows are Starlight's `left-caret` / `right-caret` icons at + 1.25rem, as in the sidebar; a disabled arrow is gray-5. The caption is + `--sl-text-sm`, gray-2. diff --git a/.agents/skills/board-diagrams/SKILL.md b/.agents/skills/board-diagrams/SKILL.md new file mode 100644 index 0000000..0715eac --- /dev/null +++ b/.agents/skills/board-diagrams/SKILL.md @@ -0,0 +1,65 @@ +--- +name: board-diagrams +description: Draw a system design as it looks on an interview whiteboard (hand-drawn shapes, board font, a design that grows one scenario at a time, a key-part view) and the board text of each step. Use for the framework page and systems/* articles; explaining diagrams that teach one idea use the crisp style instead. +--- + +# Board diagrams + +A board diagram shows only what a candidate can draw in an interview: a few +shapes, lines, and short text. You write a scene; the script measures the text, +draws the shapes with rough.js, checks the layout, and writes a static SVG. +The rules and the reasons for them are in [DECISIONS.md](DECISIONS.md). Read +it before you lay out a new design. + +## Run + +From the project root: + +```sh +bun .agents/skills/board-diagrams/scripts/build.mjs [name ...] +``` + +The script reads `board-diagrams.json` in the project root (where scenes and +SVGs live, text sizes) and renders every scene, or only the named ones. It +prints each diagram's size, the shapes that grew, and the line crossings. It +fails on a shape that grew past its limit, an overlap of shapes and texts, a +line through a shape or a text, and content outside the board. Fix the scene +until it passes, then look at the result in the browser in both themes. + +## Scenes + +A scene file is an `.mjs` module in the scenes directory. Its default export +maps diagram names to scenes, so one file can share nodes between the design +and its key part. + +```js +{ + title: 'Short name of the diagram', // + desc: 'What it shows, as alt text', // + width: 21.5, // units of 32; omit to trim to the content + steps: ['Caption of step 1', ...], // a design that grows; omit for one view + final: 'Caption of the final view', + focusMode: true, // key part: elements without focus fade + nodes: [{ id, kind, x, y, label, tech?, external?, multi?, size?, step?, focus? }], + edges: [{ from, to, label?, async?, fromSide?, toSide?, offset?, toOffset?, + elbow?: 'h' | 'v', via?: [[x, y]], labelSide?, labelShift?, labelSegment?, step?, focus? }], + notes: [{ text | table: { name, columns }, near?, side?, align?, dx?, dy?, x?, y?, anchor?, medium?, strong?, step?, focus? }], + blocks: [{ x, y, title?, lines, small?, step?, focus? }], +} +``` + +- `kind`: `client`, `service`, `store`, `files`, `cache`, `queue`, `gateway`. + A name keeps its size; the shape grows to fit. A line break in a label is + yours to choose, as on a board. +- Positions are in grid units of 32 from the top left corner. +- An edge leaves the side facing the target and stays straight unless it has + an `elbow` or `via` points. `offset` moves its ends along the sides, in units. +- A note sits `near` a node on a `side`, or at `x`, `y`. A multi-line note is + a left-aligned block. A `table` is its name, a line, then its columns. +- A block is board text: a bold title and lines in the medium size. Leading + spaces and runs of two or more spaces keep their columns. + +## Embed + +The SVG goes to the output directory. How the page shows it is the project's +job; for this site see the project section of DECISIONS.md. diff --git a/.agents/skills/board-diagrams/scripts/build.mjs b/.agents/skills/board-diagrams/scripts/build.mjs new file mode 100644 index 0000000..156c01f --- /dev/null +++ b/.agents/skills/board-diagrams/scripts/build.mjs @@ -0,0 +1,46 @@ +// Renders every board scene of the project to an SVG. +// +// Usage: bun /scripts/build.mjs [name ...] +// Reads board-diagrams.json from the current directory (the project root); +// without it, uses the defaults below. A scene file is an .mjs module in the +// scenes directory whose default export maps diagram names to scenes. +// Fails when a scene has a problem: a shape that grew past its limit, an +// overlap, or a line through a shape or a text. + +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { renderScene } from './render.mjs'; + +const defaults = { scenes: 'diagrams/board', output: 'diagrams', medium: 14, small: 12, roughness: 1, maxGrow: 0.5 }; +const file = resolve('board-diagrams.json'); +const config = { ...defaults, ...(existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : {}) }; +const only = process.argv.slice(2); + +const dir = resolve(config.scenes); +const scenes = {}; +for (const f of readdirSync(dir).filter((f) => f.endsWith('.mjs')).sort()) { + const mod = await import(pathToFileURL(join(dir, f)).href); + for (const [name, scene] of Object.entries(mod.default)) { + if (scenes[name]) throw new Error(`Diagram ${name} is defined twice`); + scenes[name] = scene; + } +} + +mkdirSync(resolve(config.output), { recursive: true }); +let failed = 0; +for (const [name, scene] of Object.entries(scenes)) { + if (only.length && !only.includes(name)) continue; + const { svg, report } = renderScene(name, scene, { m: config.medium, s: config.small, roughness: config.roughness, maxGrow: config.maxGrow }); + writeFileSync(join(resolve(config.output), `${name}.svg`), svg); + const notes = [`${report.size.join(' x ')}`]; + if (report.grown.length) notes.push(`grown: ${report.grown.join(', ')}`); + if (report.crossings.length) notes.push(`crossings: ${report.crossings.length} (${report.crossings.join('; ')})`); + console.log(`${report.problems.length ? 'FAIL' : 'ok '} ${name}: ${notes.join(', ')}`); + for (const p of report.problems) console.log(` ${p}`); + if (report.problems.length) failed++; +} +if (failed) { + console.error(`${failed} diagram(s) have problems`); + process.exit(1); +} diff --git a/.agents/skills/board-diagrams/scripts/render.mjs b/.agents/skills/board-diagrams/scripts/render.mjs new file mode 100644 index 0000000..dafd766 --- /dev/null +++ b/.agents/skills/board-diagrams/scripts/render.mjs @@ -0,0 +1,446 @@ +// Renders a board scene to a static SVG, drawn with rough.js. +// +// A scene lists nodes by class and grid position (in units), edges between +// nodes by id, notes, tables, and text blocks. The script measures every text +// (the font is monospaced), so the writer never computes sizes or arrow ends. +// Any element can belong to a step or be in focus. The SVG is colored only by +// sk-* classes, so the project's CSS decides the colors and follows the theme. +// +// renderScene also returns a report: shapes that grew, and overlaps between +// shapes, texts, and lines. + +import rough from './vendor/roughjs/rough.esm.js'; + +export const U = 32; +const MARGIN = 16; + +// Size of each class in grid units: [width, height]. +export const SIZES = { + client: [2, 2], + service: [3, 2], + store: [2, 3], + files: [2, 3], + cache: [2, 2], + queue: [5, 1], + gateway: [1, 5], +}; +const SQUARE = new Set(['client', 'cache']); +const VERTICAL = new Set(['gateway']); + +// Comic Shanns Mono: every glyph is 0.5465 em wide (1119 of 2048 units), so a +// line is chars * 0.5465 * size. Browsers round it down a little at small sizes. +const ADVANCE = 0.5465; +const LINE = 1.25; +// Padding inside a shape: along the text, and across it (line height already adds air). +const PAD = 7; +const PAD_ACROSS = 4; +// A copy behind a shape for many instances. +const COPY = 8; + +const gen = rough.generator(); + +function hash(text) { + let h = 2166136261; + for (const ch of text) h = Math.imul(h ^ ch.charCodeAt(0), 16777619); + return (h >>> 0) % 2147483647 || 1; +} + +const r2 = (v) => +v.toFixed(2); +const esc = (s) => s.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); +const px = (u) => u * U + MARGIN; +const width = (line, size) => line.length * ADVANCE * size; + +function strokes(drawable, cls) { + return gen + .toPaths(drawable) + .map((p) => ``) + .join(''); +} + +// Lines of text; y is the center of the first line. Browsers collapse runs of +// spaces in inline SVG, so in left-aligned text each run of two or more spaces +// starts a new span at its column: indents and columns line up as in the +// monospaced source. +function text(x, y, lines, cls, size, anchor = 'middle', rotate = false) { + const step = size * LINE; + const spans = lines + .map((l, i) => { + const ly = r2(y + i * step); + if (anchor !== 'start') return l.trim() ? `${esc(l.trim())}` : ''; + const runs = []; + for (const m of l.matchAll(/\S+(?: \S+)*/g)) runs.push(`${esc(m[0])}`); + return runs.join(''); + }) + .join(''); + const turn = rotate ? ` transform="rotate(-90 ${r2(x)} ${r2(y)})"` : ''; + return `${spans}`; +} + +// The box a text takes: x by anchor, top is half a line above the first line's center. +function textBox(x, y, lines, size, anchor) { + const w = Math.max(...lines.map((l) => width(l, size))); + const h = lines.length * size * LINE; + const left = anchor === 'start' ? x : anchor === 'end' ? x - w : x - w / 2; + return { x: left, y: y - (size * LINE) / 2, w, h }; +} + +// Works out the box of a node. The name stays medium; when it does not fit, +// the shape grows around its center by exactly what is needed. A square or a +// circle grows on both sides. The technology goes inside, in brackets. +export function layoutNode(n, o) { + const [wu, hu] = n.size ?? SIZES[n.kind]; + const baseW = wu * U; + const baseH = hu * U; + const cx = px(n.x) + baseW / 2; + const cy = px(n.y) + baseH / 2; + const vertical = VERTICAL.has(n.kind); + const round = n.kind === 'client'; + + const lines = n.label.split('\n'); + if (n.tech) lines.push(`(${n.tech})`); + const textW = Math.max(...lines.map((l) => width(l, o.m))); + const textH = lines.length * LINE * o.m; + + let along = vertical ? baseH : baseW; + let across = vertical ? baseW : baseH; + let grown = 0; + if (round) { + const d = Math.max(along, Math.ceil(Math.hypot(textW, textH) + 2 * PAD)); + grown = d - along; + along = across = d; + } else { + const a = Math.max(along, Math.ceil(textW + 2 * PAD)); + const c = Math.max(across, Math.ceil(textH + 2 * PAD_ACROSS)); + grown = Math.max(a - along, c - across); + if (SQUARE.has(n.kind)) along = across = Math.max(a, c); + else [along, across] = [a, c]; + } + + const w = vertical ? across : along; + const h = vertical ? along : across; + return { cx, cy, w, h, x: cx - w / 2, y: cy - h / 2, baseW, baseH, lines, vertical, round, grown }; +} + +function shape(kind, box, opts, dashed) { + const line = dashed ? 'sk-line sk-dash' : 'sk-line'; + if (kind === 'client') { + return ( + `` + + strokes(gen.ellipse(box.cx, box.cy, box.w, box.h, opts), line) + ); + } + return ( + `` + + strokes(gen.rectangle(box.x, box.y, box.w, box.h, opts), line) + ); +} + +function node(n, box, base, o) { + const opts = { ...base, seed: hash(n.id) }; + if (n.external) opts.disableMultiStroke = true; + let out = ''; + if (n.multi) { + const back = { ...box, x: box.x + COPY, y: box.y - COPY, cx: box.cx + COPY, cy: box.cy - COPY }; + out += shape(n.kind, back, { ...opts, seed: hash(`${n.id}-copy`) }, n.external); + } + out += shape(n.kind, box, opts, n.external); + const first = box.cy - ((box.lines.length - 1) * o.m * LINE) / 2; + out += box.vertical + ? text(box.cx, box.cy, box.lines, 'sk-name', o.m, 'middle', true) + : text(box.cx, first, box.lines, 'sk-name', o.m); + return out; +} + +// The areas a node takes on the board: its shape, and the copy behind it for many instances. +function nodeAreas(n, box) { + const front = { x: box.x, y: box.y, w: box.w, h: box.h }; + return n.multi ? [front, { ...front, x: front.x + COPY, y: front.y - COPY }] : [front]; +} + +// A point on a side of a box: l, r, t, b, shifted by offset units along the side. +function sidePoint(box, side, offset = 0) { + const d = offset * U; + if (box.round) { + const r = box.w / 2; + const k = Math.sqrt(Math.max(r * r - d * d, 0)); + if (side === 'l') return [box.cx - k, box.cy + d]; + if (side === 'r') return [box.cx + k, box.cy + d]; + if (side === 't') return [box.cx + d, box.cy - k]; + return [box.cx + d, box.cy + k]; + } + if (side === 'l') return [box.x, box.cy + d]; + if (side === 'r') return [box.x + box.w, box.cy + d]; + if (side === 't') return [box.cx + d, box.y]; + return [box.cx + d, box.y + box.h]; +} + +function facing(a, b) { + const dx = b.cx - a.cx; + const dy = b.cy - a.cy; + if (Math.abs(dx) >= Math.abs(dy)) return dx > 0 ? ['r', 'l'] : ['l', 'r']; + return dy > 0 ? ['b', 't'] : ['t', 'b']; +} + +function arrowHead([x1, y1], [x2, y2], opts) { + const angle = Math.atan2(y2 - y1, x2 - x1); + const len = 10; + const spread = 0.45; + const wing = (a) => [x2 - len * Math.cos(angle + a), y2 - len * Math.sin(angle + a)]; + return strokes(gen.linearPath([wing(spread), [x2, y2], wing(-spread)], { ...opts, roughness: 0.6 }), 'sk-line'); +} + +// The points of an edge. Without via or elbow, the arrow is straight and +// keeps the start's line. via: [[x, y] units]; elbow 'h' goes across first, 'v' down or up first. +function edgePoints(e, boxes) { + const a = boxes[e.from]; + const b = boxes[e.to]; + if (!a || !b) throw new Error(`Edge ${e.from} -> ${e.to}: unknown node`); + const [fs, ts] = facing(a, b); + const fromSide = e.fromSide ?? fs; + const toSide = e.toSide ?? ts; + const start = sidePoint(a, fromSide, e.offset ?? 0); + let end = sidePoint(b, toSide, e.toOffset ?? e.offset ?? 0); + if (e.via) return [start, ...e.via.map(([x, y]) => [px(x), px(y)]), end]; + if (e.elbow === 'v') return [start, [start[0], end[1]], end]; + if (e.elbow === 'h') return [start, [end[0], start[1]], end]; + end = toSide === 'l' || toSide === 'r' ? [end[0], start[1]] : [start[0], end[1]]; + return [start, end]; +} + +// The label goes by the longest segment: above a horizontal one (or below), right of a vertical one (or left). +function labelPlace(e, points, o) { + const len = (k) => Math.hypot(points[k + 1][0] - points[k][0], points[k + 1][1] - points[k][1]); + let best = e.labelSegment ?? 0; + if (e.labelSegment === undefined) for (let i = 1; i < points.length - 1; i++) if (len(i) > len(best)) best = i; + const [p, q] = [points[best], points[best + 1]]; + const mx = (p[0] + q[0]) / 2 + (e.labelShift ?? 0) * U; + const my = (p[1] + q[1]) / 2; + const lines = [e.label]; + if (Math.abs(q[1] - p[1]) < 1) { + const y = my + (e.labelSide === 'below' ? 1 : -1) * o.s * 0.8; + return { x: mx, y, lines, anchor: 'middle' }; + } + if (e.labelSide === 'left') return { x: mx - 6, y: my, lines, anchor: 'end' }; + return { x: mx + 6, y: my, lines, anchor: 'start' }; +} + +function edge(e, points, label, base, index, o) { + const opts = { ...base, seed: hash(`edge-${e.from}-${e.to}-${index}`) }; + if (e.async) opts.disableMultiStroke = true; + let out = strokes(gen.linearPath(points, opts), e.async ? 'sk-line sk-dash' : 'sk-line'); + out += arrowHead(points.at(-2), points.at(-1), base); + if (label) out += text(label.x, label.y, label.lines, 'sk-label', o.s, label.anchor); + return out; +} + +// Where a note goes. A note of several lines is a left-aligned block, also +// when it is centered on a point or ends at one. +// { x, y } units (top left for anchor start, top center for middle), +// or { near: id, side: 't' | 'b' | 'l' | 'r', align?: 'start' | 'end', dx?, dy? units }. +function notePlace(n, lines, size, boxes) { + const place = notePoint(n, lines, size, boxes); + if (place.anchor === 'start' || (place.anchor === 'middle' && lines.length === 1)) return place; + const w = Math.max(...lines.map((l) => width(l, size))); + return { ...place, x: place.anchor === 'end' ? place.x - w : place.x - w / 2, anchor: 'start' }; +} + +function notePoint(n, lines, size, boxes) { + const h = lines.length * size * LINE; + const half = (size * LINE) / 2; + const dx = (n.dx ?? 0) * U; + const dy = (n.dy ?? 0) * U; + if (!n.near) return { x: px(n.x) + dx, y: px(n.y) + half + dy, anchor: n.anchor ?? 'start' }; + const box = boxes[n.near]; + if (!box) throw new Error(`Note near ${n.near}: unknown node`); + const gap = 8; + const along = (side) => { + if (n.align === 'start') return { x: box.x + dx, anchor: 'start' }; + if (n.align === 'end') return { x: box.x + box.w + dx, anchor: 'end' }; + return { x: box.cx + dx, anchor: 'middle' }; + }; + if (n.side === 't') return { ...along(), y: box.y - gap - h + half + dy }; + if (n.side === 'b') return { ...along(), y: box.y + box.h + gap + half + dy }; + const y = box.cy - h / 2 + half + dy; + if (n.side === 'l') return { x: box.x - gap + dx, y, anchor: 'end' }; + return { x: box.x + box.w + gap + dx, y, anchor: 'start' }; +} + +function noteLines(n) { + if (n.table) return [n.table.name, '---', ...n.table.columns]; + return n.text.split('\n'); +} + +// A note: small text by default; a table is its name, three dashes, then its columns. +function note(n, place, size) { + const cls = n.strong ? 'sk-note sk-note-strong' : 'sk-note'; + return text(place.x, place.y, noteLines(n), cls, size, place.anchor); +} + +// Board text, such as requirements or an API: a heading and lines, medium by +// default. The heading is plain text, as a person writes it on a board. +function block(b, o) { + const size = b.small ? o.s : o.m; + const x = px(b.x); + let y = px(b.y) + (size * LINE) / 2; + let out = ''; + const lines = b.lines.flatMap((l) => l.split('\n')); + if (b.title) { + out += text(x, y, [b.title], 'sk-name', size, 'start'); + y += size * LINE; + } + out += text(x, y, lines, 'sk-name', size, 'start'); + return out; +} + +function blockBox(b, o) { + const size = b.small ? o.s : o.m; + const lines = [...(b.title ? [b.title] : []), ...b.lines.flatMap((l) => l.split('\n'))]; + return textBox(px(b.x), px(b.y) + (size * LINE) / 2, lines, size, 'start'); +} + +function group(el, body) { + const attrs = ['class="sk-el"']; + if (el.step) attrs.push(`data-step="${el.step}"`); + if (el.focus) attrs.push('data-focus'); + return `${body}`; +} + +// ---- Checks ---- + +const inflate = (b, d) => ({ x: b.x - d, y: b.y - d, w: b.w + 2 * d, h: b.h + 2 * d }); +const overlap = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h; + +function segmentHitsBox([x1, y1], [x2, y2], b) { + // Liang-Barsky clipping: does the segment pass through the box? + let t0 = 0; + let t1 = 1; + const dx = x2 - x1; + const dy = y2 - y1; + const tests = [ + [-dx, x1 - b.x], + [dx, b.x + b.w - x1], + [-dy, y1 - b.y], + [dy, b.y + b.h - y1], + ]; + for (const [p, q] of tests) { + if (p === 0) { + if (q < 0) return false; + } else { + const t = q / p; + if (p < 0) t0 = Math.max(t0, t); + else t1 = Math.min(t1, t); + if (t0 > t1) return false; + } + } + return true; +} + +function segmentsCross([a, b], [c, d]) { + const cross = (p, q, r) => (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]); + const d1 = cross(c, d, a); + const d2 = cross(c, d, b); + const d3 = cross(a, b, c); + const d4 = cross(a, b, d); + return ((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) && ((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0)); +} + +function check(items, lines) { + const problems = []; + for (let i = 0; i < items.length; i++) { + for (let j = i + 1; j < items.length; j++) { + if (items[i].node && items[i].node === items[j].node) continue; + if (overlap(inflate(items[i].box, 2), inflate(items[j].box, 2))) problems.push(`overlap: ${items[i].name} and ${items[j].name}`); + } + } + for (const l of lines) { + for (const item of items) { + if (l.own.includes(item.node ?? item.name)) continue; + // Lines end on a node's border, so shrink nodes a little; keep texts as they are. + const box = item.kind === 'node' ? inflate(item.box, -3) : inflate(item.box, 1); + if (l.segments.some(([p, q]) => segmentHitsBox(p, q, box))) problems.push(`line through: ${l.name} crosses ${item.name}`); + } + } + const crossings = []; + for (let i = 0; i < lines.length; i++) { + for (let j = i + 1; j < lines.length; j++) { + for (const s of lines[i].segments) for (const t of lines[j].segments) if (segmentsCross(s, t)) crossings.push(`${lines[i].name} x ${lines[j].name}`); + } + } + return { problems, crossings }; +} + +// ---- Scene ---- + +// Options: m is the medium size (names in shapes, board text), s is the small +// size (arrow labels, notes), maxGrow is how much a shape may grow, as a share of its base size. +export function renderScene(name, scene, options = {}) { + const o = { m: 14, s: 12, roughness: 1, maxGrow: 0.5, ...options }; + const base = { roughness: o.roughness, bowing: 1, preserveVertices: true }; + const nodes = scene.nodes ?? []; + const edges = scene.edges ?? []; + const notes = scene.notes ?? []; + const blocks = scene.blocks ?? []; + const boxes = Object.fromEntries(nodes.map((n) => [n.id, layoutNode(n, o)])); + + const items = []; + const lines = []; + const parts = []; + const problems = []; + + for (const n of nodes) { + const box = boxes[n.id]; + const limit = o.maxGrow * Math.max(box.baseW, box.baseH); + if (box.grown > limit) problems.push(`too long: ${n.id} grew ${box.grown} px, the limit is ${Math.round(limit)} px; shorten the name`); + nodeAreas(n, box).forEach((area, k) => items.push({ name: k ? `${n.id} copy` : n.id, kind: 'node', box: area, node: n.id })); + } + edges.forEach((e, i) => { + const points = edgePoints(e, boxes); + const label = e.label ? labelPlace(e, points, o) : undefined; + const id = `${e.from}->${e.to}${e.label ? ` (${e.label})` : ''}`; + const segments = points.slice(1).map((p, k) => [points[k], p]); + lines.push({ name: id, segments, own: [e.from, e.to, `label ${id}`] }); + if (label) items.push({ name: `label ${id}`, kind: 'text', box: textBox(label.x, label.y, label.lines, o.s, label.anchor) }); + parts.push(group(e, edge(e, points, label, base, i, o))); + }); + for (const n of nodes) parts.push(group(n, node(n, boxes[n.id], base, o))); + notes.forEach((n, i) => { + const size = n.medium ? o.m : o.s; + const ls = noteLines(n); + const place = notePlace(n, ls, size, boxes); + items.push({ name: `note ${n.near ?? i}: ${ls[0]}`, kind: 'text', box: textBox(place.x, place.y, ls, size, place.anchor) }); + parts.push(group(n, note(n, place, size))); + }); + blocks.forEach((b, i) => { + items.push({ name: `block ${b.title ?? i}`, kind: 'text', box: blockBox(b, o) }); + parts.push(group(b, block(b, o))); + }); + + const checked = check(items, lines); + problems.push(...checked.problems); + + // Without a fixed size, the board is trimmed to its content. + const right = Math.max(...items.map((it) => it.box.x + it.box.w)); + const bottom = Math.max(...items.map((it) => it.box.y + it.box.h)); + const w = Math.ceil(scene.width !== undefined ? px(scene.width) + MARGIN : right + MARGIN); + const h = Math.ceil(scene.height !== undefined ? px(scene.height) + MARGIN : bottom + MARGIN); + if (right > w - MARGIN / 2) problems.push(`out of the board: content ends at x ${Math.round(right)}, the board is ${w} wide`); + if (bottom > h - MARGIN / 2) problems.push(`out of the board: content ends at y ${Math.round(bottom)}, the board is ${h} high`); + + const attrs = [`class="sk-svg"`, `viewBox="0 0 ${w} ${h}"`, `role="img"`, `aria-labelledby="${name}-title ${name}-desc"`]; + if (scene.steps) attrs.push(`data-steps="${esc(JSON.stringify(scene.steps))}"`, `data-final="${esc(scene.final)}"`); + if (scene.focusMode) attrs.push('data-focus-mode'); + const svg = [ + ``, + `${esc(scene.title)}`, + `${esc(scene.desc)}`, + ...parts, + '', + '', + ].join('\n'); + + const grown = Object.entries(boxes).filter(([, b]) => b.grown > 0); + return { + svg, + report: { size: [w, h], grown: grown.map(([id, b]) => `${id} +${b.grown}`), problems, crossings: checked.crossings }, + }; +} diff --git a/.agents/skills/board-diagrams/scripts/vendor/roughjs/LICENSE b/.agents/skills/board-diagrams/scripts/vendor/roughjs/LICENSE new file mode 100644 index 0000000..8861089 --- /dev/null +++ b/.agents/skills/board-diagrams/scripts/vendor/roughjs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Preet Shihn + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/.agents/skills/board-diagrams/scripts/vendor/roughjs/SOURCE b/.agents/skills/board-diagrams/scripts/vendor/roughjs/SOURCE new file mode 100644 index 0000000..fbf3789 --- /dev/null +++ b/.agents/skills/board-diagrams/scripts/vendor/roughjs/SOURCE @@ -0,0 +1 @@ +rough.js 4.6.6 (MIT), bundled/rough.esm.js from the npm package. diff --git a/.agents/skills/board-diagrams/scripts/vendor/roughjs/rough.esm.js b/.agents/skills/board-diagrams/scripts/vendor/roughjs/rough.esm.js new file mode 100644 index 0000000..6d43895 --- /dev/null +++ b/.agents/skills/board-diagrams/scripts/vendor/roughjs/rough.esm.js @@ -0,0 +1 @@ +function t(t,e,s){if(t&&t.length){const[n,o]=e,a=Math.PI/180*s,h=Math.cos(a),r=Math.sin(a);for(const e of t){const[t,s]=e;e[0]=(t-n)*h-(s-o)*r+n,e[1]=(t-n)*r+(s-o)*h+o}}}function e(t,e){return t[0]===e[0]&&t[1]===e[1]}function s(s,n,o,a=1){const h=o,r=Math.max(n,.1),i=s[0]&&s[0][0]&&"number"==typeof s[0][0]?[s]:s,c=[0,0];if(h)for(const e of i)t(e,c,h);const l=function(t,s,n){const o=[];for(const s of t){const t=[...s];e(t[0],t[t.length-1])||t.push([t[0][0],t[0][1]]),t.length>2&&o.push(t)}const a=[];s=Math.max(s,.1);const h=[];for(const t of o)for(let e=0;et.ymine.ymin?1:t.xe.x?1:t.ymax===e.ymax?0:(t.ymax-e.ymax)/Math.abs(t.ymax-e.ymax))),!h.length)return a;let r=[],i=h[0].ymin,c=0;for(;r.length||h.length;){if(h.length){let t=-1;for(let e=0;ei);e++)t=e;h.splice(0,t+1).forEach((t=>{r.push({s:i,edge:t})}))}if(r=r.filter((t=>!(t.edge.ymax<=i))),r.sort(((t,e)=>t.edge.x===e.edge.x?0:(t.edge.x-e.edge.x)/Math.abs(t.edge.x-e.edge.x))),(1!==n||c%s==0)&&r.length>1)for(let t=0;t=r.length)break;const s=r[t].edge,n=r[e].edge;a.push([[Math.round(s.x),i],[Math.round(n.x),i]])}i+=n,r.forEach((t=>{t.edge.x=t.edge.x+n*t.edge.islope})),c++}return a}(i,r,a);if(h){for(const e of i)t(e,c,-h);!function(e,s,n){const o=[];e.forEach((t=>o.push(...t))),t(o,s,n)}(l,c,-h)}return l}function n(t,e){var n;const o=e.hachureAngle+90;let a=e.hachureGap;a<0&&(a=4*e.strokeWidth),a=Math.round(Math.max(a,.1));let h=1;return e.roughness>=1&&((null===(n=e.randomizer)||void 0===n?void 0:n.next())||Math.random())>.7&&(h=a),s(t,a,o,h||1)}class o{constructor(t){this.helper=t}fillPolygons(t,e){return this._fillPolygons(t,e)}_fillPolygons(t,e){const s=n(t,e);return{type:"fillSketch",ops:this.renderLines(s,e)}}renderLines(t,e){const s=[];for(const n of t)s.push(...this.helper.doubleLineOps(n[0][0],n[0][1],n[1][0],n[1][1],e));return s}}function a(t){const e=t[0],s=t[1];return Math.sqrt(Math.pow(e[0]-s[0],2)+Math.pow(e[1]-s[1],2))}class h extends o{fillPolygons(t,e){let s=e.hachureGap;s<0&&(s=4*e.strokeWidth),s=Math.max(s,.1);const o=n(t,Object.assign({},e,{hachureGap:s})),h=Math.PI/180*e.hachureAngle,r=[],i=.5*s*Math.cos(h),c=.5*s*Math.sin(h);for(const[t,e]of o)a([t,e])&&r.push([[t[0]-i,t[1]+c],[...e]],[[t[0]+i,t[1]-c],[...e]]);return{type:"fillSketch",ops:this.renderLines(r,e)}}}class r extends o{fillPolygons(t,e){const s=this._fillPolygons(t,e),n=Object.assign({},e,{hachureAngle:e.hachureAngle+90}),o=this._fillPolygons(t,n);return s.ops=s.ops.concat(o.ops),s}}class i{constructor(t){this.helper=t}fillPolygons(t,e){const s=n(t,e=Object.assign({},e,{hachureAngle:0}));return this.dotsOnLines(s,e)}dotsOnLines(t,e){const s=[];let n=e.hachureGap;n<0&&(n=4*e.strokeWidth),n=Math.max(n,.1);let o=e.fillWeight;o<0&&(o=e.strokeWidth/2);const h=n/4;for(const r of t){const t=a(r),i=t/n,c=Math.ceil(i)-1,l=t-c*n,u=(r[0][0]+r[1][0])/2-n/4,p=Math.min(r[0][1],r[1][1]);for(let t=0;t{const h=a(t),r=Math.floor(h/(s+n)),i=(h+n-r*(s+n))/2;let c=t[0],l=t[1];c[0]>l[0]&&(c=t[1],l=t[0]);const u=Math.atan((l[1]-c[1])/(l[0]-c[0]));for(let t=0;t{const o=a(t),h=Math.round(o/(2*e));let r=t[0],i=t[1];r[0]>i[0]&&(r=t[1],i=t[0]);const c=Math.atan((i[1]-r[1])/(i[0]-r[0]));for(let t=0;tn%2?t+s:t+e));a.push({key:"C",data:t}),e=t[4],s=t[5];break}case"Q":a.push({key:"Q",data:[...r]}),e=r[2],s=r[3];break;case"q":{const t=r.map(((t,n)=>n%2?t+s:t+e));a.push({key:"Q",data:t}),e=t[2],s=t[3];break}case"A":a.push({key:"A",data:[...r]}),e=r[5],s=r[6];break;case"a":e+=r[5],s+=r[6],a.push({key:"A",data:[r[0],r[1],r[2],r[3],r[4],e,s]});break;case"H":a.push({key:"H",data:[...r]}),e=r[0];break;case"h":e+=r[0],a.push({key:"H",data:[e]});break;case"V":a.push({key:"V",data:[...r]}),s=r[0];break;case"v":s+=r[0],a.push({key:"V",data:[s]});break;case"S":a.push({key:"S",data:[...r]}),e=r[2],s=r[3];break;case"s":{const t=r.map(((t,n)=>n%2?t+s:t+e));a.push({key:"S",data:t}),e=t[2],s=t[3];break}case"T":a.push({key:"T",data:[...r]}),e=r[0],s=r[1];break;case"t":e+=r[0],s+=r[1],a.push({key:"T",data:[e,s]});break;case"Z":case"z":a.push({key:"Z",data:[]}),e=n,s=o}return a}function m(t){const e=[];let s="",n=0,o=0,a=0,h=0,r=0,i=0;for(const{key:c,data:l}of t){switch(c){case"M":e.push({key:"M",data:[...l]}),[n,o]=l,[a,h]=l;break;case"C":e.push({key:"C",data:[...l]}),n=l[4],o=l[5],r=l[2],i=l[3];break;case"L":e.push({key:"L",data:[...l]}),[n,o]=l;break;case"H":n=l[0],e.push({key:"L",data:[n,o]});break;case"V":o=l[0],e.push({key:"L",data:[n,o]});break;case"S":{let t=0,a=0;"C"===s||"S"===s?(t=n+(n-r),a=o+(o-i)):(t=n,a=o),e.push({key:"C",data:[t,a,...l]}),r=l[0],i=l[1],n=l[2],o=l[3];break}case"T":{const[t,a]=l;let h=0,c=0;"Q"===s||"T"===s?(h=n+(n-r),c=o+(o-i)):(h=n,c=o);const u=n+2*(h-n)/3,p=o+2*(c-o)/3,f=t+2*(h-t)/3,d=a+2*(c-a)/3;e.push({key:"C",data:[u,p,f,d,t,a]}),r=h,i=c,n=t,o=a;break}case"Q":{const[t,s,a,h]=l,c=n+2*(t-n)/3,u=o+2*(s-o)/3,p=a+2*(t-a)/3,f=h+2*(s-h)/3;e.push({key:"C",data:[c,u,p,f,a,h]}),r=t,i=s,n=a,o=h;break}case"A":{const t=Math.abs(l[0]),s=Math.abs(l[1]),a=l[2],h=l[3],r=l[4],i=l[5],c=l[6];if(0===t||0===s)e.push({key:"C",data:[n,o,i,c,i,c]}),n=i,o=c;else if(n!==i||o!==c){x(n,o,i,c,t,s,a,h,r).forEach((function(t){e.push({key:"C",data:t})})),n=i,o=c}break}case"Z":e.push({key:"Z",data:[]}),n=a,o=h}s=c}return e}function w(t,e,s){return[t*Math.cos(s)-e*Math.sin(s),t*Math.sin(s)+e*Math.cos(s)]}function x(t,e,s,n,o,a,h,r,i,c){const l=(u=h,Math.PI*u/180);var u;let p=[],f=0,d=0,g=0,M=0;if(c)[f,d,g,M]=c;else{[t,e]=w(t,e,-l),[s,n]=w(s,n,-l);const h=(t-s)/2,c=(e-n)/2;let u=h*h/(o*o)+c*c/(a*a);u>1&&(u=Math.sqrt(u),o*=u,a*=u);const p=o*o,k=a*a,b=p*k-p*c*c-k*h*h,y=p*c*c+k*h*h,m=(r===i?-1:1)*Math.sqrt(Math.abs(b/y));g=m*o*c/a+(t+s)/2,M=m*-a*h/o+(e+n)/2,f=Math.asin(parseFloat(((e-M)/a).toFixed(9))),d=Math.asin(parseFloat(((n-M)/a).toFixed(9))),td&&(f-=2*Math.PI),!i&&d>f&&(d-=2*Math.PI)}let k=d-f;if(Math.abs(k)>120*Math.PI/180){const t=d,e=s,r=n;d=i&&d>f?f+120*Math.PI/180*1:f+120*Math.PI/180*-1,p=x(s=g+o*Math.cos(d),n=M+a*Math.sin(d),e,r,o,a,h,0,i,[d,t,g,M])}k=d-f;const b=Math.cos(f),y=Math.sin(f),m=Math.cos(d),P=Math.sin(d),v=Math.tan(k/4),S=4/3*o*v,O=4/3*a*v,L=[t,e],T=[t+S*y,e-O*b],D=[s+S*P,n-O*m],A=[s,n];if(T[0]=2*L[0]-T[0],T[1]=2*L[1]-T[1],c)return[T,D,A].concat(p);{p=[T,D,A].concat(p);const t=[];for(let e=0;e2){const o=[];for(let e=0;e2*Math.PI&&(f=0,d=2*Math.PI);const g=2*Math.PI/i.curveStepCount,M=Math.min(g/2,(d-f)/2),k=V(M,c,l,u,p,f,d,1,i);if(!i.disableMultiStroke){const t=V(M,c,l,u,p,f,d,1.5,i);k.push(...t)}return h&&(r?k.push(...$(c,l,c+u*Math.cos(f),l+p*Math.sin(f),i),...$(c,l,c+u*Math.cos(d),l+p*Math.sin(d),i)):k.push({op:"lineTo",data:[c,l]},{op:"lineTo",data:[c+u*Math.cos(f),l+p*Math.sin(f)]})),{type:"path",ops:k}}function _(t,e){const s=m(y(b(t))),n=[];let o=[0,0],a=[0,0];for(const{key:t,data:h}of s)switch(t){case"M":a=[h[0],h[1]],o=[h[0],h[1]];break;case"L":n.push(...$(a[0],a[1],h[0],h[1],e)),a=[h[0],h[1]];break;case"C":{const[t,s,o,r,i,c]=h;n.push(...Z(t,s,o,r,i,c,a,e)),a=[i,c];break}case"Z":n.push(...$(a[0],a[1],o[0],o[1],e)),a=[o[0],o[1]]}return{type:"path",ops:n}}function I(t,e){const s=[];for(const n of t)if(n.length){const t=e.maxRandomnessOffset||0,o=n.length;if(o>2){s.push({op:"move",data:[n[0][0]+G(t,e),n[0][1]+G(t,e)]});for(let a=1;a500?.4:-.0016668*i+1.233334;let l=o.maxRandomnessOffset||0;l*l*100>r&&(l=i/10);const u=l/2,p=.2+.2*W(o);let f=o.bowing*o.maxRandomnessOffset*(n-e)/200,d=o.bowing*o.maxRandomnessOffset*(t-s)/200;f=G(f,o,c),d=G(d,o,c);const g=[],M=()=>G(u,o,c),k=()=>G(l,o,c),b=o.preserveVertices;return a&&(h?g.push({op:"move",data:[t+(b?0:M()),e+(b?0:M())]}):g.push({op:"move",data:[t+(b?0:G(l,o,c)),e+(b?0:G(l,o,c))]})),h?g.push({op:"bcurveTo",data:[f+t+(s-t)*p+M(),d+e+(n-e)*p+M(),f+t+2*(s-t)*p+M(),d+e+2*(n-e)*p+M(),s+(b?0:M()),n+(b?0:M())]}):g.push({op:"bcurveTo",data:[f+t+(s-t)*p+k(),d+e+(n-e)*p+k(),f+t+2*(s-t)*p+k(),d+e+2*(n-e)*p+k(),s+(b?0:k()),n+(b?0:k())]}),g}function j(t,e,s){if(!t.length)return[];const n=[];n.push([t[0][0]+G(e,s),t[0][1]+G(e,s)]),n.push([t[0][0]+G(e,s),t[0][1]+G(e,s)]);for(let o=1;o3){const a=[],h=1-s.curveTightness;o.push({op:"move",data:[t[1][0],t[1][1]]});for(let e=1;e+21&&o.push(s)}else o.push(s);o.push(t[e+3])}else{const n=.5,a=t[e+0],h=t[e+1],r=t[e+2],i=t[e+3],c=J(a,h,n),l=J(h,r,n),u=J(r,i,n),p=J(c,l,n),f=J(l,u,n),d=J(p,f,n);K([a,c,p,d],0,s,o),K([d,f,u,i],0,s,o)}var a,h;return o}function U(t,e){return X(t,0,t.length,e)}function X(t,e,s,n,o){const a=o||[],h=t[e],r=t[s-1];let i=0,c=1;for(let n=e+1;ni&&(i=e,c=n)}return Math.sqrt(i)>n?(X(t,e,c+1,n,a),X(t,c,s,n,a)):(a.length||a.push(h),a.push(r)),a}function Y(t,e=.15,s){const n=[],o=(t.length-1)/3;for(let s=0;s0?X(n,0,n.length,s):n}const tt="none";class et{constructor(t){this.defaultOptions={maxRandomnessOffset:2,roughness:1,bowing:1,stroke:"#000",strokeWidth:1,curveTightness:0,curveFitting:.95,curveStepCount:9,fillStyle:"hachure",fillWeight:-1,hachureAngle:-41,hachureGap:-1,dashOffset:-1,dashGap:-1,zigzagOffset:-1,seed:0,disableMultiStroke:!1,disableMultiStrokeFill:!1,preserveVertices:!1,fillShapeRoughnessGain:.8},this.config=t||{},this.config.options&&(this.defaultOptions=this._o(this.config.options))}static newSeed(){return Math.floor(Math.random()*2**31)}_o(t){return t?Object.assign({},this.defaultOptions,t):this.defaultOptions}_d(t,e,s){return{shape:t,sets:e||[],options:s||this.defaultOptions}}line(t,e,s,n,o){const a=this._o(o);return this._d("line",[v(t,e,s,n,a)],a)}rectangle(t,e,s,n,o){const a=this._o(o),h=[],r=O(t,e,s,n,a);if(a.fill){const o=[[t,e],[t+s,e],[t+s,e+n],[t,e+n]];"solid"===a.fillStyle?h.push(I([o],a)):h.push(C([o],a))}return a.stroke!==tt&&h.push(r),this._d("rectangle",h,a)}ellipse(t,e,s,n,o){const a=this._o(o),h=[],r=T(s,n,a),i=D(t,e,a,r);if(a.fill)if("solid"===a.fillStyle){const s=D(t,e,a,r).opset;s.type="fillPath",h.push(s)}else h.push(C([i.estimatedPoints],a));return a.stroke!==tt&&h.push(i.opset),this._d("ellipse",h,a)}circle(t,e,s,n){const o=this.ellipse(t,e,s,s,n);return o.shape="circle",o}linearPath(t,e){const s=this._o(e);return this._d("linearPath",[S(t,!1,s)],s)}arc(t,e,s,n,o,a,h=!1,r){const i=this._o(r),c=[],l=A(t,e,s,n,o,a,h,!0,i);if(h&&i.fill)if("solid"===i.fillStyle){const h=Object.assign({},i);h.disableMultiStroke=!0;const r=A(t,e,s,n,o,a,!0,!1,h);r.type="fillPath",c.push(r)}else c.push(function(t,e,s,n,o,a,h){const r=t,i=e;let c=Math.abs(s/2),l=Math.abs(n/2);c+=G(.01*c,h),l+=G(.01*l,h);let u=o,p=a;for(;u<0;)u+=2*Math.PI,p+=2*Math.PI;p-u>2*Math.PI&&(u=0,p=2*Math.PI);const f=(p-u)/h.curveStepCount,d=[];for(let t=u;t<=p;t+=f)d.push([r+c*Math.cos(t),i+l*Math.sin(t)]);return d.push([r+c*Math.cos(p),i+l*Math.sin(p)]),d.push([r,i]),C([d],h)}(t,e,s,n,o,a,i));return i.stroke!==tt&&c.push(l),this._d("arc",c,i)}curve(t,e){const s=this._o(e),n=[],o=L(t,s);if(s.fill&&s.fill!==tt)if("solid"===s.fillStyle){const e=L(t,Object.assign(Object.assign({},s),{disableMultiStroke:!0,roughness:s.roughness?s.roughness+s.fillShapeRoughnessGain:0}));n.push({type:"fillPath",ops:this._mergedShape(e.ops)})}else{const e=[],o=t;if(o.length){const t="number"==typeof o[0][0]?[o]:o;for(const n of t)n.length<3?e.push(...n):3===n.length?e.push(...Y(H([n[0],n[0],n[1],n[2]]),10,(1+s.roughness)/2)):e.push(...Y(H(n),10,(1+s.roughness)/2))}e.length&&n.push(C([e],s))}return s.stroke!==tt&&n.push(o),this._d("curve",n,s)}polygon(t,e){const s=this._o(e),n=[],o=S(t,!0,s);return s.fill&&("solid"===s.fillStyle?n.push(I([t],s)):n.push(C([t],s))),s.stroke!==tt&&n.push(o),this._d("polygon",n,s)}path(t,e){const s=this._o(e),n=[];if(!t)return this._d("path",n,s);t=(t||"").replace(/\n/g," ").replace(/(-\s)/g,"-").replace("/(ss)/g"," ");const o=s.fill&&"transparent"!==s.fill&&s.fill!==tt,a=s.stroke!==tt,h=!!(s.simplification&&s.simplification<1),r=function(t,e,s){const n=m(y(b(t))),o=[];let a=[],h=[0,0],r=[];const i=()=>{r.length>=4&&a.push(...Y(r,e)),r=[]},c=()=>{i(),a.length&&(o.push(a),a=[])};for(const{key:t,data:e}of n)switch(t){case"M":c(),h=[e[0],e[1]],a.push(h);break;case"L":i(),a.push([e[0],e[1]]);break;case"C":if(!r.length){const t=a.length?a[a.length-1]:h;r.push([t[0],t[1]])}r.push([e[0],e[1]]),r.push([e[2],e[3]]),r.push([e[4],e[5]]);break;case"Z":i(),a.push([h[0],h[1]])}if(c(),!s)return o;const l=[];for(const t of o){const e=U(t,s);e.length&&l.push(e)}return l}(t,1,h?4-4*(s.simplification||1):(1+s.roughness)/2),i=_(t,s);if(o)if("solid"===s.fillStyle)if(1===r.length){const e=_(t,Object.assign(Object.assign({},s),{disableMultiStroke:!0,roughness:s.roughness?s.roughness+s.fillShapeRoughnessGain:0}));n.push({type:"fillPath",ops:this._mergedShape(e.ops)})}else n.push(I(r,s));else n.push(C(r,s));return a&&(h?r.forEach((t=>{n.push(S(t,!1,s))})):n.push(i)),this._d("path",n,s)}opsToPath(t,e){let s="";for(const n of t.ops){const t="number"==typeof e&&e>=0?n.data.map((t=>+t.toFixed(e))):n.data;switch(n.op){case"move":s+=`M${t[0]} ${t[1]} `;break;case"bcurveTo":s+=`C${t[0]} ${t[1]}, ${t[2]} ${t[3]}, ${t[4]} ${t[5]} `;break;case"lineTo":s+=`L${t[0]} ${t[1]} `}}return s.trim()}toPaths(t){const e=t.sets||[],s=t.options||this.defaultOptions,n=[];for(const t of e){let e=null;switch(t.type){case"path":e={d:this.opsToPath(t),stroke:s.stroke,strokeWidth:s.strokeWidth,fill:tt};break;case"fillPath":e={d:this.opsToPath(t),stroke:tt,strokeWidth:0,fill:s.fill||tt};break;case"fillSketch":e=this.fillSketch(t,s)}e&&n.push(e)}return n}fillSketch(t,e){let s=e.fillWeight;return s<0&&(s=e.strokeWidth/2),{d:this.opsToPath(t),stroke:e.fill||tt,strokeWidth:s,fill:tt}}_mergedShape(t){return t.filter(((t,e)=>0===e||"move"!==t.op))}}class st{constructor(t,e){this.canvas=t,this.ctx=this.canvas.getContext("2d"),this.gen=new et(e)}draw(t){const e=t.sets||[],s=t.options||this.getDefaultOptions(),n=this.ctx,o=t.options.fixedDecimalPlaceDigits;for(const a of e)switch(a.type){case"path":n.save(),n.strokeStyle="none"===s.stroke?"transparent":s.stroke,n.lineWidth=s.strokeWidth,s.strokeLineDash&&n.setLineDash(s.strokeLineDash),s.strokeLineDashOffset&&(n.lineDashOffset=s.strokeLineDashOffset),this._drawToContext(n,a,o),n.restore();break;case"fillPath":{n.save(),n.fillStyle=s.fill||"";const e="curve"===t.shape||"polygon"===t.shape||"path"===t.shape?"evenodd":"nonzero";this._drawToContext(n,a,o,e),n.restore();break}case"fillSketch":this.fillSketch(n,a,s)}}fillSketch(t,e,s){let n=s.fillWeight;n<0&&(n=s.strokeWidth/2),t.save(),s.fillLineDash&&t.setLineDash(s.fillLineDash),s.fillLineDashOffset&&(t.lineDashOffset=s.fillLineDashOffset),t.strokeStyle=s.fill||"",t.lineWidth=n,this._drawToContext(t,e,s.fixedDecimalPlaceDigits),t.restore()}_drawToContext(t,e,s,n="nonzero"){t.beginPath();for(const n of e.ops){const e="number"==typeof s&&s>=0?n.data.map((t=>+t.toFixed(s))):n.data;switch(n.op){case"move":t.moveTo(e[0],e[1]);break;case"bcurveTo":t.bezierCurveTo(e[0],e[1],e[2],e[3],e[4],e[5]);break;case"lineTo":t.lineTo(e[0],e[1])}}"fillPath"===e.type?t.fill(n):t.stroke()}get generator(){return this.gen}getDefaultOptions(){return this.gen.defaultOptions}line(t,e,s,n,o){const a=this.gen.line(t,e,s,n,o);return this.draw(a),a}rectangle(t,e,s,n,o){const a=this.gen.rectangle(t,e,s,n,o);return this.draw(a),a}ellipse(t,e,s,n,o){const a=this.gen.ellipse(t,e,s,n,o);return this.draw(a),a}circle(t,e,s,n){const o=this.gen.circle(t,e,s,n);return this.draw(o),o}linearPath(t,e){const s=this.gen.linearPath(t,e);return this.draw(s),s}polygon(t,e){const s=this.gen.polygon(t,e);return this.draw(s),s}arc(t,e,s,n,o,a,h=!1,r){const i=this.gen.arc(t,e,s,n,o,a,h,r);return this.draw(i),i}curve(t,e){const s=this.gen.curve(t,e);return this.draw(s),s}path(t,e){const s=this.gen.path(t,e);return this.draw(s),s}}const nt="http://www.w3.org/2000/svg";class ot{constructor(t,e){this.svg=t,this.gen=new et(e)}draw(t){const e=t.sets||[],s=t.options||this.getDefaultOptions(),n=this.svg.ownerDocument||window.document,o=n.createElementNS(nt,"g"),a=t.options.fixedDecimalPlaceDigits;for(const h of e){let e=null;switch(h.type){case"path":e=n.createElementNS(nt,"path"),e.setAttribute("d",this.opsToPath(h,a)),e.setAttribute("stroke",s.stroke),e.setAttribute("stroke-width",s.strokeWidth+""),e.setAttribute("fill","none"),s.strokeLineDash&&e.setAttribute("stroke-dasharray",s.strokeLineDash.join(" ").trim()),s.strokeLineDashOffset&&e.setAttribute("stroke-dashoffset",`${s.strokeLineDashOffset}`);break;case"fillPath":e=n.createElementNS(nt,"path"),e.setAttribute("d",this.opsToPath(h,a)),e.setAttribute("stroke","none"),e.setAttribute("stroke-width","0"),e.setAttribute("fill",s.fill||""),"curve"!==t.shape&&"polygon"!==t.shape||e.setAttribute("fill-rule","evenodd");break;case"fillSketch":e=this.fillSketch(n,h,s)}e&&o.appendChild(e)}return o}fillSketch(t,e,s){let n=s.fillWeight;n<0&&(n=s.strokeWidth/2);const o=t.createElementNS(nt,"path");return o.setAttribute("d",this.opsToPath(e,s.fixedDecimalPlaceDigits)),o.setAttribute("stroke",s.fill||""),o.setAttribute("stroke-width",n+""),o.setAttribute("fill","none"),s.fillLineDash&&o.setAttribute("stroke-dasharray",s.fillLineDash.join(" ").trim()),s.fillLineDashOffset&&o.setAttribute("stroke-dashoffset",`${s.fillLineDashOffset}`),o}get generator(){return this.gen}getDefaultOptions(){return this.gen.defaultOptions}opsToPath(t,e){return this.gen.opsToPath(t,e)}line(t,e,s,n,o){const a=this.gen.line(t,e,s,n,o);return this.draw(a)}rectangle(t,e,s,n,o){const a=this.gen.rectangle(t,e,s,n,o);return this.draw(a)}ellipse(t,e,s,n,o){const a=this.gen.ellipse(t,e,s,n,o);return this.draw(a)}circle(t,e,s,n){const o=this.gen.circle(t,e,s,n);return this.draw(o)}linearPath(t,e){const s=this.gen.linearPath(t,e);return this.draw(s)}polygon(t,e){const s=this.gen.polygon(t,e);return this.draw(s)}arc(t,e,s,n,o,a,h=!1,r){const i=this.gen.arc(t,e,s,n,o,a,h,r);return this.draw(i)}curve(t,e){const s=this.gen.curve(t,e);return this.draw(s)}path(t,e){const s=this.gen.path(t,e);return this.draw(s)}}var at={canvas:(t,e)=>new st(t,e),svg:(t,e)=>new ot(t,e),generator:t=>new et(t),newSeed:()=>et.newSeed()};export{at as default}; diff --git a/ARTICLES.md b/ARTICLES.md index 4fadb18..ad81c0e 100644 --- a/ARTICLES.md +++ b/ARTICLES.md @@ -150,7 +150,7 @@ The word means different things in different articles. Each article says which o ## Framework -- `framework` — The whole design interview, one block per step: how the interview runs and what interviewers check; functional requirements (users and their main actions, core scenarios, scope, when to move on); non-functional requirements and estimates; API and data model; high-level design; deep dives, picked by the type of system; presenting the design and defending trade-offs. Each block gives the purpose of the step, example questions, expected outputs, and time to spend. +- `framework` **(written)** — The whole design interview, one block per step: how the interview runs and what interviewers check; defending a decision; opening; functional and non-functional requirements; estimates in two passes; API, entities, data plane and control plane; data flow; high-level design; the key part and choosing technologies; resources, cost, and operations as optional steps; deep dives by type of system; wrap-up. Each step says when to take it, what to ask, what stays on the board, and how long it takes. How to pick requirements and how to count go to `fundamentals/requirements`. ## Practices diff --git a/WRITING.md b/WRITING.md index cf037ef..8d0a0fd 100644 --- a/WRITING.md +++ b/WRITING.md @@ -21,7 +21,7 @@ What an article on this site must look like. Read it before you add or change a - ends with one short standalone sentence that names the next problem, but only when this block's solution causes it ("the file keeps growing"). When the next block starts from a new feature or requirement, end without a bridge: the next block opens with it. The last block never bridges to another article. 4. **Callouts, tables, and diagrams** go where the point comes up, not in a fixed order (see below). 5. **Mark as read.** Put `::mark-as-read` after the last block and before the cheat sheet, and again at the very end of the article, after the sources. Do not add it to the framework page. -6. **Cheat sheet.** The last section: one line per block, for a quick review before an interview. Keep the conditions from the text; a cheat sheet line must never state a stricter or broader rule than the block it comes from. +6. **Cheat sheet.** The last section: one line per block, for a quick review before an interview. Keep the conditions from the text; a cheat sheet line must never state a stricter or broader rule than the block it comes from. The framework page has no cheat sheet and no Sources section: it is itself a page to review before an interview, read in full. ## Style @@ -76,6 +76,18 @@ Diagrams let the reader see the material on the running example, and grasp it fa - Every SVG has `role="img"`, `aria-labelledby`, a ``, and a `<desc>` that says what the diagram shows (it is the alt text). Prefix all IDs with the diagram name. - Before showing a diagram, check it in both themes and at phone width. +### Board diagrams + +The rules above are for explaining diagrams, which teach one idea in a crisp style. A board diagram shows a system being designed as a candidate draws it on an interview whiteboard: hand-drawn shapes, the board font, short text. Use it on the framework page and in system design articles, for the design and the text written next to it. Everything else stays an explaining diagram. + +- Draw only what a candidate can draw in an interview: a few shapes, lines, and short text. No accent color and no bold. +- Write a scene in `src/diagrams/board/<page>.mjs` and render it with the [board-diagrams](.agents/skills/board-diagrams/SKILL.md) skill. Never edit the SVG by hand. Insert it with `::diagram`, as any diagram. +- A design grows one scenario at a time, in steps. Each view has a caption that says what it shows. The key part and the design after a deep dive are the whole board with what matters in focus. +- A step before the design leaves board text: a heading and short lines, as a candidate writes them. What is only spoken, such as the wrap-up, goes into the prose as a quote. +- The board uses the numbers and names of the prose. When the text says the queue keeps messages 7 days, so does the note on the board. +- The rules and their reasons are in the skill's DECISIONS.md. Add each new decision about board diagrams there. +- Step through every view in both themes and at phone width before showing it. + ## Other articles [ARTICLES.md](ARTICLES.md) is the map of written and planned articles. Use it to decide what goes into this article and what gets one line plus a link to another one. @@ -111,7 +123,7 @@ The glossary (`src/data/glossary.mjs`) is the one place where terms are defined. - The author names the sources for each article: study notes, books, sites, or their own experience. - Back every claim with a primary source: a specification, official documentation, a paper, an engineering post about a real system, or a book that goes deep. Interview prep books, such as Alex Xu's, are often shallow: they show what interviews ask, but they are never the proof of a claim. - Prefer current material. When a topic changed in recent years (a new standard, a new database feature, a new practice), say what is current, not only the classic cases. -- The article ends with a `## Sources` section after the cheat sheet: one list of the books, papers, and articles whose ideas made it into the text. Books come first, then papers and articles; each group is sorted by the first author's last name. The text has no footnotes. +- The article ends with a `## Sources` section after the cheat sheet (the framework page has neither): one list of the books, papers, and articles whose ideas made it into the text. Books come first, then papers and articles; each group is sorted by the first author's last name. The text has no footnotes. - A book entry gives the authors, the title as a link, the edition, the publisher, the year, and the chapters used: "Martin Kleppmann, Chris Riccomini. [Designing Data-Intensive Applications](https://www.oreilly.com/library/view/designing-data-intensive-applications/9781098119058/), 2nd edition. O'Reilly, 2026. Chapter 7." Link the edition you used, on the publisher's site, or on the book's own site or a store when the publisher has no page. A paper or an article gives the authors or the company, the title as a link, where it appeared, and the year. - List only English books and articles. When we read a translation or another language's edition, cite the English edition; when there is none, leave the source out. Personal notes are never a source: cite the book or article they summarize. - A number or a test result taken from a source, such as a benchmark in a book, links to that source in the text: end the sentence with the author's name as a link, for example "([Angelakos](https://www.manning.com/books/postgresql-mistakes-and-how-to-avoid-them))". Name the conditions of the test that matter (data size, hardware, number of clients) and never present a single test as a general rule. diff --git a/astro.config.mjs b/astro.config.mjs index 0e875ca..ad62559 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -8,7 +8,6 @@ export default defineTech0verConfig({ brand: { name: 'SystemDesign', suffix: '0ver' }, sidebarWidth: 256, reading: { position: { ignoreSections: ['cheat-sheet', 'sources'] } }, - plannedTopLevel: [{ label: 'Framework', slug: 'framework' }], plannedTopics: { Fundamentals: [ { label: 'Messaging', slug: 'fundamentals/messaging' }, @@ -99,6 +98,7 @@ export default defineTech0verConfig({ Footer: './src/components/Footer.astro', }, sidebar: [ + 'framework', { label: 'Fundamentals', items: ['fundamentals/networking', 'fundamentals/storage-engines', 'fundamentals/databases', 'fundamentals/transactions', 'fundamentals/replication', 'fundamentals/sharding', 'fundamentals/consistency', 'fundamentals/caching', 'fundamentals/encoding'], diff --git a/board-diagrams.json b/board-diagrams.json new file mode 100644 index 0000000..2e16312 --- /dev/null +++ b/board-diagrams.json @@ -0,0 +1,6 @@ +{ + "scenes": "src/diagrams/board", + "output": "src/diagrams", + "medium": 16, + "small": 14 +} diff --git a/src/content/docs/framework.md b/src/content/docs/framework.md new file mode 100644 index 0000000..b4f193a --- /dev/null +++ b/src/content/docs/framework.md @@ -0,0 +1,330 @@ +--- +title: Framework +description: How to run a system design interview step by step, from the first question to the wrap-up, and what each step leaves on the board. +sidebar: + badge: WIP +--- + +A design interview gives you about an hour to turn a vague task into a working system and defend every choice in it. A framework tells you what to do at each moment of that hour, what to ask, and what to leave on the board. + +## How a design interview runs + +The interviewer gives a short task: "Design a notification service. Other teams call it to send push notifications, SMS, and email to users." The task is vague on purpose. How many users, which messages, and how fast they must arrive are for you to find out. + +The interview lasts 45 to 90 minutes. Introductions and your questions at the end take 5 to 15 of them, and the rest goes to the design. + +You lead the interview: ask the questions, make the decisions, draw, and say what comes next. The interviewer probes: asks why, changes a requirement, or pushes you into one component. The less the interviewer has to steer you, the stronger the result. + +An hour is too short to design a real system, and the interview does not ask for one. The interviewer has a system in mind and the problems it should lead to. You find that system by asking questions, and you show how you would build it by suggesting options, discussing them, and explaining your choices. The interviewer judges this as much as the design. + +The interviewer looks for five things: + +- A working system. By the end, every core scenario has a path through the design. Running out of time with half a system built is a common way to fail. +- Decisions with reasons. Each choice comes with the reason for it and the option you turned down. +- Numbers that change something. An estimate counts only when a decision uses it. +- Depth where it matters. Where the requirements are hard, you go below the boxes: the data model, what fails, where the limits are. +- A board that reads without you. Someone who missed the talk can follow the requirements, the numbers, and the design. + +Cover every step briefly, and go deep in two or three places. You pick the places, and the choice is part of what the interviewer judges. + +The steps below are a default order. Each range is the time for the step in a design part of 35 to 75 minutes: take the low end in a short interview. An optional step depends on the interviewer and the system, and a skipped step gives its time to the deep dives. + +| Step | What stays on the board | Minutes | +|---|---|---| +| Opening | The task in your words, the plan, what already exists | 1–3 | +| Functional requirements | Three to five scenarios, what is out of scope | 3–5 | +| Non-functional requirements | Qualities with numbers, ranked | 3–5 | +| Estimates | Rates and sizes, each with the decision it feeds | 1–5 | +| API and entities | One call per scenario, the main entities | 3–7 | +| Data flow (optional) | The stages data goes through | 0–5 | +| High-level design | Components, the path of each scenario, the data in each store | 8–15 | +| Key part and technologies | Load and keys of the key data, products with reasons | 5–10 | +| Deep dives | Two or three problems solved in depth | 8–20 | +| Resources (optional) | Servers per component | 0–5 | +| Cost (optional) | The main cost item, a monthly total | 0–3 | +| Operations (optional) | What fails and what you do, how you release | 0–7 | +| Wrap-up | Which requirements are met, what comes next | 1–3 | + +## Defending a decision + +Halfway through the design you put a queue in front of the senders, and the interviewer asks why. A full answer has four parts: the decision, the reason from the requirements or the numbers, the option you turned down, and when that option would win. "A queue, because a provider can be slow for minutes and callers must not wait for it. Calling the provider directly is simpler and wins when the caller needs the result in its response." + +Give the reason when you make the decision, before anyone asks. A choice explained only under questioning looks like a guess. + +Lead with the technical answer, and add the cost after it. Asked how many copies of the data to keep, say how many, where they live, and which failure they survive. Then say what the copies cost and where you would save, such as fewer copies of data you can rebuild. + +Every number you assume needs a source: the interviewer said it, you derived it from another number, or you know it from a similar system. When the interviewer gives no number, say your assumption aloud with its source and ask whether it fits: "Every team in the company sends through us, so assume the whole user base, about 50 million people. Is that the right scale?" + +When two options are close, name both, pick one with a reason, and ask whether the interviewer wants to go the other way. The interviewer often has a direction in mind and will tell you. When you do not know a detail, say what you would check and which assumption you use until then. + +The interviewer will interrupt: ask about a component before you reach it, or change a requirement. Answer, then say where you were and go back to the plan. When the change breaks an earlier decision, say which one and fix it on the board. A question about a component often means the interviewer wants depth there. + +:::avoid +"It depends" as the whole answer. Name what it depends on, pick an option for the requirements you have, and say what would change the choice. +::: + +## Opening the interview + +The first minutes decide what you build and how the hour goes. Spend one to three of them here, before the first requirement. + +Restate the task in one sentence, in your own words: "A service that other teams call to deliver a message to a user by push, SMS, or email." If you misread the task, the interviewer corrects you now, not after twenty minutes of design. + +Say the plan: the steps you will go through, in order, with the optional ones marked. The interviewer now knows where you are going and can change the route early: "Skip the API, I care more about delivery." + +Ask what already exists: a message queue, a user database, or an auth service you can call, or an old system you must work with, along with its limits. Most tasks start from scratch, and the usual answer is "assume standard infrastructure". The question still pays off: you can treat the parts outside the task as given and spend the time on its core. + +The opening leaves three lines in the corner of the board, and they stay there for the whole interview: + +::diagram{name="framework-opening"} + +:::avoid +A long list of questions in the opening. The opening needs three things: the task in your words, the plan, and what already exists. +::: + +## Functional requirements + +Functional requirements say what the system does for the people and services that use it. They set the scope of the hour: everything you design later serves one of them. The step takes three to five minutes. + +Start with who uses the system. A notification service has two sides: the teams that send messages and the users who receive them. Then write the scenarios as short sentences with an actor and an action. Propose them yourself and ask the interviewer to confirm or reorder: "These are the scenarios I see. Which ones matter most to you?" An open "What should it do?" hands the lead to the interviewer. + +Of three to five scenarios, keep the two or three you will design. Write the rest after "Out:" as out of scope: the interviewer sees that you know about them and chose to leave them out. When the interviewer agrees on the core scenarios, move on. <!-- link: fundamentals/requirements --> + +::diagram{name="framework-functional"} + +:::avoid +Qualities in the list of scenarios, such as "sending is fast" or "nothing is lost". A scenario is an actor and an action. +::: + +## Non-functional requirements + +Non-functional requirements say how well the system must do its job: how fast, how reliably, at what scale. They decide most of the design. Two systems with the same scenarios look different at a thousand and at a billion messages a day. The step takes three to five minutes. + +Walk through a short list of qualities and keep only the ones that change the design: + +- Scale: how many users, how many requests, how much data, and how high the peaks go. +- Geography: where the users are, and whether the system must keep working when a whole region fails. +- Latency: how fast each operation answers or takes effect. +- Availability: how much downtime is acceptable. +- Consistency: whether a reader must see the latest write, or can see an older value for a while. +- Durability: whether data may be lost, and how much. +- Others this system needs: order of messages, duplicates, privacy, cost. + +Attach each quality to an operation. Sending a message and checking its status need different answers: a lost message is a failure, but a status that lags by a few seconds is not. + +Give every quality a number. "Fast" becomes "accepted within 100 ms for 99% of requests", and "highly available" becomes 99.99%, about four minutes of downtime a month. A number is what lets a later decision use the requirement. Propose the numbers and ask whether they fit, as with any assumption. + +Rank the qualities, because they conflict. Waiting for more copies of a write makes it safer and slower. Showing the latest data during a network failure may mean refusing the request. The ranking says which quality wins when two of them meet, so you do not argue it again in every component. <!-- link: fundamentals/requirements --> + +::diagram{name="framework-non-functional"} + +:::avoid +"Scalable, available, fast" with no numbers and no ranking. It fits any system, so no decision can use it. +::: + +## Estimates + +Estimates turn the scale from the requirements into the numbers that decisions use: requests per second, data size, and how reads compare to writes. The step takes one to five minutes. + +Many interview guides teach a full estimate right after the requirements. At that point there is no design yet, so many of the numbers never reach a decision. Count in two passes. Right after the requirements, find the order of magnitude of the main numbers. Count the details later, in the time of the decision that needs them: how many nodes, how much memory for a cache. <!-- link: fundamentals/requirements --> + +:::explain +"I will give the scale as rough numbers now and count the details when a decision needs them. Do you want the full estimate now?" If the interviewer says yes, count it now, and still write each number next to the decision it feeds. +::: + +Write next to each number the decision it feeds. If you cannot say what a number changes, skip it. + +Numbers can also keep a design small. A thousand writes a second and a few gigabytes of data fit one database node with a copy for failover. Say so, and do not split the data. + +::diagram{name="framework-estimates"} + +:::avoid +Numbers with no decision next to them. They take time and tell the interviewer nothing about the design. +::: + +## API and entities + +The API is the boundary of the system: what callers send and what they get back. Fixing it now gives every later component a clear job, and the interviewer sees the system from the outside before you open it. The step takes three to seven minutes. + +Start with the entities, the main things the system stores and passes around, and name them. + +Then write one call per core scenario: the operation, its input, and its output. Use the API style the callers expect, usually REST over HTTP, and switch only when a scenario needs it, such as a stream of events to the client. <!-- link: technologies/api-styles --> For each call, check three things: + +- Who calls it, and whether it may. Take the caller's identity from its auth token, not from a field in the request, then check that this caller may do this action on this object. <!-- link: fundamentals/security --> +- What happens on a retry. A caller that timed out sends the request again, so a write takes an idempotency key, and a retry with the same key does not repeat the effect. +- How much it returns. A list grows without limit, so it comes in pages. + +When a call starts work that takes longer than the caller waits, it returns at once with an ID, and the caller checks the result later. + +Split the calls into two groups. The **data plane** is the path that does the system's job at full load, such as sending a message. The **control plane** changes how the system works, such as settings and accounts: it gets far fewer requests and can be slower. The two get different requirements, and the data plane must keep working with the settings it already has when the control plane is down. <!-- link: fundamentals/failures --> + +Write the calls in a short form, and say once that it is a sketch: "This is a sketch of the API. I can write out the exact fields if you want." Any form works if the interviewer can read it, and the one below fits a board. A call is its method and path, the body, and the answer after the arrow. Name the auth once, above the calls. Add a header only when it changes what the call does, such as the idempotency key. Write a status code or a type only when it is not the obvious one: `202` says that the request is accepted and the work is not done yet. + +::diagram{name="framework-api"} + +:::avoid +Every endpoint and every field. Write the calls for the core scenarios, with the fields the scenario needs. +::: + +## Data flow + +Some systems are pipelines: data enters, passes through several stages, and leaves changed or delivered. A message to a user is accepted, checked against the user's settings, built for a channel, sent, and recorded. Before you draw the design of such a system, list its stages. A system that answers each request in one pass, such as a store of user profiles, has no stages worth listing: skip this step and give its time to the deep dives. For a pipeline, the step takes up to five minutes. + +You decide on this step yourself. Say it in one sentence, and the interviewer can still ask you to skip it: "Messages pass through several stages, so I will list them before I draw." + +Write the stages in order as verbs, with what enters and leaves each one. What leaves a stage enters the next, so write a chain: what enters the first stage, then each stage with what it passes on. Mark two kinds of places. Where a stage can be slower than the one before it, data has to wait, and the design must keep it somewhere. Where a stage calls something outside the system, it can fail: a temporary failure is retried without losing the data, and a permanent one, or a timeout that leaves the result unknown, needs its own outcome. <!-- link: fundamentals/messaging --> + +::diagram{name="framework-data-flow"} + +:::avoid +Boxes and products at this step. A stage says what happens to the data. +::: + +## High-level design + +The high-level design is the first working system: every core scenario has a path through it from the caller to the data and back. It meets the functional requirements. The interviewer checks it first, so finish it before you go deep anywhere. The step takes 8 to 15 minutes. + +Build it one scenario at a time, in the order of the API. For each call, draw the path it takes, and add a component only when the path needs it. When the right choice is well known and its reason fits in one sentence, draw it at once and name the simpler option you skipped: "Sending must not wait for the providers, so a queue goes between them. The API could call the provider itself, but then the caller would wait for the provider and could miss the 100 ms to accept." When the choice takes several components or depends on numbers you have not checked, draw the simple version, mark the place, and keep it for a deep dive. + +Draw classes of components, such as a service, a database, a queue, or a cache. A class says what the component must do. + +When a path first stores data, give the data a shape. Next to the store, write what it keeps, the fields this path needs, and the key the path reads by. The way the path reads the data picks the shape. Rows found by different fields or joined with other rows make a table. A whole object fetched by one key is a key-value pair or a document. Large binary data goes to files under a path. A later path that uses the same store adds its own fields. <!-- link: fundamentals/databases --> + +Write the data so that its form shows the shape, with no label. Give a type only where it is not obvious, such as the values of a status: + +- A table: the name, a line, then the columns, with the key marked. A column that the main query reads in order, such as a time, is marked `(sort)`. +- A key-value pair: `settings:{user_id} -> {channels}`, with placeholders in braces, as in the API paths. +- A cache: a key-value pair, plus how long an entry lives and which entry leaves first when memory is full: `TTL 1 min, LRU`. +- A document: the nesting in braces, `order {id, items: [{sku, qty}]}`. +- Files: the path, `media/{user_id}/{file_id}.jpg`. +- A queue keeps data too: what a message holds and how long it stays, `{order_id, items}, kept 7 days`. When order matters, add the key of the messages that must stay in order: `key user_id`. + +Draw the path where everything works first. Then walk it again and ask at each arrow what happens when the next component is slow or down. Find the point where a request counts as accepted, and check what happens when a failure hits between two writes on the path. Mark the answer on the board in one line: a retry, a fallback, a message that waits. + +When reads and writes take different paths, draw both. The control plane can stay one box next to the data plane: it rarely decides the design. + +Keep the board readable. Name each box by its job, label each arrow with what it carries, and number the steps of a path when the order matters. + +::diagram{name="framework-hld"} + +:::avoid +Going deep into one component before every core scenario has a path. If time runs out there, the system does not work end to end. +::: + +## The key part and choosing technologies + +With a working system on the board, find the component where the hardest requirements meet: it carries the peak load, keeps the data that must not be lost, or has to satisfy two requirements that conflict. Usually it is one component, rarely more than two. Name it and say why: "The hard part is accepting a hundred thousand messages a second without losing one." The step takes 5 to 10 minutes. + +The data on the board already has a shape, fields, and a key. For the key component, go further: how many reads and writes the data gets, in what order it is read, and how long it is kept. The main query picks the primary key. When the estimates showed that the data does not fit one node, the main query also suggests the key that spreads the data across nodes. Check that this key spreads the load evenly, with no hot key that gets much more traffic than the rest. + +Then turn each class on the board into a product, starting with the key part. Choose in four moves: + +1. The class from the high-level design, such as a queue or a database. +2. The properties the requirements ask of it: how much load, what must survive a failure, what order, the shape of the data and how it is read. +3. A product that has those properties. +4. The alternative, and when it would win. + +Name open-source products by default. They run anywhere, in your own data centers or in any cloud, and you can explain how they work inside. A managed cloud service hides that work: the interviewer may not know it, may ask you to explain its insides anyway, or may rule it out. Offer it as the alternative where it fits: it spares the team that would run the cluster, and you pay for every request and gigabyte. + +The interviewer will ask how the product keeps copies, what happens when a node fails, and where it stops scaling. Prefer a familiar product you can defend to a better one you cannot explain. (More on [choosing a database](../fundamentals/databases/).) + +::diagram{name="framework-key-part"} + +<!-- link: technologies/kafka --> <!-- link: technologies/rabbitmq --> <!-- link: technologies/cassandra --> + +:::avoid +A product with no property behind it. "We use Kafka" says nothing until you add what the requirements needed from it. +::: + +## Deep dives + +Deep dives take the most time and decide the level of the result. A deep dive takes one hard problem of the design and solves it in full. The deep dives get 8 to 20 minutes, whatever is left after the time you keep for the optional steps. + +Before the first deep dive, ask which of the optional steps the interviewer wants, and keep time for them at the end: "After the deep dives, I can count the servers, estimate the cost, and cover operations. Which of these do you want? I will keep the last ten minutes for them." The optional steps come after the deep dives because they count and run the design you end with. Give each deep dive its share of the remaining time, and when the share runs out, close the deep dive with the choice made and move on. + +Propose the deep dives yourself. Starting from the key part, name two or three problems where the requirements are hardest, and ask which one to take first: "I see three hard spots: not losing an accepted message, not sending a message twice, and a provider that is down for an hour. Where do you want to start?" The interviewer may pick one of yours or bring another. Either way, the list shows that you see the problems before anyone points at them. + +Solve each problem the same way. State it with its numbers. Draw the part of the design it lives in, larger, number the steps, and mark where it breaks. Give two or three options with what each costs, from the simplest to the one that meets the requirement. Pick one, change the design on the board, and say what the choice costs and when you would revisit it. This is the defense of a decision at full depth. + +The problems repeat across systems of one type, so knowing the type tells you where to look: + +| Type of system | Usual deep dives | +|---|---| +| Short links, IDs, counters | [Unique IDs](../patterns/unique-ids/), hot keys, [a cache in front of the store](../fundamentals/caching/), counting at scale <!-- link: patterns/counting --> <!-- link: systems/url-shortener --> | +| Feeds and timelines | Fan-out on write or on read, accounts with millions of followers <!-- link: patterns/news-feed --> | +| Chat and real-time | Long-lived connections, order of messages, offline users, groups <!-- link: patterns/real-time --> | +| Nearby search and maps | Proximity search, a high rate of location updates <!-- link: patterns/proximity-search --> <!-- link: systems/ride-hailing --> | +| Booking and tickets | Two people taking the same seat, [holds that expire](../patterns/reservations/) | +| Payments and balances | Charging exactly once, a ledger, reconciliation <!-- link: patterns/ledger --> | +| Pipelines and notifications | Delivery guarantees, retries and duplicates, slow external services <!-- link: patterns/async-processing --> | +| Search and autocomplete | Building the index, prefix lookup, ranking <!-- link: patterns/search --> | +| Rate limits, locks, schedulers | Counting across nodes, a lock that outlives its holder, missed runs <!-- link: patterns/rate-limiting --> <!-- link: patterns/distributed-locks --> <!-- link: patterns/job-scheduling --> | +| Storage systems | [Splitting data across nodes](../fundamentals/sharding/), [copies](../fundamentals/replication/), consistency, failover | +| Media | Large uploads, processing in stages, delivery through a CDN <!-- link: patterns/large-files --> | + +::diagram{name="framework-deep-dive"} + +::diagram{name="framework-deep-dive-design"} + +:::avoid +Waiting for the interviewer to pick a problem, or going deep where nothing is hard. Both leave the hardest part of the system unexplained. +::: + +## Resources + +Resources turn the numbers into machines for the design you ended with. The step shows whether that design can run at all. It is optional and takes up to five minutes. + +Count only the components that are big, usually the key part and whatever takes the peak load. Say what one server is, as an assumption: "I count in servers of 16 cores and 64 GB of memory." For each component: + +1. Find the dominant resource, the one that runs out first: CPU for encryption and serialization, memory for a cache, disk for a store that keeps months of data, network for media. +2. Divide the load by what one server gives of that resource. +3. Add room for failure. A system that must survive losing one of three zones runs each zone at most two-thirds full, so it needs half again as many servers. + +Then check the latency budget. Add up every step the caller waits for on the path of a request, from the network to the user to the slowest store, each at the percentile of the requirement, and compare the sum with it. The sum is a rough budget: different requests are slow at different steps, so the real percentile is measured end to end. When the sum is over, the design changes: fewer hops, a cache, or work moved out of the request. <!-- link: fundamentals/requirements --> + +::diagram{name="framework-resources"} + +:::avoid +Servers for every box. Small components get "a few servers" and no more of your time. +::: + +## Cost + +Cost shows what the design asks for in money each month, and where money should change the design. It is optional and takes up to three minutes. + +Say where the system runs, as an assumption: cloud instances or your own servers. The two are priced differently: in a cloud you pay for each instance and for each gigabyte stored and sent, while your own servers cost money to buy and people to run. + +Find the main item first. One item is often most of the bill, and it is not always the servers: fees for each paid message, data sent out to users, or logs kept for months. Multiply the amount from the estimates and resources by a round unit price, and give one total with the main item named. <!-- link: fundamentals/requirements --> + +When one item dominates, look for a design change that cuts it, and offer it to the interviewer, since it may change a requirement: "SMS is most of the bill. Can a message try push first and fall back to SMS?" + +::diagram{name="framework-cost"} + +:::avoid +A sum of every component to the last dollar. Name the main item and the total; the rest is rounding. +::: + +## Operations + +Operations show how the system lives after launch: what fails, how you find out, and how you change it without breaking it. The step is optional and takes up to seven minutes. + +Start with failures. For each key component, write what fails, what users see, and what the system does. The high-level design and the deep dives already answered many of these, so this step collects the answers and adds the failures of whole zones and regions. <!-- link: fundamentals/failures --> + +Turn the non-functional requirements into targets you measure. The availability and latency numbers become the goals for the service, and alerts fire when users feel a problem, such as more errors or slower answers, rather than on every busy CPU. For each class of component, name what you watch: requests, errors, and latency for services, lag for queues, free space for stores. Logs and traces cost money to keep, so keep a sample. <!-- link: fundamentals/observability --> + +Say what the system gives up under overload. When load exceeds what the servers can take, decide what waits or gets dropped first, such as low-priority work, and how one caller is kept from using up the capacity of all the others. <!-- link: patterns/rate-limiting --> + +Say how a change reaches production. A new version goes to a few servers first, then to one zone at a time, while you compare its errors and latency with the old version and roll back when they get worse. A new feature hides behind a flag, so you can turn it off without a release. A change to stored data goes in steps that keep the old and new versions working together. <!-- link: practices/releases --> <!-- link: patterns/data-migration --> + +::diagram{name="framework-operations"} + +:::avoid +A list of monitoring tools with nothing about what you watch. The interviewer wants the signals and the actions, and any tool can carry them. +::: + +## Wrap-up + +Keep the last one to three minutes for the wrap-up. Walk the requirements on the board, one by one, and say which part of the design meets each. Where one is met only in part, say so and what is missing. + +Then say what comes next: the scenarios you left out, the optional steps you did not reach, and what breaks first when the load grows ten times. Add no new components at this point. When the interviewer runs over time, give the wrap-up in one sentence. + +For the notification service, it sounds like this: "All three scenarios work, and the status lags by a few seconds. An accepted message is not lost in an outage shorter than 7 days: the queue keeps it that long, in three copies. Accepting meets its numbers, and delivery meets its times while the providers answer on time. Next come templates, and at ten times the load, a separate queue per channel." diff --git a/src/data/glossary.mjs b/src/data/glossary.mjs index d237789..7b07366 100644 --- a/src/data/glossary.mjs +++ b/src/data/glossary.mjs @@ -82,6 +82,11 @@ const uniqueIds = (anchor, section) => ({ label: `Unique IDs: ${section}`, }); +const framework = (anchor, section) => ({ + href: `framework/#${anchor}`, + label: `Framework: ${section}`, +}); + export const glossarySkip = ['SQL Server', 'commit the layout', 'Recall.ai']; /** @type {Array<{id: string, term: string, aliases?: string[], expansion?: string, short: string, explanation: string, readMore?: {href: string, label: string}, explainedIn?: string[]}>} */ @@ -3926,4 +3931,22 @@ export const glossary = [ 'It needs no escaping in a URL, so it suits short codes: 7 characters give about 3.5 trillion values.', readMore: uniqueIds('short-codes-people-type-and-share', 'Short codes people type and share'), }, + { + id: 'data-plane', + term: 'Data plane', + aliases: ['data plane', 'data planes', 'Data plane'], + short: 'The part of a system that does its main job at full load, such as serving requests or moving messages.', + explanation: + 'It gets most of the traffic and the strictest requirements. It should keep working with the settings it already has when the control plane is down.', + readMore: framework('api-and-entities', 'API and entities'), + }, + { + id: 'control-plane', + term: 'Control plane', + aliases: ['control plane', 'control planes', 'Control plane'], + short: 'The part of a system that changes how it works, such as settings, accounts, and configuration.', + explanation: + 'It gets far fewer requests than the data plane and can be slower, so it often gets separate components and looser requirements.', + readMore: framework('api-and-entities', 'API and entities'), + }, ]; diff --git a/src/diagrams/board/framework.mjs b/src/diagrams/board/framework.mjs new file mode 100644 index 0000000..79abaeb --- /dev/null +++ b/src/diagrams/board/framework.mjs @@ -0,0 +1,260 @@ +// Board diagrams of the framework page: what each step leaves on the board, +// for the running example, the notification service. +// Render: bun .agents/skills/board-diagrams/scripts/build.mjs + +// Board text: a heading and lines, as written on the board. The alt text is the text itself. +function board(title, heading, lines) { + return { + title, + desc: [heading, ...lines].filter(Boolean).join(' / ').replace(/\s+/g, ' '), + blocks: [{ x: 0, y: 0, title: heading, lines }], + }; +} + +// The high-level design. Zones left to right: outside (clients, external +// systems), the API as the border, services, stores. Steps go from the top +// down. Arrows start at the one who acts: both the API and the sender point at the queue. +const nodes = [ + // 1. Send + { id: 'provider', kind: 'service', x: 0, y: 0, label: 'Provider', external: true, step: 1 }, + { id: 'team', kind: 'client', x: 0, y: 4, label: 'Team', step: 1 }, + { id: 'api', kind: 'gateway', x: 3.75, y: 1.75, size: [1, 15.5], label: 'API', step: 1 }, + { id: 'queue', kind: 'queue', x: 6, y: 4.5, size: [4, 1], label: 'Queue', tech: 'Kafka', step: 1 }, + { id: 'sender', kind: 'service', x: 11, y: 4, label: 'Sender', multi: true, step: 1 }, + // 2. Status + { id: 'store', kind: 'store', x: 19, y: 3.5, label: 'Message\nstore', tech: 'Cassandra', step: 2 }, + // 3. Settings + { id: 'user', kind: 'client', x: 0, y: 15.25, label: 'User', step: 3 }, + { id: 'settings', kind: 'service', x: 6, y: 15.25, label: 'Settings\nservice', step: 3 }, + { id: 'copy', kind: 'cache', x: 19, y: 11.25, label: 'Settings\ncopy', step: 3 }, + { id: 'settings-store', kind: 'store', x: 19, y: 14.75, label: 'Settings\nstore', step: 3 }, +]; + +// The API bar is centered at y 9.5 units, so an arrow from the API with an offset of k leaves at y 9.5 + k. +const edges = [ + // 1. Send + { from: 'team', to: 'api', fromSide: 'r', toSide: 'l', offset: -0.3, label: 'send', step: 1 }, + { from: 'api', to: 'queue', fromSide: 'r', toSide: 'l', offset: -4.5, label: 'pub', step: 1 }, + { from: 'sender', to: 'queue', label: 'sub', async: true, step: 1 }, + { from: 'sender', to: 'provider', fromSide: 't', toSide: 'r', offset: -1, toOffset: 0, elbow: 'v', label: 'deliver', step: 1 }, + // 2. Status + { from: 'sender', to: 'store', label: 'write status', labelSide: 'below', labelShift: 0.13, step: 2 }, + { from: 'team', to: 'api', fromSide: 'r', toSide: 'l', offset: 0.3, label: 'status', labelSide: 'below', step: 2 }, + { from: 'api', to: 'store', fromSide: 'r', toSide: 't', offset: -7.25, toOffset: 0, elbow: 'h', label: 'read status', labelShift: -3, step: 2 }, + // 3. Settings + { from: 'user', to: 'api', fromSide: 'r', toSide: 'l', label: 'set', step: 3 }, + { from: 'api', to: 'settings', fromSide: 'r', toSide: 'l', offset: 6.75, step: 3 }, + { from: 'settings', to: 'settings-store', label: 'save', step: 3 }, + { from: 'settings-store', to: 'copy', label: 'copy', async: true, step: 3 }, + { from: 'sender', to: 'copy', fromSide: 'b', toSide: 'l', offset: 1, toOffset: 0, elbow: 'v', label: 'read', labelSegment: 1, step: 3 }, + // 4. Failures + { from: 'sender', to: 'queue', fromSide: 'b', toSide: 'b', offset: -1, toOffset: 1.5, via: [[11.5, 6.6], [9.5, 6.6]], label: 'retry', labelSide: 'below', async: true, step: 4 }, +]; + +// Data next to its store, in the form that shows its shape. +const data = [ + { near: 'queue', side: 't', text: '{message_id, user_id,\n channel, text}\nkept 7 days', step: 1 }, + { near: 'queue', side: 'b', dx: -0.25, text: 'accepted here', step: 1 }, + { near: 'store', side: 'b', align: 'end', table: { name: 'messages, kept 30 days', columns: ['message_id (key)', 'user_id', 'channel', 'text', 'status: queued|sent|failed'] }, step: 2 }, + { x: 18.5, y: 13, anchor: 'end', text: 'the same, refreshed\nevery minute; kept if\nthe store is down', step: 3 }, + { near: 'settings-store', side: 'b', align: 'end', text: 'settings:{user_id} -> {channels}', step: 3 }, +]; +const failure = { x: 8, y: 8, text: 'provider down:\nthe message waits\nin the queue, retried\nwith backoff', step: 4 }; + +const steps = ['A team sends a message to a user', 'The team reads the message status', 'A user changes channel settings', 'The provider is down: the message waits and retries']; + +const hld = { + title: 'High-level design of the notification service, built one scenario at a time', + desc: + 'A team sends a message through the API to a queue, where it counts as accepted; senders read the queue and deliver through an external provider. ' + + 'The sender writes the status to the message store, and the team reads it through the API. ' + + 'A user saves channel settings through a settings service to a settings store; senders read a copy refreshed every minute. ' + + 'When the provider is down, the message waits in the queue and is retried with backoff. ' + + 'Next to each store, its data: the queue keeps the message for 7 days; the messages table is keyed by message_id and has a status; settings are a key-value pair by user_id.', + steps, + final: 'The whole design', + width: 21.5, + nodes: nodes.map(({ tech, ...n }) => n), + edges, + notes: [...data, failure], +}; + +// The key part: the same board, with the two components that carry the +// hardest requirements in focus, their technologies written on them, and the notes for them below. +const keyIds = ['queue', 'store']; +const keyEdges = ['pub', 'sub', 'write status', 'read status']; +const keyPart = { + title: 'The key part on the high-level design: the queue and the message store', + desc: + 'The whole design with the queue (Kafka) and the message store (Cassandra) in focus. ' + + 'Key part: accept 100k messages a second and never lose an accepted message. ' + + 'Messages get 100k writes and 10k status reads a second by message_id, are kept 30 days, and are spread across nodes by message_id. ' + + 'The queue is a log on disk with 3 copies that replays after a crash, so Kafka; RabbitMQ would win if per-message delays mattered more than volume. ' + + 'The message store spreads writes by message_id, so Cassandra; PostgreSQL would win if the data fit one node.', + focusMode: true, + width: 21.5, + nodes: nodes.map(({ step, tech, ...n }) => ({ ...n, focus: keyIds.includes(n.id), tech: keyIds.includes(n.id) ? tech : undefined })), + edges: edges.map(({ step, ...e }) => ({ ...e, focus: keyEdges.includes(e.label) })), + notes: [...data, failure].map(({ step, ...n }) => ({ ...n, focus: ['queue', 'store'].includes(n.near) })), + blocks: [ + { + x: 0, + y: 19.25, + focus: true, + title: 'Key part: accept 100k/s, never lose an accepted message', + lines: [ + 'Messages: 100k writes/s, 10k status reads/s by message_id; kept 30 days', + ' spread across nodes by message_id', + 'Queue: log on disk with 3 copies, replay after a crash -> Kafka', + ' alt: RabbitMQ, if per-message delays mattered more than volume', + 'Message store: writes spread by message_id -> Cassandra', + ' alt: PostgreSQL, if the data fit one node', + ], + }, + ], +}; + +// A deep dive: the part of the design the problem lives in, drawn larger, with +// the steps numbered. Step 1 shows where it breaks, step 2 the choice. +const deepDive = { + title: 'Deep dive: duplicates after a sender crash', + desc: + 'The sender, larger: 1. it reads a message from the queue, 2. delivers it through the provider, 3. writes the status to the message store. ' + + 'A sender that crashes between 2 and 3 leaves the message unmarked, and the next sender repeats 2. ' + + 'Options: write the status before 2 (may lose the message), after 2 (may repeat it), or send a key per message to the provider. ' + + 'Choice: deliver with key = message_id, so the provider drops a repeat; no duplicates where the provider takes keys, rare duplicates elsewhere, allowed by requirement 3.', + steps: ['The problem: a crash between 2 and 3 repeats 2', 'The choice: a key per message at the provider'], + final: 'The deep dive', + nodes: [ + { id: 'queue', kind: 'queue', x: 0, y: 0.75, size: [4, 1], label: 'Queue', step: 1 }, + { id: 'sender', kind: 'service', x: 6.5, y: 0.25, label: 'Sender', multi: true, step: 1 }, + { id: 'provider', kind: 'service', x: 14, y: 0.25, label: 'Provider', external: true, step: 1 }, + { id: 'store', kind: 'store', x: 7, y: 4.75, label: 'Message\nstore', step: 1 }, + ], + edges: [ + { from: 'sender', to: 'queue', label: '1. sub', async: true, step: 1 }, + { from: 'sender', to: 'provider', label: '2. deliver', step: 1 }, + { from: 'sender', to: 'store', label: '3. write status', step: 1 }, + ], + notes: [ + { x: 7.6, y: 2.65, anchor: 'end', text: 'crash between 2 and 3:\nthe next sender\nrepeats 2', step: 1 }, + { x: 10.1, y: 1.55, text: 'key=message_id', step: 2 }, + { near: 'provider', side: 'b', text: 'drops a repeated key', step: 2 }, + ], + blocks: [ + { + x: 0, + y: 8.75, + step: 1, + title: 'Deep dive: duplicates after a sender crash', + lines: [ + 'Problem: the sender crashes after 2, before 3;', + ' the next sender repeats 2', + 'Options: write status before 2 (may lose)', + ' write status after 2 (may repeat)', + ' key per message at the provider', + ], + }, + { + x: 0, + y: 12.75, + step: 2, + lines: [ + 'Choice: key per message: no duplicates where the provider takes keys;', + ' rare duplicates elsewhere, allowed by requirement 3', + ], + }, + ], +}; + +// The design after the deep dive: the same board with what changed in focus. +const deepDiveDesign = { + title: 'The high-level design after the deep dive: delivery with a key per message', + desc: + 'The whole design with the sender, the provider, and the deliver arrow in focus. ' + + 'The arrow now reads: deliver, key=message_id. The rest of the design is unchanged.', + focusMode: true, + width: 21.5, + nodes: nodes.map(({ step, tech, ...n }) => ({ ...n, focus: ['sender', 'provider'].includes(n.id) })), + edges: edges.map(({ step, ...e }) => (e.label === 'deliver' ? { ...e, label: 'deliver, key=message_id', focus: true } : e)), + notes: [...data, failure].map(({ step, ...n }) => n), +}; + +export default { + 'framework-opening': board('Board after the opening: the task, the plan, what already exists', '', [ + 'Notification service: teams send push, SMS, email to users', + 'Plan: requirements, estimates, API, data flow?, design, key part,', + ' deep dives, resources?, cost?, operations?', + 'Given: auth service, user database', + ]), + 'framework-functional': board('Board after the functional requirements', 'Functional:', [ + '1. A team sends a message to a user by push, SMS, or email', + '2. A user chooses which channels to receive', + '3. A team checks whether a message was delivered', + 'Out: templates, campaigns to many users, scheduled sending', + ]), + 'framework-non-functional': board('Board after the non-functional requirements', 'Non-functional:', [ + 'Scale: 50M users in one region, 1B messages a day, peaks 10x the average', + '1. An accepted message is never lost', + '2. Accept: 99.99% available, 100 ms for 99% of requests', + '3. Deliver, accept to provider, for 99%: push 5 s, SMS 30 s, email 1 min;', + ' rare duplicates are fine', + '4. Status may lag by a few seconds', + ]), + 'framework-estimates': board('Board after the estimates', 'Estimates (assume one node: ~10k writes/s, ~10 TB of disk):', [ + '1B a day / 10^5 s = 10k/s, peak 100k/s -> writes spread over several nodes', + '1 KB x 1B = 1 TB a day, 30 days = 30 TB -> data spread over several nodes', + '1 status check per 10 messages -> mostly writes', + ]), + 'framework-api': board('Board after the API and entities', '', [ + 'Entities: Message, Settings', + 'Auth: the caller\'s token on every call', + 'Data plane:', + ' POST /messages', + ' Idempotency-Key', + ' {user_id, channel, text}', + ' -> 202 {message_id}', + ' GET /messages/{id} -> {status}', + 'Control plane:', + ' PUT /me/settings {channels} -> 204', + ]), + 'framework-data-flow': board('Board after the data flow', 'Flow:', [ + 'request', + '-> accept: message', + '-> check settings: channels', + '-> build per channel: texts', + '-> send: result', + ' slow: messages wait before it', + ' calls a provider: can fail', + '-> record: status', + ]), + 'framework-hld': hld, + 'framework-key-part': keyPart, + 'framework-deep-dive': deepDive, + 'framework-deep-dive-design': deepDiveDesign, + 'framework-resources': board('Board after the resources', 'Resources:', [ + 'API: CPU, 100k/s / 10k/s per server = 10, +50% for a lost zone -> 15', + 'Queue: disk, 1 TB a day x 3 copies x 7 days = 21 TB -> 3 nodes x 8 TB', + ' (assume a log node takes ~100k writes/s of 1 KB, copies included)', + 'Message store: writes, 100k/s x 3 copies / 10k/s per node = 30,', + ' +50% for a lost zone -> 45 (disk: 90 TB / 45 = 2 TB per node)', + 'Latency of accept, 99%: 20 ms network + 5 ms API + 20 ms queue write < 100 ms', + ]), + 'framework-cost': board('Board after the cost', 'Cost per month (cloud):', [ + 'SMS fees: 10% of 30B messages x price per SMS -> most of the bill', + 'Servers: 15 API + 3 queue + 45 store + ~10 senders = ~75 x price per instance', + 'Total: SMS fees + servers (disks are in the instance price)', + 'Proposed cut: push first, SMS as a fallback', + ]), + 'framework-operations': board('Board after the operations', '', [ + 'Failures:', + ' provider down -> messages wait in the queue, retried', + ' zone lost -> two zones take the load (planned 50% extra)', + 'Targets: accept 99.99%; push 5 s, SMS 30 s, email 1 min for 99%', + 'Watch: accept errors and latency,', + ' delivery time per channel against its target,', + ' queue lag, errors per provider', + 'Overload: marketing waits, security codes go first; a limit per team', + 'Release: a few servers, then one zone at a time; roll back on errors', + ]), +}; diff --git a/src/diagrams/framework-api.svg b/src/diagrams/framework-api.svg new file mode 100644 index 0000000..f0a7536 --- /dev/null +++ b/src/diagrams/framework-api.svg @@ -0,0 +1,5 @@ +<svg class="sk-svg" viewBox="0 0 365 232" role="img" aria-labelledby="framework-api-title framework-api-desc" xmlns="http://www.w3.org/2000/svg"> +<title id="framework-api-title">Board after the API and entities +Entities: Message, Settings / Auth: the caller's token on every call / Data plane: / POST /messages / Idempotency-Key / {user_id, channel, text} / -> 202 {message_id} / GET /messages/{id} -> {status} / Control plane: / PUT /me/settings {channels} -> 204 +Entities: Message, SettingsAuth: the caller's token on every callData plane:POST /messagesIdempotency-Key{user_id, channel, text}-> 202 {message_id}GET /messages/{id} -> {status}Control plane:PUT /me/settings {channels} -> 204 + diff --git a/src/diagrams/framework-cost.svg b/src/diagrams/framework-cost.svg new file mode 100644 index 0000000..30f341f --- /dev/null +++ b/src/diagrams/framework-cost.svg @@ -0,0 +1,5 @@ + +Board after the cost +Cost per month (cloud): / SMS fees: 10% of 30B messages x price per SMS -> most of the bill / Servers: 15 API + 3 queue + 45 store + ~10 senders = ~75 x price per instance / Total: SMS fees + servers (disks are in the instance price) / Proposed cut: push first, SMS as a fallback +Cost per month (cloud):SMS fees: 10% of 30B messages x price per SMS -> most of the billServers: 15 API + 3 queue + 45 store + ~10 senders = ~75 x price per instanceTotal: SMS fees + servers (disks are in the instance price)Proposed cut: push first, SMS as a fallback + diff --git a/src/diagrams/framework-data-flow.svg b/src/diagrams/framework-data-flow.svg new file mode 100644 index 0000000..5bda862 --- /dev/null +++ b/src/diagrams/framework-data-flow.svg @@ -0,0 +1,5 @@ + +Board after the data flow +Flow: / request / -> accept: message / -> check settings: channels / -> build per channel: texts / -> send: result / slow: messages wait before it / calls a provider: can fail / -> record: status +Flow:request-> accept: message-> check settings: channels-> build per channel: texts-> send: resultslow: messages wait before itcalls a provider: can fail-> record: status + diff --git a/src/diagrams/framework-deep-dive-design.svg b/src/diagrams/framework-deep-dive-design.svg new file mode 100644 index 0000000..6cf7acc --- /dev/null +++ b/src/diagrams/framework-deep-dive-design.svg @@ -0,0 +1,33 @@ + +The high-level design after the deep dive: delivery with a key per message +The whole design with the sender, the provider, and the deliver arrow in focus. The arrow now reads: deliver, key=message_id. The rest of the design is unchanged. +send +pub +sub +deliver, key=message_id +write status +status +read status +set + +save +copy +read +retry +Provider +Team +API +Queue +Sender +Messagestore +User +Settingsservice +Settingscopy +Settingsstore +{message_id, user_id,channel, text}kept 7 days +accepted here +messages, kept 30 days---message_id (key)user_idchanneltextstatus: queued|sent|failed +the same, refreshedevery minute; kept ifthe store is down +settings:{user_id} -> {channels} +provider down:the message waitsin the queue, retriedwith backoff + diff --git a/src/diagrams/framework-deep-dive.svg b/src/diagrams/framework-deep-dive.svg new file mode 100644 index 0000000..02f9528 --- /dev/null +++ b/src/diagrams/framework-deep-dive.svg @@ -0,0 +1,16 @@ + +Deep dive: duplicates after a sender crash +The sender, larger: 1. it reads a message from the queue, 2. delivers it through the provider, 3. writes the status to the message store. A sender that crashes between 2 and 3 leaves the message unmarked, and the next sender repeats 2. Options: write the status before 2 (may lose the message), after 2 (may repeat it), or send a key per message to the provider. Choice: deliver with key = message_id, so the provider drops a repeat; no duplicates where the provider takes keys, rare duplicates elsewhere, allowed by requirement 3. +1. sub +2. deliver +3. write status +Queue +Sender +Provider +Messagestore +crash between 2 and 3:the next senderrepeats 2 +key=message_id +drops a repeated key +Deep dive: duplicates after a sender crashProblem: the sender crashes after 2, before 3;the next sender repeats 2Options: write status before 2 (may lose)write status after 2 (may repeat)key per message at the provider +Choice: key per message: no duplicates where the provider takes keys;rare duplicates elsewhere, allowed by requirement 3 + diff --git a/src/diagrams/framework-estimates.svg b/src/diagrams/framework-estimates.svg new file mode 100644 index 0000000..c40a680 --- /dev/null +++ b/src/diagrams/framework-estimates.svg @@ -0,0 +1,5 @@ + +Board after the estimates +Estimates (assume one node: ~10k writes/s, ~10 TB of disk): / 1B a day / 10^5 s = 10k/s, peak 100k/s -> writes spread over several nodes / 1 KB x 1B = 1 TB a day, 30 days = 30 TB -> data spread over several nodes / 1 status check per 10 messages -> mostly writes +Estimates (assume one node: ~10k writes/s, ~10 TB of disk):1B a day / 10^5 s = 10k/s, peak 100k/s-> writes spread over several nodes1 KB x 1B = 1 TB a day, 30 days = 30 TB-> data spread over several nodes1 status check per 10 messages-> mostly writes + diff --git a/src/diagrams/framework-functional.svg b/src/diagrams/framework-functional.svg new file mode 100644 index 0000000..04b9f68 --- /dev/null +++ b/src/diagrams/framework-functional.svg @@ -0,0 +1,5 @@ + +Board after the functional requirements +Functional: / 1. A team sends a message to a user by push, SMS, or email / 2. A user chooses which channels to receive / 3. A team checks whether a message was delivered / Out: templates, campaigns to many users, scheduled sending +Functional:1. A team sends a message to a user by push, SMS, or email2. A user chooses which channels to receive3. A team checks whether a message was deliveredOut: templates, campaigns to many users, scheduled sending + diff --git a/src/diagrams/framework-hld.svg b/src/diagrams/framework-hld.svg new file mode 100644 index 0000000..3581c8d --- /dev/null +++ b/src/diagrams/framework-hld.svg @@ -0,0 +1,33 @@ + +High-level design of the notification service, built one scenario at a time +A team sends a message through the API to a queue, where it counts as accepted; senders read the queue and deliver through an external provider. The sender writes the status to the message store, and the team reads it through the API. A user saves channel settings through a settings service to a settings store; senders read a copy refreshed every minute. When the provider is down, the message waits in the queue and is retried with backoff. Next to each store, its data: the queue keeps the message for 7 days; the messages table is keyed by message_id and has a status; settings are a key-value pair by user_id. +send +pub +sub +deliver +write status +status +read status +set + +save +copy +read +retry +Provider +Team +API +Queue +Sender +Messagestore +User +Settingsservice +Settingscopy +Settingsstore +{message_id, user_id,channel, text}kept 7 days +accepted here +messages, kept 30 days---message_id (key)user_idchanneltextstatus: queued|sent|failed +the same, refreshedevery minute; kept ifthe store is down +settings:{user_id} -> {channels} +provider down:the message waitsin the queue, retriedwith backoff + diff --git a/src/diagrams/framework-key-part.svg b/src/diagrams/framework-key-part.svg new file mode 100644 index 0000000..fe473a7 --- /dev/null +++ b/src/diagrams/framework-key-part.svg @@ -0,0 +1,34 @@ + +The key part on the high-level design: the queue and the message store +The whole design with the queue (Kafka) and the message store (Cassandra) in focus. Key part: accept 100k messages a second and never lose an accepted message. Messages get 100k writes and 10k status reads a second by message_id, are kept 30 days, and are spread across nodes by message_id. The queue is a log on disk with 3 copies that replays after a crash, so Kafka; RabbitMQ would win if per-message delays mattered more than volume. The message store spreads writes by message_id, so Cassandra; PostgreSQL would win if the data fit one node. +send +pub +sub +deliver +write status +status +read status +set + +save +copy +read +retry +Provider +Team +API +Queue(Kafka) +Sender +Messagestore(Cassandra) +User +Settingsservice +Settingscopy +Settingsstore +{message_id, user_id,channel, text}kept 7 days +accepted here +messages, kept 30 days---message_id (key)user_idchanneltextstatus: queued|sent|failed +the same, refreshedevery minute; kept ifthe store is down +settings:{user_id} -> {channels} +provider down:the message waitsin the queue, retriedwith backoff +Key part: accept 100k/s, never lose an accepted messageMessages: 100k writes/s, 10k status reads/s by message_id; kept 30 daysspread across nodes by message_idQueue: log on disk with 3 copies, replay after a crash -> Kafkaalt: RabbitMQ, if per-message delays mattered more than volumeMessage store: writes spread by message_id -> Cassandraalt: PostgreSQL, if the data fit one node + diff --git a/src/diagrams/framework-non-functional.svg b/src/diagrams/framework-non-functional.svg new file mode 100644 index 0000000..4ed86f5 --- /dev/null +++ b/src/diagrams/framework-non-functional.svg @@ -0,0 +1,5 @@ + +Board after the non-functional requirements +Non-functional: / Scale: 50M users in one region, 1B messages a day, peaks 10x the average / 1. An accepted message is never lost / 2. Accept: 99.99% available, 100 ms for 99% of requests / 3. Deliver, accept to provider, for 99%: push 5 s, SMS 30 s, email 1 min; / rare duplicates are fine / 4. Status may lag by a few seconds +Non-functional:Scale: 50M users in one region, 1B messages a day, peaks 10x the average1. An accepted message is never lost2. Accept: 99.99% available, 100 ms for 99% of requests3. Deliver, accept to provider, for 99%: push 5 s, SMS 30 s, email 1 min;rare duplicates are fine4. Status may lag by a few seconds + diff --git a/src/diagrams/framework-opening.svg b/src/diagrams/framework-opening.svg new file mode 100644 index 0000000..96ecca9 --- /dev/null +++ b/src/diagrams/framework-opening.svg @@ -0,0 +1,5 @@ + +Board after the opening: the task, the plan, what already exists +Notification service: teams send push, SMS, email to users / Plan: requirements, estimates, API, data flow?, design, key part, / deep dives, resources?, cost?, operations? / Given: auth service, user database +Notification service: teams send push, SMS, email to usersPlan: requirements, estimates, API, data flow?, design, key part,deep dives, resources?, cost?, operations?Given: auth service, user database + diff --git a/src/diagrams/framework-operations.svg b/src/diagrams/framework-operations.svg new file mode 100644 index 0000000..d769334 --- /dev/null +++ b/src/diagrams/framework-operations.svg @@ -0,0 +1,5 @@ + +Board after the operations +Failures: / provider down -> messages wait in the queue, retried / zone lost -> two zones take the load (planned 50% extra) / Targets: accept 99.99%; push 5 s, SMS 30 s, email 1 min for 99% / Watch: accept errors and latency, / delivery time per channel against its target, / queue lag, errors per provider / Overload: marketing waits, security codes go first; a limit per team / Release: a few servers, then one zone at a time; roll back on errors +Failures:provider down -> messages wait in the queue, retriedzone lost-> two zones take the load (planned 50% extra)Targets: accept 99.99%; push 5 s, SMS 30 s, email 1 min for 99%Watch: accept errors and latency,delivery time per channel against its target,queue lag, errors per providerOverload: marketing waits, security codes go first; a limit per teamRelease: a few servers, then one zone at a time; roll back on errors + diff --git a/src/diagrams/framework-resources.svg b/src/diagrams/framework-resources.svg new file mode 100644 index 0000000..1223261 --- /dev/null +++ b/src/diagrams/framework-resources.svg @@ -0,0 +1,5 @@ + +Board after the resources +Resources: / API: CPU, 100k/s / 10k/s per server = 10, +50% for a lost zone -> 15 / Queue: disk, 1 TB a day x 3 copies x 7 days = 21 TB -> 3 nodes x 8 TB / (assume a log node takes ~100k writes/s of 1 KB, copies included) / Message store: writes, 100k/s x 3 copies / 10k/s per node = 30, / +50% for a lost zone -> 45 (disk: 90 TB / 45 = 2 TB per node) / Latency of accept, 99%: 20 ms network + 5 ms API + 20 ms queue write < 100 ms +Resources:API: CPU, 100k/s / 10k/s per server = 10, +50% for a lost zone -> 15Queue: disk, 1 TB a day x 3 copies x 7 days = 21 TB -> 3 nodes x 8 TB(assume a log node takes ~100k writes/s of 1 KB, copies included)Message store: writes, 100k/s x 3 copies / 10k/s per node = 30,+50% for a lost zone -> 45 (disk: 90 TB / 45 = 2 TB per node)Latency of accept, 99%: 20 ms network + 5 ms API + 20 ms queue write < 100 ms +