import{createRequire}from'module';const require=createRequire(import.meta.url); var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) { if (typeof require !== "undefined") return require.apply(this, arguments); throw Error('Dynamic require of "' + x + '" is not supported'); }); var __commonJS = (cb, mod) => function __require2() { try { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; } catch (e) { throw mod = 0, e; } }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); // ../../node_modules/yaml/dist/nodes/identity.js var require_identity = __commonJS({ "../../node_modules/yaml/dist/nodes/identity.js"(exports) { "use strict"; var ALIAS = /* @__PURE__ */ Symbol.for("yaml.alias"); var DOC = /* @__PURE__ */ Symbol.for("yaml.document"); var MAP = /* @__PURE__ */ Symbol.for("yaml.map"); var PAIR = /* @__PURE__ */ Symbol.for("yaml.pair"); var SCALAR = /* @__PURE__ */ Symbol.for("yaml.scalar"); var SEQ = /* @__PURE__ */ Symbol.for("yaml.seq"); var NODE_TYPE = /* @__PURE__ */ Symbol.for("yaml.node.type"); var isAlias = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === ALIAS; var isDocument = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === DOC; var isMap = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === MAP; var isPair = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === PAIR; var isScalar = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SCALAR; var isSeq = (node) => !!node && typeof node === "object" && node[NODE_TYPE] === SEQ; function isCollection(node) { if (node && typeof node === "object") switch (node[NODE_TYPE]) { case MAP: case SEQ: return true; } return false; } function isNode(node) { if (node && typeof node === "object") switch (node[NODE_TYPE]) { case ALIAS: case MAP: case SCALAR: case SEQ: return true; } return false; } var hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor; exports.ALIAS = ALIAS; exports.DOC = DOC; exports.MAP = MAP; exports.NODE_TYPE = NODE_TYPE; exports.PAIR = PAIR; exports.SCALAR = SCALAR; exports.SEQ = SEQ; exports.hasAnchor = hasAnchor; exports.isAlias = isAlias; exports.isCollection = isCollection; exports.isDocument = isDocument; exports.isMap = isMap; exports.isNode = isNode; exports.isPair = isPair; exports.isScalar = isScalar; exports.isSeq = isSeq; } }); // ../../node_modules/yaml/dist/visit.js var require_visit = __commonJS({ "../../node_modules/yaml/dist/visit.js"(exports) { "use strict"; var identity = require_identity(); var BREAK = /* @__PURE__ */ Symbol("break visit"); var SKIP = /* @__PURE__ */ Symbol("skip children"); var REMOVE = /* @__PURE__ */ Symbol("remove node"); function visit(node, visitor) { const visitor_ = initVisitor(visitor); if (identity.isDocument(node)) { const cd = visit_(null, node.contents, visitor_, Object.freeze([node])); if (cd === REMOVE) node.contents = null; } else visit_(null, node, visitor_, Object.freeze([])); } visit.BREAK = BREAK; visit.SKIP = SKIP; visit.REMOVE = REMOVE; function visit_(key, node, visitor, path) { const ctrl = callVisitor(key, node, visitor, path); if (identity.isNode(ctrl) || identity.isPair(ctrl)) { replaceNode(key, path, ctrl); return visit_(key, ctrl, visitor, path); } if (typeof ctrl !== "symbol") { if (identity.isCollection(node)) { path = Object.freeze(path.concat(node)); for (let i = 0; i < node.items.length; ++i) { const ci = visit_(i, node.items[i], visitor, path); if (typeof ci === "number") i = ci - 1; else if (ci === BREAK) return BREAK; else if (ci === REMOVE) { node.items.splice(i, 1); i -= 1; } } } else if (identity.isPair(node)) { path = Object.freeze(path.concat(node)); const ck = visit_("key", node.key, visitor, path); if (ck === BREAK) return BREAK; else if (ck === REMOVE) node.key = null; const cv = visit_("value", node.value, visitor, path); if (cv === BREAK) return BREAK; else if (cv === REMOVE) node.value = null; } } return ctrl; } async function visitAsync(node, visitor) { const visitor_ = initVisitor(visitor); if (identity.isDocument(node)) { const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node])); if (cd === REMOVE) node.contents = null; } else await visitAsync_(null, node, visitor_, Object.freeze([])); } visitAsync.BREAK = BREAK; visitAsync.SKIP = SKIP; visitAsync.REMOVE = REMOVE; async function visitAsync_(key, node, visitor, path) { const ctrl = await callVisitor(key, node, visitor, path); if (identity.isNode(ctrl) || identity.isPair(ctrl)) { replaceNode(key, path, ctrl); return visitAsync_(key, ctrl, visitor, path); } if (typeof ctrl !== "symbol") { if (identity.isCollection(node)) { path = Object.freeze(path.concat(node)); for (let i = 0; i < node.items.length; ++i) { const ci = await visitAsync_(i, node.items[i], visitor, path); if (typeof ci === "number") i = ci - 1; else if (ci === BREAK) return BREAK; else if (ci === REMOVE) { node.items.splice(i, 1); i -= 1; } } } else if (identity.isPair(node)) { path = Object.freeze(path.concat(node)); const ck = await visitAsync_("key", node.key, visitor, path); if (ck === BREAK) return BREAK; else if (ck === REMOVE) node.key = null; const cv = await visitAsync_("value", node.value, visitor, path); if (cv === BREAK) return BREAK; else if (cv === REMOVE) node.value = null; } } return ctrl; } function initVisitor(visitor) { if (typeof visitor === "object" && (visitor.Collection || visitor.Node || visitor.Value)) { return Object.assign({ Alias: visitor.Node, Map: visitor.Node, Scalar: visitor.Node, Seq: visitor.Node }, visitor.Value && { Map: visitor.Value, Scalar: visitor.Value, Seq: visitor.Value }, visitor.Collection && { Map: visitor.Collection, Seq: visitor.Collection }, visitor); } return visitor; } function callVisitor(key, node, visitor, path) { if (typeof visitor === "function") return visitor(key, node, path); if (identity.isMap(node)) return visitor.Map?.(key, node, path); if (identity.isSeq(node)) return visitor.Seq?.(key, node, path); if (identity.isPair(node)) return visitor.Pair?.(key, node, path); if (identity.isScalar(node)) return visitor.Scalar?.(key, node, path); if (identity.isAlias(node)) return visitor.Alias?.(key, node, path); return void 0; } function replaceNode(key, path, node) { const parent = path[path.length - 1]; if (identity.isCollection(parent)) { parent.items[key] = node; } else if (identity.isPair(parent)) { if (key === "key") parent.key = node; else parent.value = node; } else if (identity.isDocument(parent)) { parent.contents = node; } else { const pt = identity.isAlias(parent) ? "alias" : "scalar"; throw new Error(`Cannot replace node with ${pt} parent`); } } exports.visit = visit; exports.visitAsync = visitAsync; } }); // ../../node_modules/yaml/dist/doc/directives.js var require_directives = __commonJS({ "../../node_modules/yaml/dist/doc/directives.js"(exports) { "use strict"; var identity = require_identity(); var visit = require_visit(); var escapeChars = { "!": "%21", ",": "%2C", "[": "%5B", "]": "%5D", "{": "%7B", "}": "%7D" }; var escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, (ch) => escapeChars[ch]); var Directives = class _Directives { constructor(yaml, tags) { this.docStart = null; this.docEnd = false; this.yaml = Object.assign({}, _Directives.defaultYaml, yaml); this.tags = Object.assign({}, _Directives.defaultTags, tags); } clone() { const copy = new _Directives(this.yaml, this.tags); copy.docStart = this.docStart; return copy; } /** * During parsing, get a Directives instance for the current document and * update the stream state according to the current version's spec. */ atDocument() { const res = new _Directives(this.yaml, this.tags); switch (this.yaml.version) { case "1.1": this.atNextDocument = true; break; case "1.2": this.atNextDocument = false; this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.2" }; this.tags = Object.assign({}, _Directives.defaultTags); break; } return res; } /** * @param onError - May be called even if the action was successful * @returns `true` on success */ add(line, onError) { if (this.atNextDocument) { this.yaml = { explicit: _Directives.defaultYaml.explicit, version: "1.1" }; this.tags = Object.assign({}, _Directives.defaultTags); this.atNextDocument = false; } const parts = line.trim().split(/[ \t]+/); const name = parts.shift(); switch (name) { case "%TAG": { if (parts.length !== 2) { onError(0, "%TAG directive should contain exactly two parts"); if (parts.length < 2) return false; } const [handle, prefix] = parts; this.tags[handle] = prefix; return true; } case "%YAML": { this.yaml.explicit = true; if (parts.length !== 1) { onError(0, "%YAML directive should contain exactly one part"); return false; } const [version] = parts; if (version === "1.1" || version === "1.2") { this.yaml.version = version; return true; } else { const isValid = /^\d+\.\d+$/.test(version); onError(6, `Unsupported YAML version ${version}`, isValid); return false; } } default: onError(0, `Unknown directive ${name}`, true); return false; } } /** * Resolves a tag, matching handles to those defined in %TAG directives. * * @returns Resolved tag, which may also be the non-specific tag `'!'` or a * `'!local'` tag, or `null` if unresolvable. */ tagName(source, onError) { if (source === "!") return "!"; if (source[0] !== "!") { onError(`Not a valid tag: ${source}`); return null; } if (source[1] === "<") { const verbatim = source.slice(2, -1); if (verbatim === "!" || verbatim === "!!") { onError(`Verbatim tags aren't resolved, so ${source} is invalid.`); return null; } if (source[source.length - 1] !== ">") onError("Verbatim tags must end with a >"); return verbatim; } const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s); if (!suffix) onError(`The ${source} tag has no suffix`); const prefix = this.tags[handle]; if (prefix) { try { return prefix + decodeURIComponent(suffix); } catch (error) { onError(String(error)); return null; } } if (handle === "!") return source; onError(`Could not resolve tag: ${source}`); return null; } /** * Given a fully resolved tag, returns its printable string form, * taking into account current tag prefixes and defaults. */ tagString(tag) { for (const [handle, prefix] of Object.entries(this.tags)) { if (tag.startsWith(prefix)) return handle + escapeTagName(tag.substring(prefix.length)); } return tag[0] === "!" ? tag : `!<${tag}>`; } toString(doc) { const lines = this.yaml.explicit ? [`%YAML ${this.yaml.version || "1.2"}`] : []; const tagEntries = Object.entries(this.tags); let tagNames; if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) { const tags = {}; visit.visit(doc.contents, (_key, node) => { if (identity.isNode(node) && node.tag) tags[node.tag] = true; }); tagNames = Object.keys(tags); } else tagNames = []; for (const [handle, prefix] of tagEntries) { if (handle === "!!" && prefix === "tag:yaml.org,2002:") continue; if (!doc || tagNames.some((tn) => tn.startsWith(prefix))) lines.push(`%TAG ${handle} ${prefix}`); } return lines.join("\n"); } }; Directives.defaultYaml = { explicit: false, version: "1.2" }; Directives.defaultTags = { "!!": "tag:yaml.org,2002:" }; exports.Directives = Directives; } }); // ../../node_modules/yaml/dist/doc/anchors.js var require_anchors = __commonJS({ "../../node_modules/yaml/dist/doc/anchors.js"(exports) { "use strict"; var identity = require_identity(); var visit = require_visit(); function anchorIsValid(anchor) { if (/[\x00-\x19\s,[\]{}]/.test(anchor)) { const sa = JSON.stringify(anchor); const msg = `Anchor must not contain whitespace or control characters: ${sa}`; throw new Error(msg); } return true; } function anchorNames(root) { const anchors = /* @__PURE__ */ new Set(); visit.visit(root, { Value(_key, node) { if (node.anchor) anchors.add(node.anchor); } }); return anchors; } function findNewAnchor(prefix, exclude) { for (let i = 1; true; ++i) { const name = `${prefix}${i}`; if (!exclude.has(name)) return name; } } function createNodeAnchors(doc, prefix) { const aliasObjects = []; const sourceObjects = /* @__PURE__ */ new Map(); let prevAnchors = null; return { onAnchor: (source) => { aliasObjects.push(source); prevAnchors ?? (prevAnchors = anchorNames(doc)); const anchor = findNewAnchor(prefix, prevAnchors); prevAnchors.add(anchor); return anchor; }, /** * With circular references, the source node is only resolved after all * of its child nodes are. This is why anchors are set only after all of * the nodes have been created. */ setAnchors: () => { for (const source of aliasObjects) { const ref = sourceObjects.get(source); if (typeof ref === "object" && ref.anchor && (identity.isScalar(ref.node) || identity.isCollection(ref.node))) { ref.node.anchor = ref.anchor; } else { const error = new Error("Failed to resolve repeated object (this should not happen)"); error.source = source; throw error; } } }, sourceObjects }; } exports.anchorIsValid = anchorIsValid; exports.anchorNames = anchorNames; exports.createNodeAnchors = createNodeAnchors; exports.findNewAnchor = findNewAnchor; } }); // ../../node_modules/yaml/dist/doc/applyReviver.js var require_applyReviver = __commonJS({ "../../node_modules/yaml/dist/doc/applyReviver.js"(exports) { "use strict"; function applyReviver(reviver, obj, key, val) { if (val && typeof val === "object") { if (Array.isArray(val)) { for (let i = 0, len = val.length; i < len; ++i) { const v0 = val[i]; const v1 = applyReviver(reviver, val, String(i), v0); if (v1 === void 0) delete val[i]; else if (v1 !== v0) val[i] = v1; } } else if (val instanceof Map) { for (const k of Array.from(val.keys())) { const v0 = val.get(k); const v1 = applyReviver(reviver, val, k, v0); if (v1 === void 0) val.delete(k); else if (v1 !== v0) val.set(k, v1); } } else if (val instanceof Set) { for (const v0 of Array.from(val)) { const v1 = applyReviver(reviver, val, v0, v0); if (v1 === void 0) val.delete(v0); else if (v1 !== v0) { val.delete(v0); val.add(v1); } } } else { for (const [k, v0] of Object.entries(val)) { const v1 = applyReviver(reviver, val, k, v0); if (v1 === void 0) delete val[k]; else if (v1 !== v0) val[k] = v1; } } } return reviver.call(obj, key, val); } exports.applyReviver = applyReviver; } }); // ../../node_modules/yaml/dist/nodes/toJS.js var require_toJS = __commonJS({ "../../node_modules/yaml/dist/nodes/toJS.js"(exports) { "use strict"; var identity = require_identity(); function toJS(value, arg, ctx) { if (Array.isArray(value)) return value.map((v, i) => toJS(v, String(i), ctx)); if (value && typeof value.toJSON === "function") { if (!ctx || !identity.hasAnchor(value)) return value.toJSON(arg, ctx); const data = { aliasCount: 0, count: 1, res: void 0 }; ctx.anchors.set(value, data); ctx.onCreate = (res2) => { data.res = res2; delete ctx.onCreate; }; const res = value.toJSON(arg, ctx); if (ctx.onCreate) ctx.onCreate(res); return res; } if (typeof value === "bigint" && !ctx?.keep) return Number(value); return value; } exports.toJS = toJS; } }); // ../../node_modules/yaml/dist/nodes/Node.js var require_Node = __commonJS({ "../../node_modules/yaml/dist/nodes/Node.js"(exports) { "use strict"; var applyReviver = require_applyReviver(); var identity = require_identity(); var toJS = require_toJS(); var NodeBase = class { constructor(type) { Object.defineProperty(this, identity.NODE_TYPE, { value: type }); } /** Create a copy of this node. */ clone() { const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); if (this.range) copy.range = this.range.slice(); return copy; } /** A plain JavaScript representation of this node. */ toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { if (!identity.isDocument(doc)) throw new TypeError("A document argument is required"); const ctx = { anchors: /* @__PURE__ */ new Map(), doc, keep: true, mapAsMap: mapAsMap === true, mapKeyWarned: false, maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 }; const res = toJS.toJS(this, "", ctx); if (typeof onAnchor === "function") for (const { count, res: res2 } of ctx.anchors.values()) onAnchor(res2, count); return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res; } }; exports.NodeBase = NodeBase; } }); // ../../node_modules/yaml/dist/nodes/Alias.js var require_Alias = __commonJS({ "../../node_modules/yaml/dist/nodes/Alias.js"(exports) { "use strict"; var anchors = require_anchors(); var visit = require_visit(); var identity = require_identity(); var Node = require_Node(); var toJS = require_toJS(); var Alias = class extends Node.NodeBase { constructor(source) { super(identity.ALIAS); this.source = source; Object.defineProperty(this, "tag", { set() { throw new Error("Alias nodes cannot have tags"); } }); } /** * Resolve the value of this alias within `doc`, finding the last * instance of the `source` anchor before this node. */ resolve(doc, ctx) { if (ctx?.maxAliasCount === 0) throw new ReferenceError("Alias resolution is disabled"); let nodes; if (ctx?.aliasResolveCache) { nodes = ctx.aliasResolveCache; } else { nodes = []; visit.visit(doc, { Node: (_key, node) => { if (identity.isAlias(node) || identity.hasAnchor(node)) nodes.push(node); } }); if (ctx) ctx.aliasResolveCache = nodes; } let found = void 0; for (const node of nodes) { if (node === this) break; if (node.anchor === this.source) found = node; } if (found && ctx) { const { anchors: anchors2, doc: doc2, maxAliasCount } = ctx; let data = anchors2.get(found); if (!data) { toJS.toJS(found, null, ctx); data = anchors2.get(found); } if (data?.res === void 0) { const msg = "This should not happen: Alias anchor was not resolved?"; throw new ReferenceError(msg); } if (maxAliasCount >= 0) { data.count += 1; if (data.aliasCount === 0) data.aliasCount = getAliasCount(doc2, found, anchors2); if (data.count * data.aliasCount > maxAliasCount) { const msg = "Excessive alias count indicates a resource exhaustion attack"; throw new ReferenceError(msg); } } } return found; } toJSON(_arg, ctx) { if (!ctx) return { source: this.source }; const source = this.resolve(ctx.doc, ctx); if (!source) { const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; throw new ReferenceError(msg); } return ctx.anchors.get(source).res; } toString(ctx, _onComment, _onChompKeep) { const src = `*${this.source}`; if (ctx) { anchors.anchorIsValid(this.source); if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`; throw new Error(msg); } if (ctx.implicitKey) return `${src} `; } return src; } }; function getAliasCount(doc, node, anchors2) { if (identity.isAlias(node)) { const source = node.resolve(doc); const anchor = anchors2 && source && anchors2.get(source); return anchor ? anchor.count * anchor.aliasCount : 0; } else if (identity.isCollection(node)) { let count = 0; for (const item of node.items) { const c = getAliasCount(doc, item, anchors2); if (c > count) count = c; } return count; } else if (identity.isPair(node)) { const kc = getAliasCount(doc, node.key, anchors2); const vc = getAliasCount(doc, node.value, anchors2); return Math.max(kc, vc); } return 1; } exports.Alias = Alias; } }); // ../../node_modules/yaml/dist/nodes/Scalar.js var require_Scalar = __commonJS({ "../../node_modules/yaml/dist/nodes/Scalar.js"(exports) { "use strict"; var identity = require_identity(); var Node = require_Node(); var toJS = require_toJS(); var isScalarValue = (value) => !value || typeof value !== "function" && typeof value !== "object"; var Scalar = class extends Node.NodeBase { constructor(value) { super(identity.SCALAR); this.value = value; } toJSON(arg, ctx) { return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx); } toString() { return String(this.value); } }; Scalar.BLOCK_FOLDED = "BLOCK_FOLDED"; Scalar.BLOCK_LITERAL = "BLOCK_LITERAL"; Scalar.PLAIN = "PLAIN"; Scalar.QUOTE_DOUBLE = "QUOTE_DOUBLE"; Scalar.QUOTE_SINGLE = "QUOTE_SINGLE"; exports.Scalar = Scalar; exports.isScalarValue = isScalarValue; } }); // ../../node_modules/yaml/dist/doc/createNode.js var require_createNode = __commonJS({ "../../node_modules/yaml/dist/doc/createNode.js"(exports) { "use strict"; var Alias = require_Alias(); var identity = require_identity(); var Scalar = require_Scalar(); var defaultTagPrefix = "tag:yaml.org,2002:"; function findTagObject(value, tagName, tags) { if (tagName) { const match = tags.filter((t) => t.tag === tagName); const tagObj = match.find((t) => !t.format) ?? match[0]; if (!tagObj) throw new Error(`Tag ${tagName} not found`); return tagObj; } return tags.find((t) => t.identify?.(value) && !t.format); } function createNode(value, tagName, ctx) { if (identity.isDocument(value)) value = value.contents; if (identity.isNode(value)) return value; if (identity.isPair(value)) { const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx); map.items.push(value); return map; } if (value instanceof String || value instanceof Number || value instanceof Boolean || typeof BigInt !== "undefined" && value instanceof BigInt) { value = value.valueOf(); } const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx; let ref = void 0; if (aliasDuplicateObjects && value && typeof value === "object") { ref = sourceObjects.get(value); if (ref) { ref.anchor ?? (ref.anchor = onAnchor(value)); return new Alias.Alias(ref.anchor); } else { ref = { anchor: null, node: null }; sourceObjects.set(value, ref); } } if (tagName?.startsWith("!!")) tagName = defaultTagPrefix + tagName.slice(2); let tagObj = findTagObject(value, tagName, schema.tags); if (!tagObj) { if (value && typeof value.toJSON === "function") { value = value.toJSON(); } if (!value || typeof value !== "object") { const node2 = new Scalar.Scalar(value); if (ref) ref.node = node2; return node2; } tagObj = value instanceof Map ? schema[identity.MAP] : Symbol.iterator in Object(value) ? schema[identity.SEQ] : schema[identity.MAP]; } if (onTagObj) { onTagObj(tagObj); delete ctx.onTagObj; } const node = tagObj?.createNode ? tagObj.createNode(ctx.schema, value, ctx) : typeof tagObj?.nodeClass?.from === "function" ? tagObj.nodeClass.from(ctx.schema, value, ctx) : new Scalar.Scalar(value); if (tagName) node.tag = tagName; else if (!tagObj.default) node.tag = tagObj.tag; if (ref) ref.node = node; return node; } exports.createNode = createNode; } }); // ../../node_modules/yaml/dist/nodes/Collection.js var require_Collection = __commonJS({ "../../node_modules/yaml/dist/nodes/Collection.js"(exports) { "use strict"; var createNode = require_createNode(); var identity = require_identity(); var Node = require_Node(); function collectionFromPath(schema, path, value) { let v = value; for (let i = path.length - 1; i >= 0; --i) { const k = path[i]; if (typeof k === "number" && Number.isInteger(k) && k >= 0) { const a = []; a[k] = v; v = a; } else { v = /* @__PURE__ */ new Map([[k, v]]); } } return createNode.createNode(v, void 0, { aliasDuplicateObjects: false, keepUndefined: false, onAnchor: () => { throw new Error("This should not happen, please report a bug."); }, schema, sourceObjects: /* @__PURE__ */ new Map() }); } var isEmptyPath = (path) => path == null || typeof path === "object" && !!path[Symbol.iterator]().next().done; var Collection = class extends Node.NodeBase { constructor(type, schema) { super(type); Object.defineProperty(this, "schema", { value: schema, configurable: true, enumerable: false, writable: true }); } /** * Create a copy of this collection. * * @param schema - If defined, overwrites the original's schema */ clone(schema) { const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this)); if (schema) copy.schema = schema; copy.items = copy.items.map((it) => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it); if (this.range) copy.range = this.range.slice(); return copy; } /** * Adds a value to the collection. For `!!map` and `!!omap` the value must * be a Pair instance or a `{ key, value }` object, which may not have a key * that already exists in the map. */ addIn(path, value) { if (isEmptyPath(path)) this.add(value); else { const [key, ...rest] = path; const node = this.get(key, true); if (identity.isCollection(node)) node.addIn(rest, value); else if (node === void 0 && this.schema) this.set(key, collectionFromPath(this.schema, rest, value)); else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); } } /** * Removes a value from the collection. * @returns `true` if the item was found and removed. */ deleteIn(path) { const [key, ...rest] = path; if (rest.length === 0) return this.delete(key); const node = this.get(key, true); if (identity.isCollection(node)) return node.deleteIn(rest); else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); } /** * Returns item at `key`, or `undefined` if not found. By default unwraps * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ getIn(path, keepScalar) { const [key, ...rest] = path; const node = this.get(key, true); if (rest.length === 0) return !keepScalar && identity.isScalar(node) ? node.value : node; else return identity.isCollection(node) ? node.getIn(rest, keepScalar) : void 0; } hasAllNullValues(allowScalar) { return this.items.every((node) => { if (!identity.isPair(node)) return false; const n = node.value; return n == null || allowScalar && identity.isScalar(n) && n.value == null && !n.commentBefore && !n.comment && !n.tag; }); } /** * Checks if the collection includes a value with the key `key`. */ hasIn(path) { const [key, ...rest] = path; if (rest.length === 0) return this.has(key); const node = this.get(key, true); return identity.isCollection(node) ? node.hasIn(rest) : false; } /** * Sets a value in this collection. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ setIn(path, value) { const [key, ...rest] = path; if (rest.length === 0) { this.set(key, value); } else { const node = this.get(key, true); if (identity.isCollection(node)) node.setIn(rest, value); else if (node === void 0 && this.schema) this.set(key, collectionFromPath(this.schema, rest, value)); else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`); } } }; exports.Collection = Collection; exports.collectionFromPath = collectionFromPath; exports.isEmptyPath = isEmptyPath; } }); // ../../node_modules/yaml/dist/stringify/stringifyComment.js var require_stringifyComment = __commonJS({ "../../node_modules/yaml/dist/stringify/stringifyComment.js"(exports) { "use strict"; var stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, "#"); function indentComment(comment, indent) { if (/^\n+$/.test(comment)) return comment.substring(1); return indent ? comment.replace(/^(?! *$)/gm, indent) : comment; } var lineComment = (str, indent, comment) => str.endsWith("\n") ? indentComment(comment, indent) : comment.includes("\n") ? "\n" + indentComment(comment, indent) : (str.endsWith(" ") ? "" : " ") + comment; exports.indentComment = indentComment; exports.lineComment = lineComment; exports.stringifyComment = stringifyComment; } }); // ../../node_modules/yaml/dist/stringify/foldFlowLines.js var require_foldFlowLines = __commonJS({ "../../node_modules/yaml/dist/stringify/foldFlowLines.js"(exports) { "use strict"; var FOLD_FLOW = "flow"; var FOLD_BLOCK = "block"; var FOLD_QUOTED = "quoted"; function foldFlowLines(text, indent, mode = "flow", { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) { if (!lineWidth || lineWidth < 0) return text; if (lineWidth < minContentWidth) minContentWidth = 0; const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length); if (text.length <= endStep) return text; const folds = []; const escapedFolds = {}; let end = lineWidth - indent.length; if (typeof indentAtStart === "number") { if (indentAtStart > lineWidth - Math.max(2, minContentWidth)) folds.push(0); else end = lineWidth - indentAtStart; } let split = void 0; let prev = void 0; let overflow = false; let i = -1; let escStart = -1; let escEnd = -1; if (mode === FOLD_BLOCK) { i = consumeMoreIndentedLines(text, i, indent.length); if (i !== -1) end = i + endStep; } for (let ch; ch = text[i += 1]; ) { if (mode === FOLD_QUOTED && ch === "\\") { escStart = i; switch (text[i + 1]) { case "x": i += 3; break; case "u": i += 5; break; case "U": i += 9; break; default: i += 1; } escEnd = i; } if (ch === "\n") { if (mode === FOLD_BLOCK) i = consumeMoreIndentedLines(text, i, indent.length); end = i + indent.length + endStep; split = void 0; } else { if (ch === " " && prev && prev !== " " && prev !== "\n" && prev !== " ") { const next = text[i + 1]; if (next && next !== " " && next !== "\n" && next !== " ") split = i; } if (i >= end) { if (split) { folds.push(split); end = split + endStep; split = void 0; } else if (mode === FOLD_QUOTED) { while (prev === " " || prev === " ") { prev = ch; ch = text[i += 1]; overflow = true; } const j = i > escEnd + 1 ? i - 2 : escStart - 1; if (escapedFolds[j]) return text; folds.push(j); escapedFolds[j] = true; end = j + endStep; split = void 0; } else { overflow = true; } } } prev = ch; } if (overflow && onOverflow) onOverflow(); if (folds.length === 0) return text; if (onFold) onFold(); let res = text.slice(0, folds[0]); for (let i2 = 0; i2 < folds.length; ++i2) { const fold = folds[i2]; const end2 = folds[i2 + 1] || text.length; if (fold === 0) res = ` ${indent}${text.slice(0, end2)}`; else { if (mode === FOLD_QUOTED && escapedFolds[fold]) res += `${text[fold]}\\`; res += ` ${indent}${text.slice(fold + 1, end2)}`; } } return res; } function consumeMoreIndentedLines(text, i, indent) { let end = i; let start = i + 1; let ch = text[start]; while (ch === " " || ch === " ") { if (i < start + indent) { ch = text[++i]; } else { do { ch = text[++i]; } while (ch && ch !== "\n"); end = i; start = i + 1; ch = text[start]; } } return end; } exports.FOLD_BLOCK = FOLD_BLOCK; exports.FOLD_FLOW = FOLD_FLOW; exports.FOLD_QUOTED = FOLD_QUOTED; exports.foldFlowLines = foldFlowLines; } }); // ../../node_modules/yaml/dist/stringify/stringifyString.js var require_stringifyString = __commonJS({ "../../node_modules/yaml/dist/stringify/stringifyString.js"(exports) { "use strict"; var Scalar = require_Scalar(); var foldFlowLines = require_foldFlowLines(); var getFoldOptions = (ctx, isBlock) => ({ indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart, lineWidth: ctx.options.lineWidth, minContentWidth: ctx.options.minContentWidth }); var containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str); function lineLengthOverLimit(str, lineWidth, indentLength) { if (!lineWidth || lineWidth < 0) return false; const limit = lineWidth - indentLength; const strLen = str.length; if (strLen <= limit) return false; for (let i = 0, start = 0; i < strLen; ++i) { if (str[i] === "\n") { if (i - start > limit) return true; start = i + 1; if (strLen - start <= limit) return false; } } return true; } function doubleQuotedString(value, ctx) { const json2 = JSON.stringify(value); if (ctx.options.doubleQuotedAsJSON) return json2; const { implicitKey } = ctx; const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength; const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); let str = ""; let start = 0; for (let i = 0, ch = json2[i]; ch; ch = json2[++i]) { if (ch === " " && json2[i + 1] === "\\" && json2[i + 2] === "n") { str += json2.slice(start, i) + "\\ "; i += 1; start = i; ch = "\\"; } if (ch === "\\") switch (json2[i + 1]) { case "u": { str += json2.slice(start, i); const code = json2.substr(i + 2, 4); switch (code) { case "0000": str += "\\0"; break; case "0007": str += "\\a"; break; case "000b": str += "\\v"; break; case "001b": str += "\\e"; break; case "0085": str += "\\N"; break; case "00a0": str += "\\_"; break; case "2028": str += "\\L"; break; case "2029": str += "\\P"; break; default: if (code.substr(0, 2) === "00") str += "\\x" + code.substr(2); else str += json2.substr(i, 6); } i += 5; start = i + 1; } break; case "n": if (implicitKey || json2[i + 2] === '"' || json2.length < minMultiLineLength) { i += 1; } else { str += json2.slice(start, i) + "\n\n"; while (json2[i + 2] === "\\" && json2[i + 3] === "n" && json2[i + 4] !== '"') { str += "\n"; i += 2; } str += indent; if (json2[i + 2] === " ") str += "\\"; i += 1; start = i + 1; } break; default: i += 1; } } str = start ? str + json2.slice(start) : json2; return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false)); } function singleQuotedString(value, ctx) { if (ctx.options.singleQuote === false || ctx.implicitKey && value.includes("\n") || /[ \t]\n|\n[ \t]/.test(value)) return doubleQuotedString(value, ctx); const indent = ctx.indent || (containsDocumentMarker(value) ? " " : ""); const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$& ${indent}`) + "'"; return ctx.implicitKey ? res : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); } function quotedString(value, ctx) { const { singleQuote } = ctx.options; let qs; if (singleQuote === false) qs = doubleQuotedString; else { const hasDouble = value.includes('"'); const hasSingle = value.includes("'"); if (hasDouble && !hasSingle) qs = singleQuotedString; else if (hasSingle && !hasDouble) qs = doubleQuotedString; else qs = singleQuote ? singleQuotedString : doubleQuotedString; } return qs(value, ctx); } var blockEndNewlines; try { blockEndNewlines = new RegExp("(^|(?\n"; let chomp; let endStart; for (endStart = value.length; endStart > 0; --endStart) { const ch = value[endStart - 1]; if (ch !== "\n" && ch !== " " && ch !== " ") break; } let end = value.substring(endStart); const endNlPos = end.indexOf("\n"); if (endNlPos === -1) { chomp = "-"; } else if (value === end || endNlPos !== end.length - 1) { chomp = "+"; if (onChompKeep) onChompKeep(); } else { chomp = ""; } if (end) { value = value.slice(0, -end.length); if (end[end.length - 1] === "\n") end = end.slice(0, -1); end = end.replace(blockEndNewlines, `$&${indent}`); } let startWithSpace = false; let startEnd; let startNlPos = -1; for (startEnd = 0; startEnd < value.length; ++startEnd) { const ch = value[startEnd]; if (ch === " ") startWithSpace = true; else if (ch === "\n") startNlPos = startEnd; else break; } let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd); if (start) { value = value.substring(start.length); start = start.replace(/\n+/g, `$&${indent}`); } const indentSize = indent ? "2" : "1"; let header = (startWithSpace ? indentSize : "") + chomp; if (comment) { header += " " + commentString(comment.replace(/ ?[\r\n]+/g, " ")); if (onComment) onComment(); } if (!literal) { const foldedValue = value.replace(/\n+/g, "\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, "$1$2").replace(/\n+/g, `$&${indent}`); let literalFallback = false; const foldOptions = getFoldOptions(ctx, true); if (blockQuote !== "folded" && type !== Scalar.Scalar.BLOCK_FOLDED) { foldOptions.onOverflow = () => { literalFallback = true; }; } const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions); if (!literalFallback) return `>${header} ${indent}${body}`; } value = value.replace(/\n+/g, `$&${indent}`); return `|${header} ${indent}${start}${value}${end}`; } function plainString(item, ctx, onComment, onChompKeep) { const { type, value } = item; const { actualString, implicitKey, indent, indentStep, inFlow } = ctx; if (implicitKey && value.includes("\n") || inFlow && /[[\]{},]/.test(value)) { return quotedString(value, ctx); } if (/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) { return implicitKey || inFlow || !value.includes("\n") ? quotedString(value, ctx) : blockString(item, ctx, onComment, onChompKeep); } if (!implicitKey && !inFlow && type !== Scalar.Scalar.PLAIN && value.includes("\n")) { return blockString(item, ctx, onComment, onChompKeep); } if (containsDocumentMarker(value)) { if (indent === "") { ctx.forceBlockIndent = true; return blockString(item, ctx, onComment, onChompKeep); } else if (implicitKey && indent === indentStep) { return quotedString(value, ctx); } } const str = value.replace(/\n+/g, `$& ${indent}`); if (actualString) { const test = (tag) => tag.default && tag.tag !== "tag:yaml.org,2002:str" && tag.test?.test(str); const { compat, tags } = ctx.doc.schema; if (tags.some(test) || compat?.some(test)) return quotedString(value, ctx); } return implicitKey ? str : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false)); } function stringifyString(item, ctx, onComment, onChompKeep) { const { implicitKey, inFlow } = ctx; const ss = typeof item.value === "string" ? item : Object.assign({}, item, { value: String(item.value) }); let { type } = item; if (type !== Scalar.Scalar.QUOTE_DOUBLE) { if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value)) type = Scalar.Scalar.QUOTE_DOUBLE; } const _stringify = (_type) => { switch (_type) { case Scalar.Scalar.BLOCK_FOLDED: case Scalar.Scalar.BLOCK_LITERAL: return implicitKey || inFlow ? quotedString(ss.value, ctx) : blockString(ss, ctx, onComment, onChompKeep); case Scalar.Scalar.QUOTE_DOUBLE: return doubleQuotedString(ss.value, ctx); case Scalar.Scalar.QUOTE_SINGLE: return singleQuotedString(ss.value, ctx); case Scalar.Scalar.PLAIN: return plainString(ss, ctx, onComment, onChompKeep); default: return null; } }; let res = _stringify(type); if (res === null) { const { defaultKeyType, defaultStringType } = ctx.options; const t = implicitKey && defaultKeyType || defaultStringType; res = _stringify(t); if (res === null) throw new Error(`Unsupported default string type ${t}`); } return res; } exports.stringifyString = stringifyString; } }); // ../../node_modules/yaml/dist/stringify/stringify.js var require_stringify = __commonJS({ "../../node_modules/yaml/dist/stringify/stringify.js"(exports) { "use strict"; var anchors = require_anchors(); var identity = require_identity(); var stringifyComment = require_stringifyComment(); var stringifyString = require_stringifyString(); function createStringifyContext(doc, options) { const opt = Object.assign({ blockQuote: true, commentString: stringifyComment.stringifyComment, defaultKeyType: null, defaultStringType: "PLAIN", directives: null, doubleQuotedAsJSON: false, doubleQuotedMinMultiLineLength: 40, falseStr: "false", flowCollectionPadding: true, indentSeq: true, lineWidth: 80, minContentWidth: 20, nullStr: "null", simpleKeys: false, singleQuote: null, trailingComma: false, trueStr: "true", verifyAliasOrder: true }, doc.schema.toStringOptions, options); let inFlow; switch (opt.collectionStyle) { case "block": inFlow = false; break; case "flow": inFlow = true; break; default: inFlow = null; } return { anchors: /* @__PURE__ */ new Set(), doc, flowCollectionPadding: opt.flowCollectionPadding ? " " : "", indent: "", indentStep: typeof opt.indent === "number" ? " ".repeat(opt.indent) : " ", inFlow, options: opt }; } function getTagObject(tags, item) { if (item.tag) { const match = tags.filter((t) => t.tag === item.tag); if (match.length > 0) return match.find((t) => t.format === item.format) ?? match[0]; } let tagObj = void 0; let obj; if (identity.isScalar(item)) { obj = item.value; let match = tags.filter((t) => t.identify?.(obj)); if (match.length > 1) { const testMatch = match.filter((t) => t.test); if (testMatch.length > 0) match = testMatch; } tagObj = match.find((t) => t.format === item.format) ?? match.find((t) => !t.format); } else { obj = item; tagObj = tags.find((t) => t.nodeClass && obj instanceof t.nodeClass); } if (!tagObj) { const name = obj?.constructor?.name ?? (obj === null ? "null" : typeof obj); throw new Error(`Tag not resolved for ${name} value`); } return tagObj; } function stringifyProps(node, tagObj, { anchors: anchors$1, doc }) { if (!doc.directives) return ""; const props = []; const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor; if (anchor && anchors.anchorIsValid(anchor)) { anchors$1.add(anchor); props.push(`&${anchor}`); } const tag = node.tag ?? (tagObj.default ? null : tagObj.tag); if (tag) props.push(doc.directives.tagString(tag)); return props.join(" "); } function stringify(item, ctx, onComment, onChompKeep) { if (identity.isPair(item)) return item.toString(ctx, onComment, onChompKeep); if (identity.isAlias(item)) { if (ctx.doc.directives) return item.toString(ctx); if (ctx.resolvedAliases?.has(item)) { throw new TypeError(`Cannot stringify circular structure without alias nodes`); } else { if (ctx.resolvedAliases) ctx.resolvedAliases.add(item); else ctx.resolvedAliases = /* @__PURE__ */ new Set([item]); item = item.resolve(ctx.doc); } } let tagObj = void 0; const node = identity.isNode(item) ? item : ctx.doc.createNode(item, { onTagObj: (o) => tagObj = o }); tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node)); const props = stringifyProps(node, tagObj, ctx); if (props.length > 0) ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1; const str = typeof tagObj.stringify === "function" ? tagObj.stringify(node, ctx, onComment, onChompKeep) : identity.isScalar(node) ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep) : node.toString(ctx, onComment, onChompKeep); if (!props) return str; return identity.isScalar(node) || str[0] === "{" || str[0] === "[" ? `${props} ${str}` : `${props} ${ctx.indent}${str}`; } exports.createStringifyContext = createStringifyContext; exports.stringify = stringify; } }); // ../../node_modules/yaml/dist/stringify/stringifyPair.js var require_stringifyPair = __commonJS({ "../../node_modules/yaml/dist/stringify/stringifyPair.js"(exports) { "use strict"; var identity = require_identity(); var Scalar = require_Scalar(); var stringify = require_stringify(); var stringifyComment = require_stringifyComment(); function stringifyPair({ key, value }, ctx, onComment, onChompKeep) { const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx; let keyComment = identity.isNode(key) && key.comment || null; if (simpleKeys) { if (keyComment) { throw new Error("With simple keys, key nodes cannot have comments"); } if (identity.isCollection(key) || !identity.isNode(key) && typeof key === "object") { const msg = "With simple keys, collection cannot be used as a key value"; throw new Error(msg); } } let explicitKey = !simpleKeys && (!key || keyComment && value == null && !ctx.inFlow || identity.isCollection(key) || (identity.isScalar(key) ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL : typeof key === "object")); ctx = Object.assign({}, ctx, { allNullValues: false, implicitKey: !explicitKey && (simpleKeys || !allNullValues), indent: indent + indentStep }); let keyCommentDone = false; let chompKeep = false; let str = stringify.stringify(key, ctx, () => keyCommentDone = true, () => chompKeep = true); if (!explicitKey && !ctx.inFlow && str.length > 1024) { if (simpleKeys) throw new Error("With simple keys, single line scalar must not span more than 1024 characters"); explicitKey = true; } if (ctx.inFlow) { if (allNullValues || value == null) { if (keyCommentDone && onComment) onComment(); return str === "" ? "?" : explicitKey ? `? ${str}` : str; } } else if (allNullValues && !simpleKeys || value == null && explicitKey) { str = `? ${str}`; if (keyComment && !keyCommentDone) { str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); } else if (chompKeep && onChompKeep) onChompKeep(); return str; } if (keyCommentDone) keyComment = null; if (explicitKey) { if (keyComment) str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); str = `? ${str} ${indent}:`; } else { str = `${str}:`; if (keyComment) str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment)); } let vsb, vcb, valueComment; if (identity.isNode(value)) { vsb = !!value.spaceBefore; vcb = value.commentBefore; valueComment = value.comment; } else { vsb = false; vcb = null; valueComment = null; if (value && typeof value === "object") value = doc.createNode(value); } ctx.implicitKey = false; if (!explicitKey && !keyComment && identity.isScalar(value)) ctx.indentAtStart = str.length + 1; chompKeep = false; if (!indentSeq && indentStep.length >= 2 && !ctx.inFlow && !explicitKey && identity.isSeq(value) && !value.flow && !value.tag && !value.anchor) { ctx.indent = ctx.indent.substring(2); } let valueCommentDone = false; const valueStr = stringify.stringify(value, ctx, () => valueCommentDone = true, () => chompKeep = true); let ws = " "; if (keyComment || vsb || vcb) { ws = vsb ? "\n" : ""; if (vcb) { const cs = commentString(vcb); ws += ` ${stringifyComment.indentComment(cs, ctx.indent)}`; } if (valueStr === "" && !ctx.inFlow) { if (ws === "\n" && valueComment) ws = "\n\n"; } else { ws += ` ${ctx.indent}`; } } else if (!explicitKey && identity.isCollection(value)) { const vs0 = valueStr[0]; const nl0 = valueStr.indexOf("\n"); const hasNewline = nl0 !== -1; const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0; if (hasNewline || !flow) { let hasPropsLine = false; if (hasNewline && (vs0 === "&" || vs0 === "!")) { let sp0 = valueStr.indexOf(" "); if (vs0 === "&" && sp0 !== -1 && sp0 < nl0 && valueStr[sp0 + 1] === "!") { sp0 = valueStr.indexOf(" ", sp0 + 1); } if (sp0 === -1 || nl0 < sp0) hasPropsLine = true; } if (!hasPropsLine) ws = ` ${ctx.indent}`; } } else if (valueStr === "" || valueStr[0] === "\n") { ws = ""; } str += ws + valueStr; if (ctx.inFlow) { if (valueCommentDone && onComment) onComment(); } else if (valueComment && !valueCommentDone) { str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment)); } else if (chompKeep && onChompKeep) { onChompKeep(); } return str; } exports.stringifyPair = stringifyPair; } }); // ../../node_modules/yaml/dist/log.js var require_log = __commonJS({ "../../node_modules/yaml/dist/log.js"(exports) { "use strict"; var node_process = __require("process"); function debug(logLevel, ...messages) { if (logLevel === "debug") console.log(...messages); } function warn(logLevel, warning) { if (logLevel === "debug" || logLevel === "warn") { if (typeof node_process.emitWarning === "function") node_process.emitWarning(warning); else console.warn(warning); } } exports.debug = debug; exports.warn = warn; } }); // ../../node_modules/yaml/dist/schema/yaml-1.1/merge.js var require_merge = __commonJS({ "../../node_modules/yaml/dist/schema/yaml-1.1/merge.js"(exports) { "use strict"; var identity = require_identity(); var Scalar = require_Scalar(); var MERGE_KEY = "<<"; var merge = { identify: (value) => value === MERGE_KEY || typeof value === "symbol" && value.description === MERGE_KEY, default: "key", tag: "tag:yaml.org,2002:merge", test: /^<<$/, resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), { addToJSMap: addMergeToJSMap }), stringify: () => MERGE_KEY }; var isMergeKey = (ctx, key) => (merge.identify(key) || identity.isScalar(key) && (!key.type || key.type === Scalar.Scalar.PLAIN) && merge.identify(key.value)) && ctx?.doc.schema.tags.some((tag) => tag.tag === merge.tag && tag.default); function addMergeToJSMap(ctx, map, value) { const source = resolveAliasValue(ctx, value); if (identity.isSeq(source)) for (const it of source.items) mergeValue(ctx, map, it); else if (Array.isArray(source)) for (const it of source) mergeValue(ctx, map, it); else mergeValue(ctx, map, source); } function mergeValue(ctx, map, value) { const source = resolveAliasValue(ctx, value); if (!identity.isMap(source)) throw new Error("Merge sources must be maps or map aliases"); const srcMap = source.toJSON(null, ctx, Map); for (const [key, value2] of srcMap) { if (map instanceof Map) { if (!map.has(key)) map.set(key, value2); } else if (map instanceof Set) { map.add(key); } else if (!Object.prototype.hasOwnProperty.call(map, key)) { Object.defineProperty(map, key, { value: value2, writable: true, enumerable: true, configurable: true }); } } return map; } function resolveAliasValue(ctx, value) { return ctx && identity.isAlias(value) ? value.resolve(ctx.doc, ctx) : value; } exports.addMergeToJSMap = addMergeToJSMap; exports.isMergeKey = isMergeKey; exports.merge = merge; } }); // ../../node_modules/yaml/dist/nodes/addPairToJSMap.js var require_addPairToJSMap = __commonJS({ "../../node_modules/yaml/dist/nodes/addPairToJSMap.js"(exports) { "use strict"; var log2 = require_log(); var merge = require_merge(); var stringify = require_stringify(); var identity = require_identity(); var toJS = require_toJS(); function addPairToJSMap(ctx, map, { key, value }) { if (identity.isNode(key) && key.addToJSMap) key.addToJSMap(ctx, map, value); else if (merge.isMergeKey(ctx, key)) merge.addMergeToJSMap(ctx, map, value); else { const jsKey = toJS.toJS(key, "", ctx); if (map instanceof Map) { map.set(jsKey, toJS.toJS(value, jsKey, ctx)); } else if (map instanceof Set) { map.add(jsKey); } else { const stringKey = stringifyKey(key, jsKey, ctx); const jsValue = toJS.toJS(value, stringKey, ctx); if (stringKey in map) Object.defineProperty(map, stringKey, { value: jsValue, writable: true, enumerable: true, configurable: true }); else map[stringKey] = jsValue; } } return map; } function stringifyKey(key, jsKey, ctx) { if (jsKey === null) return ""; if (typeof jsKey !== "object") return String(jsKey); if (identity.isNode(key) && ctx?.doc) { const strCtx = stringify.createStringifyContext(ctx.doc, {}); strCtx.anchors = /* @__PURE__ */ new Set(); for (const node of ctx.anchors.keys()) strCtx.anchors.add(node.anchor); strCtx.inFlow = true; strCtx.inStringifyKey = true; const strKey = key.toString(strCtx); if (!ctx.mapKeyWarned) { let jsonStr = JSON.stringify(strKey); if (jsonStr.length > 40) jsonStr = jsonStr.substring(0, 36) + '..."'; log2.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`); ctx.mapKeyWarned = true; } return strKey; } return JSON.stringify(jsKey); } exports.addPairToJSMap = addPairToJSMap; } }); // ../../node_modules/yaml/dist/nodes/Pair.js var require_Pair = __commonJS({ "../../node_modules/yaml/dist/nodes/Pair.js"(exports) { "use strict"; var createNode = require_createNode(); var stringifyPair = require_stringifyPair(); var addPairToJSMap = require_addPairToJSMap(); var identity = require_identity(); function createPair(key, value, ctx) { const k = createNode.createNode(key, void 0, ctx); const v = createNode.createNode(value, void 0, ctx); return new Pair(k, v); } var Pair = class _Pair { constructor(key, value = null) { Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR }); this.key = key; this.value = value; } clone(schema) { let { key, value } = this; if (identity.isNode(key)) key = key.clone(schema); if (identity.isNode(value)) value = value.clone(schema); return new _Pair(key, value); } toJSON(_, ctx) { const pair = ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; return addPairToJSMap.addPairToJSMap(ctx, pair, this); } toString(ctx, onComment, onChompKeep) { return ctx?.doc ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this); } }; exports.Pair = Pair; exports.createPair = createPair; } }); // ../../node_modules/yaml/dist/stringify/stringifyCollection.js var require_stringifyCollection = __commonJS({ "../../node_modules/yaml/dist/stringify/stringifyCollection.js"(exports) { "use strict"; var identity = require_identity(); var stringify = require_stringify(); var stringifyComment = require_stringifyComment(); function stringifyCollection(collection, ctx, options) { const flow = ctx.inFlow ?? collection.flow; const stringify2 = flow ? stringifyFlowCollection : stringifyBlockCollection; return stringify2(collection, ctx, options); } function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) { const { indent, options: { commentString } } = ctx; const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null }); let chompKeep = false; const lines = []; for (let i = 0; i < items.length; ++i) { const item = items[i]; let comment2 = null; if (identity.isNode(item)) { if (!chompKeep && item.spaceBefore) lines.push(""); addCommentBefore(ctx, lines, item.commentBefore, chompKeep); if (item.comment) comment2 = item.comment; } else if (identity.isPair(item)) { const ik = identity.isNode(item.key) ? item.key : null; if (ik) { if (!chompKeep && ik.spaceBefore) lines.push(""); addCommentBefore(ctx, lines, ik.commentBefore, chompKeep); } } chompKeep = false; let str2 = stringify.stringify(item, itemCtx, () => comment2 = null, () => chompKeep = true); if (comment2) str2 += stringifyComment.lineComment(str2, itemIndent, commentString(comment2)); if (chompKeep && comment2) chompKeep = false; lines.push(blockItemPrefix + str2); } let str; if (lines.length === 0) { str = flowChars.start + flowChars.end; } else { str = lines[0]; for (let i = 1; i < lines.length; ++i) { const line = lines[i]; str += line ? ` ${indent}${line}` : "\n"; } } if (comment) { str += "\n" + stringifyComment.indentComment(commentString(comment), indent); if (onComment) onComment(); } else if (chompKeep && onChompKeep) onChompKeep(); return str; } function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) { const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx; itemIndent += indentStep; const itemCtx = Object.assign({}, ctx, { indent: itemIndent, inFlow: true, type: null }); let reqNewline = false; let linesAtValue = 0; const lines = []; for (let i = 0; i < items.length; ++i) { const item = items[i]; let comment = null; if (identity.isNode(item)) { if (item.spaceBefore) lines.push(""); addCommentBefore(ctx, lines, item.commentBefore, false); if (item.comment) comment = item.comment; } else if (identity.isPair(item)) { const ik = identity.isNode(item.key) ? item.key : null; if (ik) { if (ik.spaceBefore) lines.push(""); addCommentBefore(ctx, lines, ik.commentBefore, false); if (ik.comment) reqNewline = true; } const iv = identity.isNode(item.value) ? item.value : null; if (iv) { if (iv.comment) comment = iv.comment; if (iv.commentBefore) reqNewline = true; } else if (item.value == null && ik?.comment) { comment = ik.comment; } } if (comment) reqNewline = true; let str = stringify.stringify(item, itemCtx, () => comment = null); reqNewline || (reqNewline = lines.length > linesAtValue || str.includes("\n")); if (i < items.length - 1) { str += ","; } else if (ctx.options.trailingComma) { if (ctx.options.lineWidth > 0) { reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) + (str.length + 2) > ctx.options.lineWidth); } if (reqNewline) { str += ","; } } if (comment) str += stringifyComment.lineComment(str, itemIndent, commentString(comment)); lines.push(str); linesAtValue = lines.length; } const { start, end } = flowChars; if (lines.length === 0) { return start + end; } else { if (!reqNewline) { const len = lines.reduce((sum, line) => sum + line.length + 2, 2); reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth; } if (reqNewline) { let str = start; for (const line of lines) str += line ? ` ${indentStep}${indent}${line}` : "\n"; return `${str} ${indent}${end}`; } else { return `${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`; } } } function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) { if (comment && chompKeep) comment = comment.replace(/^\n+/, ""); if (comment) { const ic = stringifyComment.indentComment(commentString(comment), indent); lines.push(ic.trimStart()); } } exports.stringifyCollection = stringifyCollection; } }); // ../../node_modules/yaml/dist/nodes/YAMLMap.js var require_YAMLMap = __commonJS({ "../../node_modules/yaml/dist/nodes/YAMLMap.js"(exports) { "use strict"; var stringifyCollection = require_stringifyCollection(); var addPairToJSMap = require_addPairToJSMap(); var Collection = require_Collection(); var identity = require_identity(); var Pair = require_Pair(); var Scalar = require_Scalar(); function findPair(items, key) { const k = identity.isScalar(key) ? key.value : key; for (const it of items) { if (identity.isPair(it)) { if (it.key === key || it.key === k) return it; if (identity.isScalar(it.key) && it.key.value === k) return it; } } return void 0; } var YAMLMap = class extends Collection.Collection { static get tagName() { return "tag:yaml.org,2002:map"; } constructor(schema) { super(identity.MAP, schema); this.items = []; } /** * A generic collection parsing method that can be extended * to other node classes that inherit from YAMLMap */ static from(schema, obj, ctx) { const { keepUndefined, replacer } = ctx; const map = new this(schema); const add = (key, value) => { if (typeof replacer === "function") value = replacer.call(obj, key, value); else if (Array.isArray(replacer) && !replacer.includes(key)) return; if (value !== void 0 || keepUndefined) map.items.push(Pair.createPair(key, value, ctx)); }; if (obj instanceof Map) { for (const [key, value] of obj) add(key, value); } else if (obj && typeof obj === "object") { for (const key of Object.keys(obj)) add(key, obj[key]); } if (typeof schema.sortMapEntries === "function") { map.items.sort(schema.sortMapEntries); } return map; } /** * Adds a value to the collection. * * @param overwrite - If not set `true`, using a key that is already in the * collection will throw. Otherwise, overwrites the previous value. */ add(pair, overwrite) { let _pair; if (identity.isPair(pair)) _pair = pair; else if (!pair || typeof pair !== "object" || !("key" in pair)) { _pair = new Pair.Pair(pair, pair?.value); } else _pair = new Pair.Pair(pair.key, pair.value); const prev = findPair(this.items, _pair.key); const sortEntries = this.schema?.sortMapEntries; if (prev) { if (!overwrite) throw new Error(`Key ${_pair.key} already set`); if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value)) prev.value.value = _pair.value; else prev.value = _pair.value; } else if (sortEntries) { const i = this.items.findIndex((item) => sortEntries(_pair, item) < 0); if (i === -1) this.items.push(_pair); else this.items.splice(i, 0, _pair); } else { this.items.push(_pair); } } delete(key) { const it = findPair(this.items, key); if (!it) return false; const del = this.items.splice(this.items.indexOf(it), 1); return del.length > 0; } get(key, keepScalar) { const it = findPair(this.items, key); const node = it?.value; return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? void 0; } has(key) { return !!findPair(this.items, key); } set(key, value) { this.add(new Pair.Pair(key, value), true); } /** * @param ctx - Conversion context, originally set in Document#toJS() * @param {Class} Type - If set, forces the returned collection type * @returns Instance of Type, Map, or Object */ toJSON(_, ctx, Type) { const map = Type ? new Type() : ctx?.mapAsMap ? /* @__PURE__ */ new Map() : {}; if (ctx?.onCreate) ctx.onCreate(map); for (const item of this.items) addPairToJSMap.addPairToJSMap(ctx, map, item); return map; } toString(ctx, onComment, onChompKeep) { if (!ctx) return JSON.stringify(this); for (const item of this.items) { if (!identity.isPair(item)) throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`); } if (!ctx.allNullValues && this.hasAllNullValues(false)) ctx = Object.assign({}, ctx, { allNullValues: true }); return stringifyCollection.stringifyCollection(this, ctx, { blockItemPrefix: "", flowChars: { start: "{", end: "}" }, itemIndent: ctx.indent || "", onChompKeep, onComment }); } }; exports.YAMLMap = YAMLMap; exports.findPair = findPair; } }); // ../../node_modules/yaml/dist/schema/common/map.js var require_map = __commonJS({ "../../node_modules/yaml/dist/schema/common/map.js"(exports) { "use strict"; var identity = require_identity(); var YAMLMap = require_YAMLMap(); var map = { collection: "map", default: true, nodeClass: YAMLMap.YAMLMap, tag: "tag:yaml.org,2002:map", resolve(map2, onError) { if (!identity.isMap(map2)) onError("Expected a mapping for this tag"); return map2; }, createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx) }; exports.map = map; } }); // ../../node_modules/yaml/dist/nodes/YAMLSeq.js var require_YAMLSeq = __commonJS({ "../../node_modules/yaml/dist/nodes/YAMLSeq.js"(exports) { "use strict"; var createNode = require_createNode(); var stringifyCollection = require_stringifyCollection(); var Collection = require_Collection(); var identity = require_identity(); var Scalar = require_Scalar(); var toJS = require_toJS(); var YAMLSeq = class extends Collection.Collection { static get tagName() { return "tag:yaml.org,2002:seq"; } constructor(schema) { super(identity.SEQ, schema); this.items = []; } add(value) { this.items.push(value); } /** * Removes a value from the collection. * * `key` must contain a representation of an integer for this to succeed. * It may be wrapped in a `Scalar`. * * @returns `true` if the item was found and removed. */ delete(key) { const idx = asItemIndex(key); if (typeof idx !== "number") return false; const del = this.items.splice(idx, 1); return del.length > 0; } get(key, keepScalar) { const idx = asItemIndex(key); if (typeof idx !== "number") return void 0; const it = this.items[idx]; return !keepScalar && identity.isScalar(it) ? it.value : it; } /** * Checks if the collection includes a value with the key `key`. * * `key` must contain a representation of an integer for this to succeed. * It may be wrapped in a `Scalar`. */ has(key) { const idx = asItemIndex(key); return typeof idx === "number" && idx < this.items.length; } /** * Sets a value in this collection. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. * * If `key` does not contain a representation of an integer, this will throw. * It may be wrapped in a `Scalar`. */ set(key, value) { const idx = asItemIndex(key); if (typeof idx !== "number") throw new Error(`Expected a valid index, not ${key}.`); const prev = this.items[idx]; if (identity.isScalar(prev) && Scalar.isScalarValue(value)) prev.value = value; else this.items[idx] = value; } toJSON(_, ctx) { const seq = []; if (ctx?.onCreate) ctx.onCreate(seq); let i = 0; for (const item of this.items) seq.push(toJS.toJS(item, String(i++), ctx)); return seq; } toString(ctx, onComment, onChompKeep) { if (!ctx) return JSON.stringify(this); return stringifyCollection.stringifyCollection(this, ctx, { blockItemPrefix: "- ", flowChars: { start: "[", end: "]" }, itemIndent: (ctx.indent || "") + " ", onChompKeep, onComment }); } static from(schema, obj, ctx) { const { replacer } = ctx; const seq = new this(schema); if (obj && Symbol.iterator in Object(obj)) { let i = 0; for (let it of obj) { if (typeof replacer === "function") { const key = obj instanceof Set ? it : String(i++); it = replacer.call(obj, key, it); } seq.items.push(createNode.createNode(it, void 0, ctx)); } } return seq; } }; function asItemIndex(key) { let idx = identity.isScalar(key) ? key.value : key; if (idx && typeof idx === "string") idx = Number(idx); return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null; } exports.YAMLSeq = YAMLSeq; } }); // ../../node_modules/yaml/dist/schema/common/seq.js var require_seq = __commonJS({ "../../node_modules/yaml/dist/schema/common/seq.js"(exports) { "use strict"; var identity = require_identity(); var YAMLSeq = require_YAMLSeq(); var seq = { collection: "seq", default: true, nodeClass: YAMLSeq.YAMLSeq, tag: "tag:yaml.org,2002:seq", resolve(seq2, onError) { if (!identity.isSeq(seq2)) onError("Expected a sequence for this tag"); return seq2; }, createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx) }; exports.seq = seq; } }); // ../../node_modules/yaml/dist/schema/common/string.js var require_string = __commonJS({ "../../node_modules/yaml/dist/schema/common/string.js"(exports) { "use strict"; var stringifyString = require_stringifyString(); var string = { identify: (value) => typeof value === "string", default: true, tag: "tag:yaml.org,2002:str", resolve: (str) => str, stringify(item, ctx, onComment, onChompKeep) { ctx = Object.assign({ actualString: true }, ctx); return stringifyString.stringifyString(item, ctx, onComment, onChompKeep); } }; exports.string = string; } }); // ../../node_modules/yaml/dist/schema/common/null.js var require_null = __commonJS({ "../../node_modules/yaml/dist/schema/common/null.js"(exports) { "use strict"; var Scalar = require_Scalar(); var nullTag = { identify: (value) => value == null, createNode: () => new Scalar.Scalar(null), default: true, tag: "tag:yaml.org,2002:null", test: /^(?:~|[Nn]ull|NULL)?$/, resolve: () => new Scalar.Scalar(null), stringify: ({ source }, ctx) => typeof source === "string" && nullTag.test.test(source) ? source : ctx.options.nullStr }; exports.nullTag = nullTag; } }); // ../../node_modules/yaml/dist/schema/core/bool.js var require_bool = __commonJS({ "../../node_modules/yaml/dist/schema/core/bool.js"(exports) { "use strict"; var Scalar = require_Scalar(); var boolTag = { identify: (value) => typeof value === "boolean", default: true, tag: "tag:yaml.org,2002:bool", test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/, resolve: (str) => new Scalar.Scalar(str[0] === "t" || str[0] === "T"), stringify({ source, value }, ctx) { if (source && boolTag.test.test(source)) { const sv = source[0] === "t" || source[0] === "T"; if (value === sv) return source; } return value ? ctx.options.trueStr : ctx.options.falseStr; } }; exports.boolTag = boolTag; } }); // ../../node_modules/yaml/dist/stringify/stringifyNumber.js var require_stringifyNumber = __commonJS({ "../../node_modules/yaml/dist/stringify/stringifyNumber.js"(exports) { "use strict"; function stringifyNumber({ format, minFractionDigits, tag, value }) { if (typeof value === "bigint") return String(value); const num = typeof value === "number" ? value : Number(value); if (!isFinite(num)) return isNaN(num) ? ".nan" : num < 0 ? "-.inf" : ".inf"; let n = Object.is(value, -0) ? "-0" : JSON.stringify(value); if (!format && minFractionDigits && (!tag || tag === "tag:yaml.org,2002:float") && /^-?\d/.test(n) && !n.includes("e")) { let i = n.indexOf("."); if (i < 0) { i = n.length; n += "."; } let d = minFractionDigits - (n.length - i - 1); while (d-- > 0) n += "0"; } return n; } exports.stringifyNumber = stringifyNumber; } }); // ../../node_modules/yaml/dist/schema/core/float.js var require_float = __commonJS({ "../../node_modules/yaml/dist/schema/core/float.js"(exports) { "use strict"; var Scalar = require_Scalar(); var stringifyNumber = require_stringifyNumber(); var floatNaN = { identify: (value) => typeof value === "number", default: true, tag: "tag:yaml.org,2002:float", test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, stringify: stringifyNumber.stringifyNumber }; var floatExp = { identify: (value) => typeof value === "number", default: true, tag: "tag:yaml.org,2002:float", format: "EXP", test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/, resolve: (str) => parseFloat(str), stringify(node) { const num = Number(node.value); return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node); } }; var float = { identify: (value) => typeof value === "number", default: true, tag: "tag:yaml.org,2002:float", test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/, resolve(str) { const node = new Scalar.Scalar(parseFloat(str)); const dot = str.indexOf("."); if (dot !== -1 && str[str.length - 1] === "0") node.minFractionDigits = str.length - dot - 1; return node; }, stringify: stringifyNumber.stringifyNumber }; exports.float = float; exports.floatExp = floatExp; exports.floatNaN = floatNaN; } }); // ../../node_modules/yaml/dist/schema/core/int.js var require_int = __commonJS({ "../../node_modules/yaml/dist/schema/core/int.js"(exports) { "use strict"; var stringifyNumber = require_stringifyNumber(); var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); var intResolve = (str, offset, radix, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix); function intStringify(node, radix, prefix) { const { value } = node; if (intIdentify(value) && value >= 0) return prefix + value.toString(radix); return stringifyNumber.stringifyNumber(node); } var intOct = { identify: (value) => intIdentify(value) && value >= 0, default: true, tag: "tag:yaml.org,2002:int", format: "OCT", test: /^0o[0-7]+$/, resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt), stringify: (node) => intStringify(node, 8, "0o") }; var int = { identify: intIdentify, default: true, tag: "tag:yaml.org,2002:int", test: /^[-+]?[0-9]+$/, resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), stringify: stringifyNumber.stringifyNumber }; var intHex = { identify: (value) => intIdentify(value) && value >= 0, default: true, tag: "tag:yaml.org,2002:int", format: "HEX", test: /^0x[0-9a-fA-F]+$/, resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), stringify: (node) => intStringify(node, 16, "0x") }; exports.int = int; exports.intHex = intHex; exports.intOct = intOct; } }); // ../../node_modules/yaml/dist/schema/core/schema.js var require_schema = __commonJS({ "../../node_modules/yaml/dist/schema/core/schema.js"(exports) { "use strict"; var map = require_map(); var _null = require_null(); var seq = require_seq(); var string = require_string(); var bool = require_bool(); var float = require_float(); var int = require_int(); var schema = [ map.map, seq.seq, string.string, _null.nullTag, bool.boolTag, int.intOct, int.int, int.intHex, float.floatNaN, float.floatExp, float.float ]; exports.schema = schema; } }); // ../../node_modules/yaml/dist/schema/json/schema.js var require_schema2 = __commonJS({ "../../node_modules/yaml/dist/schema/json/schema.js"(exports) { "use strict"; var Scalar = require_Scalar(); var map = require_map(); var seq = require_seq(); function intIdentify(value) { return typeof value === "bigint" || Number.isInteger(value); } var stringifyJSON = ({ value }) => JSON.stringify(value); var jsonScalars = [ { identify: (value) => typeof value === "string", default: true, tag: "tag:yaml.org,2002:str", resolve: (str) => str, stringify: stringifyJSON }, { identify: (value) => value == null, createNode: () => new Scalar.Scalar(null), default: true, tag: "tag:yaml.org,2002:null", test: /^null$/, resolve: () => null, stringify: stringifyJSON }, { identify: (value) => typeof value === "boolean", default: true, tag: "tag:yaml.org,2002:bool", test: /^true$|^false$/, resolve: (str) => str === "true", stringify: stringifyJSON }, { identify: intIdentify, default: true, tag: "tag:yaml.org,2002:int", test: /^-?(?:0|[1-9][0-9]*)$/, resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10), stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value) }, { identify: (value) => typeof value === "number", default: true, tag: "tag:yaml.org,2002:float", test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/, resolve: (str) => parseFloat(str), stringify: stringifyJSON } ]; var jsonError = { default: true, tag: "", test: /^/, resolve(str, onError) { onError(`Unresolved plain scalar ${JSON.stringify(str)}`); return str; } }; var schema = [map.map, seq.seq].concat(jsonScalars, jsonError); exports.schema = schema; } }); // ../../node_modules/yaml/dist/schema/yaml-1.1/binary.js var require_binary = __commonJS({ "../../node_modules/yaml/dist/schema/yaml-1.1/binary.js"(exports) { "use strict"; var node_buffer = __require("buffer"); var Scalar = require_Scalar(); var stringifyString = require_stringifyString(); var binary = { identify: (value) => value instanceof Uint8Array, // Buffer inherits from Uint8Array default: false, tag: "tag:yaml.org,2002:binary", /** * Returns a Buffer in node and an Uint8Array in browsers * * To use the resulting buffer as an image, you'll want to do something like: * * const blob = new Blob([buffer], { type: 'image/jpeg' }) * document.querySelector('#photo').src = URL.createObjectURL(blob) */ resolve(src, onError) { if (typeof node_buffer.Buffer === "function") { return node_buffer.Buffer.from(src, "base64"); } else if (typeof atob === "function") { const str = atob(src.replace(/[\n\r]/g, "")); const buffer = new Uint8Array(str.length); for (let i = 0; i < str.length; ++i) buffer[i] = str.charCodeAt(i); return buffer; } else { onError("This environment does not support reading binary tags; either Buffer or atob is required"); return src; } }, stringify({ comment, type, value }, ctx, onComment, onChompKeep) { if (!value) return ""; const buf = value; let str; if (typeof node_buffer.Buffer === "function") { str = buf instanceof node_buffer.Buffer ? buf.toString("base64") : node_buffer.Buffer.from(buf.buffer).toString("base64"); } else if (typeof btoa === "function") { let s = ""; for (let i = 0; i < buf.length; ++i) s += String.fromCharCode(buf[i]); str = btoa(s); } else { throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required"); } type ?? (type = Scalar.Scalar.BLOCK_LITERAL); if (type !== Scalar.Scalar.QUOTE_DOUBLE) { const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth); const n = Math.ceil(str.length / lineWidth); const lines = new Array(n); for (let i = 0, o = 0; i < n; ++i, o += lineWidth) { lines[i] = str.substr(o, lineWidth); } str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? "\n" : " "); } return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep); } }; exports.binary = binary; } }); // ../../node_modules/yaml/dist/schema/yaml-1.1/pairs.js var require_pairs = __commonJS({ "../../node_modules/yaml/dist/schema/yaml-1.1/pairs.js"(exports) { "use strict"; var identity = require_identity(); var Pair = require_Pair(); var Scalar = require_Scalar(); var YAMLSeq = require_YAMLSeq(); function resolvePairs(seq, onError) { if (identity.isSeq(seq)) { for (let i = 0; i < seq.items.length; ++i) { let item = seq.items[i]; if (identity.isPair(item)) continue; else if (identity.isMap(item)) { if (item.items.length > 1) onError("Each pair must have its own sequence indicator"); const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null)); if (item.commentBefore) pair.key.commentBefore = pair.key.commentBefore ? `${item.commentBefore} ${pair.key.commentBefore}` : item.commentBefore; if (item.comment) { const cn = pair.value ?? pair.key; cn.comment = cn.comment ? `${item.comment} ${cn.comment}` : item.comment; } item = pair; } seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item); } } else onError("Expected a sequence for this tag"); return seq; } function createPairs(schema, iterable, ctx) { const { replacer } = ctx; const pairs2 = new YAMLSeq.YAMLSeq(schema); pairs2.tag = "tag:yaml.org,2002:pairs"; let i = 0; if (iterable && Symbol.iterator in Object(iterable)) for (let it of iterable) { if (typeof replacer === "function") it = replacer.call(iterable, String(i++), it); let key, value; if (Array.isArray(it)) { if (it.length === 2) { key = it[0]; value = it[1]; } else throw new TypeError(`Expected [key, value] tuple: ${it}`); } else if (it && it instanceof Object) { const keys = Object.keys(it); if (keys.length === 1) { key = keys[0]; value = it[key]; } else { throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`); } } else { key = it; } pairs2.items.push(Pair.createPair(key, value, ctx)); } return pairs2; } var pairs = { collection: "seq", default: false, tag: "tag:yaml.org,2002:pairs", resolve: resolvePairs, createNode: createPairs }; exports.createPairs = createPairs; exports.pairs = pairs; exports.resolvePairs = resolvePairs; } }); // ../../node_modules/yaml/dist/schema/yaml-1.1/omap.js var require_omap = __commonJS({ "../../node_modules/yaml/dist/schema/yaml-1.1/omap.js"(exports) { "use strict"; var identity = require_identity(); var toJS = require_toJS(); var YAMLMap = require_YAMLMap(); var YAMLSeq = require_YAMLSeq(); var pairs = require_pairs(); var YAMLOMap = class _YAMLOMap extends YAMLSeq.YAMLSeq { constructor() { super(); this.add = YAMLMap.YAMLMap.prototype.add.bind(this); this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this); this.get = YAMLMap.YAMLMap.prototype.get.bind(this); this.has = YAMLMap.YAMLMap.prototype.has.bind(this); this.set = YAMLMap.YAMLMap.prototype.set.bind(this); this.tag = _YAMLOMap.tag; } /** * If `ctx` is given, the return type is actually `Map`, * but TypeScript won't allow widening the signature of a child method. */ toJSON(_, ctx) { if (!ctx) return super.toJSON(_); const map = /* @__PURE__ */ new Map(); if (ctx?.onCreate) ctx.onCreate(map); for (const pair of this.items) { let key, value; if (identity.isPair(pair)) { key = toJS.toJS(pair.key, "", ctx); value = toJS.toJS(pair.value, key, ctx); } else { key = toJS.toJS(pair, "", ctx); } if (map.has(key)) throw new Error("Ordered maps must not include duplicate keys"); map.set(key, value); } return map; } static from(schema, iterable, ctx) { const pairs$1 = pairs.createPairs(schema, iterable, ctx); const omap2 = new this(); omap2.items = pairs$1.items; return omap2; } }; YAMLOMap.tag = "tag:yaml.org,2002:omap"; var omap = { collection: "seq", identify: (value) => value instanceof Map, nodeClass: YAMLOMap, default: false, tag: "tag:yaml.org,2002:omap", resolve(seq, onError) { const pairs$1 = pairs.resolvePairs(seq, onError); const seenKeys = []; for (const { key } of pairs$1.items) { if (identity.isScalar(key)) { if (seenKeys.includes(key.value)) { onError(`Ordered maps must not include duplicate keys: ${key.value}`); } else { seenKeys.push(key.value); } } } return Object.assign(new YAMLOMap(), pairs$1); }, createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx) }; exports.YAMLOMap = YAMLOMap; exports.omap = omap; } }); // ../../node_modules/yaml/dist/schema/yaml-1.1/bool.js var require_bool2 = __commonJS({ "../../node_modules/yaml/dist/schema/yaml-1.1/bool.js"(exports) { "use strict"; var Scalar = require_Scalar(); function boolStringify({ value, source }, ctx) { const boolObj = value ? trueTag : falseTag; if (source && boolObj.test.test(source)) return source; return value ? ctx.options.trueStr : ctx.options.falseStr; } var trueTag = { identify: (value) => value === true, default: true, tag: "tag:yaml.org,2002:bool", test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/, resolve: () => new Scalar.Scalar(true), stringify: boolStringify }; var falseTag = { identify: (value) => value === false, default: true, tag: "tag:yaml.org,2002:bool", test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/, resolve: () => new Scalar.Scalar(false), stringify: boolStringify }; exports.falseTag = falseTag; exports.trueTag = trueTag; } }); // ../../node_modules/yaml/dist/schema/yaml-1.1/float.js var require_float2 = __commonJS({ "../../node_modules/yaml/dist/schema/yaml-1.1/float.js"(exports) { "use strict"; var Scalar = require_Scalar(); var stringifyNumber = require_stringifyNumber(); var floatNaN = { identify: (value) => typeof value === "number", default: true, tag: "tag:yaml.org,2002:float", test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/, resolve: (str) => str.slice(-3).toLowerCase() === "nan" ? NaN : str[0] === "-" ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY, stringify: stringifyNumber.stringifyNumber }; var floatExp = { identify: (value) => typeof value === "number", default: true, tag: "tag:yaml.org,2002:float", format: "EXP", test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/, resolve: (str) => parseFloat(str.replace(/_/g, "")), stringify(node) { const num = Number(node.value); return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node); } }; var float = { identify: (value) => typeof value === "number", default: true, tag: "tag:yaml.org,2002:float", test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/, resolve(str) { const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, ""))); const dot = str.indexOf("."); if (dot !== -1) { const f = str.substring(dot + 1).replace(/_/g, ""); if (f[f.length - 1] === "0") node.minFractionDigits = f.length; } return node; }, stringify: stringifyNumber.stringifyNumber }; exports.float = float; exports.floatExp = floatExp; exports.floatNaN = floatNaN; } }); // ../../node_modules/yaml/dist/schema/yaml-1.1/int.js var require_int2 = __commonJS({ "../../node_modules/yaml/dist/schema/yaml-1.1/int.js"(exports) { "use strict"; var stringifyNumber = require_stringifyNumber(); var intIdentify = (value) => typeof value === "bigint" || Number.isInteger(value); function intResolve(str, offset, radix, { intAsBigInt }) { const sign = str[0]; if (sign === "-" || sign === "+") offset += 1; str = str.substring(offset).replace(/_/g, ""); if (intAsBigInt) { switch (radix) { case 2: str = `0b${str}`; break; case 8: str = `0o${str}`; break; case 16: str = `0x${str}`; break; } const n2 = BigInt(str); return sign === "-" ? BigInt(-1) * n2 : n2; } const n = parseInt(str, radix); return sign === "-" ? -1 * n : n; } function intStringify(node, radix, prefix) { const { value } = node; if (intIdentify(value)) { const str = value.toString(radix); return value < 0 ? "-" + prefix + str.substr(1) : prefix + str; } return stringifyNumber.stringifyNumber(node); } var intBin = { identify: intIdentify, default: true, tag: "tag:yaml.org,2002:int", format: "BIN", test: /^[-+]?0b[0-1_]+$/, resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt), stringify: (node) => intStringify(node, 2, "0b") }; var intOct = { identify: intIdentify, default: true, tag: "tag:yaml.org,2002:int", format: "OCT", test: /^[-+]?0[0-7_]+$/, resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt), stringify: (node) => intStringify(node, 8, "0") }; var int = { identify: intIdentify, default: true, tag: "tag:yaml.org,2002:int", test: /^[-+]?[0-9][0-9_]*$/, resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt), stringify: stringifyNumber.stringifyNumber }; var intHex = { identify: intIdentify, default: true, tag: "tag:yaml.org,2002:int", format: "HEX", test: /^[-+]?0x[0-9a-fA-F_]+$/, resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt), stringify: (node) => intStringify(node, 16, "0x") }; exports.int = int; exports.intBin = intBin; exports.intHex = intHex; exports.intOct = intOct; } }); // ../../node_modules/yaml/dist/schema/yaml-1.1/set.js var require_set = __commonJS({ "../../node_modules/yaml/dist/schema/yaml-1.1/set.js"(exports) { "use strict"; var identity = require_identity(); var Pair = require_Pair(); var YAMLMap = require_YAMLMap(); var YAMLSet = class _YAMLSet extends YAMLMap.YAMLMap { constructor(schema) { super(schema); this.tag = _YAMLSet.tag; } add(key) { let pair; if (identity.isPair(key)) pair = key; else if (key && typeof key === "object" && "key" in key && "value" in key && key.value === null) pair = new Pair.Pair(key.key, null); else pair = new Pair.Pair(key, null); const prev = YAMLMap.findPair(this.items, pair.key); if (!prev) this.items.push(pair); } /** * If `keepPair` is `true`, returns the Pair matching `key`. * Otherwise, returns the value of that Pair's key. */ get(key, keepPair) { const pair = YAMLMap.findPair(this.items, key); return !keepPair && identity.isPair(pair) ? identity.isScalar(pair.key) ? pair.key.value : pair.key : pair; } set(key, value) { if (typeof value !== "boolean") throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`); const prev = YAMLMap.findPair(this.items, key); if (prev && !value) { this.items.splice(this.items.indexOf(prev), 1); } else if (!prev && value) { this.items.push(new Pair.Pair(key)); } } toJSON(_, ctx) { return super.toJSON(_, ctx, Set); } toString(ctx, onComment, onChompKeep) { if (!ctx) return JSON.stringify(this); if (this.hasAllNullValues(true)) return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep); else throw new Error("Set items must all have null values"); } static from(schema, iterable, ctx) { const { replacer } = ctx; const set2 = new this(schema); if (iterable && Symbol.iterator in Object(iterable)) for (let value of iterable) { if (typeof replacer === "function") value = replacer.call(iterable, value, value); set2.items.push(Pair.createPair(value, null, ctx)); } return set2; } }; YAMLSet.tag = "tag:yaml.org,2002:set"; var set = { collection: "map", identify: (value) => value instanceof Set, nodeClass: YAMLSet, default: false, tag: "tag:yaml.org,2002:set", createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx), resolve(map, onError) { if (identity.isMap(map)) { if (map.hasAllNullValues(true)) return Object.assign(new YAMLSet(), map); else onError("Set items must all have null values"); } else onError("Expected a mapping for this tag"); return map; } }; exports.YAMLSet = YAMLSet; exports.set = set; } }); // ../../node_modules/yaml/dist/schema/yaml-1.1/timestamp.js var require_timestamp = __commonJS({ "../../node_modules/yaml/dist/schema/yaml-1.1/timestamp.js"(exports) { "use strict"; var stringifyNumber = require_stringifyNumber(); function parseSexagesimal(str, asBigInt) { const sign = str[0]; const parts = sign === "-" || sign === "+" ? str.substring(1) : str; const num = (n) => asBigInt ? BigInt(n) : Number(n); const res = parts.replace(/_/g, "").split(":").reduce((res2, p) => res2 * num(60) + num(p), num(0)); return sign === "-" ? num(-1) * res : res; } function stringifySexagesimal(node) { let { value } = node; let num = (n) => n; if (typeof value === "bigint") num = (n) => BigInt(n); else if (isNaN(value) || !isFinite(value)) return stringifyNumber.stringifyNumber(node); let sign = ""; if (value < 0) { sign = "-"; value *= num(-1); } const _60 = num(60); const parts = [value % _60]; if (value < 60) { parts.unshift(0); } else { value = (value - parts[0]) / _60; parts.unshift(value % _60); if (value >= 60) { value = (value - parts[0]) / _60; parts.unshift(value); } } return sign + parts.map((n) => String(n).padStart(2, "0")).join(":").replace(/000000\d*$/, ""); } var intTime = { identify: (value) => typeof value === "bigint" || Number.isInteger(value), default: true, tag: "tag:yaml.org,2002:int", format: "TIME", test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/, resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt), stringify: stringifySexagesimal }; var floatTime = { identify: (value) => typeof value === "number", default: true, tag: "tag:yaml.org,2002:float", format: "TIME", test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/, resolve: (str) => parseSexagesimal(str, false), stringify: stringifySexagesimal }; var timestamp = { identify: (value) => value instanceof Date, default: true, tag: "tag:yaml.org,2002:timestamp", // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part // may be omitted altogether, resulting in a date format. In such a case, the time part is // assumed to be 00:00:00Z (start of day, UTC). test: RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"), resolve(str) { const match = str.match(timestamp.test); if (!match) throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd"); const [, year, month, day, hour, minute, second] = match.map(Number); const millisec = match[7] ? Number((match[7] + "00").substr(1, 3)) : 0; let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec); const tz = match[8]; if (tz && tz !== "Z") { let d = parseSexagesimal(tz, false); if (Math.abs(d) < 30) d *= 60; date -= 6e4 * d; } return new Date(date); }, stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\.000Z$/, "") ?? "" }; exports.floatTime = floatTime; exports.intTime = intTime; exports.timestamp = timestamp; } }); // ../../node_modules/yaml/dist/schema/yaml-1.1/schema.js var require_schema3 = __commonJS({ "../../node_modules/yaml/dist/schema/yaml-1.1/schema.js"(exports) { "use strict"; var map = require_map(); var _null = require_null(); var seq = require_seq(); var string = require_string(); var binary = require_binary(); var bool = require_bool2(); var float = require_float2(); var int = require_int2(); var merge = require_merge(); var omap = require_omap(); var pairs = require_pairs(); var set = require_set(); var timestamp = require_timestamp(); var schema = [ map.map, seq.seq, string.string, _null.nullTag, bool.trueTag, bool.falseTag, int.intBin, int.intOct, int.int, int.intHex, float.floatNaN, float.floatExp, float.float, binary.binary, merge.merge, omap.omap, pairs.pairs, set.set, timestamp.intTime, timestamp.floatTime, timestamp.timestamp ]; exports.schema = schema; } }); // ../../node_modules/yaml/dist/schema/tags.js var require_tags = __commonJS({ "../../node_modules/yaml/dist/schema/tags.js"(exports) { "use strict"; var map = require_map(); var _null = require_null(); var seq = require_seq(); var string = require_string(); var bool = require_bool(); var float = require_float(); var int = require_int(); var schema = require_schema(); var schema$1 = require_schema2(); var binary = require_binary(); var merge = require_merge(); var omap = require_omap(); var pairs = require_pairs(); var schema$2 = require_schema3(); var set = require_set(); var timestamp = require_timestamp(); var schemas = /* @__PURE__ */ new Map([ ["core", schema.schema], ["failsafe", [map.map, seq.seq, string.string]], ["json", schema$1.schema], ["yaml11", schema$2.schema], ["yaml-1.1", schema$2.schema] ]); var tagsByName = { binary: binary.binary, bool: bool.boolTag, float: float.float, floatExp: float.floatExp, floatNaN: float.floatNaN, floatTime: timestamp.floatTime, int: int.int, intHex: int.intHex, intOct: int.intOct, intTime: timestamp.intTime, map: map.map, merge: merge.merge, null: _null.nullTag, omap: omap.omap, pairs: pairs.pairs, seq: seq.seq, set: set.set, timestamp: timestamp.timestamp }; var coreKnownTags = { "tag:yaml.org,2002:binary": binary.binary, "tag:yaml.org,2002:merge": merge.merge, "tag:yaml.org,2002:omap": omap.omap, "tag:yaml.org,2002:pairs": pairs.pairs, "tag:yaml.org,2002:set": set.set, "tag:yaml.org,2002:timestamp": timestamp.timestamp }; function getTags(customTags, schemaName, addMergeTag) { const schemaTags = schemas.get(schemaName); if (schemaTags && !customTags) { return addMergeTag && !schemaTags.includes(merge.merge) ? schemaTags.concat(merge.merge) : schemaTags.slice(); } let tags = schemaTags; if (!tags) { if (Array.isArray(customTags)) tags = []; else { const keys = Array.from(schemas.keys()).filter((key) => key !== "yaml11").map((key) => JSON.stringify(key)).join(", "); throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`); } } if (Array.isArray(customTags)) { for (const tag of customTags) tags = tags.concat(tag); } else if (typeof customTags === "function") { tags = customTags(tags.slice()); } if (addMergeTag) tags = tags.concat(merge.merge); return tags.reduce((tags2, tag) => { const tagObj = typeof tag === "string" ? tagsByName[tag] : tag; if (!tagObj) { const tagName = JSON.stringify(tag); const keys = Object.keys(tagsByName).map((key) => JSON.stringify(key)).join(", "); throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`); } if (!tags2.includes(tagObj)) tags2.push(tagObj); return tags2; }, []); } exports.coreKnownTags = coreKnownTags; exports.getTags = getTags; } }); // ../../node_modules/yaml/dist/schema/Schema.js var require_Schema = __commonJS({ "../../node_modules/yaml/dist/schema/Schema.js"(exports) { "use strict"; var identity = require_identity(); var map = require_map(); var seq = require_seq(); var string = require_string(); var tags = require_tags(); var sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0; var Schema = class _Schema { constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) { this.compat = Array.isArray(compat) ? tags.getTags(compat, "compat") : compat ? tags.getTags(null, compat) : null; this.name = typeof schema === "string" && schema || "core"; this.knownTags = resolveKnownTags ? tags.coreKnownTags : {}; this.tags = tags.getTags(customTags, this.name, merge); this.toStringOptions = toStringDefaults ?? null; Object.defineProperty(this, identity.MAP, { value: map.map }); Object.defineProperty(this, identity.SCALAR, { value: string.string }); Object.defineProperty(this, identity.SEQ, { value: seq.seq }); this.sortMapEntries = typeof sortMapEntries === "function" ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null; } clone() { const copy = Object.create(_Schema.prototype, Object.getOwnPropertyDescriptors(this)); copy.tags = this.tags.slice(); return copy; } }; exports.Schema = Schema; } }); // ../../node_modules/yaml/dist/stringify/stringifyDocument.js var require_stringifyDocument = __commonJS({ "../../node_modules/yaml/dist/stringify/stringifyDocument.js"(exports) { "use strict"; var identity = require_identity(); var stringify = require_stringify(); var stringifyComment = require_stringifyComment(); function stringifyDocument(doc, options) { const lines = []; let hasDirectives = options.directives === true; if (options.directives !== false && doc.directives) { const dir = doc.directives.toString(doc); if (dir) { lines.push(dir); hasDirectives = true; } else if (doc.directives.docStart) hasDirectives = true; } if (hasDirectives) lines.push("---"); const ctx = stringify.createStringifyContext(doc, options); const { commentString } = ctx.options; if (doc.commentBefore) { if (lines.length !== 1) lines.unshift(""); const cs = commentString(doc.commentBefore); lines.unshift(stringifyComment.indentComment(cs, "")); } let chompKeep = false; let contentComment = null; if (doc.contents) { if (identity.isNode(doc.contents)) { if (doc.contents.spaceBefore && hasDirectives) lines.push(""); if (doc.contents.commentBefore) { const cs = commentString(doc.contents.commentBefore); lines.push(stringifyComment.indentComment(cs, "")); } ctx.forceBlockIndent = !!doc.comment; contentComment = doc.contents.comment; } const onChompKeep = contentComment ? void 0 : () => chompKeep = true; let body = stringify.stringify(doc.contents, ctx, () => contentComment = null, onChompKeep); if (contentComment) body += stringifyComment.lineComment(body, "", commentString(contentComment)); if ((body[0] === "|" || body[0] === ">") && lines[lines.length - 1] === "---") { lines[lines.length - 1] = `--- ${body}`; } else lines.push(body); } else { lines.push(stringify.stringify(doc.contents, ctx)); } if (doc.directives?.docEnd) { if (doc.comment) { const cs = commentString(doc.comment); if (cs.includes("\n")) { lines.push("..."); lines.push(stringifyComment.indentComment(cs, "")); } else { lines.push(`... ${cs}`); } } else { lines.push("..."); } } else { let dc = doc.comment; if (dc && chompKeep) dc = dc.replace(/^\n+/, ""); if (dc) { if ((!chompKeep || contentComment) && lines[lines.length - 1] !== "") lines.push(""); lines.push(stringifyComment.indentComment(commentString(dc), "")); } } return lines.join("\n") + "\n"; } exports.stringifyDocument = stringifyDocument; } }); // ../../node_modules/yaml/dist/doc/Document.js var require_Document = __commonJS({ "../../node_modules/yaml/dist/doc/Document.js"(exports) { "use strict"; var Alias = require_Alias(); var Collection = require_Collection(); var identity = require_identity(); var Pair = require_Pair(); var toJS = require_toJS(); var Schema = require_Schema(); var stringifyDocument = require_stringifyDocument(); var anchors = require_anchors(); var applyReviver = require_applyReviver(); var createNode = require_createNode(); var directives = require_directives(); var Document = class _Document { constructor(value, replacer, options) { this.commentBefore = null; this.comment = null; this.errors = []; this.warnings = []; Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC }); let _replacer = null; if (typeof replacer === "function" || Array.isArray(replacer)) { _replacer = replacer; } else if (options === void 0 && replacer) { options = replacer; replacer = void 0; } const opt = Object.assign({ intAsBigInt: false, keepSourceTokens: false, logLevel: "warn", prettyErrors: true, strict: true, stringKeys: false, uniqueKeys: true, version: "1.2" }, options); this.options = opt; let { version } = opt; if (options?._directives) { this.directives = options._directives.atDocument(); if (this.directives.yaml.explicit) version = this.directives.yaml.version; } else this.directives = new directives.Directives({ version }); this.setSchema(version, options); this.contents = value === void 0 ? null : this.createNode(value, _replacer, options); } /** * Create a deep copy of this Document and its contents. * * Custom Node values that inherit from `Object` still refer to their original instances. */ clone() { const copy = Object.create(_Document.prototype, { [identity.NODE_TYPE]: { value: identity.DOC } }); copy.commentBefore = this.commentBefore; copy.comment = this.comment; copy.errors = this.errors.slice(); copy.warnings = this.warnings.slice(); copy.options = Object.assign({}, this.options); if (this.directives) copy.directives = this.directives.clone(); copy.schema = this.schema.clone(); copy.contents = identity.isNode(this.contents) ? this.contents.clone(copy.schema) : this.contents; if (this.range) copy.range = this.range.slice(); return copy; } /** Adds a value to the document. */ add(value) { if (assertCollection(this.contents)) this.contents.add(value); } /** Adds a value to the document. */ addIn(path, value) { if (assertCollection(this.contents)) this.contents.addIn(path, value); } /** * Create a new `Alias` node, ensuring that the target `node` has the required anchor. * * If `node` already has an anchor, `name` is ignored. * Otherwise, the `node.anchor` value will be set to `name`, * or if an anchor with that name is already present in the document, * `name` will be used as a prefix for a new unique anchor. * If `name` is undefined, the generated anchor will use 'a' as a prefix. */ createAlias(node, name) { if (!node.anchor) { const prev = anchors.anchorNames(this); node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing !name || prev.has(name) ? anchors.findNewAnchor(name || "a", prev) : name; } return new Alias.Alias(node.anchor); } createNode(value, replacer, options) { let _replacer = void 0; if (typeof replacer === "function") { value = replacer.call({ "": value }, "", value); _replacer = replacer; } else if (Array.isArray(replacer)) { const keyToStr = (v) => typeof v === "number" || v instanceof String || v instanceof Number; const asStr = replacer.filter(keyToStr).map(String); if (asStr.length > 0) replacer = replacer.concat(asStr); _replacer = replacer; } else if (options === void 0 && replacer) { options = replacer; replacer = void 0; } const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {}; const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors( this, // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing anchorPrefix || "a" ); const ctx = { aliasDuplicateObjects: aliasDuplicateObjects ?? true, keepUndefined: keepUndefined ?? false, onAnchor, onTagObj, replacer: _replacer, schema: this.schema, sourceObjects }; const node = createNode.createNode(value, tag, ctx); if (flow && identity.isCollection(node)) node.flow = true; setAnchors(); return node; } /** * Convert a key and a value into a `Pair` using the current schema, * recursively wrapping all values as `Scalar` or `Collection` nodes. */ createPair(key, value, options = {}) { const k = this.createNode(key, null, options); const v = this.createNode(value, null, options); return new Pair.Pair(k, v); } /** * Removes a value from the document. * @returns `true` if the item was found and removed. */ delete(key) { return assertCollection(this.contents) ? this.contents.delete(key) : false; } /** * Removes a value from the document. * @returns `true` if the item was found and removed. */ deleteIn(path) { if (Collection.isEmptyPath(path)) { if (this.contents == null) return false; this.contents = null; return true; } return assertCollection(this.contents) ? this.contents.deleteIn(path) : false; } /** * Returns item at `key`, or `undefined` if not found. By default unwraps * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ get(key, keepScalar) { return identity.isCollection(this.contents) ? this.contents.get(key, keepScalar) : void 0; } /** * Returns item at `path`, or `undefined` if not found. By default unwraps * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ getIn(path, keepScalar) { if (Collection.isEmptyPath(path)) return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents; return identity.isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : void 0; } /** * Checks if the document includes a value with the key `key`. */ has(key) { return identity.isCollection(this.contents) ? this.contents.has(key) : false; } /** * Checks if the document includes a value at `path`. */ hasIn(path) { if (Collection.isEmptyPath(path)) return this.contents !== void 0; return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false; } /** * Sets a value in this document. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ set(key, value) { if (this.contents == null) { this.contents = Collection.collectionFromPath(this.schema, [key], value); } else if (assertCollection(this.contents)) { this.contents.set(key, value); } } /** * Sets a value in this document. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ setIn(path, value) { if (Collection.isEmptyPath(path)) { this.contents = value; } else if (this.contents == null) { this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value); } else if (assertCollection(this.contents)) { this.contents.setIn(path, value); } } /** * Change the YAML version and schema used by the document. * A `null` version disables support for directives, explicit tags, anchors, and aliases. * It also requires the `schema` option to be given as a `Schema` instance value. * * Overrides all previously set schema options. */ setSchema(version, options = {}) { if (typeof version === "number") version = String(version); let opt; switch (version) { case "1.1": if (this.directives) this.directives.yaml.version = "1.1"; else this.directives = new directives.Directives({ version: "1.1" }); opt = { resolveKnownTags: false, schema: "yaml-1.1" }; break; case "1.2": case "next": if (this.directives) this.directives.yaml.version = version; else this.directives = new directives.Directives({ version }); opt = { resolveKnownTags: true, schema: "core" }; break; case null: if (this.directives) delete this.directives; opt = null; break; default: { const sv = JSON.stringify(version); throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`); } } if (options.schema instanceof Object) this.schema = options.schema; else if (opt) this.schema = new Schema.Schema(Object.assign(opt, options)); else throw new Error(`With a null YAML version, the { schema: Schema } option is required`); } // json & jsonArg are only used from toJSON() toJS({ json: json2, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) { const ctx = { anchors: /* @__PURE__ */ new Map(), doc: this, keep: !json2, mapAsMap: mapAsMap === true, mapKeyWarned: false, maxAliasCount: typeof maxAliasCount === "number" ? maxAliasCount : 100 }; const res = toJS.toJS(this.contents, jsonArg ?? "", ctx); if (typeof onAnchor === "function") for (const { count, res: res2 } of ctx.anchors.values()) onAnchor(res2, count); return typeof reviver === "function" ? applyReviver.applyReviver(reviver, { "": res }, "", res) : res; } /** * A JSON representation of the document `contents`. * * @param jsonArg Used by `JSON.stringify` to indicate the array index or * property name. */ toJSON(jsonArg, onAnchor) { return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }); } /** A YAML representation of the document. */ toString(options = {}) { if (this.errors.length > 0) throw new Error("Document with errors cannot be stringified"); if ("indent" in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) { const s = JSON.stringify(options.indent); throw new Error(`"indent" option must be a positive integer, not ${s}`); } return stringifyDocument.stringifyDocument(this, options); } }; function assertCollection(contents) { if (identity.isCollection(contents)) return true; throw new Error("Expected a YAML collection as document contents"); } exports.Document = Document; } }); // ../../node_modules/yaml/dist/errors.js var require_errors = __commonJS({ "../../node_modules/yaml/dist/errors.js"(exports) { "use strict"; var YAMLError = class extends Error { constructor(name, pos, code, message) { super(); this.name = name; this.code = code; this.message = message; this.pos = pos; } }; var YAMLParseError = class extends YAMLError { constructor(pos, code, message) { super("YAMLParseError", pos, code, message); } }; var YAMLWarning = class extends YAMLError { constructor(pos, code, message) { super("YAMLWarning", pos, code, message); } }; var prettifyError = (src, lc) => (error) => { if (error.pos[0] === -1) return; error.linePos = error.pos.map((pos) => lc.linePos(pos)); const { line, col } = error.linePos[0]; error.message += ` at line ${line}, column ${col}`; let ci = col - 1; let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, ""); if (ci >= 60 && lineStr.length > 80) { const trimStart = Math.min(ci - 39, lineStr.length - 79); lineStr = "\u2026" + lineStr.substring(trimStart); ci -= trimStart - 1; } if (lineStr.length > 80) lineStr = lineStr.substring(0, 79) + "\u2026"; if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]); if (prev.length > 80) prev = prev.substring(0, 79) + "\u2026\n"; lineStr = prev + lineStr; } if (/[^ ]/.test(lineStr)) { let count = 1; const end = error.linePos[1]; if (end?.line === line && end.col > col) { count = Math.max(1, Math.min(end.col - col, 80 - ci)); } const pointer = " ".repeat(ci) + "^".repeat(count); error.message += `: ${lineStr} ${pointer} `; } }; exports.YAMLError = YAMLError; exports.YAMLParseError = YAMLParseError; exports.YAMLWarning = YAMLWarning; exports.prettifyError = prettifyError; } }); // ../../node_modules/yaml/dist/compose/resolve-props.js var require_resolve_props = __commonJS({ "../../node_modules/yaml/dist/compose/resolve-props.js"(exports) { "use strict"; function resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) { let spaceBefore = false; let atNewline = startOnNewline; let hasSpace = startOnNewline; let comment = ""; let commentSep = ""; let hasNewline = false; let reqSpace = false; let tab = null; let anchor = null; let tag = null; let newlineAfterProp = null; let comma = null; let found = null; let start = null; for (const token of tokens) { if (reqSpace) { if (token.type !== "space" && token.type !== "newline" && token.type !== "comma") onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); reqSpace = false; } if (tab) { if (atNewline && token.type !== "comment" && token.type !== "newline") { onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); } tab = null; } switch (token.type) { case "space": if (!flow && (indicator !== "doc-start" || next?.type !== "flow-collection") && token.source.includes(" ")) { tab = token; } hasSpace = true; break; case "comment": { if (!hasSpace) onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); const cb = token.source.substring(1) || " "; if (!comment) comment = cb; else comment += commentSep + cb; commentSep = ""; atNewline = false; break; } case "newline": if (atNewline) { if (comment) comment += token.source; else if (!found || indicator !== "seq-item-ind") spaceBefore = true; } else commentSep += token.source; atNewline = true; hasNewline = true; if (anchor || tag) newlineAfterProp = token; hasSpace = true; break; case "anchor": if (anchor) onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor"); if (token.source.endsWith(":")) onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true); anchor = token; start ?? (start = token.offset); atNewline = false; hasSpace = false; reqSpace = true; break; case "tag": { if (tag) onError(token, "MULTIPLE_TAGS", "A node can have at most one tag"); tag = token; start ?? (start = token.offset); atNewline = false; hasSpace = false; reqSpace = true; break; } case indicator: if (anchor || tag) onError(token, "BAD_PROP_ORDER", `Anchors and tags must be after the ${token.source} indicator`); if (found) onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.source} in ${flow ?? "collection"}`); found = token; atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind"; hasSpace = false; break; case "comma": if (flow) { if (comma) onError(token, "UNEXPECTED_TOKEN", `Unexpected , in ${flow}`); comma = token; atNewline = false; hasSpace = false; break; } // else fallthrough default: onError(token, "UNEXPECTED_TOKEN", `Unexpected ${token.type} token`); atNewline = false; hasSpace = false; } } const last = tokens[tokens.length - 1]; const end = last ? last.offset + last.source.length : offset; if (reqSpace && next && next.type !== "space" && next.type !== "newline" && next.type !== "comma" && (next.type !== "scalar" || next.source !== "")) { onError(next.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space"); } if (tab && (atNewline && tab.indent <= parentIndent || next?.type === "block-map" || next?.type === "block-seq")) onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation"); return { comma, found, spaceBefore, comment, hasNewline, anchor, tag, newlineAfterProp, end, start: start ?? end }; } exports.resolveProps = resolveProps; } }); // ../../node_modules/yaml/dist/compose/util-contains-newline.js var require_util_contains_newline = __commonJS({ "../../node_modules/yaml/dist/compose/util-contains-newline.js"(exports) { "use strict"; function containsNewline(key) { if (!key) return null; switch (key.type) { case "alias": case "scalar": case "double-quoted-scalar": case "single-quoted-scalar": if (key.source.includes("\n")) return true; if (key.end) { for (const st of key.end) if (st.type === "newline") return true; } return false; case "flow-collection": for (const it of key.items) { for (const st of it.start) if (st.type === "newline") return true; if (it.sep) { for (const st of it.sep) if (st.type === "newline") return true; } if (containsNewline(it.key) || containsNewline(it.value)) return true; } return false; default: return true; } } exports.containsNewline = containsNewline; } }); // ../../node_modules/yaml/dist/compose/util-flow-indent-check.js var require_util_flow_indent_check = __commonJS({ "../../node_modules/yaml/dist/compose/util-flow-indent-check.js"(exports) { "use strict"; var utilContainsNewline = require_util_contains_newline(); function flowIndentCheck(indent, fc, onError) { if (fc?.type === "flow-collection") { const end = fc.end[0]; if (end.indent === indent && (end.source === "]" || end.source === "}") && utilContainsNewline.containsNewline(fc)) { const msg = "Flow end indicator should be more indented than parent"; onError(end, "BAD_INDENT", msg, true); } } } exports.flowIndentCheck = flowIndentCheck; } }); // ../../node_modules/yaml/dist/compose/util-map-includes.js var require_util_map_includes = __commonJS({ "../../node_modules/yaml/dist/compose/util-map-includes.js"(exports) { "use strict"; var identity = require_identity(); function mapIncludes(ctx, items, search) { const { uniqueKeys } = ctx.options; if (uniqueKeys === false) return false; const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || identity.isScalar(a) && identity.isScalar(b) && a.value === b.value; return items.some((pair) => isEqual(pair.key, search)); } exports.mapIncludes = mapIncludes; } }); // ../../node_modules/yaml/dist/compose/resolve-block-map.js var require_resolve_block_map = __commonJS({ "../../node_modules/yaml/dist/compose/resolve-block-map.js"(exports) { "use strict"; var Pair = require_Pair(); var YAMLMap = require_YAMLMap(); var resolveProps = require_resolve_props(); var utilContainsNewline = require_util_contains_newline(); var utilFlowIndentCheck = require_util_flow_indent_check(); var utilMapIncludes = require_util_map_includes(); var startColMsg = "All mapping items must start at the same column"; function resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) { const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap; const map = new NodeClass(ctx.schema); if (ctx.atRoot) ctx.atRoot = false; let offset = bm.offset; let commentEnd = null; for (const collItem of bm.items) { const { start, key, sep, value } = collItem; const keyProps = resolveProps.resolveProps(start, { indicator: "explicit-key-ind", next: key ?? sep?.[0], offset, onError, parentIndent: bm.indent, startOnNewline: true }); const implicitKey = !keyProps.found; if (implicitKey) { if (key) { if (key.type === "block-seq") onError(offset, "BLOCK_AS_IMPLICIT_KEY", "A block sequence may not be used as an implicit map key"); else if ("indent" in key && key.indent !== bm.indent) onError(offset, "BAD_INDENT", startColMsg); } if (!keyProps.anchor && !keyProps.tag && !sep) { commentEnd = keyProps.end; if (keyProps.comment) { if (map.comment) map.comment += "\n" + keyProps.comment; else map.comment = keyProps.comment; } continue; } if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) { onError(key ?? start[start.length - 1], "MULTILINE_IMPLICIT_KEY", "Implicit keys need to be on a single line"); } } else if (keyProps.found?.indent !== bm.indent) { onError(offset, "BAD_INDENT", startColMsg); } ctx.atKey = true; const keyStart = keyProps.end; const keyNode = key ? composeNode(ctx, key, keyProps, onError) : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError); if (ctx.schema.compat) utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError); ctx.atKey = false; if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode)) onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); const valueProps = resolveProps.resolveProps(sep ?? [], { indicator: "map-value-ind", next: value, offset: keyNode.range[2], onError, parentIndent: bm.indent, startOnNewline: !key || key.type === "block-scalar" }); offset = valueProps.end; if (valueProps.found) { if (implicitKey) { if (value?.type === "block-map" && !valueProps.hasNewline) onError(offset, "BLOCK_AS_IMPLICIT_KEY", "Nested mappings are not allowed in compact mappings"); if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024) onError(keyNode.range, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key"); } const valueNode = value ? composeNode(ctx, value, valueProps, onError) : composeEmptyNode(ctx, offset, sep, null, valueProps, onError); if (ctx.schema.compat) utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError); offset = valueNode.range[2]; const pair = new Pair.Pair(keyNode, valueNode); if (ctx.options.keepSourceTokens) pair.srcToken = collItem; map.items.push(pair); } else { if (implicitKey) onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values"); if (valueProps.comment) { if (keyNode.comment) keyNode.comment += "\n" + valueProps.comment; else keyNode.comment = valueProps.comment; } const pair = new Pair.Pair(keyNode); if (ctx.options.keepSourceTokens) pair.srcToken = collItem; map.items.push(pair); } } if (commentEnd && commentEnd < offset) onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content"); map.range = [bm.offset, offset, commentEnd ?? offset]; return map; } exports.resolveBlockMap = resolveBlockMap; } }); // ../../node_modules/yaml/dist/compose/resolve-block-seq.js var require_resolve_block_seq = __commonJS({ "../../node_modules/yaml/dist/compose/resolve-block-seq.js"(exports) { "use strict"; var YAMLSeq = require_YAMLSeq(); var resolveProps = require_resolve_props(); var utilFlowIndentCheck = require_util_flow_indent_check(); function resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) { const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq; const seq = new NodeClass(ctx.schema); if (ctx.atRoot) ctx.atRoot = false; if (ctx.atKey) ctx.atKey = false; let offset = bs.offset; let commentEnd = null; for (const { start, value } of bs.items) { const props = resolveProps.resolveProps(start, { indicator: "seq-item-ind", next: value, offset, onError, parentIndent: bs.indent, startOnNewline: true }); if (!props.found) { if (props.anchor || props.tag || value) { if (value?.type === "block-seq") onError(props.end, "BAD_INDENT", "All sequence items must start at the same column"); else onError(offset, "MISSING_CHAR", "Sequence item without - indicator"); } else { commentEnd = props.end; if (props.comment) seq.comment = props.comment; continue; } } const node = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError); if (ctx.schema.compat) utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError); offset = node.range[2]; seq.items.push(node); } seq.range = [bs.offset, offset, commentEnd ?? offset]; return seq; } exports.resolveBlockSeq = resolveBlockSeq; } }); // ../../node_modules/yaml/dist/compose/resolve-end.js var require_resolve_end = __commonJS({ "../../node_modules/yaml/dist/compose/resolve-end.js"(exports) { "use strict"; function resolveEnd(end, offset, reqSpace, onError) { let comment = ""; if (end) { let hasSpace = false; let sep = ""; for (const token of end) { const { source, type } = token; switch (type) { case "space": hasSpace = true; break; case "comment": { if (reqSpace && !hasSpace) onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters"); const cb = source.substring(1) || " "; if (!comment) comment = cb; else comment += sep + cb; sep = ""; break; } case "newline": if (comment) sep += source; hasSpace = true; break; default: onError(token, "UNEXPECTED_TOKEN", `Unexpected ${type} at node end`); } offset += source.length; } } return { comment, offset }; } exports.resolveEnd = resolveEnd; } }); // ../../node_modules/yaml/dist/compose/resolve-flow-collection.js var require_resolve_flow_collection = __commonJS({ "../../node_modules/yaml/dist/compose/resolve-flow-collection.js"(exports) { "use strict"; var identity = require_identity(); var Pair = require_Pair(); var YAMLMap = require_YAMLMap(); var YAMLSeq = require_YAMLSeq(); var resolveEnd = require_resolve_end(); var resolveProps = require_resolve_props(); var utilContainsNewline = require_util_contains_newline(); var utilMapIncludes = require_util_map_includes(); var blockMsg = "Block collections are not allowed within flow collections"; var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq"); function resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) { const isMap = fc.start.source === "{"; const fcName = isMap ? "flow map" : "flow sequence"; const NodeClass = tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq); const coll = new NodeClass(ctx.schema); coll.flow = true; const atRoot = ctx.atRoot; if (atRoot) ctx.atRoot = false; if (ctx.atKey) ctx.atKey = false; let offset = fc.offset + fc.start.source.length; for (let i = 0; i < fc.items.length; ++i) { const collItem = fc.items[i]; const { start, key, sep, value } = collItem; const props = resolveProps.resolveProps(start, { flow: fcName, indicator: "explicit-key-ind", next: key ?? sep?.[0], offset, onError, parentIndent: fc.indent, startOnNewline: false }); if (!props.found) { if (!props.anchor && !props.tag && !sep && !value) { if (i === 0 && props.comma) onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); else if (i < fc.items.length - 1) onError(props.start, "UNEXPECTED_TOKEN", `Unexpected empty item in ${fcName}`); if (props.comment) { if (coll.comment) coll.comment += "\n" + props.comment; else coll.comment = props.comment; } offset = props.end; continue; } if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key)) onError( key, // checked by containsNewline() "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line" ); } if (i === 0) { if (props.comma) onError(props.comma, "UNEXPECTED_TOKEN", `Unexpected , in ${fcName}`); } else { if (!props.comma) onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`); if (props.comment) { let prevItemComment = ""; loop: for (const st of start) { switch (st.type) { case "comma": case "space": break; case "comment": prevItemComment = st.source.substring(1); break loop; default: break loop; } } if (prevItemComment) { let prev = coll.items[coll.items.length - 1]; if (identity.isPair(prev)) prev = prev.value ?? prev.key; if (prev.comment) prev.comment += "\n" + prevItemComment; else prev.comment = prevItemComment; props.comment = props.comment.substring(prevItemComment.length + 1); } } } if (!isMap && !sep && !props.found) { const valueNode = value ? composeNode(ctx, value, props, onError) : composeEmptyNode(ctx, props.end, sep, null, props, onError); coll.items.push(valueNode); offset = valueNode.range[2]; if (isBlock(value)) onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); } else { ctx.atKey = true; const keyStart = props.end; const keyNode = key ? composeNode(ctx, key, props, onError) : composeEmptyNode(ctx, keyStart, start, null, props, onError); if (isBlock(key)) onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg); ctx.atKey = false; const valueProps = resolveProps.resolveProps(sep ?? [], { flow: fcName, indicator: "map-value-ind", next: value, offset: keyNode.range[2], onError, parentIndent: fc.indent, startOnNewline: false }); if (valueProps.found) { if (!isMap && !props.found && ctx.options.strict) { if (sep) for (const st of sep) { if (st === valueProps.found) break; if (st.type === "newline") { onError(st, "MULTILINE_IMPLICIT_KEY", "Implicit keys of flow sequence pairs need to be on a single line"); break; } } if (props.start < valueProps.found.offset - 1024) onError(valueProps.found, "KEY_OVER_1024_CHARS", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key"); } } else if (value) { if ("source" in value && value.source?.[0] === ":") onError(value, "MISSING_CHAR", `Missing space after : in ${fcName}`); else onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`); } const valueNode = value ? composeNode(ctx, value, valueProps, onError) : valueProps.found ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError) : null; if (valueNode) { if (isBlock(value)) onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg); } else if (valueProps.comment) { if (keyNode.comment) keyNode.comment += "\n" + valueProps.comment; else keyNode.comment = valueProps.comment; } const pair = new Pair.Pair(keyNode, valueNode); if (ctx.options.keepSourceTokens) pair.srcToken = collItem; if (isMap) { const map = coll; if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode)) onError(keyStart, "DUPLICATE_KEY", "Map keys must be unique"); map.items.push(pair); } else { const map = new YAMLMap.YAMLMap(ctx.schema); map.flow = true; map.items.push(pair); const endRange = (valueNode ?? keyNode).range; map.range = [keyNode.range[0], endRange[1], endRange[2]]; coll.items.push(map); } offset = valueNode ? valueNode.range[2] : valueProps.end; } } const expectedEnd = isMap ? "}" : "]"; const [ce, ...ee] = fc.end; let cePos = offset; if (ce?.source === expectedEnd) cePos = ce.offset + ce.source.length; else { const name = fcName[0].toUpperCase() + fcName.substring(1); const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`; onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg); if (ce && ce.source.length !== 1) ee.unshift(ce); } if (ee.length > 0) { const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError); if (end.comment) { if (coll.comment) coll.comment += "\n" + end.comment; else coll.comment = end.comment; } coll.range = [fc.offset, cePos, end.offset]; } else { coll.range = [fc.offset, cePos, cePos]; } return coll; } exports.resolveFlowCollection = resolveFlowCollection; } }); // ../../node_modules/yaml/dist/compose/compose-collection.js var require_compose_collection = __commonJS({ "../../node_modules/yaml/dist/compose/compose-collection.js"(exports) { "use strict"; var identity = require_identity(); var Scalar = require_Scalar(); var YAMLMap = require_YAMLMap(); var YAMLSeq = require_YAMLSeq(); var resolveBlockMap = require_resolve_block_map(); var resolveBlockSeq = require_resolve_block_seq(); var resolveFlowCollection = require_resolve_flow_collection(); function resolveCollection(CN, ctx, token, onError, tagName, tag) { const coll = token.type === "block-map" ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag) : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag); const Coll = coll.constructor; if (tagName === "!" || tagName === Coll.tagName) { coll.tag = Coll.tagName; return coll; } if (tagName) coll.tag = tagName; return coll; } function composeCollection(CN, ctx, token, props, onError) { const tagToken = props.tag; const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)); if (token.type === "block-seq") { const { anchor, newlineAfterProp: nl } = props; const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken; if (lastProp && (!nl || nl.offset < lastProp.offset)) { const message = "Missing newline after block sequence props"; onError(lastProp, "MISSING_CHAR", message); } } const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq"; if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.YAMLSeq.tagName && expType === "seq") { return resolveCollection(CN, ctx, token, onError, tagName); } let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType); if (!tag) { const kt = ctx.schema.knownTags[tagName]; if (kt?.collection === expType) { ctx.schema.tags.push(Object.assign({}, kt, { default: false })); tag = kt; } else { if (kt) { onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true); } else { onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true); } return resolveCollection(CN, ctx, token, onError, tagName); } } const coll = resolveCollection(CN, ctx, token, onError, tagName, tag); const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll; const node = identity.isNode(res) ? res : new Scalar.Scalar(res); node.range = coll.range; node.tag = tagName; if (tag?.format) node.format = tag.format; return node; } exports.composeCollection = composeCollection; } }); // ../../node_modules/yaml/dist/compose/resolve-block-scalar.js var require_resolve_block_scalar = __commonJS({ "../../node_modules/yaml/dist/compose/resolve-block-scalar.js"(exports) { "use strict"; var Scalar = require_Scalar(); function resolveBlockScalar(ctx, scalar, onError) { const start = scalar.offset; const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError); if (!header) return { value: "", type: null, comment: "", range: [start, start, start] }; const type = header.mode === ">" ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL; const lines = scalar.source ? splitLines(scalar.source) : []; let chompStart = lines.length; for (let i = lines.length - 1; i >= 0; --i) { const content = lines[i][1]; if (content === "" || content === "\r") chompStart = i; else break; } if (chompStart === 0) { const value2 = header.chomp === "+" && lines.length > 0 ? "\n".repeat(Math.max(1, lines.length - 1)) : ""; let end2 = start + header.length; if (scalar.source) end2 += scalar.source.length; return { value: value2, type, comment: header.comment, range: [start, end2, end2] }; } let trimIndent = scalar.indent + header.indent; let offset = scalar.offset + header.length; let contentStart = 0; for (let i = 0; i < chompStart; ++i) { const [indent, content] = lines[i]; if (content === "" || content === "\r") { if (header.indent === 0 && indent.length > trimIndent) trimIndent = indent.length; } else { if (indent.length < trimIndent) { const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator"; onError(offset + indent.length, "MISSING_CHAR", message); } if (header.indent === 0) trimIndent = indent.length; contentStart = i; if (trimIndent === 0 && !ctx.atRoot) { const message = "Block scalar values in collections must be indented"; onError(offset, "BAD_INDENT", message); } break; } offset += indent.length + content.length + 1; } for (let i = lines.length - 1; i >= chompStart; --i) { if (lines[i][0].length > trimIndent) chompStart = i + 1; } let value = ""; let sep = ""; let prevMoreIndented = false; for (let i = 0; i < contentStart; ++i) value += lines[i][0].slice(trimIndent) + "\n"; for (let i = contentStart; i < chompStart; ++i) { let [indent, content] = lines[i]; offset += indent.length + content.length + 1; const crlf = content[content.length - 1] === "\r"; if (crlf) content = content.slice(0, -1); if (content && indent.length < trimIndent) { const src = header.indent ? "explicit indentation indicator" : "first line"; const message = `Block scalar lines must not be less indented than their ${src}`; onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message); indent = ""; } if (type === Scalar.Scalar.BLOCK_LITERAL) { value += sep + indent.slice(trimIndent) + content; sep = "\n"; } else if (indent.length > trimIndent || content[0] === " ") { if (sep === " ") sep = "\n"; else if (!prevMoreIndented && sep === "\n") sep = "\n\n"; value += sep + indent.slice(trimIndent) + content; sep = "\n"; prevMoreIndented = true; } else if (content === "") { if (sep === "\n") value += "\n"; else sep = "\n"; } else { value += sep + content; sep = " "; prevMoreIndented = false; } } switch (header.chomp) { case "-": break; case "+": for (let i = chompStart; i < lines.length; ++i) value += "\n" + lines[i][0].slice(trimIndent); if (value[value.length - 1] !== "\n") value += "\n"; break; default: value += "\n"; } const end = start + header.length + scalar.source.length; return { value, type, comment: header.comment, range: [start, end, end] }; } function parseBlockScalarHeader({ offset, props }, strict, onError) { if (props[0].type !== "block-scalar-header") { onError(props[0], "IMPOSSIBLE", "Block scalar header not found"); return null; } const { source } = props[0]; const mode = source[0]; let indent = 0; let chomp = ""; let error = -1; for (let i = 1; i < source.length; ++i) { const ch = source[i]; if (!chomp && (ch === "-" || ch === "+")) chomp = ch; else { const n = Number(ch); if (!indent && n) indent = n; else if (error === -1) error = offset + i; } } if (error !== -1) onError(error, "UNEXPECTED_TOKEN", `Block scalar header includes extra characters: ${source}`); let hasSpace = false; let comment = ""; let length = source.length; for (let i = 1; i < props.length; ++i) { const token = props[i]; switch (token.type) { case "space": hasSpace = true; // fallthrough case "newline": length += token.source.length; break; case "comment": if (strict && !hasSpace) { const message = "Comments must be separated from other tokens by white space characters"; onError(token, "MISSING_CHAR", message); } length += token.source.length; comment = token.source.substring(1); break; case "error": onError(token, "UNEXPECTED_TOKEN", token.message); length += token.source.length; break; /* istanbul ignore next should not happen */ default: { const message = `Unexpected token in block scalar header: ${token.type}`; onError(token, "UNEXPECTED_TOKEN", message); const ts = token.source; if (ts && typeof ts === "string") length += ts.length; } } } return { mode, indent, chomp, comment, length }; } function splitLines(source) { const split = source.split(/\n( *)/); const first = split[0]; const m = first.match(/^( *)/); const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first]; const lines = [line0]; for (let i = 1; i < split.length; i += 2) lines.push([split[i], split[i + 1]]); return lines; } exports.resolveBlockScalar = resolveBlockScalar; } }); // ../../node_modules/yaml/dist/compose/resolve-flow-scalar.js var require_resolve_flow_scalar = __commonJS({ "../../node_modules/yaml/dist/compose/resolve-flow-scalar.js"(exports) { "use strict"; var Scalar = require_Scalar(); var resolveEnd = require_resolve_end(); function resolveFlowScalar(scalar, strict, onError) { const { offset, type, source, end } = scalar; let _type; let value; const _onError = (rel, code, msg) => onError(offset + rel, code, msg); switch (type) { case "scalar": _type = Scalar.Scalar.PLAIN; value = plainValue(source, _onError); break; case "single-quoted-scalar": _type = Scalar.Scalar.QUOTE_SINGLE; value = singleQuotedValue(source, _onError); break; case "double-quoted-scalar": _type = Scalar.Scalar.QUOTE_DOUBLE; value = doubleQuotedValue(source, _onError); break; /* istanbul ignore next should not happen */ default: onError(scalar, "UNEXPECTED_TOKEN", `Expected a flow scalar value, but found: ${type}`); return { value: "", type: null, comment: "", range: [offset, offset + source.length, offset + source.length] }; } const valueEnd = offset + source.length; const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError); return { value, type: _type, comment: re.comment, range: [offset, valueEnd, re.offset] }; } function plainValue(source, onError) { let badChar = ""; switch (source[0]) { /* istanbul ignore next should not happen */ case " ": badChar = "a tab character"; break; case ",": badChar = "flow indicator character ,"; break; case "%": badChar = "directive indicator character %"; break; case "|": case ">": { badChar = `block scalar indicator ${source[0]}`; break; } case "@": case "`": { badChar = `reserved character ${source[0]}`; break; } } if (badChar) onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`); return unfoldLines(source); } function singleQuotedValue(source, onError) { if (source[source.length - 1] !== "'" || source.length === 1) onError(source.length, "MISSING_CHAR", "Missing closing 'quote"); return unfoldLines(source.slice(1, -1)).replace(/''/g, "'"); } function unfoldLines(source) { const line = /(.*?)\r?\n/sy; let match = line.exec(source); if (!match) return source; let trimEnd, trimBoth; try { trimEnd = new RegExp("(? wsStart ? source.slice(wsStart, i + 1) : ch; } else { res += ch; } } if (source[source.length - 1] !== '"' || source.length === 1) onError(source.length, "MISSING_CHAR", 'Missing closing "quote'); return res; } function foldNewline(source, offset) { let fold = ""; let ch = source[offset + 1]; while (ch === " " || ch === " " || ch === "\n" || ch === "\r") { if (ch === "\r" && source[offset + 2] !== "\n") break; if (ch === "\n") fold += "\n"; offset += 1; ch = source[offset + 1]; } if (!fold) fold = " "; return { fold, offset }; } var escapeCodes = { "0": "\0", // null character a: "\x07", // bell character b: "\b", // backspace e: "\x1B", // escape character f: "\f", // form feed n: "\n", // line feed r: "\r", // carriage return t: " ", // horizontal tab v: "\v", // vertical tab N: "\x85", // Unicode next line _: "\xA0", // Unicode non-breaking space L: "\u2028", // Unicode line separator P: "\u2029", // Unicode paragraph separator " ": " ", '"': '"', "/": "/", "\\": "\\", " ": " " }; function parseCharCode(source, offset, length, onError) { const cc = source.substr(offset, length); const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc); const code = ok ? parseInt(cc, 16) : NaN; try { return String.fromCodePoint(code); } catch { const raw = source.substr(offset - 2, length + 2); onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`); return raw; } } exports.resolveFlowScalar = resolveFlowScalar; } }); // ../../node_modules/yaml/dist/compose/compose-scalar.js var require_compose_scalar = __commonJS({ "../../node_modules/yaml/dist/compose/compose-scalar.js"(exports) { "use strict"; var identity = require_identity(); var Scalar = require_Scalar(); var resolveBlockScalar = require_resolve_block_scalar(); var resolveFlowScalar = require_resolve_flow_scalar(); function composeScalar(ctx, token, tagToken, onError) { const { value, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError) : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError); const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null; let tag; if (ctx.options.stringKeys && ctx.atKey) { tag = ctx.schema[identity.SCALAR]; } else if (tagName) tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError); else if (token.type === "scalar") tag = findScalarTagByTest(ctx, value, token, onError); else tag = ctx.schema[identity.SCALAR]; let scalar; try { const res = tag.resolve(value, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options); scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res); } catch (error) { const msg = error instanceof Error ? error.message : String(error); onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg); scalar = new Scalar.Scalar(value); } scalar.range = range; scalar.source = value; if (type) scalar.type = type; if (tagName) scalar.tag = tagName; if (tag.format) scalar.format = tag.format; if (comment) scalar.comment = comment; return scalar; } function findScalarTagByName(schema, value, tagName, tagToken, onError) { if (tagName === "!") return schema[identity.SCALAR]; const matchWithTest = []; for (const tag of schema.tags) { if (!tag.collection && tag.tag === tagName) { if (tag.default && tag.test) matchWithTest.push(tag); else return tag; } } for (const tag of matchWithTest) if (tag.test?.test(value)) return tag; const kt = schema.knownTags[tagName]; if (kt && !kt.collection) { schema.tags.push(Object.assign({}, kt, { default: false, test: void 0 })); return kt; } onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str"); return schema[identity.SCALAR]; } function findScalarTagByTest({ atKey, directives, schema }, value, token, onError) { const tag = schema.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value)) || schema[identity.SCALAR]; if (schema.compat) { const compat = schema.compat.find((tag2) => tag2.default && tag2.test?.test(value)) ?? schema[identity.SCALAR]; if (tag.tag !== compat.tag) { const ts = directives.tagString(tag.tag); const cs = directives.tagString(compat.tag); const msg = `Value may be parsed as either ${ts} or ${cs}`; onError(token, "TAG_RESOLVE_FAILED", msg, true); } } return tag; } exports.composeScalar = composeScalar; } }); // ../../node_modules/yaml/dist/compose/util-empty-scalar-position.js var require_util_empty_scalar_position = __commonJS({ "../../node_modules/yaml/dist/compose/util-empty-scalar-position.js"(exports) { "use strict"; function emptyScalarPosition(offset, before, pos) { if (before) { pos ?? (pos = before.length); for (let i = pos - 1; i >= 0; --i) { let st = before[i]; switch (st.type) { case "space": case "comment": case "newline": offset -= st.source.length; continue; } st = before[++i]; while (st?.type === "space") { offset += st.source.length; st = before[++i]; } break; } } return offset; } exports.emptyScalarPosition = emptyScalarPosition; } }); // ../../node_modules/yaml/dist/compose/compose-node.js var require_compose_node = __commonJS({ "../../node_modules/yaml/dist/compose/compose-node.js"(exports) { "use strict"; var Alias = require_Alias(); var identity = require_identity(); var composeCollection = require_compose_collection(); var composeScalar = require_compose_scalar(); var resolveEnd = require_resolve_end(); var utilEmptyScalarPosition = require_util_empty_scalar_position(); var CN = { composeNode, composeEmptyNode }; function composeNode(ctx, token, props, onError) { const atKey = ctx.atKey; const { spaceBefore, comment, anchor, tag } = props; let node; let isSrcToken = true; switch (token.type) { case "alias": node = composeAlias(ctx, token, onError); if (anchor || tag) onError(token, "ALIAS_PROPS", "An alias node must not specify any properties"); break; case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": case "block-scalar": node = composeScalar.composeScalar(ctx, token, tag, onError); if (anchor) node.anchor = anchor.source.substring(1); break; case "block-map": case "block-seq": case "flow-collection": try { node = composeCollection.composeCollection(CN, ctx, token, props, onError); if (anchor) node.anchor = anchor.source.substring(1); } catch (error) { const message = error instanceof Error ? error.message : String(error); onError(token, "RESOURCE_EXHAUSTION", message); } break; default: { const message = token.type === "error" ? token.message : `Unsupported token (type: ${token.type})`; onError(token, "UNEXPECTED_TOKEN", message); isSrcToken = false; } } node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError)); if (anchor && node.anchor === "") onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); if (atKey && ctx.options.stringKeys && (!identity.isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) { const msg = "With stringKeys, all keys must be strings"; onError(tag ?? token, "NON_STRING_KEY", msg); } if (spaceBefore) node.spaceBefore = true; if (comment) { if (token.type === "scalar" && token.source === "") node.comment = comment; else node.commentBefore = comment; } if (ctx.options.keepSourceTokens && isSrcToken) node.srcToken = token; return node; } function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) { const token = { type: "scalar", offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos), indent: -1, source: "" }; const node = composeScalar.composeScalar(ctx, token, tag, onError); if (anchor) { node.anchor = anchor.source.substring(1); if (node.anchor === "") onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string"); } if (spaceBefore) node.spaceBefore = true; if (comment) { node.comment = comment; node.range[2] = end; } return node; } function composeAlias({ options }, { offset, source, end }, onError) { const alias = new Alias.Alias(source.substring(1)); if (alias.source === "") onError(offset, "BAD_ALIAS", "Alias cannot be an empty string"); if (alias.source.endsWith(":")) onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true); const valueEnd = offset + source.length; const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError); alias.range = [offset, valueEnd, re.offset]; if (re.comment) alias.comment = re.comment; return alias; } exports.composeEmptyNode = composeEmptyNode; exports.composeNode = composeNode; } }); // ../../node_modules/yaml/dist/compose/compose-doc.js var require_compose_doc = __commonJS({ "../../node_modules/yaml/dist/compose/compose-doc.js"(exports) { "use strict"; var Document = require_Document(); var composeNode = require_compose_node(); var resolveEnd = require_resolve_end(); var resolveProps = require_resolve_props(); function composeDoc(options, directives, { offset, start, value, end }, onError) { const opts = Object.assign({ _directives: directives }, options); const doc = new Document.Document(void 0, opts); const ctx = { atKey: false, atRoot: true, directives: doc.directives, options: doc.options, schema: doc.schema }; const props = resolveProps.resolveProps(start, { indicator: "doc-start", next: value ?? end?.[0], offset, onError, parentIndent: 0, startOnNewline: true }); if (props.found) { doc.directives.docStart = true; if (value && (value.type === "block-map" || value.type === "block-seq") && !props.hasNewline) onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker"); } doc.contents = value ? composeNode.composeNode(ctx, value, props, onError) : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError); const contentEnd = doc.contents.range[2]; const re = resolveEnd.resolveEnd(end, contentEnd, false, onError); if (re.comment) doc.comment = re.comment; doc.range = [offset, contentEnd, re.offset]; return doc; } exports.composeDoc = composeDoc; } }); // ../../node_modules/yaml/dist/compose/composer.js var require_composer = __commonJS({ "../../node_modules/yaml/dist/compose/composer.js"(exports) { "use strict"; var node_process = __require("process"); var directives = require_directives(); var Document = require_Document(); var errors = require_errors(); var identity = require_identity(); var composeDoc = require_compose_doc(); var resolveEnd = require_resolve_end(); function getErrorPos(src) { if (typeof src === "number") return [src, src + 1]; if (Array.isArray(src)) return src.length === 2 ? src : [src[0], src[1]]; const { offset, source } = src; return [offset, offset + (typeof source === "string" ? source.length : 1)]; } function parsePrelude(prelude) { let comment = ""; let atComment = false; let afterEmptyLine = false; for (let i = 0; i < prelude.length; ++i) { const source = prelude[i]; switch (source[0]) { case "#": comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " "); atComment = true; afterEmptyLine = false; break; case "%": if (prelude[i + 1]?.[0] !== "#") i += 1; atComment = false; break; default: if (!atComment) afterEmptyLine = true; atComment = false; } } return { comment, afterEmptyLine }; } var Composer = class { constructor(options = {}) { this.doc = null; this.atDirectives = false; this.prelude = []; this.errors = []; this.warnings = []; this.onError = (source, code, message, warning) => { const pos = getErrorPos(source); if (warning) this.warnings.push(new errors.YAMLWarning(pos, code, message)); else this.errors.push(new errors.YAMLParseError(pos, code, message)); }; this.directives = new directives.Directives({ version: options.version || "1.2" }); this.options = options; } decorate(doc, afterDoc) { const { comment, afterEmptyLine } = parsePrelude(this.prelude); if (comment) { const dc = doc.contents; if (afterDoc) { doc.comment = doc.comment ? `${doc.comment} ${comment}` : comment; } else if (afterEmptyLine || doc.directives.docStart || !dc) { doc.commentBefore = comment; } else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) { let it = dc.items[0]; if (identity.isPair(it)) it = it.key; const cb = it.commentBefore; it.commentBefore = cb ? `${comment} ${cb}` : comment; } else { const cb = dc.commentBefore; dc.commentBefore = cb ? `${comment} ${cb}` : comment; } } if (afterDoc) { for (let i = 0; i < this.errors.length; ++i) doc.errors.push(this.errors[i]); for (let i = 0; i < this.warnings.length; ++i) doc.warnings.push(this.warnings[i]); } else { doc.errors = this.errors; doc.warnings = this.warnings; } this.prelude = []; this.errors = []; this.warnings = []; } /** * Current stream status information. * * Mostly useful at the end of input for an empty stream. */ streamInfo() { return { comment: parsePrelude(this.prelude).comment, directives: this.directives, errors: this.errors, warnings: this.warnings }; } /** * Compose tokens into documents. * * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. */ *compose(tokens, forceDoc = false, endOffset = -1) { for (const token of tokens) yield* this.next(token); yield* this.end(forceDoc, endOffset); } /** Advance the composer by one CST token. */ *next(token) { if (node_process.env.LOG_STREAM) console.dir(token, { depth: null }); switch (token.type) { case "directive": this.directives.add(token.source, (offset, message, warning) => { const pos = getErrorPos(token); pos[0] += offset; this.onError(pos, "BAD_DIRECTIVE", message, warning); }); this.prelude.push(token.source); this.atDirectives = true; break; case "document": { const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError); if (this.atDirectives && !doc.directives.docStart) this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line"); this.decorate(doc, false); if (this.doc) yield this.doc; this.doc = doc; this.atDirectives = false; break; } case "byte-order-mark": case "space": break; case "comment": case "newline": this.prelude.push(token.source); break; case "error": { const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message; const error = new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg); if (this.atDirectives || !this.doc) this.errors.push(error); else this.doc.errors.push(error); break; } case "doc-end": { if (!this.doc) { const msg = "Unexpected doc-end without preceding document"; this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", msg)); break; } this.doc.directives.docEnd = true; const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError); this.decorate(this.doc, true); if (end.comment) { const dc = this.doc.comment; this.doc.comment = dc ? `${dc} ${end.comment}` : end.comment; } this.doc.range[2] = end.offset; break; } default: this.errors.push(new errors.YAMLParseError(getErrorPos(token), "UNEXPECTED_TOKEN", `Unsupported token ${token.type}`)); } } /** * Call at end of input to yield any remaining document. * * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document. * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly. */ *end(forceDoc = false, endOffset = -1) { if (this.doc) { this.decorate(this.doc, true); yield this.doc; this.doc = null; } else if (forceDoc) { const opts = Object.assign({ _directives: this.directives }, this.options); const doc = new Document.Document(void 0, opts); if (this.atDirectives) this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line"); doc.range = [0, endOffset, endOffset]; this.decorate(doc, false); yield doc; } } }; exports.Composer = Composer; } }); // ../../node_modules/yaml/dist/parse/cst-scalar.js var require_cst_scalar = __commonJS({ "../../node_modules/yaml/dist/parse/cst-scalar.js"(exports) { "use strict"; var resolveBlockScalar = require_resolve_block_scalar(); var resolveFlowScalar = require_resolve_flow_scalar(); var errors = require_errors(); var stringifyString = require_stringifyString(); function resolveAsScalar(token, strict = true, onError) { if (token) { const _onError = (pos, code, message) => { const offset = typeof pos === "number" ? pos : Array.isArray(pos) ? pos[0] : pos.offset; if (onError) onError(offset, code, message); else throw new errors.YAMLParseError([offset, offset + 1], code, message); }; switch (token.type) { case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": return resolveFlowScalar.resolveFlowScalar(token, strict, _onError); case "block-scalar": return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError); } } return null; } function createScalarToken(value, context) { const { implicitKey = false, indent, inFlow = false, offset = -1, type = "PLAIN" } = context; const source = stringifyString.stringifyString({ type, value }, { implicitKey, indent: indent > 0 ? " ".repeat(indent) : "", inFlow, options: { blockQuote: true, lineWidth: -1 } }); const end = context.end ?? [ { type: "newline", offset: -1, indent, source: "\n" } ]; switch (source[0]) { case "|": case ">": { const he = source.indexOf("\n"); const head = source.substring(0, he); const body = source.substring(he + 1) + "\n"; const props = [ { type: "block-scalar-header", offset, indent, source: head } ]; if (!addEndtoBlockProps(props, end)) props.push({ type: "newline", offset: -1, indent, source: "\n" }); return { type: "block-scalar", offset, indent, props, source: body }; } case '"': return { type: "double-quoted-scalar", offset, indent, source, end }; case "'": return { type: "single-quoted-scalar", offset, indent, source, end }; default: return { type: "scalar", offset, indent, source, end }; } } function setScalarValue(token, value, context = {}) { let { afterKey = false, implicitKey = false, inFlow = false, type } = context; let indent = "indent" in token ? token.indent : null; if (afterKey && typeof indent === "number") indent += 2; if (!type) switch (token.type) { case "single-quoted-scalar": type = "QUOTE_SINGLE"; break; case "double-quoted-scalar": type = "QUOTE_DOUBLE"; break; case "block-scalar": { const header = token.props[0]; if (header.type !== "block-scalar-header") throw new Error("Invalid block scalar header"); type = header.source[0] === ">" ? "BLOCK_FOLDED" : "BLOCK_LITERAL"; break; } default: type = "PLAIN"; } const source = stringifyString.stringifyString({ type, value }, { implicitKey: implicitKey || indent === null, indent: indent !== null && indent > 0 ? " ".repeat(indent) : "", inFlow, options: { blockQuote: true, lineWidth: -1 } }); switch (source[0]) { case "|": case ">": setBlockScalarValue(token, source); break; case '"': setFlowScalarValue(token, source, "double-quoted-scalar"); break; case "'": setFlowScalarValue(token, source, "single-quoted-scalar"); break; default: setFlowScalarValue(token, source, "scalar"); } } function setBlockScalarValue(token, source) { const he = source.indexOf("\n"); const head = source.substring(0, he); const body = source.substring(he + 1) + "\n"; if (token.type === "block-scalar") { const header = token.props[0]; if (header.type !== "block-scalar-header") throw new Error("Invalid block scalar header"); header.source = head; token.source = body; } else { const { offset } = token; const indent = "indent" in token ? token.indent : -1; const props = [ { type: "block-scalar-header", offset, indent, source: head } ]; if (!addEndtoBlockProps(props, "end" in token ? token.end : void 0)) props.push({ type: "newline", offset: -1, indent, source: "\n" }); for (const key of Object.keys(token)) if (key !== "type" && key !== "offset") delete token[key]; Object.assign(token, { type: "block-scalar", indent, props, source: body }); } } function addEndtoBlockProps(props, end) { if (end) for (const st of end) switch (st.type) { case "space": case "comment": props.push(st); break; case "newline": props.push(st); return true; } return false; } function setFlowScalarValue(token, source, type) { switch (token.type) { case "scalar": case "double-quoted-scalar": case "single-quoted-scalar": token.type = type; token.source = source; break; case "block-scalar": { const end = token.props.slice(1); let oa = source.length; if (token.props[0].type === "block-scalar-header") oa -= token.props[0].source.length; for (const tok of end) tok.offset += oa; delete token.props; Object.assign(token, { type, source, end }); break; } case "block-map": case "block-seq": { const offset = token.offset + source.length; const nl = { type: "newline", offset, indent: token.indent, source: "\n" }; delete token.items; Object.assign(token, { type, source, end: [nl] }); break; } default: { const indent = "indent" in token ? token.indent : -1; const end = "end" in token && Array.isArray(token.end) ? token.end.filter((st) => st.type === "space" || st.type === "comment" || st.type === "newline") : []; for (const key of Object.keys(token)) if (key !== "type" && key !== "offset") delete token[key]; Object.assign(token, { type, indent, source, end }); } } } exports.createScalarToken = createScalarToken; exports.resolveAsScalar = resolveAsScalar; exports.setScalarValue = setScalarValue; } }); // ../../node_modules/yaml/dist/parse/cst-stringify.js var require_cst_stringify = __commonJS({ "../../node_modules/yaml/dist/parse/cst-stringify.js"(exports) { "use strict"; var stringify = (cst) => "type" in cst ? stringifyToken(cst) : stringifyItem(cst); function stringifyToken(token) { switch (token.type) { case "block-scalar": { let res = ""; for (const tok of token.props) res += stringifyToken(tok); return res + token.source; } case "block-map": case "block-seq": { let res = ""; for (const item of token.items) res += stringifyItem(item); return res; } case "flow-collection": { let res = token.start.source; for (const item of token.items) res += stringifyItem(item); for (const st of token.end) res += st.source; return res; } case "document": { let res = stringifyItem(token); if (token.end) for (const st of token.end) res += st.source; return res; } default: { let res = token.source; if ("end" in token && token.end) for (const st of token.end) res += st.source; return res; } } } function stringifyItem({ start, key, sep, value }) { let res = ""; for (const st of start) res += st.source; if (key) res += stringifyToken(key); if (sep) for (const st of sep) res += st.source; if (value) res += stringifyToken(value); return res; } exports.stringify = stringify; } }); // ../../node_modules/yaml/dist/parse/cst-visit.js var require_cst_visit = __commonJS({ "../../node_modules/yaml/dist/parse/cst-visit.js"(exports) { "use strict"; var BREAK = /* @__PURE__ */ Symbol("break visit"); var SKIP = /* @__PURE__ */ Symbol("skip children"); var REMOVE = /* @__PURE__ */ Symbol("remove item"); function visit(cst, visitor) { if ("type" in cst && cst.type === "document") cst = { start: cst.start, value: cst.value }; _visit(Object.freeze([]), cst, visitor); } visit.BREAK = BREAK; visit.SKIP = SKIP; visit.REMOVE = REMOVE; visit.itemAtPath = (cst, path) => { let item = cst; for (const [field, index] of path) { const tok = item?.[field]; if (tok && "items" in tok) { item = tok.items[index]; } else return void 0; } return item; }; visit.parentCollection = (cst, path) => { const parent = visit.itemAtPath(cst, path.slice(0, -1)); const field = path[path.length - 1][0]; const coll = parent?.[field]; if (coll && "items" in coll) return coll; throw new Error("Parent collection not found"); }; function _visit(path, item, visitor) { let ctrl = visitor(item, path); if (typeof ctrl === "symbol") return ctrl; for (const field of ["key", "value"]) { const token = item[field]; if (token && "items" in token) { for (let i = 0; i < token.items.length; ++i) { const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor); if (typeof ci === "number") i = ci - 1; else if (ci === BREAK) return BREAK; else if (ci === REMOVE) { token.items.splice(i, 1); i -= 1; } } if (typeof ctrl === "function" && field === "key") ctrl = ctrl(item, path); } } return typeof ctrl === "function" ? ctrl(item, path) : ctrl; } exports.visit = visit; } }); // ../../node_modules/yaml/dist/parse/cst.js var require_cst = __commonJS({ "../../node_modules/yaml/dist/parse/cst.js"(exports) { "use strict"; var cstScalar = require_cst_scalar(); var cstStringify = require_cst_stringify(); var cstVisit = require_cst_visit(); var BOM = "\uFEFF"; var DOCUMENT = ""; var FLOW_END = ""; var SCALAR = ""; var isCollection = (token) => !!token && "items" in token; var isScalar = (token) => !!token && (token.type === "scalar" || token.type === "single-quoted-scalar" || token.type === "double-quoted-scalar" || token.type === "block-scalar"); function prettyToken(token) { switch (token) { case BOM: return ""; case DOCUMENT: return ""; case FLOW_END: return ""; case SCALAR: return ""; default: return JSON.stringify(token); } } function tokenType(source) { switch (source) { case BOM: return "byte-order-mark"; case DOCUMENT: return "doc-mode"; case FLOW_END: return "flow-error-end"; case SCALAR: return "scalar"; case "---": return "doc-start"; case "...": return "doc-end"; case "": case "\n": case "\r\n": return "newline"; case "-": return "seq-item-ind"; case "?": return "explicit-key-ind"; case ":": return "map-value-ind"; case "{": return "flow-map-start"; case "}": return "flow-map-end"; case "[": return "flow-seq-start"; case "]": return "flow-seq-end"; case ",": return "comma"; } switch (source[0]) { case " ": case " ": return "space"; case "#": return "comment"; case "%": return "directive-line"; case "*": return "alias"; case "&": return "anchor"; case "!": return "tag"; case "'": return "single-quoted-scalar"; case '"': return "double-quoted-scalar"; case "|": case ">": return "block-scalar-header"; } return null; } exports.createScalarToken = cstScalar.createScalarToken; exports.resolveAsScalar = cstScalar.resolveAsScalar; exports.setScalarValue = cstScalar.setScalarValue; exports.stringify = cstStringify.stringify; exports.visit = cstVisit.visit; exports.BOM = BOM; exports.DOCUMENT = DOCUMENT; exports.FLOW_END = FLOW_END; exports.SCALAR = SCALAR; exports.isCollection = isCollection; exports.isScalar = isScalar; exports.prettyToken = prettyToken; exports.tokenType = tokenType; } }); // ../../node_modules/yaml/dist/parse/lexer.js var require_lexer = __commonJS({ "../../node_modules/yaml/dist/parse/lexer.js"(exports) { "use strict"; var cst = require_cst(); function isEmpty(ch) { switch (ch) { case void 0: case " ": case "\n": case "\r": case " ": return true; default: return false; } } var hexDigits = new Set("0123456789ABCDEFabcdef"); var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"); var flowIndicatorChars = new Set(",[]{}"); var invalidAnchorChars = new Set(" ,[]{}\n\r "); var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch); var Lexer = class { constructor() { this.atEnd = false; this.blockScalarIndent = -1; this.blockScalarKeep = false; this.buffer = ""; this.flowKey = false; this.flowLevel = 0; this.indentNext = 0; this.indentValue = 0; this.lineEndPos = null; this.next = null; this.pos = 0; } /** * Generate YAML tokens from the `source` string. If `incomplete`, * a part of the last line may be left as a buffer for the next call. * * @returns A generator of lexical tokens */ *lex(source, incomplete = false) { if (source) { if (typeof source !== "string") throw TypeError("source is not a string"); this.buffer = this.buffer ? this.buffer + source : source; this.lineEndPos = null; } this.atEnd = !incomplete; let next = this.next ?? "stream"; while (next && (incomplete || this.hasChars(1))) next = yield* this.parseNext(next); } atLineEnd() { let i = this.pos; let ch = this.buffer[i]; while (ch === " " || ch === " ") ch = this.buffer[++i]; if (!ch || ch === "#" || ch === "\n") return true; if (ch === "\r") return this.buffer[i + 1] === "\n"; return false; } charAt(n) { return this.buffer[this.pos + n]; } continueScalar(offset) { let ch = this.buffer[offset]; if (this.indentNext > 0) { let indent = 0; while (ch === " ") ch = this.buffer[++indent + offset]; if (ch === "\r") { const next = this.buffer[indent + offset + 1]; if (next === "\n" || !next && !this.atEnd) return offset + indent + 1; } return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1; } if (ch === "-" || ch === ".") { const dt = this.buffer.substr(offset, 3); if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3])) return -1; } return offset; } getLine() { let end = this.lineEndPos; if (typeof end !== "number" || end !== -1 && end < this.pos) { end = this.buffer.indexOf("\n", this.pos); this.lineEndPos = end; } if (end === -1) return this.atEnd ? this.buffer.substring(this.pos) : null; if (this.buffer[end - 1] === "\r") end -= 1; return this.buffer.substring(this.pos, end); } hasChars(n) { return this.pos + n <= this.buffer.length; } setNext(state) { this.buffer = this.buffer.substring(this.pos); this.pos = 0; this.lineEndPos = null; this.next = state; return null; } peek(n) { return this.buffer.substr(this.pos, n); } *parseNext(next) { switch (next) { case "stream": return yield* this.parseStream(); case "line-start": return yield* this.parseLineStart(); case "block-start": return yield* this.parseBlockStart(); case "doc": return yield* this.parseDocument(); case "flow": return yield* this.parseFlowCollection(); case "quoted-scalar": return yield* this.parseQuotedScalar(); case "block-scalar": return yield* this.parseBlockScalar(); case "plain-scalar": return yield* this.parsePlainScalar(); } } *parseStream() { let line = this.getLine(); if (line === null) return this.setNext("stream"); if (line[0] === cst.BOM) { yield* this.pushCount(1); line = line.substring(1); } if (line[0] === "%") { let dirEnd = line.length; let cs = line.indexOf("#"); while (cs !== -1) { const ch = line[cs - 1]; if (ch === " " || ch === " ") { dirEnd = cs - 1; break; } else { cs = line.indexOf("#", cs + 1); } } while (true) { const ch = line[dirEnd - 1]; if (ch === " " || ch === " ") dirEnd -= 1; else break; } const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true)); yield* this.pushCount(line.length - n); this.pushNewline(); return "stream"; } if (this.atLineEnd()) { const sp = yield* this.pushSpaces(true); yield* this.pushCount(line.length - sp); yield* this.pushNewline(); return "stream"; } yield cst.DOCUMENT; return yield* this.parseLineStart(); } *parseLineStart() { const ch = this.charAt(0); if (!ch && !this.atEnd) return this.setNext("line-start"); if (ch === "-" || ch === ".") { if (!this.atEnd && !this.hasChars(4)) return this.setNext("line-start"); const s = this.peek(3); if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) { yield* this.pushCount(3); this.indentValue = 0; this.indentNext = 0; return s === "---" ? "doc" : "stream"; } } this.indentValue = yield* this.pushSpaces(false); if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1))) this.indentNext = this.indentValue; return yield* this.parseBlockStart(); } *parseBlockStart() { const [ch0, ch1] = this.peek(2); if (!ch1 && !this.atEnd) return this.setNext("block-start"); if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) { const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true)); this.indentNext = this.indentValue + 1; this.indentValue += n; return "block-start"; } return "doc"; } *parseDocument() { yield* this.pushSpaces(true); const line = this.getLine(); if (line === null) return this.setNext("doc"); let n = yield* this.pushIndicators(); switch (line[n]) { case "#": yield* this.pushCount(line.length - n); // fallthrough case void 0: yield* this.pushNewline(); return yield* this.parseLineStart(); case "{": case "[": yield* this.pushCount(1); this.flowKey = false; this.flowLevel = 1; return "flow"; case "}": case "]": yield* this.pushCount(1); return "doc"; case "*": yield* this.pushUntil(isNotAnchorChar); return "doc"; case '"': case "'": return yield* this.parseQuotedScalar(); case "|": case ">": n += yield* this.parseBlockScalarHeader(); n += yield* this.pushSpaces(true); yield* this.pushCount(line.length - n); yield* this.pushNewline(); return yield* this.parseBlockScalar(); default: return yield* this.parsePlainScalar(); } } *parseFlowCollection() { let nl, sp; let indent = -1; do { nl = yield* this.pushNewline(); if (nl > 0) { sp = yield* this.pushSpaces(false); this.indentValue = indent = sp; } else { sp = 0; } sp += yield* this.pushSpaces(true); } while (nl + sp > 0); const line = this.getLine(); if (line === null) return this.setNext("flow"); if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) { const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}"); if (!atFlowEndMarker) { this.flowLevel = 0; yield cst.FLOW_END; return yield* this.parseLineStart(); } } let n = 0; while (line[n] === ",") { n += yield* this.pushCount(1); n += yield* this.pushSpaces(true); this.flowKey = false; } n += yield* this.pushIndicators(); switch (line[n]) { case void 0: return "flow"; case "#": yield* this.pushCount(line.length - n); return "flow"; case "{": case "[": yield* this.pushCount(1); this.flowKey = false; this.flowLevel += 1; return "flow"; case "}": case "]": yield* this.pushCount(1); this.flowKey = true; this.flowLevel -= 1; return this.flowLevel ? "flow" : "doc"; case "*": yield* this.pushUntil(isNotAnchorChar); return "flow"; case '"': case "'": this.flowKey = true; return yield* this.parseQuotedScalar(); case ":": { const next = this.charAt(1); if (this.flowKey || isEmpty(next) || next === ",") { this.flowKey = false; yield* this.pushCount(1); yield* this.pushSpaces(true); return "flow"; } } // fallthrough default: this.flowKey = false; return yield* this.parsePlainScalar(); } } *parseQuotedScalar() { const quote = this.charAt(0); let end = this.buffer.indexOf(quote, this.pos + 1); if (quote === "'") { while (end !== -1 && this.buffer[end + 1] === "'") end = this.buffer.indexOf("'", end + 2); } else { while (end !== -1) { let n = 0; while (this.buffer[end - 1 - n] === "\\") n += 1; if (n % 2 === 0) break; end = this.buffer.indexOf('"', end + 1); } } const qb = this.buffer.substring(0, end); let nl = qb.indexOf("\n", this.pos); if (nl !== -1) { while (nl !== -1) { const cs = this.continueScalar(nl + 1); if (cs === -1) break; nl = qb.indexOf("\n", cs); } if (nl !== -1) { end = nl - (qb[nl - 1] === "\r" ? 2 : 1); } } if (end === -1) { if (!this.atEnd) return this.setNext("quoted-scalar"); end = this.buffer.length; } yield* this.pushToIndex(end + 1, false); return this.flowLevel ? "flow" : "doc"; } *parseBlockScalarHeader() { this.blockScalarIndent = -1; this.blockScalarKeep = false; let i = this.pos; while (true) { const ch = this.buffer[++i]; if (ch === "+") this.blockScalarKeep = true; else if (ch > "0" && ch <= "9") this.blockScalarIndent = Number(ch) - 1; else if (ch !== "-") break; } return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#"); } *parseBlockScalar() { let nl = this.pos - 1; let indent = 0; let ch; loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) { switch (ch) { case " ": indent += 1; break; case "\n": nl = i2; indent = 0; break; case "\r": { const next = this.buffer[i2 + 1]; if (!next && !this.atEnd) return this.setNext("block-scalar"); if (next === "\n") break; } // fallthrough default: break loop; } } if (!ch && !this.atEnd) return this.setNext("block-scalar"); if (indent >= this.indentNext) { if (this.blockScalarIndent === -1) this.indentNext = indent; else { this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext); } do { const cs = this.continueScalar(nl + 1); if (cs === -1) break; nl = this.buffer.indexOf("\n", cs); } while (nl !== -1); if (nl === -1) { if (!this.atEnd) return this.setNext("block-scalar"); nl = this.buffer.length; } } let i = nl + 1; ch = this.buffer[i]; while (ch === " ") ch = this.buffer[++i]; if (ch === " ") { while (ch === " " || ch === " " || ch === "\r" || ch === "\n") ch = this.buffer[++i]; nl = i - 1; } else if (!this.blockScalarKeep) { do { let i2 = nl - 1; let ch2 = this.buffer[i2]; if (ch2 === "\r") ch2 = this.buffer[--i2]; const lastChar = i2; while (ch2 === " ") ch2 = this.buffer[--i2]; if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar) nl = i2; else break; } while (true); } yield cst.SCALAR; yield* this.pushToIndex(nl + 1, true); return yield* this.parseLineStart(); } *parsePlainScalar() { const inFlow = this.flowLevel > 0; let end = this.pos - 1; let i = this.pos - 1; let ch; while (ch = this.buffer[++i]) { if (ch === ":") { const next = this.buffer[i + 1]; if (isEmpty(next) || inFlow && flowIndicatorChars.has(next)) break; end = i; } else if (isEmpty(ch)) { let next = this.buffer[i + 1]; if (ch === "\r") { if (next === "\n") { i += 1; ch = "\n"; next = this.buffer[i + 1]; } else end = i; } if (next === "#" || inFlow && flowIndicatorChars.has(next)) break; if (ch === "\n") { const cs = this.continueScalar(i + 1); if (cs === -1) break; i = Math.max(i, cs - 2); } } else { if (inFlow && flowIndicatorChars.has(ch)) break; end = i; } } if (!ch && !this.atEnd) return this.setNext("plain-scalar"); yield cst.SCALAR; yield* this.pushToIndex(end + 1, true); return inFlow ? "flow" : "doc"; } *pushCount(n) { if (n > 0) { yield this.buffer.substr(this.pos, n); this.pos += n; return n; } return 0; } *pushToIndex(i, allowEmpty) { const s = this.buffer.slice(this.pos, i); if (s) { yield s; this.pos += s.length; return s.length; } else if (allowEmpty) yield ""; return 0; } *pushIndicators() { let n = 0; loop: while (true) { switch (this.charAt(0)) { case "!": n += yield* this.pushTag(); n += yield* this.pushSpaces(true); continue loop; case "&": n += yield* this.pushUntil(isNotAnchorChar); n += yield* this.pushSpaces(true); continue loop; case "-": // this is an error case "?": // this is an error outside flow collections case ":": { const inFlow = this.flowLevel > 0; const ch1 = this.charAt(1); if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) { if (!inFlow) this.indentNext = this.indentValue + 1; else if (this.flowKey) this.flowKey = false; n += yield* this.pushCount(1); n += yield* this.pushSpaces(true); continue loop; } } } break loop; } return n; } *pushTag() { if (this.charAt(1) === "<") { let i = this.pos + 2; let ch = this.buffer[i]; while (!isEmpty(ch) && ch !== ">") ch = this.buffer[++i]; return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false); } else { let i = this.pos + 1; let ch = this.buffer[i]; while (ch) { if (tagChars.has(ch)) ch = this.buffer[++i]; else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) { ch = this.buffer[i += 3]; } else break; } return yield* this.pushToIndex(i, false); } } *pushNewline() { const ch = this.buffer[this.pos]; if (ch === "\n") return yield* this.pushCount(1); else if (ch === "\r" && this.charAt(1) === "\n") return yield* this.pushCount(2); else return 0; } *pushSpaces(allowTabs) { let i = this.pos - 1; let ch; do { ch = this.buffer[++i]; } while (ch === " " || allowTabs && ch === " "); const n = i - this.pos; if (n > 0) { yield this.buffer.substr(this.pos, n); this.pos = i; } return n; } *pushUntil(test) { let i = this.pos; let ch = this.buffer[i]; while (!test(ch)) ch = this.buffer[++i]; return yield* this.pushToIndex(i, false); } }; exports.Lexer = Lexer; } }); // ../../node_modules/yaml/dist/parse/line-counter.js var require_line_counter = __commonJS({ "../../node_modules/yaml/dist/parse/line-counter.js"(exports) { "use strict"; var LineCounter = class { constructor() { this.lineStarts = []; this.addNewLine = (offset) => this.lineStarts.push(offset); this.linePos = (offset) => { let low = 0; let high = this.lineStarts.length; while (low < high) { const mid = low + high >> 1; if (this.lineStarts[mid] < offset) low = mid + 1; else high = mid; } if (this.lineStarts[low] === offset) return { line: low + 1, col: 1 }; if (low === 0) return { line: 0, col: offset }; const start = this.lineStarts[low - 1]; return { line: low, col: offset - start + 1 }; }; } }; exports.LineCounter = LineCounter; } }); // ../../node_modules/yaml/dist/parse/parser.js var require_parser = __commonJS({ "../../node_modules/yaml/dist/parse/parser.js"(exports) { "use strict"; var node_process = __require("process"); var cst = require_cst(); var lexer = require_lexer(); function includesToken(list, type) { for (let i = 0; i < list.length; ++i) if (list[i].type === type) return true; return false; } function findNonEmptyIndex(list) { for (let i = 0; i < list.length; ++i) { switch (list[i].type) { case "space": case "comment": case "newline": break; default: return i; } } return -1; } function isFlowToken(token) { switch (token?.type) { case "alias": case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": case "flow-collection": return true; default: return false; } } function getPrevProps(parent) { switch (parent.type) { case "document": return parent.start; case "block-map": { const it = parent.items[parent.items.length - 1]; return it.sep ?? it.start; } case "block-seq": return parent.items[parent.items.length - 1].start; /* istanbul ignore next should not happen */ default: return []; } } function getFirstKeyStartProps(prev) { if (prev.length === 0) return []; let i = prev.length; loop: while (--i >= 0) { switch (prev[i].type) { case "doc-start": case "explicit-key-ind": case "map-value-ind": case "seq-item-ind": case "newline": break loop; } } while (prev[++i]?.type === "space") { } return prev.splice(i, prev.length); } function arrayPushArray(target, source) { if (source.length < 1e5) Array.prototype.push.apply(target, source); else for (let i = 0; i < source.length; ++i) target.push(source[i]); } function fixFlowSeqItems(fc) { if (fc.start.type === "flow-seq-start") { for (const it of fc.items) { if (it.sep && !it.value && !includesToken(it.start, "explicit-key-ind") && !includesToken(it.sep, "map-value-ind")) { if (it.key) it.value = it.key; delete it.key; if (isFlowToken(it.value)) { if (it.value.end) arrayPushArray(it.value.end, it.sep); else it.value.end = it.sep; } else arrayPushArray(it.start, it.sep); delete it.sep; } } } } var Parser = class { /** * @param onNewLine - If defined, called separately with the start position of * each new line (in `parse()`, including the start of input). */ constructor(onNewLine) { this.atNewLine = true; this.atScalar = false; this.indent = 0; this.offset = 0; this.onKeyLine = false; this.stack = []; this.source = ""; this.type = ""; this.lexer = new lexer.Lexer(); this.onNewLine = onNewLine; } /** * Parse `source` as a YAML stream. * If `incomplete`, a part of the last line may be left as a buffer for the next call. * * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens. * * @returns A generator of tokens representing each directive, document, and other structure. */ *parse(source, incomplete = false) { if (this.onNewLine && this.offset === 0) this.onNewLine(0); for (const lexeme of this.lexer.lex(source, incomplete)) yield* this.next(lexeme); if (!incomplete) yield* this.end(); } /** * Advance the parser by the `source` of one lexical token. */ *next(source) { this.source = source; if (node_process.env.LOG_TOKENS) console.log("|", cst.prettyToken(source)); if (this.atScalar) { this.atScalar = false; yield* this.step(); this.offset += source.length; return; } const type = cst.tokenType(source); if (!type) { const message = `Not a YAML token: ${source}`; yield* this.pop({ type: "error", offset: this.offset, message, source }); this.offset += source.length; } else if (type === "scalar") { this.atNewLine = false; this.atScalar = true; this.type = "scalar"; } else { this.type = type; yield* this.step(); switch (type) { case "newline": this.atNewLine = true; this.indent = 0; if (this.onNewLine) this.onNewLine(this.offset + source.length); break; case "space": if (this.atNewLine && source[0] === " ") this.indent += source.length; break; case "explicit-key-ind": case "map-value-ind": case "seq-item-ind": if (this.atNewLine) this.indent += source.length; break; case "doc-mode": case "flow-error-end": return; default: this.atNewLine = false; } this.offset += source.length; } } /** Call at end of input to push out any remaining constructions */ *end() { while (this.stack.length > 0) yield* this.pop(); } get sourceToken() { const st = { type: this.type, offset: this.offset, indent: this.indent, source: this.source }; return st; } *step() { const top = this.peek(1); if (this.type === "doc-end" && top?.type !== "doc-end") { while (this.stack.length > 0) yield* this.pop(); this.stack.push({ type: "doc-end", offset: this.offset, source: this.source }); return; } if (!top) return yield* this.stream(); switch (top.type) { case "document": return yield* this.document(top); case "alias": case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": return yield* this.scalar(top); case "block-scalar": return yield* this.blockScalar(top); case "block-map": return yield* this.blockMap(top); case "block-seq": return yield* this.blockSequence(top); case "flow-collection": return yield* this.flowCollection(top); case "doc-end": return yield* this.documentEnd(top); } yield* this.pop(); } peek(n) { return this.stack[this.stack.length - n]; } *pop(error) { const token = error ?? this.stack.pop(); if (!token) { const message = "Tried to pop an empty stack"; yield { type: "error", offset: this.offset, source: "", message }; } else if (this.stack.length === 0) { yield token; } else { const top = this.peek(1); if (token.type === "block-scalar") { token.indent = "indent" in top ? top.indent : 0; } else if (token.type === "flow-collection" && top.type === "document") { token.indent = 0; } if (token.type === "flow-collection") fixFlowSeqItems(token); switch (top.type) { case "document": top.value = token; break; case "block-scalar": top.props.push(token); break; case "block-map": { const it = top.items[top.items.length - 1]; if (it.value) { top.items.push({ start: [], key: token, sep: [] }); this.onKeyLine = true; return; } else if (it.sep) { it.value = token; } else { Object.assign(it, { key: token, sep: [] }); this.onKeyLine = !it.explicitKey; return; } break; } case "block-seq": { const it = top.items[top.items.length - 1]; if (it.value) top.items.push({ start: [], value: token }); else it.value = token; break; } case "flow-collection": { const it = top.items[top.items.length - 1]; if (!it || it.value) top.items.push({ start: [], key: token, sep: [] }); else if (it.sep) it.value = token; else Object.assign(it, { key: token, sep: [] }); return; } /* istanbul ignore next should not happen */ default: yield* this.pop(); yield* this.pop(token); } if ((top.type === "document" || top.type === "block-map" || top.type === "block-seq") && (token.type === "block-map" || token.type === "block-seq")) { const last = token.items[token.items.length - 1]; if (last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every((st) => st.type !== "comment" || st.indent < token.indent))) { if (top.type === "document") top.end = last.start; else top.items.push({ start: last.start }); token.items.splice(-1, 1); } } } } *stream() { switch (this.type) { case "directive-line": yield { type: "directive", offset: this.offset, source: this.source }; return; case "byte-order-mark": case "space": case "comment": case "newline": yield this.sourceToken; return; case "doc-mode": case "doc-start": { const doc = { type: "document", offset: this.offset, start: [] }; if (this.type === "doc-start") doc.start.push(this.sourceToken); this.stack.push(doc); return; } } yield { type: "error", offset: this.offset, message: `Unexpected ${this.type} token in YAML stream`, source: this.source }; } *document(doc) { if (doc.value) return yield* this.lineEnd(doc); switch (this.type) { case "doc-start": { if (findNonEmptyIndex(doc.start) !== -1) { yield* this.pop(); yield* this.step(); } else doc.start.push(this.sourceToken); return; } case "anchor": case "tag": case "space": case "comment": case "newline": doc.start.push(this.sourceToken); return; } const bv = this.startBlockValue(doc); if (bv) this.stack.push(bv); else { yield { type: "error", offset: this.offset, message: `Unexpected ${this.type} token in YAML document`, source: this.source }; } } *scalar(scalar) { if (this.type === "map-value-ind") { const prev = getPrevProps(this.peek(2)); const start = getFirstKeyStartProps(prev); let sep; if (scalar.end) { sep = scalar.end; sep.push(this.sourceToken); delete scalar.end; } else sep = [this.sourceToken]; const map = { type: "block-map", offset: scalar.offset, indent: scalar.indent, items: [{ start, key: scalar, sep }] }; this.onKeyLine = true; this.stack[this.stack.length - 1] = map; } else yield* this.lineEnd(scalar); } *blockScalar(scalar) { switch (this.type) { case "space": case "comment": case "newline": scalar.props.push(this.sourceToken); return; case "scalar": scalar.source = this.source; this.atNewLine = true; this.indent = 0; if (this.onNewLine) { let nl = this.source.indexOf("\n") + 1; while (nl !== 0) { this.onNewLine(this.offset + nl); nl = this.source.indexOf("\n", nl) + 1; } } yield* this.pop(); break; /* istanbul ignore next should not happen */ default: yield* this.pop(); yield* this.step(); } } *blockMap(map) { const it = map.items[map.items.length - 1]; switch (this.type) { case "newline": this.onKeyLine = false; if (it.value) { const end = "end" in it.value ? it.value.end : void 0; const last = Array.isArray(end) ? end[end.length - 1] : void 0; if (last?.type === "comment") end?.push(this.sourceToken); else map.items.push({ start: [this.sourceToken] }); } else if (it.sep) { it.sep.push(this.sourceToken); } else { it.start.push(this.sourceToken); } return; case "space": case "comment": if (it.value) { map.items.push({ start: [this.sourceToken] }); } else if (it.sep) { it.sep.push(this.sourceToken); } else { if (this.atIndentedComment(it.start, map.indent)) { const prev = map.items[map.items.length - 2]; const end = prev?.value?.end; if (Array.isArray(end)) { arrayPushArray(end, it.start); end.push(this.sourceToken); map.items.pop(); return; } } it.start.push(this.sourceToken); } return; } if (this.indent >= map.indent) { const atMapIndent = !this.onKeyLine && this.indent === map.indent; const atNextItem = atMapIndent && (it.sep || it.explicitKey) && this.type !== "seq-item-ind"; let start = []; if (atNextItem && it.sep && !it.value) { const nl = []; for (let i = 0; i < it.sep.length; ++i) { const st = it.sep[i]; switch (st.type) { case "newline": nl.push(i); break; case "space": break; case "comment": if (st.indent > map.indent) nl.length = 0; break; default: nl.length = 0; } } if (nl.length >= 2) start = it.sep.splice(nl[1]); } switch (this.type) { case "anchor": case "tag": if (atNextItem || it.value) { start.push(this.sourceToken); map.items.push({ start }); this.onKeyLine = true; } else if (it.sep) { it.sep.push(this.sourceToken); } else { it.start.push(this.sourceToken); } return; case "explicit-key-ind": if (!it.sep && !it.explicitKey) { it.start.push(this.sourceToken); it.explicitKey = true; } else if (atNextItem || it.value) { start.push(this.sourceToken); map.items.push({ start, explicitKey: true }); } else { this.stack.push({ type: "block-map", offset: this.offset, indent: this.indent, items: [{ start: [this.sourceToken], explicitKey: true }] }); } this.onKeyLine = true; return; case "map-value-ind": if (it.explicitKey) { if (!it.sep) { if (includesToken(it.start, "newline")) { Object.assign(it, { key: null, sep: [this.sourceToken] }); } else { const start2 = getFirstKeyStartProps(it.start); this.stack.push({ type: "block-map", offset: this.offset, indent: this.indent, items: [{ start: start2, key: null, sep: [this.sourceToken] }] }); } } else if (it.value) { map.items.push({ start: [], key: null, sep: [this.sourceToken] }); } else if (includesToken(it.sep, "map-value-ind")) { this.stack.push({ type: "block-map", offset: this.offset, indent: this.indent, items: [{ start, key: null, sep: [this.sourceToken] }] }); } else if (isFlowToken(it.key) && !includesToken(it.sep, "newline")) { const start2 = getFirstKeyStartProps(it.start); const key = it.key; const sep = it.sep; sep.push(this.sourceToken); delete it.key; delete it.sep; this.stack.push({ type: "block-map", offset: this.offset, indent: this.indent, items: [{ start: start2, key, sep }] }); } else if (start.length > 0) { it.sep = it.sep.concat(start, this.sourceToken); } else { it.sep.push(this.sourceToken); } } else { if (!it.sep) { Object.assign(it, { key: null, sep: [this.sourceToken] }); } else if (it.value || atNextItem) { map.items.push({ start, key: null, sep: [this.sourceToken] }); } else if (includesToken(it.sep, "map-value-ind")) { this.stack.push({ type: "block-map", offset: this.offset, indent: this.indent, items: [{ start: [], key: null, sep: [this.sourceToken] }] }); } else { it.sep.push(this.sourceToken); } } this.onKeyLine = true; return; case "alias": case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": { const fs = this.flowScalar(this.type); if (atNextItem || it.value) { map.items.push({ start, key: fs, sep: [] }); this.onKeyLine = true; } else if (it.sep) { this.stack.push(fs); } else { Object.assign(it, { key: fs, sep: [] }); this.onKeyLine = true; } return; } default: { const bv = this.startBlockValue(map); if (bv) { if (bv.type === "block-seq") { if (!it.explicitKey && it.sep && !includesToken(it.sep, "newline")) { yield* this.pop({ type: "error", offset: this.offset, message: "Unexpected block-seq-ind on same line with key", source: this.source }); return; } } else if (atMapIndent) { map.items.push({ start }); } this.stack.push(bv); return; } } } } yield* this.pop(); yield* this.step(); } *blockSequence(seq) { const it = seq.items[seq.items.length - 1]; switch (this.type) { case "newline": if (it.value) { const end = "end" in it.value ? it.value.end : void 0; const last = Array.isArray(end) ? end[end.length - 1] : void 0; if (last?.type === "comment") end?.push(this.sourceToken); else seq.items.push({ start: [this.sourceToken] }); } else it.start.push(this.sourceToken); return; case "space": case "comment": if (it.value) seq.items.push({ start: [this.sourceToken] }); else { if (this.atIndentedComment(it.start, seq.indent)) { const prev = seq.items[seq.items.length - 2]; const end = prev?.value?.end; if (Array.isArray(end)) { arrayPushArray(end, it.start); end.push(this.sourceToken); seq.items.pop(); return; } } it.start.push(this.sourceToken); } return; case "anchor": case "tag": if (it.value || this.indent <= seq.indent) break; it.start.push(this.sourceToken); return; case "seq-item-ind": if (this.indent !== seq.indent) break; if (it.value || includesToken(it.start, "seq-item-ind")) seq.items.push({ start: [this.sourceToken] }); else it.start.push(this.sourceToken); return; } if (this.indent > seq.indent) { const bv = this.startBlockValue(seq); if (bv) { this.stack.push(bv); return; } } yield* this.pop(); yield* this.step(); } *flowCollection(fc) { const it = fc.items[fc.items.length - 1]; if (this.type === "flow-error-end") { let top; do { yield* this.pop(); top = this.peek(1); } while (top?.type === "flow-collection"); } else if (fc.end.length === 0) { switch (this.type) { case "comma": case "explicit-key-ind": if (!it || it.sep) fc.items.push({ start: [this.sourceToken] }); else it.start.push(this.sourceToken); return; case "map-value-ind": if (!it || it.value) fc.items.push({ start: [], key: null, sep: [this.sourceToken] }); else if (it.sep) it.sep.push(this.sourceToken); else Object.assign(it, { key: null, sep: [this.sourceToken] }); return; case "space": case "comment": case "newline": case "anchor": case "tag": if (!it || it.value) fc.items.push({ start: [this.sourceToken] }); else if (it.sep) it.sep.push(this.sourceToken); else it.start.push(this.sourceToken); return; case "alias": case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": { const fs = this.flowScalar(this.type); if (!it || it.value) fc.items.push({ start: [], key: fs, sep: [] }); else if (it.sep) this.stack.push(fs); else Object.assign(it, { key: fs, sep: [] }); return; } case "flow-map-end": case "flow-seq-end": fc.end.push(this.sourceToken); return; } const bv = this.startBlockValue(fc); if (bv) this.stack.push(bv); else { yield* this.pop(); yield* this.step(); } } else { const parent = this.peek(2); if (parent.type === "block-map" && (this.type === "map-value-ind" && parent.indent === fc.indent || this.type === "newline" && !parent.items[parent.items.length - 1].sep)) { yield* this.pop(); yield* this.step(); } else if (this.type === "map-value-ind" && parent.type !== "flow-collection") { const prev = getPrevProps(parent); const start = getFirstKeyStartProps(prev); fixFlowSeqItems(fc); const sep = fc.end.splice(1, fc.end.length); sep.push(this.sourceToken); const map = { type: "block-map", offset: fc.offset, indent: fc.indent, items: [{ start, key: fc, sep }] }; this.onKeyLine = true; this.stack[this.stack.length - 1] = map; } else { yield* this.lineEnd(fc); } } } flowScalar(type) { if (this.onNewLine) { let nl = this.source.indexOf("\n") + 1; while (nl !== 0) { this.onNewLine(this.offset + nl); nl = this.source.indexOf("\n", nl) + 1; } } return { type, offset: this.offset, indent: this.indent, source: this.source }; } startBlockValue(parent) { switch (this.type) { case "alias": case "scalar": case "single-quoted-scalar": case "double-quoted-scalar": return this.flowScalar(this.type); case "block-scalar-header": return { type: "block-scalar", offset: this.offset, indent: this.indent, props: [this.sourceToken], source: "" }; case "flow-map-start": case "flow-seq-start": return { type: "flow-collection", offset: this.offset, indent: this.indent, start: this.sourceToken, items: [], end: [] }; case "seq-item-ind": return { type: "block-seq", offset: this.offset, indent: this.indent, items: [{ start: [this.sourceToken] }] }; case "explicit-key-ind": { this.onKeyLine = true; const prev = getPrevProps(parent); const start = getFirstKeyStartProps(prev); start.push(this.sourceToken); return { type: "block-map", offset: this.offset, indent: this.indent, items: [{ start, explicitKey: true }] }; } case "map-value-ind": { this.onKeyLine = true; const prev = getPrevProps(parent); const start = getFirstKeyStartProps(prev); return { type: "block-map", offset: this.offset, indent: this.indent, items: [{ start, key: null, sep: [this.sourceToken] }] }; } } return null; } atIndentedComment(start, indent) { if (this.type !== "comment") return false; if (this.indent <= indent) return false; return start.every((st) => st.type === "newline" || st.type === "space"); } *documentEnd(docEnd) { if (this.type !== "doc-mode") { if (docEnd.end) docEnd.end.push(this.sourceToken); else docEnd.end = [this.sourceToken]; if (this.type === "newline") yield* this.pop(); } } *lineEnd(token) { switch (this.type) { case "comma": case "doc-start": case "doc-end": case "flow-seq-end": case "flow-map-end": case "map-value-ind": yield* this.pop(); yield* this.step(); break; case "newline": this.onKeyLine = false; // fallthrough case "space": case "comment": default: if (token.end) token.end.push(this.sourceToken); else token.end = [this.sourceToken]; if (this.type === "newline") yield* this.pop(); } } }; exports.Parser = Parser; } }); // ../../node_modules/yaml/dist/public-api.js var require_public_api = __commonJS({ "../../node_modules/yaml/dist/public-api.js"(exports) { "use strict"; var composer = require_composer(); var Document = require_Document(); var errors = require_errors(); var log2 = require_log(); var identity = require_identity(); var lineCounter = require_line_counter(); var parser = require_parser(); function parseOptions(options) { const prettyErrors = options.prettyErrors !== false; const lineCounter$1 = options.lineCounter || prettyErrors && new lineCounter.LineCounter() || null; return { lineCounter: lineCounter$1, prettyErrors }; } function parseAllDocuments2(source, options = {}) { const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options); const parser$1 = new parser.Parser(lineCounter2?.addNewLine); const composer$1 = new composer.Composer(options); const docs = Array.from(composer$1.compose(parser$1.parse(source))); if (prettyErrors && lineCounter2) for (const doc of docs) { doc.errors.forEach(errors.prettifyError(source, lineCounter2)); doc.warnings.forEach(errors.prettifyError(source, lineCounter2)); } if (docs.length > 0) return docs; return Object.assign([], { empty: true }, composer$1.streamInfo()); } function parseDocument(source, options = {}) { const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options); const parser$1 = new parser.Parser(lineCounter2?.addNewLine); const composer$1 = new composer.Composer(options); let doc = null; for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) { if (!doc) doc = _doc; else if (doc.options.logLevel !== "silent") { doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()")); break; } } if (prettyErrors && lineCounter2) { doc.errors.forEach(errors.prettifyError(source, lineCounter2)); doc.warnings.forEach(errors.prettifyError(source, lineCounter2)); } return doc; } function parse(src, reviver, options) { let _reviver = void 0; if (typeof reviver === "function") { _reviver = reviver; } else if (options === void 0 && reviver && typeof reviver === "object") { options = reviver; } const doc = parseDocument(src, options); if (!doc) return null; doc.warnings.forEach((warning) => log2.warn(doc.options.logLevel, warning)); if (doc.errors.length > 0) { if (doc.options.logLevel !== "silent") throw doc.errors[0]; else doc.errors = []; } return doc.toJS(Object.assign({ reviver: _reviver }, options)); } function stringify(value, replacer, options) { let _replacer = null; if (typeof replacer === "function" || Array.isArray(replacer)) { _replacer = replacer; } else if (options === void 0 && replacer) { options = replacer; } if (typeof options === "string") options = options.length; if (typeof options === "number") { const indent = Math.round(options); options = indent < 1 ? void 0 : indent > 8 ? { indent: 8 } : { indent }; } if (value === void 0) { const { keepUndefined } = options ?? replacer ?? {}; if (!keepUndefined) return void 0; } if (identity.isDocument(value) && !_replacer) return value.toString(options); return new Document.Document(value, _replacer, options).toString(options); } exports.parse = parse; exports.parseAllDocuments = parseAllDocuments2; exports.parseDocument = parseDocument; exports.stringify = stringify; } }); // ../../node_modules/yaml/dist/index.js var require_dist = __commonJS({ "../../node_modules/yaml/dist/index.js"(exports) { "use strict"; var composer = require_composer(); var Document = require_Document(); var Schema = require_Schema(); var errors = require_errors(); var Alias = require_Alias(); var identity = require_identity(); var Pair = require_Pair(); var Scalar = require_Scalar(); var YAMLMap = require_YAMLMap(); var YAMLSeq = require_YAMLSeq(); var cst = require_cst(); var lexer = require_lexer(); var lineCounter = require_line_counter(); var parser = require_parser(); var publicApi = require_public_api(); var visit = require_visit(); exports.Composer = composer.Composer; exports.Document = Document.Document; exports.Schema = Schema.Schema; exports.YAMLError = errors.YAMLError; exports.YAMLParseError = errors.YAMLParseError; exports.YAMLWarning = errors.YAMLWarning; exports.Alias = Alias.Alias; exports.isAlias = identity.isAlias; exports.isCollection = identity.isCollection; exports.isDocument = identity.isDocument; exports.isMap = identity.isMap; exports.isNode = identity.isNode; exports.isPair = identity.isPair; exports.isScalar = identity.isScalar; exports.isSeq = identity.isSeq; exports.Pair = Pair.Pair; exports.Scalar = Scalar.Scalar; exports.YAMLMap = YAMLMap.YAMLMap; exports.YAMLSeq = YAMLSeq.YAMLSeq; exports.CST = cst; exports.Lexer = lexer.Lexer; exports.LineCounter = lineCounter.LineCounter; exports.Parser = parser.Parser; exports.parse = publicApi.parse; exports.parseAllDocuments = publicApi.parseAllDocuments; exports.parseDocument = publicApi.parseDocument; exports.stringify = publicApi.stringify; exports.visit = visit.visit; exports.visitAsync = visit.visitAsync; } }); // src/server.ts import { createServer } from "node:http"; import { createReadStream, existsSync, statSync } from "node:fs"; import { extname, join, normalize, resolve } from "node:path"; // ../../packages/engine/src/search.ts var STOP = new Set( "a an and are as at be but by can do does for from how i if in into is it its me my of on or so than that the their them then there these they this to was what when where which who why will with you your".split( " " ) ); function tokenize(text) { return text.toLowerCase().replace(/[`*_#>()[\]{}"',;:!?|=]/g, " ").split(/\s+/).map((t) => t.replace(/^[.-]+|[.-]+$/g, "")).filter((t) => t.length > 1 && !STOP.has(t)).flatMap((t) => t.includes("-") || t.includes("/") ? [t, ...t.split(/[-/]/).filter((p) => p.length > 1)] : [t]).map(stem); } function stem(t) { if (t.length > 4 && t.endsWith("ies")) return t.slice(0, -3) + "y"; if (t.length > 3 && t.endsWith("es") && /(ss|x|ch|sh)es$/.test(t)) return t.slice(0, -2); if (t.length > 3 && t.endsWith("s") && !t.endsWith("ss") && !t.endsWith("us")) return t.slice(0, -1); return t; } var KIND_BOOST = { lesson: 1.3, section: 1, faq: 1, glossary: 1.2, comparison: 1.15, question: 0.8, lab: 0.9, flashcard: 0.85 }; var SearchIndex = class { docs = []; tf = []; titleTokens = []; len = []; df = /* @__PURE__ */ new Map(); avgLen = 0; constructor(docs) { for (const d of docs) this.add(d); this.avgLen = this.len.reduce((a, b) => a + b, 0) / Math.max(1, this.len.length); } add(doc) { const tokens = tokenize(`${doc.title} ${doc.title} ${doc.text}`); const tf = /* @__PURE__ */ new Map(); for (const t of tokens) tf.set(t, (tf.get(t) ?? 0) + 1); for (const t of tf.keys()) this.df.set(t, (this.df.get(t) ?? 0) + 1); this.docs.push(doc); this.tf.push(tf); this.titleTokens.push(new Set(tokenize(doc.title))); this.len.push(tokens.length); } get size() { return this.docs.length; } search(query, opts = {}) { const q2 = [...new Set(tokenize(query))]; if (!q2.length) return []; const N = this.docs.length; const k1 = 1.4; const b = 0.75; const hits = []; for (let i = 0; i < N; i++) { const doc = this.docs[i]; if (opts.kinds && !opts.kinds.includes(doc.kind)) continue; const tf = this.tf[i]; let score = 0; let matched = 0; for (const term of q2) { const f = tf.get(term); if (!f) continue; matched++; const df = this.df.get(term) ?? 0; const idf = Math.log(1 + (N - df + 0.5) / (df + 0.5)); score += idf * (f * (k1 + 1) / (f + k1 * (1 - b + b * this.len[i] / this.avgLen))); if (this.titleTokens[i].has(term)) score += idf * 0.6; } if (!score) continue; score *= KIND_BOOST[doc.kind] * (0.6 + 0.4 * matched / q2.length); if (opts.boostLesson && doc.lessonId === opts.boostLesson) score *= 1.5; hits.push({ doc, score }); } hits.sort((a, b2) => b2.score - a.score); return hits.slice(0, opts.limit ?? 10); } }; // ../../packages/content/src/infra/lessons-1.ts var netFundamentals = { id: "infra-net-fundamentals", title: "Network fundamentals: from URL to bytes", stage: 0, order: 1, objectives: ["net-fundamentals"], scope: "senior", estMinutes: 30, summary: "DNS, TCP, TLS 1.3 and HTTP/1.1\u20132\u20133 as one latency budget: what each round trip costs, how congestion control and head-of-line blocking shape throughput, and the kernel-level failure modes (TIME_WAIT, ephemeral ports, negative caching) that show up in production.", what: `Network fundamentals for infrastructure interviews is the ability to walk a request end to end and **price every step in round trips (RTTs)**. The layers that matter in practice are the TCP/IP ones: link, IP (routing, MTU), transport (TCP, UDP, QUIC on UDP), and application (DNS, TLS, HTTP). OSI is a vocabulary for talking about "L4" vs "L7"; nobody runs a seven-layer stack. A senior engineer treats the network as a **latency and failure budget**: a cold HTTPS request to a server 80 ms away costs DNS + TCP handshake + TLS handshake + request before the first byte arrives, and every one of those can fail independently.`, why: `Most "the app is slow" and "random 5xx under load" incidents are network-shaped: a DNS TTL that kept clients on a dead IP, a connection pool that re-handshakes TLS on every request, ephemeral ports exhausted by a NAT, an HTTP/2 connection stalled by one lost packet. Interviewers use "what happens when you type a URL" precisely because it reveals whether you can reason across layers, quantify cost, and name the failure mode at each hop.`, problem: `Without a mental model of RTTs and congestion control, teams make predictable mistakes: they move a service to another region and are surprised that a chatty protocol with 6 sequential calls adds 6 \xD7 70 ms; they raise bandwidth on a long-haul link and see no throughput change because the TCP window, not the pipe, is the limit; they set DNS TTLs to 1 day and cannot fail over; they open a new connection per request and burn CPU on handshakes while accumulating tens of thousands of sockets in TIME_WAIT.`, how: `Walk the request in order and count RTTs. - **DNS resolution.** The stub resolver asks a recursive resolver (often local cache first). On a miss, the recursive walks root \u2192 TLD \u2192 authoritative, then caches each answer for its **TTL**. A NXDOMAIN is cached too (**negative caching**, bounded by the SOA minimum/negative TTL), so a record created right after a failed lookup can stay "missing" for minutes. Cached hit: ~0 RTT; cold: several RTTs to distant servers. - **TCP handshake.** SYN \u2192 SYN-ACK \u2192 ACK costs **1 RTT** before data can be sent. Data then starts under **slow start**: the congestion window (cwnd) begins small (commonly 10 segments, ~14 KB) and roughly doubles per RTT until loss or the receiver window caps it. Short transfers therefore never reach link speed. - **TLS 1.3.** Client sends key share in ClientHello; server replies with its share, certificate and Finished in one flight: **1 RTT** for a full handshake (TLS 1.2 needed 2). With a resumption ticket, **0-RTT** lets the client send early data with the first flight, but early data is **replayable** by an attacker, so only idempotent requests (GETs without side effects) should use it. - **HTTP.** HTTP/1.1 allows one outstanding request per connection in practice, so browsers open ~6 connections per origin. **HTTP/2** multiplexes many streams over one TCP connection with header compression (HPACK), fixing application-level head-of-line (HOL) blocking, but a single lost TCP segment stalls **all** streams until retransmission: transport-level HOL blocking. **HTTP/3** runs over **QUIC** (UDP), which merges transport and TLS 1.3 handshakes into **1 RTT** (0-RTT on resumption), retransmits per stream so loss on one stream does not block others, and supports connection migration via connection IDs (survives a phone switching from Wi-Fi to cellular). - **Throughput ceiling.** Max throughput of one TCP flow \u2248 window / RTT. To fill a pipe you need window \u2265 **bandwidth-delay product (BDP)** = bandwidth \xD7 RTT. - **Teardown.** The side that closes first enters **TIME_WAIT** for 2\xD7MSL (60 s on Linux) to absorb stray segments. A client making many short connections to the same destination IP:port can exhaust its **ephemeral port range** (Linux default 32768\u201360999, ~28k ports), and so can a NAT gateway translating many clients to one IP.`, components: [ { name: "Recursive resolver and TTLs", description: "Caches positive answers for the record TTL and negative answers per the SOA. TTL is your failover speed limit: clients and intermediate resolvers may hold an answer for the full TTL, and some clients ignore TTLs entirely (long-lived JVM caches, connection pools pinned to an IP)." }, { name: "TCP congestion control", description: "Slow start, congestion avoidance and loss recovery decide how fast a flow ramps. Loss-based algorithms (CUBIC, the Linux default) back off on loss; model-based BBR estimates bottleneck bandwidth and RTT and degrades less on lossy long paths." }, { name: "TLS 1.3 handshake", description: "One RTT full handshake, forward secrecy by default, encrypted certificate. Session resumption with PSK tickets enables 0-RTT early data with replay risk. Termination point (LB, sidecar, app) decides where plaintext exists." }, { name: "HTTP/2 multiplexing", description: "Many concurrent streams over one TCP connection; removes the need for domain sharding and multiple connections, but concentrates risk: one lossy connection stalls every stream, and long-lived connections defeat naive L4 load balancing." }, { name: "QUIC / HTTP/3", description: "UDP-based transport with built-in TLS 1.3, per-stream loss recovery, and connection IDs. Costs: more userspace CPU than kernel TCP, UDP sometimes blocked or rate-limited by middleboxes, so clients fall back to HTTP/2." }, { name: "Socket lifecycle", description: "Ephemeral ports, TIME_WAIT, keepalive and connection pooling. Reusing connections amortises TCP+TLS handshakes and avoids port exhaustion; idle timeouts must be aligned (client < LB < server) to avoid resets on reuse." } ], misconceptions: [ { myth: "More bandwidth makes a single transfer faster.", reality: "For a long-RTT path a single flow is bounded by window/RTT. A 64 KB window over 100 ms RTT caps at ~5 Mbit/s regardless of a 10 Gbit/s link. Fix the window (window scaling, buffer tuning), use parallel flows, or move closer." }, { myth: "HTTP/2 eliminates head-of-line blocking.", reality: "It removes HOL at the HTTP layer only. A lost TCP segment blocks all multiplexed streams until retransmitted, which can make HTTP/2 worse than several HTTP/1.1 connections on lossy networks. QUIC removes transport HOL." }, { myth: "Setting a DNS TTL of 60 s means clients move within 60 s of a change.", reality: "TTL is an upper bound that well-behaved resolvers honour. Client-side caches, connection reuse and resolvers that enforce minimum TTLs mean a long tail keeps hitting the old address. Plan for minutes and drain old endpoints rather than killing them." }, { myth: "TIME_WAIT sockets are a leak to be killed with kernel tweaks.", reality: "TIME_WAIT protects against delayed duplicate segments corrupting a new connection. The fix for exhaustion is connection reuse (pooling, keepalive) or more source IPs/ports, not disabling the safety mechanism." } ], example: { title: "Pricing a cold HTTPS request and a long-haul transfer", description: `Client in Frankfurt, origin in Virginia, RTT ~90 ms (order of magnitude). First request, nothing cached, HTTP/2 over TCP: - DNS: resolver cache miss to authoritative, ~1 RTT to a distant authoritative (often less via anycast) \u2248 50\u201390 ms - TCP handshake: 1 RTT = 90 ms - TLS 1.3: 1 RTT = 90 ms - Request/response: 1 RTT = 90 ms + server time \u2248 **320\u2013360 ms before first byte**, of which ~230\u2013270 ms is connection setup (DNS + TCP + TLS). HTTP/3 merges TCP+TLS (saves 90 ms); a warm pooled connection skips both (saves 180 ms); a CDN edge 10 ms away cuts each handshake RTT to 10 ms. The BDP calculation below explains why a bulk copy over the same path underperforms.`, code: `# Bandwidth-delay product for a 1 Gbit/s path with 90 ms RTT BDP = 1e9 bit/s * 0.090 s = 90e6 bit = ~11.25 MB in flight # A flow limited to a 4 MB window: throughput = 4 MB * 8 / 0.090 s = ~356 Mbit/s (~36% of the link) # Inspect on Linux ss -ti dst 203.0.113.10 # cwnd, rtt, retrans per socket sysctl net.ipv4.ip_local_port_range # default 32768 60999 ss -tan state time-wait | wc -l # TIME_WAIT count dig +trace example.com # walk root -> TLD -> authoritative curl -w '%{time_namelookup} %{time_connect} %{time_appconnect} %{time_starttransfer}\\n' -o /dev/null -s https://example.com`, language: "bash" }, exercise: { prompt: `A service in one region calls a dependency in another region (RTT 70 ms) using a client library that opens a new HTTPS connection per call. It handles 2,000 calls/s from a single egress IP through a NAT, and p50 latency is ~220 ms. Estimate where the time goes, identify the scaling cliff, and propose fixes with expected impact.`, solution: `**Latency:** TCP (70) + TLS 1.3 (70) + request (70) \u2248 210 ms + server time, matching the 220 ms p50. Two-thirds is handshake. **Cliff:** each call consumes a source port toward the same destination IP:port, and the closing side holds it in TIME_WAIT for ~60 s. 2,000/s \xD7 60 s = **120,000** ports needed vs ~28k (Linux default range) or the NAT's per-destination port budget. Expect intermittent connect failures as load grows, worst at peaks. **Fixes:** - Connection pooling with keepalive (HTTP/2 multiplexing): p50 drops to ~70 ms + server time, handshake CPU largely disappears, ports in use drop to a few dozen. - Align idle timeouts (client pool idle < NAT/LB idle) to avoid resets on reuse. - If cross-region calls are frequent, cache or co-locate; batching N sequential calls into one saves (N\u22121) \xD7 70 ms. - As a stopgap, more NAT source IPs multiply the port budget; it does not fix latency.` }, faq: [ { q: "Should we enable TLS 0-RTT?", a: "Only for idempotent, side-effect-free requests, and only where the server or edge enforces that policy. Early data can be replayed by an attacker who captures it, so a POST that charges a card must never be accepted as 0-RTT." }, { q: "Why does a load balancer show uneven load with HTTP/2 or gRPC clients?", a: "Clients multiplex all requests over a few long-lived connections, so an L4 balancer that distributes connections, not requests, pins traffic to whichever backends got those connections. Use L7 (per-request) balancing or client-side balancing, and cap connection age so connections rebalance." }, { q: "What is MTU and why does it bite in cloud networks?", a: "The largest packet a link carries without fragmentation (1500 bytes is the common Ethernet default; some cloud networks support larger jumbo frames internally). Tunnels and VPNs add headers, so if path MTU discovery is broken by filtered ICMP, large packets silently drop: small requests work, large responses hang." } ], keyTerms: ["RTT", "bandwidth-delay product", "slow start", "congestion window", "TLS 1.3 1-RTT / 0-RTT", "head-of-line blocking", "QUIC", "TIME_WAIT", "ephemeral port exhaustion", "negative caching"], deeper: `Staff-level nuance lives in the interactions. **Retries and slow start compound**: after a failover every client reconnects at once, every new connection starts at a small cwnd, and TLS handshakes spike CPU on the new target, so the "healthy" side browns out; connection rate limits and jittered reconnects matter as much as capacity. **Middleboxes ossify protocols**: QUIC encrypts most of its headers precisely so middleboxes cannot depend on them, which also means your own network team loses visibility they had with TCP. **Tail latency is dominated by loss**: a single retransmission timeout (minimum around 200 ms on Linux) dwarfs a 1 ms service time, so p99 on a lossy path is a network property, not an application one. Finally, **DNS is a control plane**: the resolver fleet is a shared dependency for everything, and resolver saturation or a misconfigured negative TTL can look like a total outage of unrelated services.`, interview: { seniorAnswer: `Frame it as a budget: "A cold HTTPS request costs DNS plus 1 RTT TCP, 1 RTT TLS 1.3, 1 RTT for the request; on HTTP/3 the first two merge." Then name the levers in order of impact: connection reuse, moving the edge closer, protocol upgrades. Call out the failure mode at each layer (DNS TTL and negative caching, slow start after failover, HOL blocking on lossy links, TIME_WAIT/port exhaustion through NAT) and quantify with BDP or port arithmetic. Close with how you would observe it: \`curl -w\` timing phases, \`ss -ti\` for cwnd/retransmits, resolver metrics.`, followUps: [ { q: "Why is HTTP/3 not universally faster?", a: "Handshake savings and per-stream recovery help most on high-RTT or lossy mobile paths. On clean datacenter links the gain is small, userspace QUIC costs more CPU per byte than kernel TCP with offloads, and some networks block or throttle UDP, forcing fallback." }, { q: "How would you fail over a service quickly using DNS?", a: "Lower TTL well before the change (old TTL must expire first), use health-checked records, keep the old endpoint serving and drain it, and accept a long tail from clients that ignore TTL. For seconds-level failover prefer anycast or a load balancer VIP that does not change." }, { q: "A transfer between regions gets 300 Mbit/s on a 10 Gbit/s link. Diagnose.", a: "Compute BDP: at 80 ms, 10 Gbit/s needs ~100 MB in flight. Check socket buffers/window scaling, retransmits with `ss -ti`, and whether a single flow is used. Fix with larger buffers, parallel streams, or BBR on lossy paths." }, { q: "What does TIME_WAIT protect against and who holds it?", a: "The side that actively closes holds it for 2\xD7MSL so delayed duplicates from an old connection with the same 4-tuple are not accepted by a new one. Make servers not close first where possible, and reuse connections on clients." } ], redFlags: [ "Reciting the OSI model without pricing any step in round trips", "Claiming HTTP/2 fully solves head-of-line blocking", "Treating DNS TTL as an exact failover time", "Proposing to disable TIME_WAIT or set tcp_tw_recycle as a fix", "Ignoring that 0-RTT data is replayable" ], numbers: [ "Same-AZ RTT ~0.1\u20130.5 ms; cross-AZ ~1\u20132 ms; cross-continent ~70\u2013150 ms (order of magnitude)", "TCP handshake 1 RTT; TLS 1.3 1 RTT (TLS 1.2: 2 RTT); QUIC combined 1 RTT; resumption 0-RTT", "Initial cwnd commonly 10 segments (~14 KB)", "Throughput \u2248 window / RTT; BDP = bandwidth \xD7 RTT", "Linux ephemeral range 32768\u201360999 (~28k ports); TIME_WAIT 60 s" ] }, references: [ { title: "High Performance Browser Networking (Ilya Grigorik)", url: "https://hpbn.co/" }, { title: "RFC 8446: TLS 1.3", url: "https://www.rfc-editor.org/rfc/rfc8446" }, { title: "RFC 9000: QUIC", url: "https://www.rfc-editor.org/rfc/rfc9000" }, { title: "RFC 9293: Transmission Control Protocol", url: "https://www.rfc-editor.org/rfc/rfc9293" } ] }; var netCloud = { id: "infra-net-cloud", title: "Cloud network design: VPCs, CIDR and hybrid connectivity", stage: 0, order: 2, objectives: ["net-cloud"], scope: "senior", estMinutes: 35, summary: "Designing VPC/VNet address space for many accounts and regions without overlap, subnet tiers and route tables, NAT egress cost and AZ affinity, stateful vs stateless filtering, peering vs transit hubs, private endpoints, and VPN vs dedicated interconnect with hybrid DNS.", what: `A cloud virtual network (**VPC** on AWS and Google Cloud, **VNet** on Azure) is a software-defined private network: you choose an address space (from RFC 1918 ranges), carve it into subnets, attach route tables, and control traffic with stateful and stateless filters. Note a structural difference: AWS VPCs and Azure VNets are regional with subnets bound to an AZ (AWS) or spanning the region (Azure), while a Google Cloud VPC is global with regional subnets. Cloud network design is the discipline of planning **address space, segmentation, egress, connectivity between networks, and connectivity to on-premises** so that the organisation can grow to hundreds of accounts and several regions without re-addressing.`, why: `Network topology is one of the hardest things to change later. Overlapping CIDRs block peering and hybrid routing forever (or force NAT-between-networks hacks); a single shared NAT gateway becomes both a cost line item and a cross-AZ failure dependency; a flat network turns a single compromised instance into an organisation-wide incident. Senior interviewers probe whether you design for growth, blast radius and cost on day one.`, problem: `Typical failure stories: two acquired companies both used \`10.0.0.0/16\` and cannot be connected; a team peered 40 VPCs in a mesh and now manages hundreds of peering connections and route entries; a data-heavy workload pulls terabytes from object storage through a NAT gateway and the per-GB processing charge exceeds the compute bill; an AZ outage takes down egress for all AZs because every private subnet routed through one NAT in the failed AZ.`, how: `Design top-down. - **Allocate a supernet per region/environment**, managed centrally (an IPAM). Example: \`10.0.0.0/8\` split into \`/12\` per region, \`/16\` per account-environment, with ranges reserved for on-prem and future regions. Never reuse a range anywhere that might ever be routed together. - **Subnet tiers per AZ**: public (route to internet gateway; only load balancers and NAT live here), private (default route to NAT for egress), and isolated/data (no internet route). Size subnets for peak IP consumption including container pod IPs, which can consume an IP per pod. - **Egress via NAT**: one NAT gateway **per AZ**, and each AZ's private route table points to its own NAT. This keeps egress zonal (an AZ failure does not break others) and avoids cross-AZ data charges. NAT also has per-GB processing cost, so route high-volume traffic to provider services through **private/gateway endpoints** instead. - **Filtering**: **security groups** (AWS) / NSGs (Azure) / firewall rules (GCP) are **stateful** \u2014 return traffic is automatically allowed \u2014 and attached to instances or interfaces; they can reference other groups, which scales better than IP lists. **NACLs** (AWS) are **stateless** subnet-level filters: you must allow return traffic on ephemeral ports explicitly, and rules are evaluated in number order. - **Connecting networks**: **peering** is point-to-point and **non-transitive** (A\u2013B and B\u2013C does not give A\u2013C), and needs non-overlapping CIDRs. Beyond a handful of networks, use a **hub**: AWS Transit Gateway, Azure Virtual WAN or hub VNet, Google Cloud Network Connectivity Center. Hubs give transitive routing, central inspection and route-table segmentation (prod cannot reach dev), at a per-GB processing cost. - **Private access to services**: **private endpoints** (AWS PrivateLink, Azure Private Link, GCP Private Service Connect) expose a service as a private IP in your subnet, avoiding the internet, NAT, and the need for CIDR non-overlap with the provider. - **Hybrid**: **site-to-site VPN** over the internet (quick, encrypted, throughput limited per tunnel and variable latency) vs **dedicated interconnect** (AWS Direct Connect, Azure ExpressRoute, Google Cloud Interconnect): private circuits with predictable latency and lower egress rates, but weeks to provision and needs redundant circuits in separate locations. Common pattern: interconnect primary, VPN backup, BGP for route exchange. - **Hybrid DNS**: conditional forwarding both ways \u2014 cloud resolver endpoints forward \`corp.example\` to on-prem DNS, on-prem forwards cloud private zones to inbound resolver endpoints. Private endpoints usually depend on private DNS zones overriding the public name; getting this wrong sends traffic to the public endpoint.`, components: [ { name: "IPAM and CIDR plan", description: "The central allocation of non-overlapping ranges per region, environment and account, including on-prem and future growth. Without it, every new connection is a negotiation." }, { name: "Subnets and route tables", description: "Route tables, not subnet names, make a subnet public or private. Longest-prefix match decides the next hop; a more specific route (e.g. to an inspection appliance) overrides the default." }, { name: "NAT gateway", description: "Managed source-NAT for outbound-only access. Zonal resource; deploy one per AZ. Charged per hour and per GB processed; has per-destination connection and port limits." }, { name: "Security groups vs NACLs", description: "Stateful, allow-only, instance-level and referencable by group vs stateless, ordered allow/deny, subnet-level. Use groups for intent, NACLs as a coarse guardrail (e.g. deny a known bad range)." }, { name: "Transit hub", description: "A regional router connecting many VPCs and on-prem links with multiple route tables for segmentation. Replaces an N\xD7(N\u22121)/2 peering mesh with N attachments." }, { name: "Private endpoints and interconnects", description: "Private endpoints map a provider or partner service to a private IP in your network; interconnects give dedicated, BGP-routed private circuits to on-prem." } ], misconceptions: [ { myth: "A subnet is public because it is called public or because instances have public IPs.", reality: "It is public only if its route table has a default route to an internet gateway. An instance with a public IP in a subnet without that route is unreachable from the internet." }, { myth: "Peering three VPCs in a chain connects all of them.", reality: "Peering is non-transitive; traffic will not be forwarded through the middle network. You need direct peering for each pair or a transit hub." }, { myth: "One NAT gateway is enough for a multi-AZ deployment.", reality: "It works until its AZ fails, then all private-subnet egress breaks, and meanwhile you pay cross-AZ data transfer for traffic from other AZs. One per AZ with zonal routing is the resilient pattern." }, { myth: "Traffic to the cloud provider\u2019s object storage from a private subnet stays on the private network automatically.", reality: "Without a gateway or private endpoint it is routed via NAT to the public endpoint, incurring NAT processing charges. Add the endpoint and the matching route/DNS so it takes the private path." } ], example: { title: "CIDR plan for 3 regions \xD7 3 environments with on-prem", description: `An organisation with on-prem in \`10.0.0.0/12\`, three regions, prod/staging/dev, and expected growth to ~50 accounts. Each workload account gets a \`/20\` (4,096 addresses) carved into per-AZ tiers; large Kubernetes accounts get a \`/18\` or use a secondary range for pods. Everything is non-overlapping, so any two networks can later be connected through the regional hub.`, code: `10.0.0.0/8 organisation supernet 10.0.0.0/12 on-prem (reserved, never used in cloud) 10.16.0.0/12 region A 10.16.0.0/14 prod (64 x /20 accounts) 10.20.0.0/14 staging 10.24.0.0/14 dev 10.28.0.0/14 shared services / hub / reserved 10.32.0.0/12 region B (same layout) 10.48.0.0/12 region C 10.64.0.0/10 reserved for future regions / acquisitions One /20 workload account, 3 AZs: public 10.16.0.0/24 10.16.1.0/24 10.16.2.0/24 (LBs, NAT) private 10.16.4.0/22 10.16.8.0/22 10.16.12.0/22 (app, ~1,000 IPs/AZ) data 10.16.3.0/26 10.16.3.64/26 10.16.3.128/26 (no internet route) Route tables: private-az1: 0.0.0.0/0 -> nat-az1 ; 10.0.0.0/8 -> transit-hub ; storage prefix -> gateway endpoint data-az1: 10.0.0.0/8 -> transit-hub (no default route)`, language: "text" }, exercise: { prompt: `A workload in private subnets across 3 AZs reads 50 TB/month from object storage in the same region and calls a SaaS API over the internet (2 TB/month). Today everything egresses through a single NAT gateway in AZ-a. Propose a design that improves resilience and cost, and estimate the saving assuming a NAT processing charge of ~$0.045/GB and cross-AZ transfer of ~$0.01/GB each direction (illustrative numbers; check your provider).`, solution: `**Current:** 52 TB through NAT \u2248 52,000 GB \xD7 $0.045 \u2248 **$2,340/month** processing. Roughly two-thirds of traffic originates in AZ-b/c and crosses to AZ-a: ~35 TB \xD7 ~$0.02 (both directions) \u2248 **$700/month**. AZ-a failure kills all egress. **Proposed:** - Gateway/private endpoint for object storage with routes in every private route table: 50 TB leaves the NAT path. Gateway-type endpoints for object storage on AWS carry no per-GB charge; interface endpoints have a smaller per-GB charge. - One NAT per AZ, each AZ routing to its own NAT: remaining 2 TB \u2248 $90/month processing plus three NAT hourly charges, no cross-AZ hop. **Result:** from ~$3,000/month to ~$90 + NAT hourly fees, and an AZ failure now only affects that AZ's egress. Also verify the endpoint policy restricts access to your own buckets to avoid creating an exfiltration path.` }, faq: [ { q: "When should I use a transit hub instead of peering?", a: "Once you have more than a handful of networks, need transitive routing to on-prem, central inspection, or route segmentation. Peering stays useful for a few high-volume pairs because it avoids hub per-GB processing charges." }, { q: "VPN or dedicated interconnect?", a: "VPN is days to set up, encrypted, but limited per-tunnel throughput and internet-variable latency. Interconnect gives predictable latency, higher bandwidth and usually cheaper egress, but takes weeks and needs two circuits in different facilities for resilience. Many run interconnect primary with VPN as backup." }, { q: "How do I avoid running out of IPs with Kubernetes?", a: "Plan pod IP consumption up front: CNIs that give pods VPC IPs consume subnet space fast. Use secondary CIDRs for pods, prefix delegation, or an overlay CNI, and size subnets for peak node count \xD7 pods per node." } ], keyTerms: ["VPC / VNet", "CIDR", "RFC 1918", "route table", "NAT gateway", "security group (stateful)", "NACL (stateless)", "non-transitive peering", "transit hub", "private endpoint", "dedicated interconnect", "conditional forwarding"], deeper: `At staff level the network is an **organisational interface**. Centralised IPAM and a hub-and-spoke topology owned by a platform team let application teams self-serve accounts with pre-allocated ranges. Decide early whether egress is centralised (an inspection VPC with firewalls behind the hub: one control point but a shared failure and cost domain) or distributed (NAT per account: simpler, harder to audit). **IPv6** sidesteps exhaustion and overlap but every component (security tooling, logging, on-prem) must support it; dual-stack is the realistic path. Another subtlety: **AZ names are not guaranteed consistent across accounts** on some providers (AWS can map the same AZ name to different physical zones in different accounts; zone IDs such as \`use1-az1\` are stable), which matters when you align NATs, endpoints and zonal services across accounts. Finally, private endpoints scale connectivity without routing, which makes them a good tool for multi-tenant SaaS and for connecting networks that already overlap.`, interview: { seniorAnswer: `Start from requirements: number of accounts and regions, on-prem connectivity, compliance boundaries, expected growth. Propose a central IPAM with non-overlapping supernets per region and environment, three subnet tiers per AZ, NAT per AZ, private endpoints for provider services, and a regional transit hub with separate route tables for prod and non-prod. For hybrid, dual interconnect circuits with VPN backup and BGP, plus bidirectional conditional DNS forwarding. Name the trade-offs explicitly: hub processing cost vs operational simplicity, centralised vs distributed egress, and the blast radius of shared components.`, followUps: [ { q: "Security group vs NACL: when do you use each?", a: "Security groups for application intent: stateful, allow-only, can reference other groups so rules follow instances. NACLs as a coarse, stateless subnet guardrail, e.g. explicit denies; remember to allow ephemeral return ports." }, { q: "Two networks overlap and must talk. Options?", a: "Re-address one (best long-term), expose specific services via private endpoints (no routing needed), or NAT between them through an intermediate network. All but re-addressing add complexity and debugging pain." }, { q: "How do you make private endpoints work with on-prem clients?", a: "On-prem DNS conditionally forwards the service zone to an inbound cloud resolver endpoint, which resolves the name to the private endpoint IP via the private zone; routing to that IP goes over interconnect/VPN." }, { q: "Where would you put egress inspection?", a: "A central inspection network attached to the hub with route tables forcing 0.0.0.0/0 through firewalls deployed per AZ, keeping flows symmetric (same AZ in and out) so stateful firewalls see both directions." } ], redFlags: [ 'Using 10.0.0.0/16 everywhere "because it is the default"', "Assuming peering is transitive", "A single NAT gateway for all AZs", "Confusing stateful security groups with stateless NACLs", "No plan for hybrid DNS when using private endpoints" ], numbers: [ "RFC 1918: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16", "A /16 = 65,536 addresses; /20 = 4,096; /24 = 256 (providers reserve a few per subnet, 5 on AWS)", "Full peering mesh: N\xD7(N\u22121)/2 links; hub: N attachments", "NAT and hub charges are per GB processed in addition to hourly; cross-AZ transfer is billed on most providers" ] }, references: [ { title: "Amazon VPC User Guide: What is Amazon VPC?", url: "https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html" }, { title: "RFC 1918: Address Allocation for Private Internets", url: "https://www.rfc-editor.org/rfc/rfc1918" }, { title: "Google Cloud Architecture Center", url: "https://cloud.google.com/architecture" }, { title: "Azure Well-Architected Framework", url: "https://learn.microsoft.com/en-us/azure/well-architected/" } ] }; var netEdge = { id: "infra-net-edge", title: "Load balancing and the edge", stage: 0, order: 3, objectives: ["net-edge"], scope: "senior", estMinutes: 30, summary: "L4 vs L7 load balancing, health checks and connection draining, session affinity, balancing algorithms, global traffic via anycast vs DNS-based GSLB, CDN cache keys and hit ratio, and WAF/DDoS layering.", what: `The edge is everything between a user and your service tier: global traffic steering (DNS or anycast), CDN and edge caches, WAF and DDoS protection, and regional load balancers that spread requests across healthy backends. **L4 load balancers** forward TCP/UDP flows based on the 5-tuple without parsing payload: very high throughput, low latency, preserve the client connection end to end (or pass through TLS). **L7 load balancers** terminate the connection, parse HTTP/gRPC, and route per request on host, path, header or cookie; they can retry, rewrite, enforce auth and observe status codes, at the cost of more CPU and a TLS termination point.`, why: `The edge decides availability during the moments that matter: deploys, AZ failures, traffic spikes and attacks. Badly tuned health checks cause cascading ejection or route traffic into dead backends; missing draining turns every deploy into a burst of 502s; a low CDN hit ratio turns a viral spike into an origin outage; a DNS-only failover strategy leaves users stranded for the TTL tail.`, problem: `Common incidents: a health check that hits a deep \`/health\` endpoint which checks the database, so a DB blip marks every backend unhealthy and the LB has nowhere to send traffic; a cache key that includes a tracking query parameter, so the hit ratio collapses to near zero; sticky sessions pinning a hot tenant to one instance; gRPC traffic balanced at L4 so new pods receive no requests; a global failover that depends on clients re-resolving DNS.`, how: `Trace a request from the user inward. - **Global steering.** Either **DNS-based GSLB** (the authoritative DNS returns region-specific IPs based on resolver location, latency or health; failover speed bounded by TTL and client caching) or **anycast** (the same IP announced via BGP from many edge locations; the internet routes users to the nearest, and withdrawing a route moves traffic in seconds to minutes without client cooperation). Global anycast L7 load balancers (e.g. Google Cloud's global external Application Load Balancer, AWS Global Accelerator for L4, Azure Front Door) combine anycast entry with backend selection. - **DDoS and WAF.** Volumetric L3/L4 attacks are absorbed by provider scale at anycast edges (AWS Shield, Azure DDoS Protection, Google Cloud Armor). L7 attacks and exploits are handled by a **WAF**: managed rule sets (e.g. OWASP-style injection rules), rate limiting per key, bot controls. Put these before the origin and make the origin accept traffic only from the edge. - **CDN.** The edge caches responses by a **cache key** (by default host + path + selected query params/headers). Hit ratio is the biggest lever: normalise the key (drop irrelevant params, avoid \`Vary: User-Agent\`), set \`Cache-Control\` with \`s-maxage\` and \`stale-while-revalidate\`, use an **origin shield** (mid-tier cache) to collapse misses from many PoPs into one origin request, and version static assets (\`app.3f9a.js\`) so they can be cached for a year. - **Regional load balancer.** Algorithms: round robin, least outstanding requests (better for heterogeneous latency), consistent hashing (for cache affinity), and **power of two random choices** (pick two, send to the less loaded; near-optimal with little coordination). **Session affinity** by cookie or source IP helps stateful legacy apps but skews load and breaks on scale-in; prefer external session state. - **Health checks.** Active checks (probe every N s, unhealthy after K failures) plus passive/outlier detection (eject backends returning 5xx). Make checks **shallow** for liveness of the instance; deep dependency checks should degrade, not eject everyone. Have a fail-open rule: if all backends are unhealthy, send to all rather than none. - **Connection draining / deregistration delay.** On scale-in or deploy, stop sending new requests to a backend but let in-flight requests finish for a bounded time (e.g. 30\u2013300 s), while the app stops accepting keepalive reuse. Align timeouts: client idle < LB idle < backend keepalive, otherwise the backend closes a connection the LB is about to reuse and you get intermittent 502s.`, components: [ { name: "L4 load balancer", description: "Flow-level forwarding (5-tuple hashing), millions of connections, TLS pass-through possible, preserves source IP in many designs. Balances connections, not requests, so long-lived multiplexed connections skew load." }, { name: "L7 load balancer / reverse proxy", description: "Terminates TLS, routes per request, retries idempotent requests, adds headers (X-Forwarded-For), exposes per-route metrics. Becomes a policy point and a potential bottleneck." }, { name: "Health checking and outlier detection", description: "Active probes with thresholds plus passive ejection on errors. Tuning interval \xD7 threshold sets detection time; ejection caps prevent removing too many backends at once." }, { name: "Global traffic management", description: "DNS GSLB with health-checked, latency- or geo-based answers, or anycast VIPs. Anycast fails over without client action; DNS gives per-user control but obeys caching." }, { name: "CDN and origin shield", description: "Edge caches keyed by normalised request attributes; origin shield collapses concurrent misses. Hit ratio and TTL policy determine origin load and egress cost." }, { name: "WAF and DDoS protection", description: "Volumetric absorption at the provider edge, L7 filtering and rate limiting by IP, token or path. Rules need a count/monitor mode before blocking to avoid false positives." } ], misconceptions: [ { myth: "Health checks should verify every dependency.", reality: "A deep check that fails when a shared dependency fails marks all instances unhealthy simultaneously, turning partial degradation into a total outage. Check the instance itself; handle dependency failure with degraded responses and alerts." }, { myth: "DNS failover is instant if the TTL is low.", reality: "Resolvers and clients cache beyond TTL, and established connections never re-resolve. Expect a tail of minutes; use anycast or a stable VIP for fast failover and drain the old target." }, { myth: "Sticky sessions are harmless.", reality: "They defeat load balancing (hot users pin to hot instances), make scale-in lose sessions, and slow deploys. Externalise session state and use affinity only as a cache-locality optimisation." }, { myth: "A CDN only helps static assets.", reality: "Short TTLs (even 1\u20135 s) on popular dynamic responses with request collapsing can absorb massive read spikes; the CDN also terminates TLS near users and keeps warm connections to origin." } ], example: { title: "Draining and timeout alignment for zero-error deploys", description: `A service behind an L7 LB sees ~0.3% 502s during every deploy and a trickle at random times. Root causes: pods are killed immediately on termination, and the backend keepalive timeout (5 s) is shorter than the LB idle timeout (60 s), so the backend closes idle connections the LB then reuses. The fix aligns the chain and adds draining.`, code: `Timeout chain (must increase inward): client idle < LB idle timeout < backend keepalive e.g. 30 s < 60 s < 75 s On termination (Kubernetes example): 1. Pod marked terminating -> removed from endpoints (propagates in seconds) 2. preStop hook: sleep 10s # keep serving while LBs notice 3. App stops accepting new conns, sends Connection: close / GOAWAY 4. In-flight requests finish (bounded by terminationGracePeriodSeconds) 5. LB deregistration delay: 30 s Health check: GET /healthz (process-local), interval 5 s, unhealthy after 3 failures (~15 s detection), healthy after 2 Outlier ejection: 5 consecutive 5xx -> eject 30 s, max 20% of hosts ejected`, language: "text" }, exercise: { prompt: `A news site serves 200k requests/s at peak; 70% are article pages that change at most once a minute, 30% are personalised API calls. The CDN hit ratio is 40% and origin is struggling. The cache key includes the full query string and the \`Cookie\` header. Propose changes and estimate origin load before and after.`, solution: `**Before:** origin load = 200k \xD7 (1 \u2212 0.40) = **120k req/s**. **Changes:** - Remove \`Cookie\` and marketing params (\`utm_*\`, \`fbclid\`) from the cache key for article pages; personalise via a separate API call or edge logic. - \`Cache-Control: public, s-maxage=60, stale-while-revalidate=30\` on articles; enable request collapsing and an origin shield so each article misses once per TTL globally, not once per PoP. - Leave personalised API calls uncached (or micro-cache with per-user keys if allowed). **After:** article requests (140k/s) achieve ~98\u201399% hit ratio (misses only on expiry and the long tail) \u2192 ~2\u20133k req/s to origin; API 60k/s still reach origin. Total \u2248 **62\u201363k req/s**, about half the original, with the remaining load being genuinely dynamic. Next step: reduce API load by caching per-user data briefly or splitting public fragments out.` }, faq: [ { q: "Should TLS terminate at the load balancer?", a: "Usually at the L7 edge for routing, WAF and observability, then re-encrypt to backends if policy requires encryption in transit inside the network. Use L4 pass-through when the backend must hold the keys (e.g. mTLS with client certs end to end) and you only need connection distribution." }, { q: "Anycast or DNS GSLB for multi-region?", a: "Anycast for fast, client-independent failover and DDoS absorption; DNS for fine-grained per-region weighting, data residency steering and cheap setup. Many architectures use DNS to pick a region and anycast or regional VIPs within it." }, { q: "How do I balance gRPC traffic?", a: "gRPC uses long-lived HTTP/2 connections, so use an L7 balancer or service mesh that balances per request, or client-side balancing with a name resolver. Cap connection age (max connection age) so clients reconnect and spread over new backends." } ], keyTerms: ["L4 vs L7", "health check", "outlier detection", "connection draining", "session affinity", "least outstanding requests", "power of two choices", "anycast", "GSLB", "cache key", "origin shield", "WAF"], deeper: `The edge is where **retry amplification** is born: an L7 LB retrying on 5xx, plus client retries, plus SDK retries can multiply load 3\u201327\xD7 on a struggling backend; cap retries at one layer and use retry budgets. **Fail-open vs fail-closed** is a real design choice: a WAF or auth check that fails closed during its own outage takes the site down; one that fails open accepts risk. **Cross-zone load balancing** spreads evenly across AZs but adds cross-AZ latency and cost; disabling it improves zonal isolation but requires balanced capacity per AZ. For static stability, the edge should never need its control plane to keep serving: health checks and routes must keep working from cached config if the provider API is degraded. Finally, measure **origin offload** (bytes and requests) not just hit ratio: a high request hit ratio with a low byte hit ratio means large objects are missing.`, interview: { seniorAnswer: `Describe the path layer by layer: global entry (anycast or DNS GSLB) with DDoS protection, WAF and CDN with a normalised cache key and origin shield, regional L7 balancers with per-request algorithms, shallow health checks plus outlier detection, and draining aligned with timeouts. For each, state the failure mode it prevents and the one it introduces (deep checks cascading, sticky sessions skewing, DNS TTL tails, retry amplification). Quote detection time (interval \xD7 threshold), hit-ratio arithmetic for origin load, and the timeout ordering rule.`, followUps: [ { q: "All backends fail their health checks at once. What should the LB do?", a: "Fail open: route to all backends, since a mass failure usually means the check or a shared dependency is broken, not every instance. Many proxies support a panic threshold for this." }, { q: "How do you get zero-downtime deploys behind a load balancer?", a: "Readiness gating before registration, deregistration delay plus a preStop pause before shutdown, graceful connection close (GOAWAY), idempotent retries at one layer, and aligned idle timeouts." }, { q: "Why can least-connections be worse than round robin?", a: "With multiple LB nodes each having partial views, or with new instances that look idle, everyone stampedes the newest/emptiest backend. Slow start for new backends and power-of-two choices mitigate." }, { q: "How would you protect an origin from a cache miss storm when TTLs expire?", a: "Request collapsing at edge and shield, stale-while-revalidate to serve stale while one fetch refreshes, and jittered TTLs so popular objects do not all expire together." } ], redFlags: [ "Health checks that call the database", "DNS as the only fast-failover mechanism", "No mention of draining or timeout alignment for deploys", "Using L4 balancing for gRPC and wondering why load is uneven", "WAF rules deployed straight to block mode" ], numbers: [ "Detection time \u2248 check interval \xD7 unhealthy threshold (e.g. 5 s \xD7 3 = 15 s)", "Origin load = total requests \xD7 (1 \u2212 hit ratio): 90% \u2192 99% hit ratio is a 10\xD7 origin reduction", "Deregistration/draining delay commonly 30\u2013300 s", "Retries at 3 layers with 3 attempts each can amplify load up to 27\xD7" ] }, references: [ { title: "Google SRE book: Handling Overload", url: "https://sre.google/sre-book/handling-overload/" }, { title: "Google SRE book: Addressing Cascading Failures", url: "https://sre.google/sre-book/addressing-cascading-failures/" }, { title: "OWASP Top Ten", url: "https://owasp.org/www-project-top-ten/" }, { title: "High Performance Browser Networking", url: "https://hpbn.co/" } ] }; var computeModels = { id: "infra-compute-models", title: "Compute models: VMs, containers and serverless", stage: 1, order: 1, objectives: ["compute-models"], scope: "senior", estMinutes: 30, summary: "Choosing between VMs, containers and functions by isolation, startup time, density, operational ownership and cost curve; instance families; spot/preemptible capacity and interruption handling; immutable infrastructure.", what: `Compute models are the units in which you rent CPU and memory, each moving the line of **who operates what**: - **Virtual machines** (EC2, Azure VMs, Compute Engine): a full guest OS on a hypervisor. Hardware-virtualised isolation, you own the OS, patching and packing. - **Containers** on an orchestrator (EKS/AKS/GKE, or ECS / Azure Container Apps / Cloud Run as managed container platforms): processes isolated by kernel namespaces and cgroups sharing the host kernel. Fast start, high density, image-based delivery. - **Serverless functions** (Lambda, Azure Functions, Cloud Run functions): event-triggered code where the provider owns capacity, scaling to zero and billing per invocation and duration, often isolated in micro-VMs (e.g. Firecracker for Lambda). Orthogonal choices: **instance family** (general, compute-, memory-, storage-optimised, accelerated, Arm vs x86) and **purchase model** (on-demand, commitments, spot/preemptible).`, why: `The compute model sets the cost curve, the latency floor, the security boundary and the operational load for years. Picking functions for a steady 5,000 req/s service can cost multiples of containers; picking VMs for spiky event processing pays for idle capacity; picking containers without a platform team creates an orchestration burden nobody owns. Interviewers expect you to choose by workload shape rather than fashion.`, problem: `Teams hit recurring traps: cold starts adding hundreds of milliseconds to a latency-sensitive API on functions; a multi-tenant container cluster where a kernel exploit crosses tenants because containers were treated as a hard security boundary; fleets of hand-patched "pet" VMs that drift until nobody can rebuild them; spot capacity used for stateful workloads with no interruption handling, losing work on every reclaim.`, how: `Decide along five axes. - **Workload shape.** Steady, high utilisation favours VMs or containers on committed capacity. Spiky or low-duty-cycle event processing favours functions or scale-to-zero containers. Long-running (> 15 min), stateful, or needing special hardware (GPUs, local NVMe) favours VMs or containers. - **Startup latency.** VM boot is tens of seconds to minutes (image size, init scripts). Container start is sub-second to seconds once the image is cached; image pull can dominate. Function cold start ranges from ~100 ms to seconds depending on runtime, package size and VPC attachment; mitigate with provisioned/minimum instances, smaller packages, and lazy initialisation. - **Isolation.** VMs and micro-VMs give a hardware-virtualisation boundary. Plain containers share a kernel; for untrusted multi-tenant code use sandboxed runtimes (gVisor, Kata Containers) or separate nodes/VMs per tenant. - **Operational ownership.** VMs: you patch OS, manage images, autoscaling groups. Containers: you (or a platform team) run the orchestrator, upgrades, networking. Functions: provider handles almost everything, but you accept limits (execution time, payload size, concurrency quotas) and less control over networking and runtime. - **Cost curve.** Functions are cheapest at low and bursty utilisation and most expensive at sustained high utilisation; there is a crossover point (compute it). Containers improve VM economics by **bin packing**. **Spot/preemptible** capacity is typically ~60\u201390% cheaper than on-demand but can be reclaimed with short notice (about 2 minutes on AWS, ~30 s on Google Cloud and Azure); use it for stateless, checkpointed or fault-tolerant work, diversify across instance types and AZs, and handle the interruption signal by draining. **Immutable infrastructure** applies to all three: never patch in place; build a new image (AMI/VM image or container image) through CI, roll it out, and destroy the old. This gives reproducibility, fast rollback (redeploy previous image) and eliminates drift.`, components: [ { name: "Hypervisor and micro-VMs", description: "Hardware-assisted virtualisation for VMs; lightweight micro-VMs (Firecracker) give VM-grade isolation with ~100 ms-class boot, used by serverless platforms to isolate tenants." }, { name: "Container runtime", description: "Namespaces (pid, net, mount, user) for isolation and cgroups for resource limits, sharing the host kernel. OCI images give a portable, immutable artifact." }, { name: "Function platform", description: "Event sources, concurrency-based scaling, per-invocation billing, execution limits (e.g. Lambda max 15 minutes), cold vs warm execution environments, provisioned concurrency to pre-warm." }, { name: "Instance families", description: "Ratios of vCPU to memory, network bandwidth and local storage. Arm-based instances (Graviton, Ampere/Axion-class) often give better price-performance for recompilable workloads." }, { name: "Spot / preemptible capacity", description: "Spare capacity at deep discount with reclaim notice. Requires diversified pools, interruption handlers, checkpointing and an on-demand fallback." }, { name: "Golden images and immutability", description: "Pipelines that bake OS, agents and hardening into versioned images; deploy by replacement; config injected at boot or runtime rather than mutated by SSH." } ], misconceptions: [ { myth: "Serverless is always cheaper.", reality: "Per-request pricing wins at low or bursty utilisation. At sustained load, the per-GB-second premium usually exceeds the cost of right-sized containers or VMs, especially with commitments. Compute the crossover." }, { myth: "Containers are a security boundary equivalent to VMs.", reality: "They share the host kernel; a kernel or runtime escape crosses tenants. For hostile multi-tenancy use sandboxed runtimes, separate node pools or VMs per tenant." }, { myth: "Spot instances are only for batch jobs.", reality: "Stateless web tiers behind a load balancer, CI runners and Kubernetes worker pools run well on spot when capacity is diversified and interruption notices trigger draining, with an on-demand base for the minimum." }, { myth: "Bigger instances are always more efficient.", reality: "Large instances increase blast radius and reduce bin-packing flexibility; many small ones increase per-instance overhead. Choose sizes so that losing one is tolerable and packing stays efficient." } ], example: { title: "Function vs container crossover, worked", description: `An API averages 300 req/s, each using 512 MB for 120 ms. Illustrative prices (check your provider): functions at ~$0.0000167 per GB-second plus ~$0.20 per million requests; a container instance with 2 vCPU / 4 GB at ~$0.08/hour handling ~150 req/s each at target utilisation.`, code: `Requests/month = 300 * 86,400 * 30 = ~777.6 M GB-seconds = 777.6 M * 0.5 GB * 0.12 s = ~46.7 M GB-s Function cost = 46.7 M * 0.0000167 + 777.6 * 0.20 = ~$780 + ~$156 = ~$936 / month Containers = ceil(300 / 150) = 2, run 3 for N+1 redundancy Container cost = 3 * $0.08 * 730 h = ~$175 / month At 10 req/s average with bursts to 200: Function cost = ~$31 / month (scales to zero overnight) Containers = still >= 2 instances for HA = ~$117 / month`, language: "text" }, exercise: { prompt: `You must host three workloads: (1) a thumbnail generator triggered by uploads, 50k/day with bursts of 2k/min; (2) a latency-sensitive checkout API at 1,500 req/s steady with p99 target 150 ms; (3) a nightly 6-hour ML feature job that can checkpoint every 10 minutes. Choose a compute model and purchase option for each, and name one failure mode you would design for.`, solution: `- **Thumbnails:** functions triggered by storage events (or scale-to-zero containers). Low duty cycle, bursty, short tasks. Failure mode: bursts exceeding concurrency quota or overwhelming a downstream; put a queue between the event and the function, set reserved concurrency, and make processing idempotent (events can be delivered more than once). - **Checkout API:** containers on a managed orchestrator or autoscaling VMs, on-demand/committed base capacity, multi-AZ. Steady load makes functions expensive and cold starts threaten p99. Failure mode: scale-out lag during spikes; keep headroom (~30%) and pre-scale for known events. - **ML job:** VMs or batch containers on **spot**, diversified across instance types and AZs, checkpointing to object storage. Interruption loses at most 10 minutes of work. Failure mode: no spot capacity at all; fall back to on-demand after a deadline so the job still finishes before morning.` }, faq: [ { q: "How do I reduce function cold starts?", a: "Smaller deployment packages, lighter runtimes, initialising clients outside the handler and lazily, avoiding unnecessary VPC attachment where it adds latency, and provisioned/minimum instances for the latency-critical path. Measure p99 including cold starts, not just warm averages." }, { q: "When do VMs still win over containers?", a: "Licensed software tied to hosts, workloads needing a custom kernel or full OS control, very large stateful single-instance systems, strict isolation requirements, or teams without the capacity to run an orchestrator." }, { q: "Is Arm worth it?", a: "Often, for workloads you can recompile or that run on managed runtimes: price-performance gains are commonly cited in the 20\u201340% range. Costs are multi-arch image builds, testing, and dependencies with x86-only native code." } ], keyTerms: ["virtual machine", "micro-VM", "container (namespaces, cgroups)", "serverless function", "cold start", "provisioned concurrency", "instance family", "spot / preemptible", "bin packing", "immutable infrastructure", "golden image"], deeper: `The staff-level frame is **total cost of ownership including people**: a platform that saves 30% on compute but needs three engineers to run may lose to a managed service. Second, **concurrency models** matter more than CPU: a standard Lambda execution environment handles one request at a time (Cloud Run and some newer function hosting modes allow many concurrent requests per instance), so downstream connection counts scale with concurrency and can exhaust database connections; front databases with a pooler or proxy. Third, **noisy neighbours** exist at every layer: CPU throttling from cgroup quotas (CFS throttling shows up as p99 latency even when average CPU is low), burstable instance credits running out, and shared network bandwidth. Finally, immutable infrastructure is also a security control: short-lived instances shrink the window for persistence after compromise, and image provenance (signed, scanned images) ties into supply-chain controls.`, interview: { seniorAnswer: `Choose by workload shape, not preference: steady high utilisation \u2192 containers or VMs on committed capacity; bursty event-driven \u2192 functions or scale-to-zero; long-running, stateful or hardware-specific \u2192 VMs. Quantify the crossover cost, state the latency floor (cold starts, image pulls, boot times), the isolation boundary (kernel-shared vs hypervisor), and who operates what. Use spot for interruption-tolerant work with diversification and fallback, and treat all compute as immutable images built by CI.`, followUps: [ { q: "How would you run untrusted customer code?", a: "Hypervisor-level isolation per tenant: micro-VMs or sandboxed runtimes (gVisor/Kata), no shared kernel, strict egress controls, resource limits, and no credentials on the host. Plain containers on shared nodes are not enough." }, { q: "How do you handle spot interruptions in a Kubernetes cluster?", a: "Diversify node pools across instance types and AZs, run a node termination handler that cordons and drains on notice, use PodDisruptionBudgets, keep an on-demand baseline for critical replicas, and let the cluster autoscaler replace capacity." }, { q: "Your function-based service started failing with database connection errors under load. Why?", a: "Each concurrent execution environment opens its own connections; a burst to 1,000 concurrent invocations means 1,000+ connections. Use a connection proxy/pooler, cap reserved concurrency, or move the hot path to a pooled container service." } ], redFlags: [ 'Choosing serverless or Kubernetes "because it is modern" without workload analysis', "Treating containers as a hard multi-tenant security boundary", "Running stateful, non-checkpointed work on spot with no fallback", "SSH-patching production instances" ], numbers: [ "Spot/preemptible discount ~60\u201390% vs on-demand; reclaim notice ~2 min (AWS), ~30 s (GCP, Azure)", "Lambda max execution 15 minutes", "VM boot tens of seconds to minutes; container start sub-second to seconds once image is cached", "Function cold start ~100 ms to several seconds depending on runtime and package" ] }, references: [ { title: "NIST SP 800-145: The NIST Definition of Cloud Computing", url: "https://csrc.nist.gov/pubs/sp/800/145/final" }, { title: "AWS Well-Architected Framework", url: "https://aws.amazon.com/architecture/well-architected/" }, { title: "The Twelve-Factor App", url: "https://12factor.net/" } ] }; var computeScaling = { id: "infra-compute-scaling", title: "Scaling and capacity planning", stage: 1, order: 2, objectives: ["compute-scaling"], scope: "senior", estMinutes: 30, summary: "Horizontal vs vertical scaling, choosing autoscaling signals, the end-to-end scale-out lag and how warm pools and headroom hide it, capacity planning from demand forecasts and per-instance throughput, load testing, and bin packing.", what: `Scaling is matching capacity to demand. **Vertical** scaling makes one instance bigger (simple, but bounded, often needs a restart, and concentrates risk). **Horizontal** scaling adds instances behind a load balancer (needs stateless or partitioned services, but scales nearly linearly and improves fault tolerance). **Autoscaling** adjusts instance count from a signal: target tracking (keep CPU at 60%), step scaling, scheduled scaling, or predictive scaling from historical patterns. **Capacity planning** is the longer-horizon work: forecasting demand, knowing per-instance throughput from load tests, and ensuring quotas, IP space, and dependencies can absorb the plan.`, why: `Autoscaling is the difference between paying for peak 24/7 and paying for what you use, but it is reactive. A spike that arrives faster than your scale-out lag is served by whatever headroom exists; without headroom it becomes queueing, timeouts, retries and a cascading failure. Capacity planning catches what autoscaling cannot: account quotas, regional capacity, downstream limits, and launch events.`, problem: `Classic failures: scaling on CPU for an I/O-bound service that saturates its thread pool at 30% CPU, so the autoscaler never reacts; a scale-out that takes 6 minutes (instance boot, agent install, JIT warm-up, LB registration) while the spike peaks in 2; a scale-in that oscillates with scale-out (flapping); a fleet that scales to 300 instances and then hits the database connection limit, which is the real bottleneck; a launch day that hits the account's vCPU quota.`, how: `Build it from the bottleneck outward. - **Measure per-instance capacity.** Load test one instance to find the throughput at which latency breaches SLO (the knee of the latency curve). Plan to run at a target utilisation below the knee, commonly 50\u201370%, to absorb bursts and an AZ loss. - **Pick the right signal.** CPU works for CPU-bound services. For I/O-bound or concurrency-limited services, scale on **in-flight requests per instance**, request rate per target, or **queue depth/age** for workers. Latency is a poor primary signal (it rises late and also rises for reasons scaling cannot fix, like a slow dependency). - **Account for scale-out lag.** Total lag = metric collection interval + evaluation periods + provisioning (VM boot or pod scheduling, possibly a new node) + application warm-up + LB health checks. Commonly 2\u201310 minutes for VMs, tens of seconds to minutes for containers (longer when nodes must be added). - **Hide lag** with headroom sized for the fastest credible ramp over the lag window, **warm pools** of pre-initialised stopped instances, overprovisioned placeholder pods (low-priority pods evicted when real pods need room), scheduled scaling before known peaks, and predictive scaling. - **Prevent flapping** with asymmetric policies: scale out fast, scale in slowly (cooldowns or stabilisation windows of several minutes) and in small steps. - **Bin packing** for containers: set accurate requests (based on observed usage, e.g. p95), choose node sizes that fit common pod shapes, and use mixed instance types. Over-requesting wastes nodes; under-requesting causes contention and evictions. - **Plan capacity end to end**: forecast peak (organic growth \xD7 seasonality \xD7 launch multiplier), divide by per-instance throughput at target utilisation, add N+1 per AZ (survive the loss of an AZ: with 3 AZs, each must hold 50% of peak), then check quotas, IPs, database connections, downstream rate limits and spot availability.`, components: [ { name: "Scaling signal", description: "CPU, request rate per target, concurrency, queue depth or age, or custom business metrics. Must be a leading indicator that correlates with the bottleneck resource." }, { name: "Scaling policy", description: "Target tracking for steady control, step scaling for big jumps, scheduled for known patterns, predictive for daily cycles. Asymmetric scale-in to avoid flapping." }, { name: "Provisioning path", description: "Image size, boot and init time, container pull, node autoscaling, warm-up (JIT, caches), and LB registration. Each second here is a second of exposure to spikes." }, { name: "Warm pools and overprovisioning", description: "Pre-initialised capacity or placeholder pods that convert minutes of provisioning into seconds of attach or preemption." }, { name: "Load testing", description: "Find the knee of latency vs throughput per instance, verify linear scaling across instances, and expose the first shared bottleneck. Use realistic payloads and cache hit rates." }, { name: "Capacity model", description: "Forecast, per-unit throughput, utilisation target, redundancy (N+1, AZ loss), and dependency limits, reviewed before launches and quarterly." } ], misconceptions: [ { myth: "Autoscaling means we do not need headroom.", reality: "Autoscaling reacts after the signal moves and takes minutes to deliver capacity. Headroom covers the ramp during that lag; warm pools and predictive scaling shrink the lag but do not eliminate it." }, { myth: "CPU is a fine default scaling metric.", reality: "Only for CPU-bound services. I/O-bound services saturate threads, connections or memory at low CPU; scale on concurrency, request rate per target, or queue age instead." }, { myth: "Scaling out always helps.", reality: "If the bottleneck is a shared dependency (database, lock, third-party API), adding instances adds load to it and can worsen the outage. Find the first shared bottleneck in load tests." }, { myth: "Running at 90% utilisation is efficient.", reality: "Queueing delay grows non-linearly as utilisation approaches 100%; at high utilisation small bursts produce large latency spikes, and there is no room to absorb an AZ failure." } ], example: { title: "Capacity plan for a launch with an AZ-loss requirement", description: `Current peak 8,000 req/s, expected to triple for a launch. Load tests show one instance serves 400 req/s at the latency knee. Target utilisation 60% of the knee. Three AZs; must survive the loss of one AZ at peak without breaching SLO.`, code: `Launch peak = 8,000 * 3 = 24,000 req/s Per-instance at target = 400 * 0.60 = 240 req/s Instances needed = 24,000 / 240 = 100 Survive AZ loss: remaining 2 AZs must carry the full peak per-AZ capacity = 100 / 2 = 50 instances per AZ total provisioned = 50 * 3 = 150 instances (or accept running at the knee, not 60%, during an AZ loss: 24,000 / 400 = 60 needed across 2 AZs -> 30/AZ -> 90 total) Scale-out lag ~5 min; observed max ramp ~+20%/min -> need ~+100% within the lag window: pre-scale to launch peak via scheduled scaling 30 min before; autoscale above that. Checks: vCPU quota >= 150 * vCPUs; subnet IPs; DB pool: 150 instances * 20 conns = 3,000 conns -> needs a pooler`, language: "text" }, exercise: { prompt: `A queue-worker fleet processes jobs averaging 2 s each, single-threaded, 4 workers per instance. Normal inflow is 100 jobs/s; a nightly batch drops 300,000 jobs at once and must drain within 30 minutes. Instances take 3 minutes to become ready. Design the scaling signal and estimate the required peak fleet.`, solution: `**Per-instance throughput:** 4 workers / 2 s = 2 jobs/s. **Normal:** 100 / 2 = 50 instances (plus headroom, ~60). **Batch:** effective drain time is 30 \u2212 3 (provisioning) = ~27 min = 1,620 s. Required rate = 300,000 / 1,620 + 100 ongoing \u2248 185 + 100 = **~285 jobs/s \u2192 ~143 instances**, so scale to ~150. **Signal:** scale on **backlog per instance** (queue depth / instances) or oldest-message age, not CPU: target backlog = acceptable latency \xD7 per-instance rate, e.g. 2 jobs/s \xD7 600 s = 1,200 jobs per instance. With a step policy, a backlog of 300k immediately requests ~250 instances; cap the max at the downstream's limit. Add scheduled pre-scaling before the known batch to remove the 3-minute lag, and scale in slowly after the backlog clears. Verify downstream (DB, APIs) can take 285 jobs/s.` }, faq: [ { q: "How do I pick a target utilisation?", a: "From the load test knee and your failure tolerance. With 3 AZs and an AZ-loss requirement, running each AZ at about two-thirds of the knee lets the remaining two absorb the lost one. Bursty traffic or slow scale-out argues for lower targets." }, { q: "Horizontal or vertical for a database?", a: "Vertical first: it is simple and a modern large instance handles a lot. Add read replicas for read scaling, and shard only when write throughput or dataset size exceeds a single primary; sharding is a one-way door with large operational cost." }, { q: "How do Kubernetes autoscalers interact?", a: "The horizontal pod autoscaler adds pods based on metrics; pending pods trigger the cluster autoscaler (or Karpenter-style provisioners) to add nodes, adding node boot time to the lag. Overprovisioning placeholder pods keep spare node capacity for instant scheduling." } ], keyTerms: ["horizontal vs vertical scaling", "target tracking", "scale-out lag", "warm pool", "headroom", "flapping / stabilisation window", "queue backlog per instance", "latency knee", "N+1 / AZ-loss capacity", "bin packing"], deeper: `Staff-level capacity work is about **shared bottlenecks and coordination**. Autoscalers are local controllers; when every service scales at once (a regional failover), they compete for the same quotas, the same scarce instance types, and the same downstream database. **Static stability** says the system should survive the loss of an AZ without needing to scale at all, because control planes and capacity are least available exactly when an AZ fails; that argues for pre-provisioned AZ-loss capacity for critical tiers. **Little's law** (concurrency = arrival rate \xD7 latency) links scaling signals: if latency doubles because a dependency slows, required concurrency doubles even at constant traffic, so concurrency-based autoscaling may scale out into a slow dependency and amplify it. Pair autoscaling with load shedding and maximum limits so the fleet cannot grow into a dependency's failure.`, interview: { seniorAnswer: `Start from per-instance capacity measured by load testing, pick a utilisation target below the latency knee, and size for the failure you must survive (an AZ loss). Choose a scaling signal that leads the bottleneck (concurrency or queue age for I/O-bound work), quantify scale-out lag, and cover it with headroom, warm pools or scheduled/predictive scaling. Scale out fast and in slowly. Then check everything that does not autoscale: quotas, IPs, database connections, downstream limits.`, followUps: [ { q: "Why not scale on latency?", a: "Latency rises late, is noisy, and often rises because of a slow dependency; scaling out then adds pressure on that dependency. Use it as an SLO alert, not as the control signal." }, { q: "Your autoscaler keeps flapping. Fix it.", a: "Add a scale-in stabilisation window, scale in by smaller steps, check that the metric is not itself affected by scaling (e.g. per-instance averages that drop sharply when new instances start empty), and widen the gap between scale-out and scale-in thresholds." }, { q: "How do you capacity plan for an event 10\xD7 normal traffic?", a: "Load test at 10\xD7 including dependencies, pre-scale ahead of the event rather than relying on autoscaling, raise quotas and reserve capacity, cache aggressively, prepare load-shedding and feature degradation switches, and run a game day." } ], redFlags: [ "Assuming autoscaling removes the need for headroom", "CPU as the universal scaling metric", "No consideration of downstream limits when scaling out", "Sizing for average load rather than peak plus failure scenario" ], numbers: [ "Target utilisation commonly 50\u201370% of measured capacity", "With N AZs, surviving one AZ loss needs each AZ sized to peak / (N \u2212 1)", "VM scale-out lag ~2\u201310 min end to end; pods seconds to minutes (longer if nodes are added)", "Little's law: concurrency = arrival rate \xD7 time in system" ] }, references: [ { title: "AWS Builders\u2019 Library: Static stability using Availability Zones", url: "https://aws.amazon.com/builders-library/static-stability-using-availability-zones/" }, { title: "Google SRE book: Handling Overload", url: "https://sre.google/sre-book/handling-overload/" }, { title: "Google Cloud Well-Architected Framework", url: "https://cloud.google.com/architecture/framework" } ] }; var computePlatform = { id: "infra-compute-platform", title: "Kubernetes as a multi-tenant platform", stage: 1, order: 3, objectives: ["compute-platform"], scope: "senior", estMinutes: 35, summary: "Running Kubernetes as an internal product: tenancy models and isolation layers, cluster topology and blast radius, node pools, safe upgrades, and platform engineering with golden paths.", what: `Kubernetes as a platform means operating clusters for many teams rather than one application: providing **tenancy** (namespaces, quotas, policies), **isolation** proportional to trust, a **cluster topology** that limits blast radius, **upgrade and lifecycle** processes that do not break tenants, and **golden paths** (templates, CI, defaults) that make the right way the easy way. Managed control planes (EKS, AKS, GKE) remove etcd and API server operations but leave you owning node pools, add-ons (CNI, ingress, DNS, autoscaler, policy engines), upgrades, and tenant experience.`, why: `Platform decisions scale both ways: a good one lets 50 teams ship safely with little friction; a bad one makes the cluster a shared failure domain where one team's misconfigured webhook, runaway job or CRD upgrade takes everyone down. Senior interviews probe whether you can reason about isolation, blast radius and upgrade safety rather than just YAML.`, problem: `Recurring incidents: a validating admission webhook with \`failurePolicy: Fail\` whose backend is down blocks all pod creation cluster-wide; a tenant without resource quotas schedules thousands of pods and starves others; a Kubernetes minor version upgrade removes a deprecated API that dozens of Helm charts still use; a single giant cluster per region means any control-plane or CNI issue is a regional outage; noisy neighbours on shared nodes cause latency spikes because pods have no limits.`, how: `Layer isolation and lifecycle deliberately. - **Tenancy model.** Namespace-per-team (soft multi-tenancy) within shared clusters, or cluster-per-tenant (hard isolation, more overhead). Common hybrid: shared clusters per environment and region for trusted internal teams; dedicated clusters or node pools for regulated or untrusted workloads. - **Isolation layers in a shared cluster.** RBAC scoped to namespaces; **ResourceQuota** and **LimitRange** for fairness; **NetworkPolicy** default-deny with explicit allows; Pod Security Admission (\`restricted\` profile) to block privileged pods; admission policies (OPA Gatekeeper, Kyverno, or built-in ValidatingAdmissionPolicy) for org rules; workload identity instead of node credentials; separate node pools with taints/tolerations for sensitive or noisy workloads; sandboxed runtimes for untrusted code. - **Topology.** More, smaller clusters reduce blast radius and make upgrades incremental, at the cost of fleet management (GitOps, cluster templates, multi-cluster service discovery). Rule of thumb: at least per environment and per region; avoid stretching one cluster's control plane across regions. - **Node pools.** Separate pools by instance type (general, memory, GPU, Arm), purchase model (on-demand base, spot burst), and trust. Use node auto-provisioning to pick shapes; keep system add-ons on a stable on-demand pool. - **Upgrades.** Kubernetes ships about three minor releases per year and upstream supports roughly the latest three; providers have their own support windows, so plan for upgrades at least yearly. Process: scan for removed APIs before upgrading, upgrade non-prod first, control plane then nodes, **surge or blue/green node pools**, respect PodDisruptionBudgets, and keep add-on versions compatible. Treat clusters as cattle: being able to recreate a cluster from code is the ultimate rollback. - **Platform engineering.** Offer **golden paths**: service templates with CI/CD, sane defaults (probes, requests, PDBs, network policies), observability wired in, and a self-service portal or CLI. Measure adoption, lead time and incident rate; keep escape hatches for advanced teams.`, components: [ { name: "Namespaces, RBAC and quotas", description: "The basic soft-tenancy unit: who can do what, and how much CPU, memory, object count and storage a tenant may consume." }, { name: "NetworkPolicy and Pod Security", description: "Default-deny east-west traffic per namespace; Pod Security Admission levels (privileged, baseline, restricted) enforced per namespace." }, { name: "Admission control", description: "Validating/mutating webhooks and in-process policies that enforce org rules. Webhooks are in the API request path: availability, timeouts and failure policy are critical." }, { name: "Node pools and scheduling", description: "Taints, tolerations, affinity, topology spread constraints and priority classes to place workloads by hardware, trust and failure domain." }, { name: "Cluster lifecycle", description: "IaC/GitOps-defined clusters, version skew policy, deprecated API scanning, surge or blue/green node upgrades, PDB-aware draining." }, { name: "Golden paths / internal developer platform", description: "Opinionated templates, pipelines and defaults offered as a product with documentation, SLOs and feedback loops." } ], misconceptions: [ { myth: "Namespaces isolate tenants.", reality: "Namespaces are a naming and policy scope. Without RBAC, quotas, network policies, pod security and node isolation, tenants share kernel, network and control plane freely." }, { myth: "One big cluster is cheaper and simpler.", reality: "It maximises bin packing but concentrates blast radius, makes upgrades all-or-nothing, and runs into scale limits (API server load, etcd size, IP space). Most organisations land on several medium clusters managed as a fleet." }, { myth: "Managed Kubernetes means the provider handles upgrades.", reality: "Providers upgrade the control plane (often on a schedule you must follow), but deprecated APIs in your manifests, add-on compatibility, node upgrades and tenant disruption are yours." }, { myth: "A platform team should hide Kubernetes completely.", reality: "Abstractions that hide everything leak during incidents. Good golden paths cover the common case with defaults and let teams see and override underlying resources when needed." } ], example: { title: "Tenant namespace baseline", description: `A baseline every tenant namespace gets from the platform via GitOps: quota, default limits, default-deny network policy, and restricted pod security. Teams add allow rules for their own traffic.`, code: `apiVersion: v1 kind: Namespace metadata: name: team-payments labels: pod-security.kubernetes.io/enforce: restricted --- apiVersion: v1 kind: ResourceQuota metadata: { name: quota, namespace: team-payments } spec: hard: requests.cpu: "40" requests.memory: 80Gi limits.memory: 120Gi pods: "300" --- apiVersion: v1 kind: LimitRange metadata: { name: defaults, namespace: team-payments } spec: limits: - type: Container defaultRequest: { cpu: 100m, memory: 128Mi } default: { memory: 512Mi } --- apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: { name: default-deny, namespace: team-payments } spec: podSelector: {} policyTypes: [Ingress, Egress] egress: - to: - namespaceSelector: {} podSelector: { matchLabels: { k8s-app: kube-dns } } ports: [{ protocol: UDP, port: 53 }, { protocol: TCP, port: 53 }]`, language: "yaml" }, exercise: { prompt: `You run 4 production clusters (2 regions \xD7 2) hosting 60 teams, currently one minor version behind the provider's oldest supported version in 3 months. Design an upgrade programme that minimises tenant disruption, and list the guardrails you would add so the next upgrade is routine.`, solution: `**Programme:** - Week 1: scan all manifests and Helm releases for APIs removed in the target versions (deprecation tooling plus API server audit logs of deprecated calls); open tickets per owning team with a deadline. - Upgrade non-prod clusters first, one minor version at a time (control plane cannot skip minors); validate add-ons (CNI, ingress, DNS, autoscaler, policy engine) against the compatibility matrix. - Production: one cluster at a time, starting with the lowest-traffic region. Control plane, then node pools via **blue/green pools** (new pool at target version, cordon and drain old pool respecting PDBs), with traffic shifted away from the cluster at the global LB if multi-cluster serving allows. - Pause criteria: SLO burn, PDB-blocked drains, failed health checks. **Guardrails:** CI policy that rejects deprecated APIs; mandatory PDBs and readiness probes via admission policy; webhooks with \`failurePolicy: Ignore\` or highly available backends, short timeouts and namespace selectors that exclude system namespaces; a quarterly upgrade cadence so you are never more than one version behind; cluster recreation from code tested regularly.` }, faq: [ { q: "Soft or hard multi-tenancy?", a: "Soft (shared cluster, namespace isolation) for teams within one trust boundary. Hard (separate clusters or sandboxed runtimes plus dedicated nodes) when tenants are untrusted, regulated, or need conflicting cluster-scoped configuration like different CRD versions." }, { q: "How many clusters should we have?", a: "Enough to bound blast radius and match failure domains (at least per environment and region), few enough that the platform team can manage them as a fleet with automation. Splitting further by compliance boundary or tenant tier is common." }, { q: "How do I stop a webhook from taking down the cluster?", a: "Run it highly available with PDBs, set short timeouts, exclude kube-system and the webhook\u2019s own namespace via selectors, alert on webhook latency and rejections, and choose failurePolicy consciously: Fail for security-critical checks, Ignore for convenience mutations." } ], keyTerms: ["soft vs hard multi-tenancy", "ResourceQuota", "LimitRange", "NetworkPolicy", "Pod Security Admission", "admission webhook failurePolicy", "node pool", "taints and tolerations", "PodDisruptionBudget", "golden path"], deeper: `The real scaling limit of a shared platform is usually **cluster-scoped state**: CRDs, webhooks, operators and controllers are global, and every tenant depends on them. Treat each cluster-wide add-on as a tier-0 service with its own SLO and change process. **Priority and preemption** let critical system pods evict batch work, but misuse lets one team preempt another. **Control plane load** from chatty controllers (frequent list/watch, large objects, excessive events) degrades the API server for everyone; API Priority and Fairness exists to isolate this, and you should know it is there. At staff level, measure the platform like a product: adoption of golden paths, time-to-first-deploy for a new service, percentage of workloads on supported versions, and the share of incidents caused by the platform versus by tenants.`, interview: { seniorAnswer: `Treat the platform as a product with layered isolation and controlled blast radius. Explain the tenancy model (namespaces with RBAC, quotas, default-deny network policy, restricted pod security, workload identity; dedicated pools or clusters for untrusted or regulated tenants), the topology (multiple clusters per environment and region, managed as a fleet via GitOps), and the lifecycle (regular upgrades, deprecated API scanning, blue/green node pools, PDBs). Call out shared cluster-scoped components (webhooks, CRDs, CNI) as the main cross-tenant risk, and describe golden paths that make the secure default the easy one.`, followUps: [ { q: "A tenant\u2019s CronJob created 20,000 pods. What should have prevented it?", a: "ResourceQuota on pods and compute per namespace, LimitRange defaults, concurrencyPolicy on the CronJob, and object-count quotas. Also alert on pending pods per namespace." }, { q: "How do you give pods cloud access without node credentials?", a: "Workload identity: bind a Kubernetes service account to a cloud identity (IRSA/EKS Pod Identity, Azure Workload Identity, GKE Workload Identity) so each pod gets short-lived, scoped credentials, and block access to the node metadata endpoint." }, { q: "How do you roll back a bad cluster upgrade?", a: "Control-plane minors usually cannot be downgraded in place. Roll back by shifting traffic to another cluster or recreating from code at the previous version; for node pools, keep the old pool until the new one is validated." } ], redFlags: [ "Believing namespaces alone provide isolation", "No quota or limit defaults for tenants", "Webhooks with failurePolicy Fail and a single replica", "Treating upgrades as rare, manual events", "One cluster per region for everything with no plan for blast radius" ], numbers: [ "Kubernetes: ~3 minor releases per year; upstream maintains roughly the latest 3", "Control plane upgrades go one minor version at a time", "Pod Security Admission levels: privileged, baseline, restricted" ] }, references: [ { title: "Kubernetes documentation: Multi-tenancy", url: "https://kubernetes.io/docs/concepts/security/multi-tenancy/" }, { title: "Open Policy Agent documentation", url: "https://www.openpolicyagent.org/docs/latest/" }, { title: "CNCF projects", url: "https://www.cncf.io/projects/" } ] }; var storageTypes = { id: "infra-storage-types", title: "Storage types, durability and performance", stage: 2, order: 1, objectives: ["storage-types"], scope: "senior", estMinutes: 30, summary: "Block vs file vs object storage, how object stores reach eleven nines of durability, durability vs availability, IOPS vs throughput vs latency, consistency guarantees of object stores, storage classes and lifecycle, and what snapshots do and do not protect.", what: `Cloud storage comes in three access models: - **Block** (EBS, Azure Managed Disks, Persistent Disk): a raw volume attached to one instance (some support limited multi-attach), formatted with a filesystem. Lowest latency, zonal, sized and billed by provisioned capacity and performance. - **File** (EFS, Azure Files, Filestore): a shared POSIX/NFS or SMB filesystem mounted by many clients. Convenient for shared state and lift-and-shift; metadata operations and small files are the weak spot. - **Object** (S3, Azure Blob Storage, Cloud Storage): immutable objects addressed by key over HTTP APIs, effectively unlimited scale, regional or multi-region, very high durability, higher per-request latency, billed per GB-month plus requests and egress. Two properties are routinely confused: **durability** (probability data is not lost) and **availability** (probability you can access it right now).`, why: `Storage choice drives cost, latency, failure behaviour and recovery. Putting a database on a network file share causes latency and locking problems; serving millions of small files from block volumes forces you to manage fleets; storing backups in the same account and region as production means one credential compromise or regional event destroys both. Senior engineers are expected to reason in IOPS, throughput, durability and RPO, not product names.`, problem: `Incidents in this space are expensive: a database on a volume provisioned for 3,000 IOPS starts queueing when a batch job adds random reads, and latency jumps from 1 ms to 50 ms; a team assumes snapshots are backups, then an attacker with the same credentials deletes both; a lifecycle rule moves objects to an archive tier with a retrieval time of hours during an incident that needs them in minutes; a single-AZ volume becomes unavailable during an AZ event and the service has no replica.`, how: `Understand the mechanism behind each property. - **Object durability.** Providers advertise designs for **99.999999999% (eleven nines)** annual durability for standard object storage. Mechanism: each object is split into fragments with **erasure coding** (e.g. k data + m parity fragments, any k recover the object) spread across many devices and, for regional classes, across multiple AZs; continuous background **scrubbing** verifies checksums and repairs lost fragments faster than further failures accumulate. Durability is a function of fragment spread, failure rates and repair time. It does **not** protect against you deleting or overwriting data: that is what versioning, object lock and cross-account replication are for. - **Availability** is lower and separate: standard object storage availability SLAs are typically in the 99.9\u201399.99% range. Data can be perfectly durable and temporarily unreachable. - **Block performance.** Three numbers: **IOPS** (operations/s, matters for random small I/O like databases), **throughput** (MB/s, matters for sequential scans and streaming), and **latency** (per-op, network-attached block is sub-millisecond to low milliseconds; local NVMe is lower). Throughput \u2248 IOPS \xD7 I/O size, and each volume and each instance has caps; the instance's storage bandwidth limit is often the hidden ceiling. Queue depth links them: achievable IOPS \u2248 queue depth / latency (Little's law). - **Block durability** is replicated within an AZ, so annual failure rates are low but not eleven nines; snapshots (incremental, stored in object storage) are how you get cross-AZ and cross-region recovery points. - **Object consistency.** Major object stores now provide **strong read-after-write consistency** for object PUTs and DELETEs and for listings (S3 since December 2020; Cloud Storage and Azure Blob are strongly consistent too). There is still no multi-object transaction; renaming is copy + delete, and cross-region replication is asynchronous. - **Storage classes and lifecycle.** Hot/standard, infrequent access (cheaper storage, retrieval fee, minimum duration), archive (cheapest, retrieval minutes to hours). Lifecycle rules move or expire objects by age; tier based on actual access patterns, and model retrieval and minimum-duration charges. - **Snapshots vs backups.** A snapshot is a point-in-time copy, typically crash-consistent unless you quiesce the application. A **backup** strategy needs isolation (separate account, immutable or locked storage), multiple recovery points, and tested restores. Rule of thumb 3-2-1: three copies, two media/services, one offsite/isolated.`, components: [ { name: "Block volume", description: "Zonal, attached to an instance, with provisioned or baseline IOPS and throughput. Best for databases and boot disks; size performance explicitly." }, { name: "Local instance storage", description: "NVMe directly attached to the host: lowest latency and highest IOPS, but ephemeral, lost when the instance stops or the host fails. Use for caches, scratch, or replicated databases that tolerate node loss." }, { name: "Shared file system", description: "NFS/SMB semantics for many clients; throughput may scale with stored size or provisioned capacity. Weak at metadata-heavy workloads and file locking across clients." }, { name: "Object storage", description: "HTTP API, flat key namespace, erasure-coded across devices and AZs, strong read-after-write consistency, per-request and egress pricing, versioning and object lock for protection." }, { name: "Storage classes and lifecycle", description: "Tiering by access frequency with different storage, retrieval and minimum-duration costs; automated by lifecycle rules or intelligent tiering." }, { name: "Snapshots and replication", description: "Incremental point-in-time copies of volumes; asynchronous cross-region replication for objects. Both have RPO greater than zero and need isolation from the source credentials." } ], misconceptions: [ { myth: "Eleven nines of durability means my data cannot be lost.", reality: "It covers hardware failure. It does not cover deletion, overwrite, ransomware, a bad lifecycle rule or a compromised credential. Use versioning, object lock, and replication to an isolated account." }, { myth: "Durability and availability are the same thing.", reality: "Durability is about not losing data; availability is about reaching it now. Object stores design for eleven nines durability but offer three-to-four nines availability." }, { myth: "Snapshots are backups.", reality: "Snapshots in the same account and region share the source\u2019s blast radius and credentials. They become backups when copied to an isolated, immutable location with tested restores." }, { myth: "A bigger volume is always faster.", reality: "Performance depends on the volume type\u2019s IOPS/throughput settings and the instance\u2019s storage bandwidth cap. A large volume on a small instance can be limited by the instance." } ], example: { title: "Sizing a database volume: IOPS, throughput and the instance cap", description: `A PostgreSQL primary needs 6,000 random 16 KB reads/s at peak plus 2,000 writes/s, and a nightly sequential scan at 400 MB/s. Volume caps and instance bandwidth vary by provider and type; the numbers below are illustrative.`, code: `Random I/O: (6,000 + 2,000) ops/s = 8,000 IOPS 8,000 * 16 KB = ~128 MB/s Sequential: 400 MB/s at 256 KB I/O = ~1,600 IOPS Provision: >= 10,000 IOPS (25% headroom), >= 600 MB/s throughput (covers random 128 + scan 400 = 528 MB/s if they overlap) Little's law check (at ~1 ms per op): queue depth needed = IOPS * latency = 8,000 * 0.001 = 8 outstanding I/Os Instance cap: if the instance's storage bandwidth is 600 MB/s, random + scan together (128 + 400 = 528 MB/s) fits, barely. Run the scan on a read replica to protect the primary. Durability plan: - synchronous standby in another AZ (RPO ~0 for AZ loss) - continuous WAL archiving to object storage (PITR) - daily snapshot copied to a separate backup account, locked 35 days - quarterly restore test, measured RTO`, language: "text" }, exercise: { prompt: `Design storage for a media platform: 2 PB of user-uploaded videos (90% are rarely accessed after 30 days), a metadata database, and transcoding workers that need fast scratch space. Requirements: survive an AZ loss with no data loss for uploads, survive account compromise, and minimise cost. Specify storage types, classes, protection mechanisms and one cost estimate.`, solution: `- **Videos:** regional object storage (multi-AZ erasure coding gives AZ-loss durability). Lifecycle: standard for 30 days, then infrequent access; very old content to archive only if a retrieval delay is acceptable for that product. Enable versioning and object lock (or deletion protection) for a retention window, and replicate to a separate account (and optionally region) with independent credentials. - **Metadata DB:** block volumes with a multi-AZ synchronous standby, PITR via log archiving, and snapshots copied to the backup account. - **Transcoding scratch:** local NVMe on the workers (ephemeral, fast); inputs and outputs are in object storage, so a lost node just retries the job. - **Cost sketch (illustrative prices):** 2 PB = 2,000,000 GB. All standard at ~$0.021/GB-month \u2248 $42k/month. With 10% standard and 90% infrequent access at ~$0.0125/GB-month \u2248 $4.2k + $22.5k = **~$26.7k/month**, saving ~$15k/month before retrieval fees. Check that minimum-duration and per-GB retrieval charges do not eat the saving for content that gets re-popularised.` }, faq: [ { q: "When should I use a shared file system instead of object storage?", a: "When applications need POSIX semantics (legacy apps, shared home directories, some ML training pipelines) and cannot be changed. For new applications, object storage is cheaper and scales better; use file systems sparingly and watch metadata performance." }, { q: "Are object stores eventually consistent?", a: "Not anymore for the major providers: S3, Cloud Storage and Azure Blob provide strong read-after-write consistency for object operations. Cross-region replication is still asynchronous, and there are no multi-object transactions." }, { q: "How do I protect against ransomware in cloud storage?", a: "Versioning plus object lock (WORM) with a retention period, backups in a separate account with separate admin identities, MFA/approval for deletion, and alerting on mass deletes or encryption-key changes." } ], keyTerms: ["block vs file vs object", "durability vs availability", "eleven nines", "erasure coding", "IOPS", "throughput", "queue depth", "read-after-write consistency", "storage class / lifecycle", "snapshot", "object lock", "3-2-1 backup"], deeper: `At staff level the question is **correlated failure**, because durability math assumes independent failures. Shared firmware bugs, a bad deploy of the storage control plane, a region-wide event, or one compromised IAM principal are correlated and are the real risks: that is why isolation (separate accounts, regions, credentials and ideally providers for the most critical backups) matters more than an extra nine. **Small-object economics** often dominate cost: per-request charges and per-object metadata overhead mean billions of tiny objects should be batched or packed. **Egress** turns "cheap" storage into an expensive serving path; front with a CDN or keep compute co-located. Finally, measure RPO and RTO in drills: a backup that takes 40 hours to restore 200 TB is a backup with a 40-hour RTO, so test restore throughput, not just backup success.`, interview: { seniorAnswer: `Pick storage by access pattern: block for low-latency single-writer state (databases), file for shared POSIX needs, object for everything large, shared or durable. Separate durability (eleven nines via erasure coding across AZs plus scrubbing) from availability (three to four nines) and from protection against humans and attackers (versioning, object lock, isolated-account backups). Size block storage in IOPS, throughput and instance caps, explain object consistency (strong read-after-write on major providers, async cross-region replication), and quantify tiering savings net of retrieval fees.`, followUps: [ { q: "How does an object store achieve eleven nines?", a: "Erasure coding across many devices and AZs so multiple simultaneous failures are survivable, checksums on every fragment, continuous scrubbing and fast repair so the window of reduced redundancy is short." }, { q: "Your database p99 latency spikes during nightly jobs. Storage-related causes?", a: "Volume IOPS or throughput cap reached, instance storage bandwidth cap reached, burst credits exhausted on burstable volume types, or the job saturating queue depth. Check volume metrics (queue length, throttling), move the job to a replica, or provision more performance." }, { q: "What is the RPO of cross-region object replication?", a: "Greater than zero: replication is asynchronous, typically seconds to minutes, with some providers offering an SLA-backed replication time for a fee. Design for the lag and monitor replication backlog." } ], redFlags: [ "Equating durability with availability", "Calling same-account snapshots a backup strategy", "Claiming object storage is eventually consistent (outdated for major providers)", "Sizing volumes by capacity only, ignoring IOPS/throughput and instance caps" ], numbers: [ "Standard object storage designed for 99.999999999% annual durability; availability SLAs ~99.9\u201399.99%", "Throughput \u2248 IOPS \xD7 I/O size; IOPS \u2248 queue depth / latency", "Network block latency ~sub-ms to low ms; local NVMe tens to low hundreds of \xB5s (order of magnitude)", "3-2-1 backup rule: 3 copies, 2 media, 1 offsite/isolated" ] }, references: [ { title: "AWS Well-Architected Framework", url: "https://aws.amazon.com/architecture/well-architected/" }, { title: "Google Cloud Well-Architected Framework", url: "https://cloud.google.com/architecture/framework" }, { title: "Brendan Gregg: The USE Method", url: "https://www.brendangregg.com/usemethod.html" } ] }; var dataDatabases = { id: "infra-data-databases", title: "Databases at scale: replication, sharding and operations", stage: 2, order: 2, objectives: ["data-databases"], scope: "senior", estMinutes: 35, summary: "Relational vs NoSQL by access pattern, synchronous vs asynchronous replication and replication lag, read-your-writes, choosing shard keys and avoiding hot partitions, resharding, connection pooling, and online schema migrations.", what: `Operating databases at scale is about three axes: **replication** (copies for durability, availability and read scaling), **partitioning/sharding** (splitting data so writes and storage scale beyond one node), and **operations** (connections, schema change, failover, backups). **Relational** databases (PostgreSQL, MySQL, and managed offerings such as RDS/Aurora, Azure Database, Cloud SQL/AlloyDB, plus distributed SQL like Spanner or CockroachDB) give transactions, joins and a flexible query model. **NoSQL** stores (key-value and wide-column such as DynamoDB, Cosmos DB, Bigtable, Cassandra; document stores such as MongoDB) trade query flexibility for predictable scale-out on a known access pattern.`, why: `The database is usually the hardest component to scale and the most expensive to get wrong: it holds state, it is where consistency is decided, and changes are slow and risky. Senior interviews almost always reach "what happens when the database is the bottleneck", and the expected answer is a ladder of options with costs, not a jump straight to sharding.`, problem: `Typical failures: a user updates their profile, the page reloads from a lagging replica and shows the old value; a shard key on \`created_date\` sends all writes to the newest partition; a celebrity account turns one partition hot; 400 application pods each open 20 connections and exhaust the database's connection limit; an \`ALTER TABLE\` takes an exclusive lock and blocks all writes for minutes; failover to an async replica silently loses the last seconds of committed writes.`, how: `Climb the ladder only as far as needed. - **Optimise first**: indexes, query plans, avoiding N+1 queries, and vertical scaling. A large modern instance handles a lot. - **Replication.** The primary ships its log (WAL/binlog) to replicas. **Synchronous** replication waits for at least one replica to acknowledge before commit: RPO \u2248 0 for that replica, at the cost of commit latency (cross-AZ ~1\u20132 ms extra) and availability coupling. **Asynchronous** replication commits locally and ships later: no latency cost, but **replication lag** (normally milliseconds, seconds to minutes under load or long transactions) and possible data loss on failover. Common pattern: synchronous standby in another AZ for HA, async replicas for reads and cross-region DR. - **Read-your-writes** with replicas: route a user's reads to the primary for a short window after they write, or track the write's log position (LSN/GTID) and read from a replica only once it has caught up, or keep session-critical reads on the primary. - **Connection management.** Each connection costs memory and, for process-per-connection databases like PostgreSQL, a process; thousands of idle connections hurt. Use a pooler (PgBouncer, RDS Proxy, or similar) in transaction-pooling mode so thousands of clients share tens to low hundreds of server connections; size application pools so pods \xD7 pool size stays under the limit. - **Partitioning/sharding.** Choose a **shard key** that (1) appears in most queries, so queries hit one shard, (2) has high cardinality and even distribution, and (3) avoids monotonic hot spots. Hash on tenant or user ID is common; time-based keys need a hash prefix or bucket. **Hot keys** (a celebrity, a big tenant) need special handling: split the key (\`key#0..N\` write sharding with read fan-in), move big tenants to dedicated shards, or cache. Cross-shard queries and transactions become expensive or unsupported. - **Resharding.** Use many **logical shards** (e.g. 1,024) mapped to fewer physical nodes, so growth moves logical shards rather than rehashing all data; consistent hashing serves the same goal. Migration pattern: copy snapshot, stream changes (CDC), verify, cut over per shard with a brief write freeze or dual writes. - **Online schema migration.** Expand/contract: add nullable column or new table (expand), dual-write and backfill in batches, switch reads, then drop old (contract), each step deployed separately and backward-compatible with the previous app version. For large tables, use online tools (e.g. gh-ost or pt-online-schema-change for MySQL; for PostgreSQL, operations like \`CREATE INDEX CONCURRENTLY\`) and set \`lock_timeout\` so DDL fails fast instead of queueing behind long transactions and blocking everyone.`, components: [ { name: "Primary and replicas", description: "Single writer with log-shipping replicas. Sync for zero-RPO failover, async for read scaling and DR with lag." }, { name: "Failover controller", description: "Detects primary failure, promotes a replica, repoints clients (DNS or proxy). Must fence the old primary to avoid split brain; failover time is commonly tens of seconds to a couple of minutes on managed services." }, { name: "Connection pooler / proxy", description: "Multiplexes many client connections onto few server connections, smooths failover, and protects the database from connection storms." }, { name: "Shard map and router", description: "Maps keys to logical shards and logical shards to physical nodes; lives in the application, a proxy layer, or the database itself (distributed SQL, managed NoSQL)." }, { name: "Change data capture (CDC)", description: "Streams committed changes from the log for replication, resharding, cache invalidation and analytics without dual writes in application code." }, { name: "Schema migration tooling", description: "Versioned migrations, expand/contract discipline, online DDL tools, lock timeouts and batched backfills." } ], misconceptions: [ { myth: "Read replicas are a free read-scaling win.", reality: "They introduce replication lag, so reads may be stale and read-your-writes breaks. Applications must tolerate or route around staleness, and replica lag needs monitoring and alerting." }, { myth: "Failover to a replica never loses data.", reality: "Only if the promoted replica was synchronous. Async failover loses whatever had not replicated, typically the last seconds of writes; that is your RPO." }, { myth: "NoSQL scales automatically.", reality: "It scales if your partition key distributes load evenly and your queries match the key. A bad key creates hot partitions that throttle at a single partition\u2019s limit regardless of total capacity." }, { myth: "Schema changes are just a migration file.", reality: "On a large, busy table DDL can take locks that block writes or rewrite the table for hours. Use expand/contract, online tools, lock timeouts and batched backfills, and keep each step compatible with the running code." } ], example: { title: "Connection budget and safe DDL on PostgreSQL", description: `400 pods each configured with a pool of 20 connections would open 8,000 connections against a database whose max_connections is ~2,000. A transaction-mode pooler collapses this to a few hundred server connections. Separately, adding a column with a default and an index on a 500 M-row table must not block writes.`, code: `# Connection budget clients: 400 pods * 20 = 8,000 client connections -> PgBouncer (transaction mode) server pool: ~200 connections (roughly a few per CPU core, tune by load test) -- Safe DDL (PostgreSQL 11+: ADD COLUMN with a constant default is metadata-only) SET lock_timeout = '3s'; -- fail fast instead of queueing behind long txns SET statement_timeout = '0'; ALTER TABLE orders ADD COLUMN region text DEFAULT 'unknown'; CREATE INDEX CONCURRENTLY idx_orders_region ON orders (region); -- Backfill in batches, not one giant UPDATE UPDATE orders SET region = c.region FROM customers c WHERE orders.customer_id = c.id AND orders.id BETWEEN :start AND :start + 10000 AND orders.region = 'unknown';`, language: "text" }, exercise: { prompt: `A multi-tenant SaaS on a single PostgreSQL primary (64 vCPU) is at 75% CPU with 80% of load being reads; writes are growing 8% per month; the largest tenant generates 15% of all traffic. Lay out a scaling roadmap for the next 24 months, including when you would shard, the shard key, and how you handle the big tenant.`, solution: `**Now:** query and index tuning, a pooler, and 2\u20133 async read replicas for read-heavy, staleness-tolerant endpoints, with read-your-writes routing (primary for a few seconds after a user's write, or LSN-based). Expect primary CPU to fall well below 50%. **Write growth:** 8%/month compounds to ~2.5\xD7 in 12 months and ~6.3\xD7 in 24 months. Writes are ~20% of today's load, so the primary handles that for roughly a year after offloading reads; vertical headroom buys a little more. **Months 9\u201315: shard by tenant_id.** Almost all queries are tenant-scoped, cardinality is high, and it enables per-tenant isolation. Use ~1,024 logical shards on a handful of physical clusters, a shard directory (tenant \u2192 logical shard), and CDC-based migration per tenant with a short write freeze per tenant at cutover. **Big tenant:** 15% of traffic would make its shard hot, so place it on a dedicated physical cluster (the directory makes this a mapping change), and plan intra-tenant partitioning by a secondary key if it keeps growing. **Alternatives to evaluate:** distributed SQL (avoids app-level sharding at the cost of latency and migration effort) or moving specific high-volume tables to a key-value store.` }, faq: [ { q: "When should I choose NoSQL over relational?", a: "When the access patterns are known and key-based, scale or availability requirements exceed a single primary, and you can give up ad-hoc joins and multi-row transactions (or use the limited transactions NoSQL offers). Relational remains the default for most business data." }, { q: "How do I monitor replication lag?", a: "Track replica lag in bytes and seconds (log position difference and replay timestamp), alert when it exceeds what readers can tolerate, and automatically pull lagging replicas out of read rotation." }, { q: "Is distributed SQL a replacement for sharding?", a: "It automates sharding, rebalancing and cross-shard transactions with consensus replication, at the cost of higher write latency (consensus round trips), cost and operational novelty. Data modelling for locality still matters to avoid cross-region transactions." } ], keyTerms: ["synchronous vs asynchronous replication", "replication lag", "read-your-writes", "RPO on failover", "connection pooling", "shard key", "hot partition", "logical shards", "resharding", "CDC", "expand/contract migration", "lock_timeout"], deeper: `The staff-level view is that **consistency is a product decision expressed in routing**: which endpoints accept stale reads, how stale, and what the user sees during failover. Make it explicit per endpoint rather than letting the ORM choose. **Failover safety** depends on fencing: the old primary must be prevented from accepting writes (by revoking its role, isolating it in the proxy, or STONITH) or you get split brain and divergent histories that are painful to reconcile. **Long-running transactions** are a hidden global hazard in MVCC databases: they block vacuum (bloat), hold back replication on some setups, and make DDL queue behind them, which then blocks every other query. Finally, **multi-region writes** force a choice between consensus latency on every write (Spanner-style), single-region writes with regional read replicas, or partitioning data by home region; most systems should pick the last.`, interview: { seniorAnswer: `Present a scaling ladder with costs: tune queries and indexes, scale vertically, add a pooler, add async read replicas with explicit read-your-writes handling, then partition by a key that matches the access pattern. State replication trade-offs (sync for RPO\u22480 at a latency cost, async for reads and DR with lag and failover loss), the shard-key criteria (query locality, cardinality, no monotonic hot spots), how hot keys are split or isolated, and how resharding works with logical shards and CDC. Mention online schema migration (expand/contract, lock timeouts) and connection budgets as day-2 realities.`, followUps: [ { q: "How would you implement read-your-writes with async replicas?", a: "Capture the commit LSN/GTID on write, store it in the session, and only read from a replica whose replay position is at or past it; otherwise go to the primary. A simpler variant routes a user to the primary for N seconds after any write." }, { q: "A DynamoDB-style table is throttling even though total capacity is underused. Why?", a: "A hot partition: traffic concentrates on a few partition keys, hitting per-partition throughput limits. Fix the key design (higher cardinality, write sharding with suffixes) or cache hot reads." }, { q: "How do you migrate a column type on a 2 TB table with zero downtime?", a: "Expand/contract: add a new column, dual-write from the app (or triggers/CDC), backfill in batches with throttling, verify, switch reads, stop writing the old column, drop it later. Each step is a separate deploy compatible with the previous app version." }, { q: "What is split brain and how is it prevented?", a: "Two nodes both acting as primary after a partition, accepting conflicting writes. Prevent with quorum-based leader election, fencing of the old primary, and clients that connect via a proxy or endpoint that only points to the elected leader." } ], redFlags: [ "Jumping to sharding before replicas, tuning and vertical scaling", "Ignoring replication lag and read-your-writes", "Choosing a timestamp or auto-increment as the shard key", "Unbounded per-pod connection pools", "Running blocking DDL on large tables in production" ], numbers: [ "Sync replication across AZs adds roughly a cross-AZ RTT (~1\u20132 ms) per commit", "Async replica lag normally ms, can grow to minutes under load", "Managed database failover commonly tens of seconds to ~2 minutes", "Compound growth: 8%/month \u2248 2.5\xD7/year" ] }, references: [ { title: "PostgreSQL docs: High Availability, Load Balancing, and Replication", url: "https://www.postgresql.org/docs/current/high-availability.html" }, { title: "Jepsen: Consistency Models", url: "https://jepsen.io/consistency" }, { title: "The System Design Primer", url: "https://github.com/donnemartin/system-design-primer" } ] }; var dataCaching = { id: "infra-data-caching", title: "Caching: patterns, invalidation and failure modes", stage: 2, order: 3, objectives: ["data-caching"], scope: "senior", estMinutes: 30, summary: "Cache-aside, read-through, write-through and write-back; TTLs and invalidation; stampede and thundering-herd mitigation with request coalescing, jittered TTLs and stale-while-revalidate; hot keys; and cache tiers from CDN to in-process.", what: `A cache stores the result of expensive work closer to where it is needed so the next request is cheaper. Tiers, from nearest to farthest: **in-process** memory (nanoseconds, per-instance, inconsistent across instances), **distributed cache** (Redis, Memcached; managed as ElastiCache/MemoryDB, Azure Cache for Redis / Azure Managed Redis, Memorystore; sub-millisecond within an AZ), **CDN/edge** (close to users, for HTTP responses), and database-internal buffer caches. Patterns describe who populates and updates the cache: **cache-aside** (application reads cache, on miss reads the database and fills the cache), **read-through** (the cache library loads on miss), **write-through** (writes go to cache and database synchronously), and **write-back/write-behind** (writes go to cache and are flushed later).`, why: `Caching is the cheapest way to cut latency and protect databases, and also one of the most common causes of outages and correctness bugs. A cache at 95% hit ratio means the database sees 5% of reads; if the cache empties, the database sees 20\xD7 its normal read load instantly. Interviewers look for whether you treat the cache as an optimisation that can fail, and whether you can reason about staleness.`, problem: `Classic incidents: a cache cluster restart drops the hit ratio to zero and the database collapses under the miss storm; a popular key expires and 10,000 concurrent requests all miss and recompute it (stampede); a race between invalidation and a concurrent read repopulates the cache with stale data that then lives for the full TTL; a single viral key saturates one cache node's network while others idle; write-back caching loses acknowledged writes when a node dies.`, how: `Design caching as a system with explicit staleness and failure behaviour. - **Cache-aside (default).** Read: get from cache; on miss, read DB, set with TTL. Write: update DB, then **delete** the cache key (not set it), so the next reader repopulates from the source of truth. Deleting avoids races where two writers set values out of order, though a read-before-delete race can still write back stale data; short TTLs bound that window, and versioned values or lease tokens close it. - **Write-through** keeps cache and DB in sync on write at the cost of write latency and caching data that may never be read. **Write-back** gives fast writes and write coalescing but risks loss of acknowledged writes; use only when loss is acceptable or the cache is itself durable and replicated. - **TTLs and invalidation.** TTL is the safety net bounding staleness; explicit invalidation (on write, or via **CDC** from the database log) keeps hot data fresh. Choose TTL per data type by how stale is acceptable and how expensive a miss is. - **Stampede / thundering herd mitigation.** - **Request coalescing** (single-flight): only one request per key recomputes on a miss; others wait for its result. In a distributed setting, take a short lock/lease in the cache. - **Jittered TTLs**: TTL = base \xB1 random (e.g. 10\u201320%) so keys populated together do not expire together. - **Stale-while-revalidate / early refresh**: serve the stale value while one worker refreshes; probabilistic early expiration refreshes hot keys slightly before TTL. - **Cold-start protection**: warm caches before shifting traffic, ramp traffic gradually, and rate-limit database access on misses so a cold cache degrades latency instead of taking the database down. - **Hot keys.** Detect via per-key metrics or sampling. Mitigate with an in-process L1 cache for the hottest keys (short TTL), replicate the key across nodes with suffixes (\`key#1..N\`, read a random one), or read from replicas. - **Sizing and eviction.** Working set must fit in memory; LRU/LFU eviction under pressure; monitor hit ratio, evictions, memory fragmentation and latency. Avoid huge values and unbounded collections that block single-threaded engines. - **Failure behaviour.** Timeouts on cache calls shorter than the DB path, circuit-break to the database with load shedding if the cache is down, and never make the cache the only copy of data you cannot lose (unless intentionally using a durable store).`, components: [ { name: "In-process cache (L1)", description: "Fastest, no network, but per-instance copies diverge and memory is limited. Ideal for small, hot, rarely-changing data with short TTLs." }, { name: "Distributed cache (L2)", description: "Shared across instances, sharded by key (client-side consistent hashing or cluster mode), optional replicas for availability. The main database shield." }, { name: "CDN / edge cache", description: "HTTP response caching near users with Cache-Control, request collapsing and stale-while-revalidate. Best for public or cacheable-per-segment responses." }, { name: "Invalidation pipeline", description: "Delete-on-write in the app or CDC-driven invalidation from the database log; TTL as a backstop for missed events." }, { name: "Stampede controls", description: "Single-flight coalescing, distributed leases, jittered TTLs, early refresh and serve-stale policies." }, { name: "Cache observability", description: "Hit ratio per key prefix, eviction rate, memory, p99 latency, hot-key detection and the database read rate as the true measure of cache effectiveness." } ], misconceptions: [ { myth: "On write, update the cache with the new value.", reality: "Concurrent writers can set values in a different order than they committed to the database, leaving the cache permanently stale until TTL. Deleting the key on write and letting the next read repopulate is safer." }, { myth: "A cache is optional infrastructure; if it fails we just go to the database.", reality: "Once the database is sized for the cache\u2019s hit ratio, losing the cache multiplies database load by 1 / (1 \u2212 hit ratio). The cache is a capacity dependency; plan for its failure with warming, rate limits and degraded modes." }, { myth: "Short TTLs solve consistency.", reality: "They bound staleness but increase miss rate and stampede frequency. Combine moderate TTLs with explicit invalidation and coalescing." }, { myth: "Higher hit ratio is always better.", reality: "Past a point, chasing hit ratio means caching rarely-read data and long TTLs that increase staleness. Optimise for database load and latency SLOs, not the hit ratio alone." } ], example: { title: "Cache-aside with coalescing, jitter and serve-stale", description: `Read path for a product page cache. Values carry a soft expiry (refresh early) and a hard TTL (evict). A short lease prevents stampedes: one request refreshes while others serve the stale value or wait briefly.`, code: `get_product(id): v = cache.get("product:" + id) if v and now < v.soft_expiry: return v.data # fresh hit if v: # stale but present if cache.set_nx("lease:product:" + id, ttl=5s): async refresh(id) # one refresher only return v.data # serve stale meanwhile # hard miss if cache.set_nx("lease:product:" + id, ttl=5s): return refresh(id) sleep(50ms); retry cache.get (bounded), else read DB with rate limit refresh(id): data = db.read(id) base = 300s ttl = base * random(0.9, 1.1) # jitter cache.set("product:" + id, {data, soft_expiry: now + ttl * 0.8}, ttl = ttl + 60s) on_write(id): db.update(...); cache.delete("product:" + id)`, language: "text" }, exercise: { prompt: `A service handles 50k reads/s with a 96% cache hit ratio; the database comfortably handles 4k reads/s and falls over at ~8k. A cache node failure (1 of 4 shards) drops the overall hit ratio. (a) Estimate database load during the failure and after a full cache flush. (b) Propose design changes so neither event causes an outage.`, solution: `**(a)** Normal DB load = 50k \xD7 0.04 = **2k reads/s**. Losing 1 of 4 shards makes ~25% of keys miss: hit ratio \u2248 0.96 \xD7 0.75 = 0.72 \u2192 DB load \u2248 50k \xD7 0.28 = **14k reads/s**, well past the ~8k collapse point. A full flush means **50k reads/s**, 25\xD7 normal. **(b)** - Replicas per shard with automatic failover so a node loss does not empty a shard; spread shards and replicas across AZs. - Consistent hashing so a lost node only remaps its own keys. - Request coalescing so concurrent misses for the same key produce one DB read; with skewed popularity this cuts miss traffic dramatically. - A database-side concurrency limit or token bucket on the miss path, with load shedding or serve-stale for non-critical reads; latency degrades instead of the DB falling over. - An in-process L1 for the hottest keys, absorbing a large share of reads even when L2 is cold. - Warm-up procedure: pre-populate hot keys from a snapshot or recent access log before shifting traffic, and ramp traffic. - Capacity: decide explicitly whether the DB must survive a single-shard loss (size to ~14k reads/s, or reduce the gap with the controls above).` }, faq: [ { q: "Redis or Memcached?", a: "Memcached is a simple multithreaded key-value cache. Redis adds data structures, replication, persistence options, Lua scripting and cluster mode; most teams pick Redis-compatible services for flexibility. Note that Redis executes commands on a single main thread, so large values or O(N) commands block other clients." }, { q: "How do I cache data that is personalised?", a: "Cache shared fragments globally and per-user data under per-user keys with shorter TTLs, or cache per segment (locale, plan). At the CDN, only cache personalised responses if the cache key includes the identity safely; otherwise you risk serving one user\u2019s data to another." }, { q: "How do I keep cache and database consistent?", a: "You cannot make them perfectly consistent without distributed transactions. Use delete-on-write plus TTL, or CDC-driven invalidation from the database log for reliability, and design reads to tolerate bounded staleness; for strict consistency, read from the source of truth." } ], keyTerms: ["cache-aside", "read-through", "write-through", "write-back", "TTL", "invalidation", "cache stampede / thundering herd", "request coalescing (single-flight)", "jittered TTL", "stale-while-revalidate", "hot key", "hit ratio"], deeper: `Staff-level caching is about **metastable failure**: a system that is stable with a warm cache and stays down after a cold start, because the miss storm overloads the database, slow responses cause timeouts and retries, and the cache never warms because requests fail before filling it. Breaking the loop needs load shedding and admission control on the miss path, not more capacity. **Lease-based caching** (the cache hands a token to the first misser; sets without the current token are rejected) addresses both stampedes and the stale-set race and is the pattern large-scale memcache deployments describe. **Cache keys are an API**: changing a serialisation format or key schema is a migration that needs versioned keys (\`v2:product:123\`) and a warm-up plan. Finally, security: a cache shared across tenants must namespace keys by tenant, and an edge cache that ignores an authorisation header is a data leak.`, interview: { seniorAnswer: `Default to cache-aside with delete-on-write and a TTL backstop, add CDC-driven invalidation when freshness matters, and state the staleness each endpoint tolerates. Treat the cache as a capacity dependency: quantify database load as total reads \xD7 (1 \u2212 hit ratio) for normal, shard-loss and cold-cache cases, and design for each with replicas, consistent hashing, request coalescing, jittered TTLs, serve-stale, rate-limited misses and warm-up. Handle hot keys with L1 caching or key replication, and pick write-through or write-back only with explicit durability reasoning.`, followUps: [ { q: "What is a cache stampede and how do you prevent it?", a: "Many concurrent requests miss the same key (expiry or cold cache) and all hit the database. Prevent with single-flight/lease coalescing, serving stale while one request refreshes, probabilistic early refresh and jittered TTLs." }, { q: "Why delete instead of update the cache on write?", a: "Updates from concurrent writers can arrive out of order, caching a value older than the database; delete makes the next read fetch the current value. A residual race remains with concurrent readers, bounded by TTL or closed by leases/versions." }, { q: "One key receives 200k reads/s. What do you do?", a: "Serve it from an in-process cache on each instance with a short TTL, or replicate it across N cache keys/nodes and read a random copy; consider pushing it to the CDN if it is a public response." }, { q: "When is write-back acceptable?", a: "When losing recent writes is tolerable (counters, analytics, view counts) or when the cache is replicated and persistent enough to meet the RPO. Never for financial or user-critical writes without durable acknowledgement." } ], redFlags: [ "Treating the cache as optional with no plan for a cold start", "Setting the cache on write without considering ordering races", "No TTL on cached entries", "Ignoring hot keys and stampedes", "Caching authenticated responses at the CDN without identity in the key" ], numbers: [ "DB read load = total reads \xD7 (1 \u2212 hit ratio); 99% \u2192 90% hit ratio is 10\xD7 more DB reads", "In-process ~ns\u2013\xB5s; distributed cache in-AZ ~sub-ms; cross-AZ adds ~1 ms (order of magnitude)", "TTL jitter commonly \xB110\u201320%", "Losing 1 of N cache shards without replicas removes ~1/N of hits" ] }, references: [ { title: "Azure Architecture Center: Cloud design patterns (Cache-Aside)", url: "https://learn.microsoft.com/en-us/azure/architecture/patterns/" }, { title: "Google SRE book: Addressing Cascading Failures", url: "https://sre.google/sre-book/addressing-cascading-failures/" }, { title: "The System Design Primer", url: "https://github.com/donnemartin/system-design-primer" } ] }; var infraLessons1 = [ netFundamentals, netCloud, netEdge, computeModels, computeScaling, computePlatform, storageTypes, dataDatabases, dataCaching ]; // ../../packages/content/src/infra/lessons-2.ts var infraLessons2 = [ // ---------------------------------------------------------------- Stage 3: Distributed Systems { id: "infra-dist-theory", title: "Distributed systems theory: consistency, consensus and clocks", stage: 3, order: 1, objectives: ["dist-theory", "data-databases"], scope: "senior", estMinutes: 35, summary: "CAP stated correctly, PACELC, the consistency ladder from linearizable to eventual, quorum arithmetic, Raft, why clocks lie, and how fencing tokens stop split brain from corrupting data.", what: `Distributed systems theory is the small set of results that tell you what is **impossible**, what is **expensive**, and what is merely **hard** when state lives on more than one machine connected by an unreliable network. - **CAP**: when a network **partition** happens, a replicated system must choose, for the affected operations, between **consistency** (linearizability: every read sees the latest completed write or a newer one, in real-time order) and **availability** (every request to a non-failed node gets a non-error response). It says nothing about the normal, healthy case. - **PACELC** extends it: if **P**artition, choose **A** or **C**; **E**lse (normal operation), choose **L**atency or **C**onsistency. The "else" half is what you pay every day. - **Consistency models** describe which histories a client can observe. **Consensus** (Raft, Paxos) is how a group of nodes agrees on one ordered log despite crashes. **Clocks** decide whether "before" means anything across machines.`, why: `Almost every senior design question hides a consistency question: "can two users buy the last seat?", "can a deleted permission still grant access?", "what does a replica return during failover?". Interviewers use this topic to separate engineers who repeat "CAP: pick two" from those who can say **which operations** need linearizability, **what it costs in round trips**, and **what breaks** when the leader is partitioned. Operationally, the theory explains real incidents: stale reads after failover, two primaries both accepting writes (split brain), lease expiry during a long GC pause, and lost updates from last-writer-wins on skewed clocks.`, problem: `Networks drop, delay, duplicate and reorder messages, and a slow node is indistinguishable from a dead one. That creates three concrete problems: - **Failure detection is guesswork.** A timeout only says "no reply yet". Declare death too fast and you fail over a healthy-but-slow leader; too slow and you sit unavailable. - **Replicas diverge.** With asynchronous replication, the primary can acknowledge a write and crash before a replica has it; failover then loses the write. - **Time is not shared.** NTP keeps clocks within roughly milliseconds on a good network but can step, drift or be wrong by much more on a bad day, so wall-clock timestamps cannot safely order events on different machines.`, how: `**1. Pick the consistency model per operation, not per system.** From strongest to weakest: - **Linearizable**: operations appear to take effect atomically at one instant between call and return, in real-time order. Needed for locks, leader election, uniqueness and balances. Costs a quorum round trip (and cross-region latency if replicas span regions). - **Sequential**: all clients see one total order consistent with each client's program order, but not necessarily real time. - **Causal**: operations that are causally related are seen in order by everyone; concurrent ones may differ. - **Session guarantees** such as **read-your-writes** and monotonic reads: a single client never sees its own write disappear. Often implemented by sticky routing or by reading at a version no older than the client's last write. - **Eventual**: replicas converge if writes stop; no bound on staleness. **2. Quorums.** With N replicas, write to W and read from R. If **R + W > N**, every read set intersects every write set, so a read can see the latest acknowledged write (with versioning to pick it). N=3, W=2, R=2 tolerates one node down for both reads and writes. N=3, W=3, R=1 gives fast reads but any single failure blocks writes. Caveats: **sloppy quorums** with hinted handoff break the intersection, and concurrent writes still need conflict resolution, so R+W>N alone is not linearizability. **3. Consensus with Raft.** Time is divided into numbered **terms**. - Followers expect heartbeats from the leader. If none arrives within a **randomized election timeout** (the paper suggests on the order of 150\u2013300 ms), a follower becomes a candidate, increments the term, votes for itself and sends RequestVote. - A node grants at most one vote per term and only to a candidate whose log is **at least as up to date** as its own. A majority of votes makes a leader. Randomization makes split votes rare. - The leader appends client commands to its log and replicates via AppendEntries. An entry is **committed** once stored on a majority (and the entry is from the current term); only then is it applied and acknowledged. - A deposed leader that sees a higher term steps down. Because any two majorities overlap, a committed entry survives any leader change. A 5-node group tolerates 2 failures; a 3-node group tolerates 1. Even sizes add cost without adding tolerance. **4. Clocks.** Use **monotonic** clocks for durations and timeouts, never wall time. For ordering, use **logical clocks** (Lamport counters; vector clocks to detect concurrency) or **hybrid logical clocks** (HLC: a physical timestamp plus a logical counter, which stays close to wall time but never goes backwards and respects causality). Google Spanner instead bounds clock uncertainty with TrueTime and **waits out** the uncertainty interval before committing. **5. Split brain and fencing.** A leader holding a lease can pause (GC, VM migration) past lease expiry, wake up, and still believe it is leader. The fix is a **fencing token**: the lock service issues a monotonically increasing number with each lease (Raft's term works), the leader sends it with every write, and the storage layer **rejects any token lower than the highest it has seen**. Safety then no longer depends on clocks.`, components: [ { name: "CAP / PACELC", description: "CAP constrains behaviour **only during a partition**; PACELC adds the everyday latency vs consistency trade-off. Classify per operation: e.g. Dynamo-style stores lean PA/EL, Spanner-style lean PC/EC." }, { name: "Consistency models", description: "Linearizable > sequential > causal > session guarantees (read-your-writes, monotonic reads) > eventual. Each step down removes coordination and latency, and adds anomalies the application must tolerate." }, { name: "Quorums", description: "R + W > N guarantees read/write set overlap. Tune W and R for read-heavy vs write-heavy load and for which failures you must survive." }, { name: "Consensus (Raft / Paxos)", description: "Majority-replicated log with terms and leader election. Basis of etcd, Consul, ZooKeeper-like coordination and many distributed databases. Tolerates f failures with 2f+1 nodes." }, { name: "Clocks and ordering", description: "Physical clocks drift and step; logical, vector and hybrid logical clocks give causal ordering; bounded-uncertainty clocks (TrueTime) enable external consistency at the cost of commit wait." }, { name: "Fencing tokens", description: "Monotonic tokens checked by the resource itself, so a zombie leader with an expired lease cannot write." } ], misconceptions: [ { myth: "CAP means you pick any two of consistency, availability and partition tolerance.", reality: "Partitions are not optional on real networks. CAP says that **when** one occurs you must sacrifice C or A for the affected operations. Without a partition you can have both; the real everyday trade-off is latency vs consistency (PACELC)." }, { myth: "R + W > N makes a quorum store linearizable.", reality: "It guarantees overlap, not linearizability. Sloppy quorums, concurrent writes, last-writer-wins on skewed clocks and read repair timing can still produce anomalies. Linearizability needs consensus or careful read/write protocols." }, { myth: "Synchronized NTP clocks are good enough to order writes across servers.", reality: "NTP skew is typically milliseconds but unbounded on bad days, and clocks can jump. Last-writer-wins by wall clock silently drops writes. Use logical/hybrid clocks, versions, or consensus." }, { myth: "A distributed lock with a TTL guarantees mutual exclusion.", reality: "A paused holder can outlive its lease. Only a fencing token checked by the protected resource makes it safe." } ], example: { title: "Quorum and failure arithmetic for a 5-node, 3-AZ store", description: `Work the numbers aloud: what each configuration survives and what it costs. Assume intra-AZ RTT ~0.5 ms and cross-AZ RTT ~1\u20132 ms (order of magnitude).`, language: "text", code: `Replicas N = 5 placed 2 / 2 / 1 across AZ-a, AZ-b, AZ-c Config A: W=3, R=3 (R+W=6 > 5, overlap guaranteed) - survives 2 node failures for reads AND writes - lose AZ-a (2 nodes): 3 left -> still W=3, R=3 OK - write latency = 3rd-fastest ack ~ cross-AZ RTT (~1-2 ms) Config B: W=5, R=1 (fast reads) - any single node failure blocks ALL writes -> poor availability Config C: W=1, R=1 (R+W=2 <= 5) - fast, always available, reads may be stale: eventual only Raft group of 5 (majority = 3): - tolerates 2 failures; losing AZ-a + one more node -> 2 left -> no leader, writes stop - leader election ~ election timeout (150-300 ms) + one RequestVote round - 4 nodes would still need 3 for majority -> tolerates only 1: no gain Split brain check: old leader term=7 paused 20 s; new leader elected term=8 old leader wakes, sends write with token 7 -> storage has seen 8 -> REJECT` }, exercise: { prompt: `A payments team stores account balances in a multi-region database with asynchronous cross-region replication and reads from the local region. Users report that after topping up, the balance sometimes shows the old value, and during a regional failover a top-up was lost. Explain each symptom in consistency terms and propose fixes with their latency cost.`, solution: `- **Stale balance after top-up** is a **read-your-writes** violation: the write went to one replica, the read hit another that had not caught up. Fix cheaply with session consistency: route the user's reads to the write region for a short window, or attach the write's version/LSN to the session and have replicas wait (or redirect) until they have applied it. No cross-region cost on most reads. - **Lost top-up on failover** is the asynchronous-replication **RPO > 0** problem: the primary acknowledged before any other region had the write. Fix by making balance writes **synchronous to a quorum spanning regions** (consensus-backed), accepting an extra cross-region round trip (tens of ms) on writes, or by keeping a single home region per account and failing over only after confirming replication lag is zero. - Balances need **linearizable** writes (no double spend); browse-only data such as transaction history can stay eventual. Say this distinction explicitly.` }, faq: [ { q: "Is a single-leader database with sync replicas CP or AP?", a: `For writes it is CP-leaning: if the leader cannot reach its synchronous replica, it blocks or fails writes rather than diverge. Reads from async replicas are AP-ish (available, possibly stale). Classify per operation, not per product.` }, { q: "Why does Raft use majorities rather than all nodes?", a: `Any two majorities intersect, so a new leader is guaranteed to have every committed entry, while still tolerating a minority of failures. Requiring all nodes would make every single failure an outage.` }, { q: "Where do vector clocks show up in practice?", a: `In Dynamo-style stores and CRDT systems to detect **concurrent** updates (neither happened-before the other) so they can be merged or surfaced as siblings instead of silently overwritten.` } ], keyTerms: ["CAP theorem", "PACELC", "linearizability", "read-your-writes", "quorum (R + W > N)", "Raft term", "hybrid logical clock", "split brain", "fencing token"], deeper: `The FLP result shows that deterministic consensus is impossible in a fully asynchronous system with even one crash, which is why every practical protocol relies on timeouts (partial synchrony) for **liveness** while keeping **safety** independent of timing. Jepsen's consistency map is the best single picture of how models relate, including serializability (a transaction property) vs linearizability (a single-object, real-time property); "strict serializable" is both. Most databases default to weaker isolation (often read committed), and some engines' "serializable" or "repeatable read" levels are actually snapshot isolation, which permits write skew.`, interview: { seniorAnswer: `A strong answer states CAP precisely (a constraint **during partitions**), immediately moves to PACELC because latency is the everyday cost, and classifies **operations**: uniqueness, locks and money need linearizable writes via consensus or a single leader; feeds, counters and caches tolerate eventual or session consistency. It quantifies: a Raft write costs one majority round trip, so placing replicas across regions adds tens of milliseconds per write; 5 nodes tolerate 2 failures, 4 nodes still only 1. It names the failure modes (async failover losing acknowledged writes, stale reads, split brain from paused leaders) and their mitigations (synchronous quorum, session tokens, fencing tokens, monotonic clocks for timeouts).`, followUps: [ { q: "How would you implement read-your-writes on top of async read replicas?", a: `Return the commit position (LSN/version) with the write; store it in the session; on read, send to a replica whose applied position is at least that, or fall back to the primary. Alternatively, pin the user to the primary for a few seconds after a write.` }, { q: "Why not run a 2-node consensus cluster?", a: `Majority of 2 is 2, so any one failure halts it, and a partition cannot be distinguished from a peer crash. Use 3 (tolerates 1) or 5 (tolerates 2), spread across failure domains, or add a lightweight witness/arbiter.` }, { q: "What does a leader lease buy you, and what does it risk?", a: `It lets the leader serve linearizable reads locally without a quorum round trip, relying on bounded clock drift. If clocks drift beyond the assumed bound or the leader pauses, a deposed leader can serve **stale reads** while a new leader exists. Writes through the Raft log stay safe (term checks reject the old leader), but side effects on external resources still need fencing tokens.` }, { q: "How does Spanner get external consistency?", a: `TrueTime returns an interval with bounded uncertainty; a transaction picks a commit timestamp and waits until that timestamp is guaranteed to be in the past everywhere (commit wait) before making the result visible, so timestamp order matches real-time order.` } ], redFlags: [ 'Saying "we chose AP" for an entire system without naming which operations can tolerate staleness.', "Ordering events across machines by wall-clock timestamps.", "Proposing an even-sized consensus cluster or a cluster placed in a single AZ.", "Relying on a TTL lock for correctness with no fencing at the resource.", 'Treating "eventually consistent" as having a bounded or small delay by default.' ], numbers: [ "Raft/Paxos: 2f+1 nodes tolerate f failures (3 -> 1, 5 -> 2)", "Raft election timeout in the paper: ~150-300 ms randomized", "Quorum overlap rule: R + W > N; typical N=3, W=2, R=2", "Intra-AZ RTT ~0.5 ms, cross-AZ ~1-2 ms, cross-region tens to 100+ ms (order of magnitude)", "NTP skew: usually milliseconds, unbounded in failure cases" ] }, references: [ { title: "Raft consensus algorithm", url: "https://raft.github.io/" }, { title: "Jepsen: Consistency models", url: "https://jepsen.io/consistency" }, { title: "The System Design Primer", url: "https://github.com/donnemartin/system-design-primer" } ] }, { id: "infra-dist-patterns", title: "Resilience patterns: timeouts, retries, breakers and load shedding", stage: 3, order: 2, objectives: ["dist-patterns"], scope: "senior", estMinutes: 35, summary: "How to stop one slow dependency from taking down a fleet: timeout budgets, bounded retries with full jitter, idempotency keys, circuit breakers, bulkheads, token buckets, load shedding and backpressure.", what: `Resilience patterns are the client- and server-side mechanisms that keep a service healthy when its dependencies are slow, failing or overloaded. - **Client side**: timeouts, retries with exponential backoff and jitter, idempotency keys, circuit breakers, hedged requests. - **Server side**: rate limiting (token bucket), concurrency limits and bulkheads, load shedding, backpressure, graceful degradation. Together they turn "dependency is slow" from a cascading outage into a bounded, partial degradation.`, why: `The most common large outages are not a single crash but a **cascade**: a dependency slows down, callers hold threads and connections waiting, retries multiply load, queues grow, latency exceeds client timeouts, and everything upstream falls over. A senior engineer is expected to know the exact mechanics and the defaults that prevent it, because these settings live in every service config and are frequently wrong (infinite timeouts, retries at every layer, no jitter).`, problem: `Consider a 3-tier call path: edge -> API -> service -> database. The database gets slow (lock contention, failover). Without protection: - Each layer waits for its default timeout (often 30\u201360 s or none), so worker pools fill with blocked requests. - Each layer retries 3 times. Retries compound **multiplicatively**: 3 layers x 3 attempts = up to **27 attempts** at the database for one user click, arriving exactly when it is weakest. - Retries without jitter synchronize into waves. Clients time out but the server keeps doing the now-useless work. - When the database recovers, the backlog plus retry storm knocks it over again (a **metastable** failure that persists after the trigger is gone).`, how: `**1. Timeouts with a budget.** Every network call gets a timeout. Set it from the dependency's latency distribution (for example slightly above its p99.9) and from the caller's **deadline**: if the user-facing SLO is 1 s, the edge sets a 1 s deadline and propagates the **remaining** budget downstream (gRPC deadlines do this natively). A downstream call that cannot finish within the remaining budget should not start. **2. Retries, bounded and in one place.** Retry only transient errors (timeouts, 503, connection reset), only idempotent operations, and ideally at **one layer** (usually closest to the caller, or the edge). Cap attempts (2\u20133) and add a **retry budget**: retries may be at most ~10% of requests per client, so a widespread failure cannot multiply load. **3. Exponential backoff with full jitter.** \`sleep = random(0, min(cap, base * 2^attempt))\`. Exponential growth spreads retries over time; full jitter de-correlates clients so they do not arrive in synchronized waves. **4. Idempotency keys.** For non-idempotent operations (create payment), the client generates a unique key per logical operation and sends it on every attempt. The server stores key -> result (with a TTL, e.g. 24 h) atomically with the side effect; a duplicate returns the stored result. This makes retries safe across timeouts where the client does not know whether the first attempt succeeded. **5. Circuit breaker.** Three states: - **Closed**: calls flow; failures and slow calls are counted over a rolling window. - **Open**: when the failure rate exceeds a threshold (e.g. 50% over at least 20 calls), calls fail fast (or use a fallback) for a cool-down period. - **Half-open**: a few trial calls are allowed; success closes the breaker, failure re-opens it. This frees threads immediately and gives the dependency room to recover. **6. Bulkheads.** Separate pools (threads, connections, queues, even cells) per dependency or tenant so one slow dependency can exhaust only its own pool. **7. Rate limiting with a token bucket.** A bucket holds up to **b** tokens and refills at **r** tokens/s; each request consumes one; empty bucket means reject (HTTP 429 with Retry-After). It allows bursts of size b while bounding the average rate to r. Apply per client/tenant and globally. **8. Load shedding and backpressure.** When the server is past its capacity (concurrency or queue time above a threshold), reject early and cheaply instead of queuing; prioritize critical traffic (checkout over recommendations). Drop requests whose client deadline has already passed. Bound every queue; use **LIFO or deadline-aware** dequeuing under overload so fresh requests succeed. Backpressure propagates "slow down" upstream (bounded queues, 429/503, TCP flow control, reactive streams) instead of letting memory grow.`, components: [ { name: "Timeouts and deadlines", description: "Per-call timeouts derived from dependency latency; end-to-end deadline propagated so downstream work stops when the caller has given up." }, { name: "Retries with backoff and full jitter", description: "Bounded attempts, transient errors only, one layer, retry budget (~10%), randomized exponential delay." }, { name: "Idempotency keys", description: "Client-generated unique key per logical operation; server dedupes and returns the original result, making retries safe for side effects." }, { name: "Circuit breaker", description: "Closed -> open on failure threshold -> half-open probes -> closed. Fails fast to protect callers and the struggling dependency." }, { name: "Bulkheads and concurrency limits", description: "Isolated pools per dependency/tenant; adaptive concurrency limits that shrink when latency rises." }, { name: "Rate limiting, load shedding, backpressure", description: "Token bucket per tenant; reject early with 429/503 under overload; prioritize critical paths; bounded queues." } ], misconceptions: [ { myth: "More retries make a system more reliable.", reality: "Retries help with rare, independent, transient faults. During a real overload they multiply load (27x across 3 layers of 3 attempts) and turn a slowdown into an outage. Bound them, budget them and retry in one layer." }, { myth: "A long timeout is safer because fewer requests fail.", reality: "Long timeouts hold threads and connections, which is exactly how a slow dependency exhausts a caller. Fail fast and fall back; a timeout longer than the caller's own deadline is pure waste." }, { myth: "Exponential backoff alone prevents retry storms.", reality: "Without jitter, all clients that failed at the same moment retry at the same moments. Full jitter is what spreads them out." }, { myth: "Circuit breakers replace timeouts.", reality: "A breaker needs timeouts to detect slowness in the first place, and it acts on aggregate rates. Use both." } ], example: { title: "Retry amplification and a token bucket, worked numerically", description: `Numbers you can derive on a whiteboard, then the fixed policy.`, language: "text", code: `BEFORE: edge -> api -> svc -> db, each layer: 3 attempts, 30 s timeout 1 user request -> up to 3 x 3 x 3 = 27 db calls normal load 2,000 rps at db; 10% start timing out extra db load ~ 2,000 x 0.10 x 26 = ~5,200 rps extra -> db saturated -> 100% fail AFTER: deadline 1,000 ms set at edge, propagated timeouts: api->svc 400 ms, svc->db 150 ms (db p99.9 = 120 ms) retries: only at api, max 2 attempts, retry budget 10% of requests backoff: sleep = random(0, min(1000 ms, 50 ms * 2^attempt)) breaker on svc->db: open if >=50% failures over >=20 calls in 10 s; 5 s cool-down worst-case amplification: 2x per user request, capped at 1.1x fleet-wide Token bucket per tenant: r = 100 req/s, b = 200 idle tenant bursts 200 requests instantly, then sustains 100/s tenant sending 300/s for 10 s: accepted = 200 + 100*10 = 1,200; rejected 1,800 (429)` }, exercise: { prompt: `A checkout service calls inventory (p99 80 ms), pricing (p99 50 ms) and a recommendations service (p99 300 ms, frequently degraded). Checkout's SLO is p99 < 800 ms. Design the timeout, retry, breaker and bulkhead configuration, and say what happens to the page when recommendations is down.`, solution: `- Edge sets an 800 ms deadline. Inventory and pricing timeouts ~150 ms and ~100 ms (above p99.9, below budget), one retry each with jitter only if remaining budget allows; inventory reservation uses an **idempotency key** so the retry cannot double-reserve. - Recommendations: timeout ~250 ms, **no retry**, separate bulkhead pool (small fixed concurrency), circuit breaker that opens on error/slow-call rate and returns an empty or cached list. - Call inventory and pricing in parallel; recommendations asynchronously or in parallel with a hard cutoff. - When recommendations is down, the breaker opens, checkout renders without recommendations, and checkout latency and availability are unaffected: **graceful degradation**. Alert on breaker state but do not page checkout on-call for it.` }, faq: [ { q: "When should I use hedged requests?", a: `For idempotent reads with long tail latency: send a second request after the first exceeds roughly the p95, take whichever returns first, and cancel the other. Cap hedges (a few % of traffic) so they do not become load amplification.` }, { q: "Should the server or the client decide to retry?", a: `The client decides, but the server should signal retryability (429/503 with Retry-After vs 400). Servers under load should shed cheaply so the signal arrives fast.` }, { q: "What is a metastable failure?", a: `A state where the system stays overloaded even after the trigger is removed, sustained by its own feedback loop (retries, cache misses, queue backlog). Breaking it usually needs load shedding, dropping the backlog, or temporarily blocking traffic.` } ], keyTerms: ["timeout budget", "deadline propagation", "retry amplification", "full jitter", "idempotency key", "circuit breaker", "bulkhead", "token bucket", "load shedding", "backpressure"], deeper: `Adaptive concurrency limits (inspired by TCP congestion control, e.g. AIMD or gradient algorithms) adjust a service's allowed in-flight requests based on observed latency, which avoids hand-tuning fixed limits. Google's SRE material describes client-side adaptive throttling: each client tracks requests vs accepts and probabilistically rejects locally when the backend is rejecting, so overload is shed before it reaches the network.`, interview: { seniorAnswer: `A strong answer starts from the cascade mechanism (slow dependency -> resource exhaustion -> retries amplify -> metastable overload) and walks through defences layer by layer with numbers: deadlines propagated from the user SLO, per-call timeouts near the dependency's p99.9, retries at one layer only with 2\u20133 attempts, full jitter and a ~10% retry budget, idempotency keys for side effects, a breaker with explicit thresholds, bulkheads per dependency, token-bucket limits per tenant, and load shedding that prioritizes critical traffic and drops expired requests. It names what degrades gracefully and what must fail, and how you would test it (fault injection of latency, not just errors).`, followUps: [ { q: 'Why does full jitter beat "equal jitter" or no jitter?', a: `Full jitter spreads retries uniformly over the whole backoff window, minimizing collisions and total work in contention; AWS's analysis found it gives the lowest load among the common variants at a small latency cost.` }, { q: "How do you store idempotency keys safely?", a: `In the same transaction as the side effect (or with a unique constraint), with request fingerprint to reject key reuse with different payloads, a TTL longer than the client's maximum retry horizon, and a stored response to replay.` }, { q: "FIFO or LIFO queue under overload?", a: `Under overload, FIFO serves the oldest requests, whose clients have often already timed out. LIFO or deadline-aware dequeue serves fresh requests that can still succeed; combine with dropping expired items.` }, { q: "How would you test these patterns?", a: `Inject latency and partial failure (not just hard errors) in staging and in controlled production experiments; verify breaker trips, shed rate, and that p99 of unaffected endpoints holds.` } ], redFlags: [ "Retrying at every layer, or retrying non-idempotent writes without a key.", "No timeouts, or default 30\u201360 s client timeouts on internal calls.", "Exponential backoff with no jitter.", 'Unbounded in-memory queues as a "buffer" for overload.', "Treating a circuit breaker as a replacement for capacity planning." ], numbers: [ "Retry amplification: attempts^layers (3 layers x 3 attempts = 27x)", "Retry budget: ~10% of requests", "Max attempts: 2-3 with exponential backoff + full jitter", "Timeout: slightly above dependency p99.9 and below remaining deadline", "Token bucket: sustained rate r, burst b" ] }, references: [ { title: "AWS Builders' Library: Timeouts, retries and backoff with jitter", url: "https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/" }, { title: "AWS Builders' Library: Making retries safe with idempotent APIs", url: "https://aws.amazon.com/builders-library/making-retries-safe-with-idempotent-APIs/" }, { title: "Google SRE book: Addressing cascading failures", url: "https://sre.google/sre-book/addressing-cascading-failures/" }, { title: "Martin Fowler: CircuitBreaker", url: "https://martinfowler.com/bliki/CircuitBreaker.html" } ] }, { id: "infra-dist-messaging", title: "Queues and streams: delivery semantics, ordering and the outbox", stage: 3, order: 3, objectives: ["dist-messaging"], scope: "senior", estMinutes: 35, summary: "Queue vs log, why at-least-once plus idempotent consumers is the real-world contract, per-partition ordering, consumer lag, DLQs and poison messages, the transactional outbox and sagas.", what: `Asynchronous messaging decouples producers from consumers in time and rate. Two families: - **Message queue** (SQS on AWS, Service Bus queues on Azure, Pub/Sub subscriptions on Google Cloud, RabbitMQ): messages are delivered to one of many competing consumers, **acknowledged and removed**. Good for work distribution. - **Log / stream** (Apache Kafka and its managed offerings, Kinesis Data Streams on AWS, Event Hubs on Azure): an append-only, **retained**, partitioned log. Consumers track their own **offset**; many independent consumer groups can read the same data and **replay** it. Good for event distribution, change data capture and rebuilding state.`, why: `Messaging is how large systems absorb spikes, isolate failures and integrate services, and it is the source of a predictable class of bugs: duplicates, out-of-order events, lost events between a database write and a publish, poison messages that block a partition, and lag that silently grows for hours. Interviewers probe whether you know that "exactly-once" is a scoped guarantee and how you make the end-to-end pipeline correct anyway.`, problem: `- A service writes an order row and then publishes "OrderCreated". If it crashes between the two, the event is lost; if it publishes first, the event may describe an order that was never committed. This is the **dual-write problem**. - A consumer processes a message, performs a side effect, then crashes before acknowledging. The broker redelivers; the side effect happens twice. - One malformed message makes the consumer throw on every attempt; with strict ordering, everything behind it on that partition stops. - Producers run at 5,000 msg/s, consumers at 4,500 msg/s; lag grows by 500 msg/s, i.e. 1.8 million messages per hour, until data ages out of retention.`, how: `**1. Delivery semantics.** - **At-most-once**: ack before processing; a crash loses the message. - **At-least-once**: ack after processing; a crash causes redelivery, so duplicates happen. This is the default you should design for. - **Exactly-once** is achievable only within a boundary. Kafka's idempotent producer plus transactions give exactly-once **read-process-write within Kafka** (consume offsets and produced records commit atomically). Once a side effect leaves that boundary (an email, a payment API, a different database), you are back to at-least-once and need **idempotent consumers**. **2. Idempotent consumers.** Give every message a stable ID. In the same transaction as the side effect, insert the ID into a processed-messages table with a unique constraint (or use a natural idempotent write such as an upsert keyed by entity and version). A duplicate fails the insert and is acked without re-applying. **3. Ordering.** Logs guarantee order **within a partition** only. Choose the partition key so that events that must be ordered share it (e.g. \`account_id\`); global order would require a single partition and caps throughput at one consumer. Re-partitioning (adding partitions) changes key-to-partition mapping and can reorder in-flight keys. Standard queues are best-effort ordered; FIFO queues (SQS FIFO, Service Bus sessions) order per group key at lower throughput. **4. Consumer groups and lag.** In a group, each partition is consumed by one member; parallelism is capped by partition count. **Lag** = latest offset minus committed offset, per partition. Alert on lag **age/time-to-drain**, not just message count. Drain time = lag / (consume rate - produce rate). Rebalances (member joins/leaves) pause consumption; keep processing time well under session and poll timeouts. **5. Visibility timeout (queues).** A received message is hidden for a visibility timeout; if not deleted before it expires, it is redelivered. Set it above the worst-case processing time (or extend it while working), otherwise the same message is processed concurrently by two consumers. **6. Dead-letter queues and poison messages.** After N failed attempts (e.g. 5) move the message to a **DLQ** with error metadata, so it stops blocking or burning capacity. Alarm on DLQ depth > 0, and build a reviewed **redrive** path. Distinguish transient errors (retry with backoff) from permanent ones (straight to DLQ). **7. Transactional outbox.** Write the business row and an **outbox** row (event payload) in the **same local transaction**. A relay publishes outbox rows to the broker, by polling or by tailing the database's change log (CDC, e.g. Debezium), and marks them sent. The relay is at-least-once, so consumers must dedupe by event ID. This removes the dual-write gap without distributed transactions. **8. Sagas.** A business transaction spanning services is a sequence of local transactions, each with a **compensating action** (reserve inventory -> release inventory). **Orchestration** uses a coordinator that drives steps and compensations (easier to reason about and observe); **choreography** has services react to each other's events (looser coupling, harder to trace). Sagas give atomicity eventually, not isolation: intermediate states are visible, so design for them (e.g. "pending" status).`, components: [ { name: "Queue", description: "Competing consumers, per-message ack and deletion, visibility timeout, DLQ. Scales consumers freely; ordering only with FIFO/session features." }, { name: "Partitioned log", description: "Retained, replayable, ordered per partition; consumers own offsets; multiple independent consumer groups; parallelism bounded by partition count." }, { name: "Idempotent consumer", description: "Dedup table or idempotent upsert committed atomically with the side effect; the real fix for duplicates." }, { name: "Dead-letter queue", description: "Quarantine for messages that fail N times; alarmed, inspected, and redriven deliberately." }, { name: "Transactional outbox + relay", description: "Business change and event written in one local transaction; relay (poll or CDC) publishes at-least-once." }, { name: "Saga", description: "Multi-service workflow of local transactions with compensations; orchestrated or choreographed." } ], misconceptions: [ { myth: "Enabling exactly-once in the broker means my consumers never see duplicates.", reality: "Broker exactly-once covers reads and writes inside that broker. External side effects (databases, emails, APIs) still see at-least-once delivery and need idempotency." }, { myth: "Kafka guarantees ordering.", reality: "Only within a partition, and only if producers preserve it (idempotent producer, careful retry settings). Across partitions there is no order." }, { myth: "A growing queue is fine because the queue is durable.", reality: "Backlog is latency. Retention limits turn sustained lag into data loss, and a huge backlog can take hours to drain because drain rate is consume minus produce rate." }, { myth: "Two-phase commit between the database and the broker is the standard fix for dual writes.", reality: "Most cloud brokers do not participate in XA, and 2PC adds coordinator failure modes. The transactional outbox (or CDC) is the standard answer." } ], example: { title: "Outbox schema, idempotent consumer and lag arithmetic", description: `The minimal SQL shape of the outbox and dedup, plus the numbers for sizing a consumer group.`, language: "text", code: `-- producer side, one local transaction BEGIN; INSERT INTO orders(id, account_id, total) VALUES ('o-981', 'a-17', 42.00); INSERT INTO outbox(event_id, aggregate_id, type, payload) VALUES ('e-5531', 'a-17', 'OrderCreated', '{"order":"o-981","total":42.00}'); COMMIT; -- relay publishes outbox rows keyed by aggregate_id (keeps per-account order) -- consumer side, one local transaction per message BEGIN; INSERT INTO processed_events(event_id) VALUES ('e-5531'); -- UNIQUE; duplicate -> skip UPDATE loyalty SET points = points + 42 WHERE account_id = 'a-17'; COMMIT; -- then commit offset / delete message Sizing: produce 5,000 msg/s; one consumer handles 400 msg/s need >= 13 consumers -> use 16 partitions (headroom + replay) incident left 3,600,000 msgs of lag; 16 consumers x 400 = 6,400/s drain time = 3,600,000 / (6,400 - 5,000) = ~2,570 s = ~43 min` }, exercise: { prompt: `An order service updates Postgres and then calls the payment service synchronously, then publishes "OrderPaid" to a stream that shipping consumes. During a deploy, some orders were charged but never shipped, and a few were shipped twice. Redesign the flow.`, solution: `- **Charged but never shipped**: dual write; the process died between payment and publish. Use a **transactional outbox**: record the order state change and the "OrderPaid" event in one transaction; a relay publishes it. - **Shipped twice**: at-least-once redelivery (relay retry, consumer crash before offset commit). Make shipping an **idempotent consumer** keyed by event ID or order ID with a unique constraint on shipment creation. - Make the payment call idempotent with an **idempotency key** = order ID so retries cannot double-charge. - Model the whole flow as an **orchestrated saga**: reserve inventory -> charge -> create shipment, with compensations (refund, release) and explicit pending states; DLQ plus alarm for messages that fail repeatedly; partition the stream by order ID for per-order ordering.` }, faq: [ { q: "Queue or log: how do I choose?", a: `Queue for task distribution where each job is done once and then forgotten, with per-message retry and DLQ. Log when several consumers need the same events, you need replay or reprocessing, or ordering per key matters at high throughput.` }, { q: "How many partitions should a topic have?", a: `Enough for peak consumer parallelism with headroom (consumers <= partitions), considering that adding partitions later remaps keys. Too many increases broker metadata, open files and rebalance time.` }, { q: "How should a consumer handle a message it cannot parse?", a: `Do not retry forever. Classify it as permanent, send it with error context to the DLQ, commit/ack, and alarm. Retries are for transient failures only.` } ], keyTerms: ["at-least-once", "idempotent consumer", "exactly-once (scoped)", "partition key", "consumer lag", "visibility timeout", "dead-letter queue", "transactional outbox", "saga", "compensating action"], deeper: `Large queue backlogs create a fairness problem: one noisy tenant can fill a shared queue and delay everyone. Mitigations include per-tenant queues or shards, shuffle sharding, and prioritizing recent messages while a separate worker drains old backlog. CDC-based outboxes also let you publish events without a polling relay and preserve commit order from the write-ahead log, at the cost of coupling event schema to table schema unless you transform them.`, interview: { seniorAnswer: `A strong answer contrasts queues and logs by consumption model, retention and ordering, then states the honest contract: **at-least-once delivery plus idempotent consumers**, with "exactly-once" only inside a broker's transactional boundary. It solves dual writes with the transactional outbox or CDC, chooses a partition key for the ordering that matters, sizes partitions from throughput and consumer capacity, monitors lag as time-to-drain, isolates poison messages with a DLQ and redrive process, and handles cross-service workflows with sagas and compensations rather than distributed transactions.`, followUps: [ { q: "What happens to ordering when a consumer retries a message in place?", a: `Retrying in place blocks that partition (head-of-line). Moving it to a retry topic unblocks the partition but breaks order for that key; if order matters per key, park subsequent messages for the same key or retry in place with a bounded attempt count then DLQ.` }, { q: "How do you safely replay a topic from the beginning?", a: `Use a new consumer group or reset offsets in a controlled window, ensure consumers are idempotent, throttle replay to protect downstream stores, and make sure retention still covers the range.` }, { q: "Choreography or orchestration for a 6-step saga?", a: `Orchestration: with many steps, an explicit coordinator gives one place for state, timeouts, compensations and visibility. Choreography suits 2\u20133 loosely coupled steps.` } ], redFlags: [ "Claiming end-to-end exactly-once without idempotent side effects.", "Publishing to a broker after a database commit with no outbox or CDC.", "Expecting global ordering from a multi-partition topic.", "No DLQ, or a DLQ nobody alarms on.", "Measuring lag only in message count with no time-to-drain view." ], numbers: [ "Drain time = lag / (consume rate - produce rate)", "Max consumer parallelism in a group = partition count", "Typical DLQ threshold: ~3-5 receive attempts", "Visibility timeout > worst-case processing time" ] }, references: [ { title: "Apache Kafka documentation", url: "https://kafka.apache.org/documentation/" }, { title: "AWS Builders' Library: Avoiding insurmountable queue backlogs", url: "https://aws.amazon.com/builders-library/avoiding-insurmountable-queue-backlogs/" }, { title: "Azure Architecture Center: Cloud design patterns", url: "https://learn.microsoft.com/en-us/azure/architecture/patterns/" } ] }, // ---------------------------------------------------------------- Stage 4: Reliability & SRE { id: "infra-rel-slo", title: "SLIs, SLOs and error budgets", stage: 4, order: 1, objectives: ["rel-slo", "obs-signals"], scope: "senior", estMinutes: 35, summary: "Choosing user-centric SLIs, availability arithmetic, composing dependencies, error budget policy, and multi-window multi-burn-rate alerting.", what: `- An **SLI** (service level indicator) is a measured ratio of good events to valid events, e.g. "proportion of HTTP requests served successfully in under 300 ms". - An **SLO** (objective) is a target for that SLI over a window, e.g. "99.9% over 28 or 30 rolling days". - The **error budget** is 1 - SLO: the amount of unreliability you are allowed to spend, on incidents, risky releases or planned maintenance. - An **SLA** is a contract with consequences (credits) and should be looser than the internal SLO.`, why: `SLOs turn "is it reliable enough?" from an opinion into a number that product and engineering share. They decide when to ship faster and when to freeze, which alerts page a human, and how much redundancy is worth paying for. In senior interviews this topic tests whether you can choose a meaningful SLI, do the nines arithmetic in your head, reason about dependency budgets, and design alerts that are both fast and quiet.`, problem: `Typical failure states: - SLIs measured on the server's CPU or "the process is up" rather than what users experience; dashboards are green while users see errors. - A 100% target, which makes every change a risk and every blip an incident. - Static threshold alerts ("error rate > 1% for 5 minutes") that page on brief spikes that barely touch the budget, yet miss a slow 0.5% leak that burns the whole month's budget. - An SLO nobody acts on: budget exhausted, releases continue.`, how: `**1. Choose SLIs from the user journey.** Measure as close to the user as practical (load balancer or client telemetry rather than the app's own logs). Common types: **availability** (good responses / valid requests, excluding client errors), **latency** (requests faster than a threshold / requests; use thresholds, not averages), **freshness** for pipelines, **correctness** and **durability** for storage. **2. Request-based vs window-based.** - **Request-based**: good requests / total requests over the window. Weights busy periods more, is easy to compute from counters, and is the usual default. - **Window-based**: proportion of time slices (e.g. 1-minute windows) that met a condition. Treats a 3 a.m. outage like a peak-hour one and is useful for low-traffic services where a few requests skew the ratio. **3. Do the availability arithmetic.** Downtime allowed per average month (~30.44 days, ~43,830 minutes): - 99% ~ 7.3 hours; 99.5% ~ 3.65 hours; 99.9% ~ **43.8 minutes**; 99.95% ~ 21.9 minutes; 99.99% ~ **4.4 minutes**; 99.999% ~ 26 seconds. - Per year: 99.9% ~ 8.77 hours; 99.99% ~ 52.6 minutes. Each extra nine costs roughly an order of magnitude more effort: 4.4 minutes per month is less than a typical human detect-and-respond loop, so 99.99% requires automated detection and failover. **4. Compose dependencies.** For **serial** hard dependencies, availabilities multiply: three components at 99.9% give 0.999^3 ~ **99.7%**. Your SLO cannot exceed the product of your hard dependencies unless you add redundancy, caching or graceful degradation. For **redundant** independent components, unavailability multiplies: two 99.9% replicas give 1 - 0.001^2 = 99.9999% in theory, but correlated failures and the failover mechanism itself dominate in practice. **5. Write an error budget policy** agreed with product before it is needed, e.g.: budget > 50% remaining, normal velocity; < 25%, only low-risk changes and reliability work prioritized; exhausted, feature freeze except fixes and security until the rolling window recovers; a single incident consuming > 20% of budget requires a postmortem with tracked action items. **6. Alert on burn rate.** Burn rate = observed error rate / allowed error rate. Burn rate 1 spends exactly the budget over the window. For a 30-day window, the SRE workbook's recommended **multi-window, multi-burn-rate** set is: - **Page**: burn rate 14.4 over 1 h (2% of budget), confirmed by a 5 m short window. - **Page**: burn rate 6 over 6 h (5% of budget), confirmed by a 30 m short window. - **Ticket**: burn rate 1 over 3 days (10% of budget), confirmed by a 6 h short window. The long window gives significance (no paging on blips); the short window makes the alert **reset quickly** after recovery.`, components: [ { name: "SLI", description: "Ratio of good to valid events measured near the user: availability, latency threshold, freshness, correctness." }, { name: "SLO and window", description: 'Target plus a rolling (28/30-day) or calendar window. Rolling windows avoid "budget reset" behaviour at month boundaries.' }, { name: "Error budget", description: "1 - SLO, expressed in bad requests or minutes. The currency for release risk and maintenance." }, { name: "Error budget policy", description: "Pre-agreed actions at budget thresholds: slow releases, freeze, prioritize reliability, mandatory postmortems." }, { name: "Burn-rate alerts", description: "Multi-window, multi-burn-rate alerts that page on fast burns and ticket on slow leaks, with low false-positive rates." }, { name: "SLA", description: "External contract, deliberately looser than the internal SLO so you breach the SLO first and have time to react." } ], misconceptions: [ { myth: "The SLO should be as high as possible, ideally 100%.", reality: "Users cannot tell 99.99% from 100% through their own unreliable networks and devices, and 100% leaves zero budget for change. Set the SLO at the point where users stop being happy, not higher." }, { myth: "Average latency is a good latency SLI.", reality: 'Averages hide the tail. Use "proportion of requests under X ms" at one or two thresholds (e.g. 300 ms and 1 s), which also composes into a budget.' }, { myth: "Our service has 99.99% because each of our dependencies does.", reality: "Serial dependencies multiply: five 99.99% hard dependencies give ~99.95% before your own failures." }, { myth: "Alert when the error rate exceeds the SLO error rate.", reality: "That is burn rate 1: it pages on every short blip and takes a whole window to mean anything. Use burn-rate thresholds over paired long and short windows." } ], example: { title: "Budget, composition and burn-rate alert rules for a 99.9% API", description: `Numbers for a service handling ~100 million requests per 30 days, plus Prometheus-style alert expressions (the recording-rule names are illustrative).`, language: "yaml", code: `# SLO 99.9% over 30 days; 100,000,000 requests/30d # error budget = 0.1% = 100,000 bad requests (~43.2 min of full outage in 30 days) # serial dependencies: LB 99.99% x app 99.95% x db 99.95% = ~99.89% -> below SLO! # -> add a cache/fallback for read paths or raise db availability groups: - name: api-slo-burn rules: - alert: ApiErrorBudgetFastBurn # 2% of budget in 1 h expr: | job:slo_errors_per_request:ratio_rate1h{job="api"} > (14.4 * 0.001) and job:slo_errors_per_request:ratio_rate5m{job="api"} > (14.4 * 0.001) labels: {severity: page} - alert: ApiErrorBudgetMediumBurn # 5% of budget in 6 h expr: | job:slo_errors_per_request:ratio_rate6h{job="api"} > (6 * 0.001) and job:slo_errors_per_request:ratio_rate30m{job="api"} > (6 * 0.001) labels: {severity: page} - alert: ApiErrorBudgetSlowBurn # 10% of budget in 3 d expr: | job:slo_errors_per_request:ratio_rate3d{job="api"} > (1 * 0.001) and job:slo_errors_per_request:ratio_rate6h{job="api"} > (1 * 0.001) labels: {severity: ticket}` }, exercise: { prompt: `A product team wants a 99.99% availability SLO for an internal API. It depends synchronously on an auth service (99.95%) and a database (99.95%), has one on-call engineer with a 15-minute response time, and deploys 20 times a week. Evaluate the target and propose an SLO, an SLI and a budget policy.`, solution: `- 99.99% allows ~4.4 minutes/month. The serial dependencies alone give 0.9995 x 0.9995 ~ **99.90%**, so the target is unachievable without removing hard dependencies (cache auth tokens/decisions locally, read replicas or fallbacks for the DB). - A 15-minute human response consumes ~3.4x the whole monthly 99.99% budget in one incident; that target would demand automated detection and rollback. - Propose **99.9%** request-based availability SLI measured at the load balancer: good = non-5xx responses (excluding 429s from client abuse, by explicit decision) / all valid requests, over 30 rolling days, plus a latency SLI (99% under 400 ms). - Policy: fast/medium burn pages; budget < 25% means canary-only deploys with automatic rollback; exhausted means freeze except fixes; any incident > 20% of budget gets a postmortem. Revisit after a quarter of data.` }, faq: [ { q: "Should planned maintenance count against the budget?", a: `If users experience it, yes. That is the point of the budget: it forces maintenance to be designed as zero-downtime or to be paid for explicitly.` }, { q: "How do I handle low-traffic services where one failed request is 1% of the day?", a: `Use window-based SLIs, longer windows, synthetic probes to add valid traffic, or combine low-traffic services into a single SLO for alerting purposes.` }, { q: "Do 4xx responses count as errors?", a: `Generally no: client errors are excluded from valid events. But 429s caused by your own over-aggressive throttling, or 404s from a broken deploy, are your failures; decide explicitly and document it in the SLI definition.` } ], keyTerms: ["SLI", "SLO", "SLA", "error budget", "error budget policy", "burn rate", "multi-window alert", "request-based SLI", "window-based SLI", "serial availability"], deeper: `SLOs can also drive capacity and cost: if a service is consistently far above its SLO, it may be over-provisioned or over-replicated, and the surplus budget can be spent on faster releases or cheaper infrastructure (e.g. fewer replicas, spot capacity). Some teams deliberately inject planned downtime into overly reliable services so consumers do not build implicit dependencies on reliability that is not promised.`, interview: { seniorAnswer: `A strong answer picks SLIs from user journeys and measures them at the edge, prefers request-based ratios with latency thresholds rather than averages, does the arithmetic instantly (99.9% ~ 43.8 min/month, 99.99% ~ 4.4 min/month), composes serial dependencies by multiplication and explains how caching, redundancy and degradation break that ceiling. It ties the budget to a pre-agreed policy with product, and alerts using multi-window multi-burn-rate rules (14.4x/1 h and 6x/6 h page, 1x/3 d ticket), explaining why long windows give significance and short windows give fast reset.`, followUps: [ { q: "Why is a burn rate of 14.4 chosen for the 1-hour window?", a: `Over a 30-day (720-hour) window, burning at 14.4x for 1 hour spends 14.4/720 = 2% of the budget, a threshold that is significant enough to page but still leaves time to react before the budget is gone (~50 hours at that rate).` }, { q: "How would you set an SLO for a batch pipeline?", a: `Use freshness and correctness SLIs: e.g. 99% of hourly partitions available within 90 minutes of the hour, and 99.99% of records passing validation; alert on missed deadlines rather than job failures that were retried successfully.` }, { q: "What do you do when one team's dependency keeps burning your budget?", a: `Show the budget attribution data, negotiate their SLO to meet yours or reduce the hard dependency (cache, async, fallback), and escalate through the budget policy rather than absorbing it silently.` } ], redFlags: [ "Proposing 100% or five nines without discussing cost or human response time.", "Latency SLI based on average or max.", "Alerting on CPU or static error-rate thresholds instead of user-facing symptoms and burn rate.", "No error budget policy, or one that product never agreed to.", "Adding dependency availabilities instead of multiplying them." ], numbers: [ "99.9% ~ 43.8 min/month, ~8.77 h/year", "99.95% ~ 21.9 min/month", "99.99% ~ 4.4 min/month, ~52.6 min/year", "Serial: multiply availabilities (0.999^3 ~ 99.7%)", "Burn-rate alerts (30-day window): 14.4x/1h + 5m, 6x/6h + 30m page; 1x/3d + 6h ticket" ] }, references: [ { title: "Google SRE book: Service level objectives", url: "https://sre.google/sre-book/service-level-objectives/" }, { title: "Google SRE workbook: Alerting on SLOs", url: "https://sre.google/workbook/alerting-on-slos/" }, { title: "Google SRE book: Monitoring distributed systems", url: "https://sre.google/sre-book/monitoring-distributed-systems/" } ] }, { id: "infra-rel-incidents", title: "Incident response, postmortems and toil", stage: 4, order: 2, objectives: ["rel-incidents"], scope: "senior", estMinutes: 30, summary: "How a mature organization runs an incident: roles, severity, mitigation before root cause, communication cadence, blameless postmortems with real action items, and toil reduction.", what: `Incident management is the practised process for restoring service when something user-visible breaks, and for learning from it afterwards. It has three phases: **detect and declare**, **mitigate and communicate**, and **learn** (postmortem and follow-up). Toil management is the ongoing work of removing the manual, repetitive operational load that makes on-call unsustainable.`, why: `Senior and staff engineers are expected to lead incidents, not just debug them, and almost every behavioural loop includes "tell me about an outage you handled". Interviewers look for structure under pressure: clear roles, early declaration, mitigation first, regular communication, and a postmortem that produces systemic fixes instead of blame. Poor incident practice turns a 10-minute rollback into a 3-hour outage with five people debugging the same graph.`, problem: `Common failure patterns in real incidents: - Nobody declares an incident, so a dozen engineers investigate in parallel without coordination. - The most senior engineer both debugs and coordinates, and does neither well. - The team chases root cause for an hour while a rollback would have restored service in minutes. - Stakeholders and support get no updates, so they interrupt responders. - The postmortem names a person ("operator ran the wrong command"), action items have no owners, and the same class of incident recurs.`, how: `**1. Detect and declare.** Alerts are symptom-based (SLO burn), so the page itself is evidence of user impact. Declare early: it is cheaper to downgrade a false alarm than to coordinate late. Assign a **severity** using a shared rubric, for example: - **SEV1**: broad user-facing outage or data loss/security exposure; all hands, executive comms. - **SEV2**: significant degradation or a major feature down for a subset of users. - **SEV3**: minor or contained impact, workaround exists. - **SEV4**: no user impact yet; follow up in working hours. **2. Assign roles** (from the Incident Command System, as adapted in the SRE book): - **Incident commander (IC)**: owns the incident, sets priorities, assigns work, decides; does **not** debug. - **Operations / tech lead**: the only people changing production; coordinate changes through the IC. - **Communications lead**: posts status updates on a fixed cadence (e.g. every 30 minutes for SEV1) to stakeholders and the status page. - **Scribe** (optional): keeps the timeline of observations, decisions and actions with timestamps. Hand over the IC role explicitly when shifts change. **3. Mitigate first, then find root cause.** Ask "what changed?" (deploys, config, flags, traffic, dependencies). Prefer fast, reversible mitigations: roll back the latest deploy, disable a feature flag, fail over or drain an AZ/region, shed load, scale up, block an abusive client. Restore service, then investigate with the pressure off. Preserve evidence (logs, heap dumps, snapshots) before destroying it with a restart when that is safe. **4. Communicate.** Internal channel for responders, separate channel for stakeholders. Each update: current impact, what is being done, next update time. Do not speculate on root cause publicly. **5. Resolve and hand off.** Define "resolved" (SLIs back within SLO for a period), then schedule the postmortem. **6. Blameless postmortem.** Written within days, reviewed, and shared. Structure: - Summary and **impact** (users affected, duration, budget consumed, revenue/data effects). - **Timeline** with detection, escalation and mitigation timestamps; compute time to detect and time to mitigate. - **Root cause and contributing factors**: usually several (a latent bug, a missing guardrail, an alert that did not fire, a confusing runbook). - What went well, what went poorly, **where we got lucky**. - **Action items**: each with an owner, priority and tracking ticket; categorized as prevent, detect and mitigate. Prefer systemic fixes (guardrails, automation, tests) over "be more careful" or "more training". Blameless means assuming people acted reasonably given the information and tools they had, and fixing the system that made the error possible. **7. Reduce toil.** Toil is operational work that is manual, repetitive, automatable, tactical, has no enduring value and **scales linearly with the service**. Google's SRE guidance caps toil at about **50%** of an SRE's time; measure it (tickets, pages, manual runs), and spend engineering time automating the top items. Track pager load too: the SRE book suggests on the order of at most two incidents per 12-hour on-call shift so each can be handled and followed up properly.`, components: [ { name: "Severity rubric", description: "Shared, impact-based definitions (SEV1\u2013SEV4) that set response expectations, paging scope and comms cadence." }, { name: "Incident commander", description: "Coordinates, prioritizes and decides; delegates debugging; owns hand-offs and declares resolution." }, { name: "Operations and communications roles", description: "Ops lead makes production changes; comms lead updates stakeholders on a fixed cadence; scribe keeps the timeline." }, { name: "Mitigation playbook", description: "Rollback, flag off, drain/failover, shed load, scale out, block traffic; pre-tested and fast." }, { name: "Blameless postmortem", description: "Impact, timeline, contributing factors, lucky breaks, owned and prioritized action items across prevent/detect/mitigate." }, { name: "Toil budget", description: "Measured manual operational work, capped (~50%) and reduced by automation and self-service." } ], misconceptions: [ { myth: "You must understand the root cause before you act.", reality: "Mitigation comes first. A rollback or failover restores users while you investigate; root cause analysis is a postmortem activity." }, { myth: "Blameless means no accountability.", reality: "Accountability moves to fixing the system: owners for action items, deadlines and reviews. Blame discourages honest timelines, which destroys the data you need." }, { myth: "Every incident has a single root cause.", reality: "Complex systems fail through several contributing factors lining up. A postmortem with a single cause and a single fix usually missed the detection and mitigation gaps." }, { myth: "The most experienced engineer should be incident commander and fix it.", reality: "The IC should coordinate, not debug. Splitting the roles is what keeps a large incident from becoming chaos." } ], example: { title: "SEV2 timeline and postmortem action items", description: `A condensed, realistic timeline showing mitigation before root cause, with the metrics a postmortem should compute.`, language: "text", code: `14:02 Deploy v412 of checkout begins (canary skipped: "small config change") 14:07 v412 fully rolled out; 5xx jumps to ~30% (burn rate ~300x on 99.9%) 14:10 Fast-burn SLO alert pages on-call (1h window crosses 14.4x after ~14.4/300 x 60 min = ~3 min) 14:12 On-call declares SEV2, takes IC; pulls in ops lead + comms lead 14:15 IC asks "what changed?" -> v412 deploy finished 14:07 14:17 Ops lead starts rollback to v411 (decision: mitigate, don't debug) 14:24 5xx back to baseline; comms posts update #2; IC keeps incident open 14:54 SLIs within SLO for 30 min -> resolved Metrics: time to detect 3 min (14:07 -> 14:10), time to mitigate 14 min (14:10 -> 14:24), user impact ~17 min at ~30% errors ~5 min-equivalent of full outage = ~12% of a 43.8-min monthly budget Root cause: new connection-pool setting reduced max connections 100 -> 10 Contributing: canary skippable for "config"; no config validation; alert fine Lucky: deploy happened during low traffic Action items (owner, priority): P0 make canary mandatory for config changes (delivery team, 1 wk) P1 schema + range validation for pool settings (checkout, 2 wk) P1 auto-rollback on canary SLO burn (delivery team, 4 wk) P2 runbook: "rollback first" decision guidance (SRE, 2 wk)` }, exercise: { prompt: `You join a team whose on-call engineer receives ~40 pages per week, most auto-resolve, and postmortems are rarely written. Outline a 90-day plan to fix incident response and on-call health.`, solution: `- **Measure**: categorize a month of pages (actionable vs not, by alert), count toil hours, list incidents and their time to detect/mitigate. - **Alerting**: delete or downgrade non-actionable alerts; move to SLO burn-rate pages for symptoms; route cause-based signals to dashboards or tickets. Target a few actionable pages per week. - **Process**: publish a severity rubric and IC/ops/comms roles, run tabletop exercises, add an incident bot or template for declaration, status cadence and timeline capture. - **Learning**: postmortems mandatory for SEV1/SEV2 and for incidents above a budget threshold; review weekly; track action items to closure as a team metric. - **Toil**: automate the top three manual tasks; cap toil at ~50% and report it. Re-measure at day 90.` }, faq: [ { q: "When should I escalate or page more people?", a: `As soon as the IC sees the incident needs skills or authority not present, or the mitigation is not working within the expected time. Escalating early is cheap; heroics are not.` }, { q: "Should postmortems name people?", a: `Use roles ("the on-call engineer"), not names, in the shared document. Include the decisions people made and the information they had, so the reader understands why it seemed reasonable.` }, { q: "How do you prevent postmortem action items from rotting?", a: `Give each an owner, priority and ticket, review open items in a recurring operations meeting, and link the error budget policy so an exhausted budget prioritizes them over features.` } ], keyTerms: ["incident commander", "severity level", "communications lead", "mitigation", "time to detect", "time to mitigate", "blameless postmortem", "contributing factors", "action item", "toil"], deeper: `Mean-time metrics (MTTR, MTTD) are noisy for small incident counts and can be gamed; many teams prefer tracking distributions and the proportion of incidents detected by alerting rather than by customers. Learning-focused reviews borrow from resilience engineering: instead of asking only what failed, they study how operators normally succeed under pressure, which often reveals the guardrails worth automating.`, interview: { seniorAnswer: `A strong answer describes a repeatable structure: symptom-based detection, early declaration with an impact-based severity, explicit roles (IC who coordinates and does not debug, ops lead who changes production, comms lead on a fixed cadence), "what changed?" and **mitigate first** with reversible actions, and a clear resolution criterion. Afterwards a blameless postmortem with impact in budget terms, a precise timeline, several contributing factors, lucky breaks, and owned action items across prevent, detect and mitigate. It also covers on-call sustainability: actionable pages only, toil measured and capped around 50%.`, followUps: [ { q: "The rollback did not fix it. What now?", a: `Re-check "what changed" beyond your own deploys (dependencies, config, traffic, certificates, quotas), widen the blast radius view (one AZ? one tenant?), try the next mitigation (drain AZ, fail over, shed non-critical traffic), and escalate. Keep updates going.` }, { q: "How do you measure whether incident response is improving?", a: `Time to detect and mitigate distributions, percentage detected by alerting vs customers, repeat incidents of the same class, action item closure rate, pages per shift and toil percentage.` }, { q: "How do you run a postmortem when another team caused the outage?", a: `Joint, blameless review focused on the interface: why their change could affect you, why you did not detect or contain it (missing fallbacks, timeouts, bulkheads), with action items on both sides.` } ], redFlags: [ "Debugging for root cause while users remain impacted and a rollback is available.", "IC also acting as the main debugger in a large incident.", 'Postmortems blaming an individual or ending with "be more careful".', "Action items with no owners or deadlines.", "Accepting high page volume as normal on-call life." ], numbers: [ "Toil cap: ~50% of SRE time (Google guidance)", "Pager load: on the order of <= 2 incidents per 12-hour shift", "SEV1 comms cadence: commonly every 15-30 minutes", "99.9% budget: ~43.8 min/month, so a 45-minute outage exhausts it" ] }, references: [ { title: "Google SRE book: Postmortem culture", url: "https://sre.google/sre-book/postmortem-culture/" }, { title: "Google SRE book: Eliminating toil", url: "https://sre.google/sre-book/eliminating-toil/" }, { title: "Google SRE workbook", url: "https://sre.google/workbook/table-of-contents/" } ] }, { id: "infra-rel-resilience", title: "High availability and disaster recovery", stage: 4, order: 3, objectives: ["rel-resilience", "rel-slo"], scope: "senior", estMinutes: 35, summary: "Failure domains, static stability, DR strategies from backup/restore to active-active with their RPO, RTO and cost, DNS failover pitfalls, cell-based architecture and chaos engineering.", what: `**High availability (HA)** keeps a service running through component and zone failures, usually automatically. **Disaster recovery (DR)** restores service after a larger loss (region, account compromise, data corruption) within agreed targets: - **RPO** (recovery point objective): how much data, measured in time, you may lose. - **RTO** (recovery time objective): how long until service is restored. Both are business decisions with steep cost curves, and both must be proven by testing.`, why: `"How would you make this survive an AZ or region failure?" is a standard senior follow-up, and the weak answer is "make it multi-region". A strong answer chooses the cheapest strategy that meets the RPO/RTO, identifies which failure domains are actually covered, removes dependencies on control planes during recovery, and explains how failover is triggered, tested and reversed. Real outages often come from the recovery path itself: untested restores, DNS caching, cold standby that cannot scale, or failover tooling that depends on the failed region.`, problem: `- A "multi-AZ" deployment still has one primary database in one AZ and a NAT gateway in another; losing either takes the service down. - During a zone outage, autoscaling tries to launch replacement capacity in the remaining zones at the same moment as everyone else, and the control plane is degraded. - Backups exist, but nobody has restored one; the first restore during a real incident takes 9 hours instead of the 1-hour RTO. - DNS failover is configured with a 60 s TTL, but clients and intermediate resolvers keep old answers, and long-lived connections never re-resolve. - A bad config push hits every region at once, so multi-region provided no protection.`, how: `**1. Map failure domains.** Host/rack < availability zone (one or more datacentres with independent power and networking) < region < provider/account. Also **logical** domains: a deployment, a config push, a shared dependency (identity, DNS), a tenant. Decide explicitly which failures you design for. **2. Multi-AZ by default, statically stable.** Spread stateless capacity across at least 3 AZs and provision enough that losing one AZ needs **no new launches**: with 3 AZs, each AZ must carry 50% of peak (150% total) so two AZs carry 100%. That is **static stability**: the data plane keeps working without calling the control plane during the failure. Use zonal replicas of per-AZ dependencies (NAT gateway per AZ, zonal load balancer targets) and synchronous or quorum replication across AZs for state. **3. Choose a DR strategy from RPO, RTO and cost:** - **Backup and restore**: backups (snapshots, PITR logs) copied to another region/account. RPO hours (or minutes with continuous log shipping), RTO hours to a day. Lowest cost. - **Pilot light**: data replicated continuously to the DR region; core infrastructure defined in IaC but compute mostly off. RPO minutes or less, RTO tens of minutes to hours (scale-up time). Low cost. - **Warm standby**: a scaled-down but running copy that can take traffic immediately and scale up. RPO seconds to minutes, RTO minutes. Moderate cost. - **Active-passive (hot standby)**: full-size standby, traffic switched on failover. RTO minutes; cost ~2x. - **Active-active (multi-site)**: all regions serve traffic; RTO near zero for routing. RPO depends on replication: asynchronous means some recent writes can be lost; synchronous cross-region writes add tens of milliseconds. Highest cost and complexity (conflict handling, data residency, global capacity for N-1). **4. Make failover boring.** Prefer failing over by **stopping** the bad region (health checks fail, traffic manager stops sending to it) rather than by actions that need the failed region's control plane. Pre-scale or keep warm capacity. Keep runbooks and tooling outside the region they protect. **5. Mind DNS.** DNS-based failover is bounded by TTL **plus** caching that ignores TTL (some resolvers, client runtimes with their own DNS caches, connection pools and HTTP keep-alive that never re-resolve). Use low TTLs (30\u201360 s) on failover records, cap connection lifetimes, and where possible use anycast or global load balancers whose IPs do not change. **6. Cell-based architecture.** Partition the service into independent **cells** (full stacks serving a subset of customers), with a thin routing layer mapping customer to cell. A bad deploy, poison request or noisy tenant affects one cell's share of customers (e.g. 1 of 20 = 5%). Deploy cell by cell, and size cells so they can be load-tested at maximum size. **7. Back up for corruption, not just loss.** Replication faithfully copies a bad delete. Keep point-in-time recovery, immutable or logically separated backups (different account, deletion protection), and test restores on a schedule, measuring the real RTO. **8. Chaos engineering.** Define steady state from SLIs, hypothesize it holds under a fault (kill an AZ's instances, add latency to a dependency, fail DNS), run in production-like conditions with a limited blast radius and an abort switch, and fix what breaks. Game days rehearse humans and runbooks as well as systems.`, components: [ { name: "Failure domains", description: "Physical (host, AZ, region) and logical (deploy, config, dependency, tenant) units that fail together. Redundancy only helps across independent domains." }, { name: "Static stability", description: "Pre-provisioned capacity and data-plane-only recovery so losing a domain needs no new launches or control-plane calls." }, { name: "DR strategy ladder", description: "Backup/restore -> pilot light -> warm standby -> hot standby -> active-active, trading cost for lower RPO and RTO." }, { name: "Traffic failover", description: "Health-checked DNS or global load balancing; TTL and client caching determine real switch-over time." }, { name: "Cells", description: "Independent full-stack partitions behind a thin router; caps blast radius of deploys, poison requests and noisy tenants." }, { name: "Restore and chaos testing", description: "Scheduled restores with measured RTO, game days, and controlled fault injection against SLO-defined steady state." } ], misconceptions: [ { myth: "Multi-region is always more reliable than multi-AZ.", reality: "It protects against region-level failure but adds replication, failover and consistency complexity that causes its own outages, and it does not help with global config pushes or bad code deployed everywhere. Many services meet their SLO with a well-built multi-AZ design." }, { myth: "Replication is a backup.", reality: "Replication copies corruption and deletes within seconds. You need point-in-time, isolated backups for logical failures and ransomware." }, { myth: "A 60-second DNS TTL means failover in 60 seconds.", reality: "Resolvers, runtimes and connection pools can hold stale answers or connections much longer. Measure real client behaviour." }, { myth: "Active-active has zero RPO.", reality: "Only if writes are synchronously committed across regions. With async replication, writes acknowledged in the failed region but not yet replicated are lost or must be reconciled." } ], example: { title: "Choosing a DR tier for three services", description: `Map business requirements to strategy, cost and the capacity rule for static stability.`, language: "text", code: `Service RPO RTO Strategy Approx. extra cost --------------- ------- ------- ---------------------- ------------------- Payments ledger ~0 < 5 min multi-AZ quorum DB + high (2-3x infra, warm standby region sync-in-region) Catalog API 15 min 1 h pilot light: async DB low-moderate replica + IaC, scale up Analytics batch 24 h 24 h backup/restore to very low another region/account Static stability for stateless tier, peak = 3,000 rps, 1 instance = 100 rps: 2 AZs: survive 1 loss -> each AZ 3,000 rps -> 60 instances total (200%) 3 AZs: each AZ 1,500 rps -> 45 instances total (150%) 4 AZs: each AZ 1,000 rps -> 40 instances total (133%) Cells: 20 cells, customer -> cell by hash; bad deploy in cell 1 -> 5% of customers DNS: failover record TTL 60 s; client pool max connection age 5 min` }, exercise: { prompt: `An e-commerce site runs in one region across 2 AZs, with a single-AZ primary database and nightly snapshots in the same account. The business asks for "survive a region outage with at most 5 minutes of data loss and 1 hour of downtime". Propose a design, the order of work, and how you would prove it.`, solution: `- **First fix the region itself**: 3 AZs with static stability (150% capacity), multi-AZ database with synchronous standby, NAT and other per-AZ dependencies duplicated. This removes the most likely failures cheaply. - **Backups**: enable point-in-time recovery, copy backups to another region **and account** with deletion protection, schedule restore tests. - **DR**: RPO 5 min / RTO 1 h fits **pilot light or warm standby**: an async cross-region read replica (lag alarmed well under 5 minutes), infrastructure in IaC, a small running app tier, images and secrets replicated, and a global load balancer or health-checked DNS with low TTL. - **Failover runbook** that does not depend on the primary region: promote replica, scale DR tier, shift traffic, freeze writes in the old region on recovery and plan failback. - **Prove it**: quarterly game day that fails over a production-like environment, measuring actual RPO (replication lag at cut-over) and RTO end to end; fix gaps until both meet target.` }, faq: [ { q: "What is the difference between RTO and MTTR?", a: `RTO is a target set by the business for a disaster scenario; MTTR is a measured average across incidents. You validate RTO by drills.` }, { q: "Why do failover plans warn against relying on the control plane?", a: `Control planes (launching instances, changing configuration) are more complex and more likely to be impaired or throttled during large events, while data planes (serving existing resources) are designed to keep running. Recovery that only needs data-plane operations is more dependable.` }, { q: "How big should a cell be?", a: `Small enough that the blast radius is acceptable and that you can load-test a cell at its maximum size; large enough that per-cell overhead and cross-cell operations stay manageable. Cap cell size and add cells rather than growing them.` } ], keyTerms: ["failure domain", "availability zone", "static stability", "RPO", "RTO", "pilot light", "warm standby", "active-active", "cell-based architecture", "chaos engineering"], deeper: `Shuffle sharding extends cells: each customer is assigned to a random small combination of workers, so two customers rarely share the same full set, and a poison customer can only take down the few combinations it touches. Also consider **failback**: after a regional failover, data written in the DR region must be replicated back and reconciled before returning traffic, which is often harder than the original failover.`, interview: { seniorAnswer: `A strong answer enumerates failure domains (including logical ones like deploys and config), makes multi-AZ statically stable with explicit capacity math (N AZs -> N/(N-1) of peak), then picks a DR tier by RPO, RTO and cost rather than defaulting to active-active. It is honest that async replication means RPO > 0, warns about DNS and client caching during failover, keeps recovery off control planes and outside the failed region, uses cells to cap blast radius, separates backups from replication for corruption scenarios, and insists on measured restore drills and chaos experiments.`, followUps: [ { q: "How do you avoid split brain when failing over a database across regions?", a: `Fence the old primary (revoke its write access or network, increment an epoch/term checked by clients), make promotion a deliberate single-writer decision, and never let automatic failover promote without a quorum or a human for cross-region cases.` }, { q: "Active-active across two regions: how much capacity do you need?", a: `Each region must handle full traffic when the other fails, so ~200% of peak in total (or N/(N-1) with N regions), plus data-layer headroom for the extra write load. This is the main cost driver.` }, { q: "What does a good game day look like?", a: `A written hypothesis tied to SLIs, a bounded blast radius, an abort criterion, observers, real runbooks used by on-call, measured RTO/RPO, and tracked follow-ups.` } ], redFlags: [ '"Just make it multi-region" with no RPO/RTO or cost discussion.', "Treating replication as backup.", "Failover plans that require launching capacity during the event with no headroom.", "Never having tested a restore.", "Ignoring DNS caching and long-lived connections in failover timing." ], numbers: [ "Static stability: N AZs need N/(N-1) of peak (3 AZs -> 150%)", "Two-region active-active: ~200% of peak capacity", "Failover DNS TTL: typically 30-60 s, real switch-over often longer", "Cells: blast radius ~ 1 / number of cells", "Intra-region cross-AZ RTT ~1-2 ms; cross-region tens to 100+ ms (order of magnitude)" ] }, references: [ { title: "AWS Builders' Library: Static stability using Availability Zones", url: "https://aws.amazon.com/builders-library/static-stability-using-availability-zones/" }, { title: "Principles of Chaos Engineering", url: "https://principlesofchaos.org/" }, { title: "AWS Well-Architected Framework", url: "https://aws.amazon.com/architecture/well-architected/" }, { title: "Google Cloud Architecture Center", url: "https://cloud.google.com/architecture" } ] }, // ---------------------------------------------------------------- Stage 5: Security & Identity { id: "infra-sec-identity", title: "Identity, least privilege and zero trust", stage: 5, order: 1, objectives: ["sec-identity"], scope: "senior", estMinutes: 35, summary: "How cloud IAM evaluates a request, why roles and short-lived credentials beat users and keys, federation and workload identity, guardrails above accounts, and zero trust per NIST SP 800-207.", what: `Cloud identity and access management answers one question for every API call: **may this principal perform this action on this resource under these conditions?** - **Principals**: human users (ideally federated from an identity provider), roles assumed by humans or workloads, service accounts / managed identities. - **Policies**: identity-based (attached to the principal), resource-based (attached to the bucket, key, queue), and organization-level **guardrails** that cap what any principal in an account or folder can do. - **Zero trust**: an architecture in which no request is trusted because of its network location; every access is authenticated, authorized and evaluated per session against identity, device and context. Rough equivalents: AWS IAM roles and SCPs, Azure Entra ID with Azure RBAC and Azure Policy, Google Cloud IAM with organization policies and IAM deny policies.`, why: `Most cloud breaches involve identity rather than exotic exploits: leaked long-lived access keys, over-permissive roles, public resources, or a CI system with administrator rights. Interviewers expect a senior engineer to explain how policy evaluation actually works, to design least privilege that teams can live with, to eliminate static secrets for workloads, and to put organization-wide guardrails in place so one mistake cannot become a company-wide incident.`, problem: `A typical legacy setup: - Engineers have IAM users with console passwords and access keys created years ago, some in laptops and CI variables. - Applications on VMs or Kubernetes read a static key from an environment variable. - Roles are granted wildcard actions (\`"Action": "*"\`) "to unblock the launch". - Nothing at the organization level prevents someone from disabling audit logging, creating resources in an unapproved region, or making a bucket public. - Network location ("it is inside the VPC") is treated as authentication.`, how: `**1. Understand policy evaluation (AWS model, conceptually similar elsewhere).** - Start from **implicit deny**: nothing is allowed unless something allows it. - Evaluate all applicable policies. If **any** applicable policy has an **explicit deny** matching the request, the answer is deny. **Explicit deny always wins.** - Organization guardrails (service control policies, resource control policies and similar) must **permit** the action; they never grant permissions on their own, they only cap them. (On AWS, SCPs do not apply to the management account or to service-linked roles.) - Then an allow is needed from the identity-based policy and/or the resource-based policy (cross-account access usually needs both sides to agree). - **Permission boundaries** and **session policies**, if present, further cap the effective permissions: the result is the intersection. Azure RBAC is additive role assignments with deny assignments taking precedence; Google Cloud IAM evaluates deny policies before allow policies. In all three, "deny wins" and "guardrails cap" are the mental model. **2. Prefer roles over users.** Humans sign in through **federation** (SAML or OIDC from the corporate IdP, with MFA) and assume roles that issue **short-lived credentials** (minutes to hours). No long-lived human access keys. Offboarding is then a single IdP action. **3. Workload identity, no static keys.** The platform attests the workload and exchanges that for short-lived cloud credentials: - VMs: instance profiles / managed identities / attached service accounts via the metadata service. - Kubernetes: projected service-account tokens federated to cloud roles (EKS Pod Identity or IRSA on AWS, Microsoft Entra Workload ID on AKS, Workload Identity Federation for GKE). - CI/CD: the CI system issues an **OIDC token** describing the repository, branch and workflow; the cloud's trust policy accepts only tokens whose claims match (e.g. a specific repo and the main branch) and returns credentials for one deploy role. Credentials expire on their own, so a leak has a short useful life. **4. Least privilege that scales.** Start from managed or narrowly scoped policies, use conditions (resource tags, source VPC, organization ID, MFA present) and **access analysis** of actual usage (last-accessed data, policy analyzers) to remove unused permissions. Separate accounts/subscriptions/projects per environment and team: the account boundary is the strongest blast-radius control. **5. Guardrails and delegated administration.** At the organization level: deny disabling audit logs, deny leaving the organization, restrict regions, block public access settings, require encryption. **Permission boundaries** let platform teams allow developers to create roles for their services without being able to create a role more powerful than the boundary, which prevents privilege escalation through role creation. **6. Zero trust (NIST SP 800-207).** Access decisions are made per request or session by a **policy decision point** (the policy engine plus policy administrator) and enforced by a **policy enforcement point** in front of the resource, using identity, device posture and context signals. Its seven tenets: all data sources and computing services are resources; all communication is secured regardless of network location; access to each resource is granted per session with least privilege; access is determined by dynamic policy (identity, application, asset state, behavioural and environmental attributes); the enterprise monitors the integrity and security posture of all assets; authentication and authorization are dynamic and strictly enforced before access; and the enterprise collects as much state as possible (assets, network, communications) to improve its posture. Practically: identity-aware proxies instead of VPN-as-trust, mTLS and workload identity between services, and continuous evaluation. **7. Break-glass.** A small number of emergency credentials, stored offline, MFA-protected, alarmed on any use, and tested periodically.`, components: [ { name: "Principals", description: "Federated humans, roles, service accounts / managed identities. Humans and workloads get short-lived credentials, not keys." }, { name: "Identity and resource policies", description: "Allow statements scoped by action, resource and condition; resource policies enable controlled cross-account access." }, { name: "Explicit deny and guardrails", description: "Explicit deny overrides any allow; organization policies (SCP-style, Azure Policy, org policies, IAM deny) cap whole accounts or folders." }, { name: "Permission boundaries", description: "Upper bound on what a principal (or roles it creates) can ever do; enables safe delegation of role creation." }, { name: "Federation and workload identity", description: "SAML/OIDC for humans; platform-attested tokens (metadata service, Kubernetes service account tokens, CI OIDC) exchanged for short-lived credentials." }, { name: "Zero-trust decision and enforcement points", description: "Policy engine/administrator decides per session; enforcement points (identity-aware proxy, mesh sidecar, gateway) apply the decision at each resource." } ], misconceptions: [ { myth: "An organization guardrail policy that allows an action grants it to everyone.", reality: "Guardrails only cap permissions. A principal still needs an identity- or resource-based allow, and any explicit deny anywhere wins." }, { myth: "Rotating access keys every 90 days makes them safe.", reality: "A leaked key is useful immediately. Remove long-lived keys entirely in favour of federation and workload identity with credentials that expire in minutes to hours." }, { myth: "Traffic inside the VPC is trusted, so internal services do not need authentication.", reality: "Zero trust treats network location as insufficient. Lateral movement after one compromised host is the classic breach pattern; authenticate and authorize every call." }, { myth: "Least privilege means hand-writing perfect policies up front.", reality: "Least privilege is iterative: start scoped, observe actual usage, tighten, and rely on account boundaries and guardrails so imperfect policies cannot do catastrophic damage." } ], example: { title: "Layered policies: identity allow, explicit deny and an organization guardrail", description: `Three AWS-style policy documents shown together. The service role may read and write its own prefix; an explicit deny blocks non-TLS access even though the allow matches; the organization guardrail caps every account to approved regions (global services would need exemptions in a real policy). Evaluate a PutObject to \`eu-west-1\` over TLS: allowed. The same call over plain HTTP: denied by the explicit deny. Any call in \`us-east-2\`: denied by the guardrail regardless of the role's allow.`, language: "json", code: `{ "identityPolicy_orders_service": { "Version": "2012-10-17", "Statement": [ { "Sid": "OwnPrefixReadWrite", "Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject"], "Resource": "arn:aws:s3:::acme-orders-prod/orders/*" }, { "Sid": "DenyInsecureTransport", "Effect": "Deny", "Action": "s3:*", "Resource": "*", "Condition": { "Bool": { "aws:SecureTransport": "false" } } } ] }, "orgGuardrail_regions": { "Version": "2012-10-17", "Statement": [ { "Sid": "DenyOutsideApprovedRegions", "Effect": "Deny", "Action": "*", "Resource": "*", "Condition": { "StringNotEquals": { "aws:RequestedRegion": ["eu-west-1", "eu-central-1"] } } } ] } }` }, exercise: { prompt: `Your GitHub Actions pipelines deploy to production using an access key with administrator rights stored as a repository secret, shared by 40 repositories. Design the replacement and the guardrails.`, solution: `- Replace the key with **OIDC federation**: configure the CI provider's OIDC issuer as an identity provider in the cloud; create one deploy role per service or environment whose trust policy accepts only tokens with matching audience and subject claims (e.g. \`repo:acme/orders:ref:refs/heads/main\` or a protected environment). - Scope each role to what its deployment touches (its stack, its artifact bucket, \`iam:PassRole\` only for its runtime role), attach a **permission boundary** so it cannot create more powerful roles. - Credentials last minutes to an hour and cannot be exfiltrated for later use. - Add organization guardrails: deny disabling audit logging, deny unapproved regions, deny public access changes; alarm on use of the old key, then delete it. - Review access analyzer findings and last-used data after a few weeks and tighten further.` }, faq: [ { q: "Users or roles for humans?", a: `Roles via federation from the corporate IdP with MFA. Humans get short-lived sessions; access follows group membership; offboarding is immediate.` }, { q: "How does cross-account access work safely?", a: `The target account's role trusts a specific principal (or organization) in the source account, ideally with conditions such as external ID for third parties; the source principal must also be allowed to assume it. Both sides consent.` }, { q: "What is the confused deputy problem?", a: `A trusted service is tricked into using its own permissions on behalf of an attacker. Mitigate with conditions binding the request to the original caller (source account/ARN conditions, external IDs).` } ], keyTerms: ["implicit deny", "explicit deny", "service control policy", "permission boundary", "federation", "OIDC", "workload identity", "short-lived credentials", "zero trust", "policy enforcement point"], deeper: `Attribute-based access control (ABAC) scales least privilege by writing a few policies over tags (e.g. a principal may act on resources whose \`team\` tag equals its own), which avoids an explosion of role-per-resource policies, but makes tag integrity a security control: who can set or change tags must itself be restricted.`, interview: { seniorAnswer: `A strong answer explains evaluation precisely (implicit deny, explicit deny wins, guardrails and boundaries cap, allows from identity or resource policies, intersection for sessions), removes long-lived credentials entirely with federation for humans and workload identity / CI OIDC for machines, uses accounts or projects as the primary blast-radius boundary with organization guardrails on top, and treats least privilege as an iterative process driven by usage data. It frames zero trust as per-request decisions on identity and context with enforcement points at each resource, citing NIST SP 800-207, and mentions break-glass access with alarms.`, followUps: [ { q: "A developer needs to create IAM roles for their Lambda/functions. How do you allow that safely?", a: `Allow role creation only with a mandatory permission boundary attached and only within a naming path; deny removing the boundary. Any role they create is capped by the boundary, so no escalation.` }, { q: "How would you detect a leaked credential being used?", a: `Audit logs streamed to a central account, anomaly detection on new source IPs/regions/APIs, alarms on use of break-glass or legacy keys, and short lifetimes so the window is small.` }, { q: "Is a VPN required in a zero-trust model?", a: `Not as a trust mechanism. Access goes through identity-aware proxies or gateways that evaluate user and device on each session; private networking may still exist for routing, not for authorization.` } ], redFlags: [ "Long-lived access keys in CI variables, environment variables or code.", "Wildcard actions and resources as a normal practice.", "Believing an allow in a guardrail policy grants access.", 'Treating "inside the VPC" as authenticated.', "No organization-level protection for audit logs." ], numbers: [ "Short-lived credentials: minutes to ~1-12 hours, not months", "Evaluation: explicit deny > guardrail cap > allow (identity/resource) > implicit deny", "Break-glass accounts: a handful, MFA, alarmed on every use" ] }, references: [ { title: "NIST SP 800-207: Zero Trust Architecture", url: "https://csrc.nist.gov/pubs/sp/800/207/final" }, { title: "AWS Well-Architected Framework", url: "https://aws.amazon.com/architecture/well-architected/" }, { title: "Google Cloud Well-Architected Framework", url: "https://cloud.google.com/architecture/framework" } ] }, { id: "infra-sec-data", title: "Encryption, key management and secrets", stage: 5, order: 2, objectives: ["sec-data", "sec-identity"], scope: "senior", estMinutes: 35, summary: "Envelope encryption with a KMS (DEK and KEK), key rotation and its limits, TLS and mTLS between services, secrets managers vs environment variables, and network segmentation as defence in depth.", what: `Data protection in the cloud has four layers: - **Encryption at rest** using keys held in a **key management service** (AWS KMS, Azure Key Vault / Managed HSM, Google Cloud KMS), usually through **envelope encryption**. - **Encryption in transit** with TLS 1.3 at the edge and between services, and **mTLS** where both sides must prove identity. - **Secrets management**: database passwords, API tokens and certificates stored in a secrets manager (AWS Secrets Manager, Azure Key Vault, Google Secret Manager or HashiCorp Vault), delivered to workloads at runtime and rotated. - **Segmentation**: network and account boundaries that limit what a compromised component can reach.`, why: `"Encrypt everything" is table stakes; interviews probe whether you know **what encryption actually protects against**. Disk encryption with a provider-managed key protects lost drives, not an attacker with your IAM credentials. The control that matters is **who can use the key**, which turns key policy into an access-control layer. Senior candidates are expected to explain envelope encryption, rotation trade-offs, crypto-shredding, why secrets do not belong in images or plain environment variables, and how mTLS gives workload identity.`, problem: `- A database password is baked into a container image and committed in a Helm values file; rotating it requires a redeploy of 30 services. - Every service uses one KMS key, so any role with \`kms:Decrypt\` on it can read every tenant's data. - Encrypting a 5 GB file directly with the KMS API fails (KMS encrypt calls accept only small payloads, e.g. 4 KB on AWS KMS) and would be slow and expensive per call anyway. - Internal traffic is plaintext HTTP "because it is inside the VPC"; one compromised pod can sniff or spoof calls. - Key rotation is enabled, and the team believes old data has been re-encrypted. It has not.`, how: `**1. Envelope encryption, step by step.** - The application asks KMS to **generate a data key** under a **key-encryption key (KEK)** that never leaves the KMS/HSM. - KMS returns the **data encryption key (DEK)** twice: in plaintext and encrypted under the KEK. - The application encrypts the data locally with the plaintext DEK (e.g. AES-256-GCM), stores the **encrypted DEK alongside the ciphertext**, and wipes the plaintext DEK from memory. - To decrypt, it sends the encrypted DEK to KMS; KMS checks the caller's permission (key policy + IAM + conditions), decrypts and returns the DEK; the application decrypts locally. Benefits: bulk data never travels to KMS; one KMS call per object or per session (cache DEKs briefly to cut cost and latency); access to data is governed and **audited** at the KMS decrypt call. Bind ciphertext to context with **additional authenticated data / encryption context** (e.g. tenant ID), so a DEK for one tenant cannot be replayed for another. **2. Key hierarchy and separation.** Separate KEKs per environment, data classification and (for high-sensitivity multi-tenant systems) per tenant. Key policies grant encrypt/decrypt to specific roles; separate duties so key **administrators** cannot use keys and key **users** cannot change policy. Customer-managed keys allow you to revoke or disable access, and **crypto-shredding**: destroying a tenant's key renders all their data unreadable, including in backups. **3. Rotation and its limits.** Automatic KEK rotation (commonly yearly by default; configurable on some providers) creates new key material for **new** encryptions while retaining old versions to decrypt old data. It does **not** re-encrypt existing data, and because old versions remain usable it does not help after a key compromise. After compromise, re-encrypt (or re-wrap DEKs) under a new key and disable the old. Re-wrapping DEKs is cheap: only the small encrypted DEKs change, not the bulk data. **4. TLS and mTLS.** Terminate TLS 1.3 at the edge (1-RTT handshake, forward secrecy by default). Between services, use **mTLS**: each workload gets a short-lived certificate encoding its identity (e.g. a SPIFFE ID), issued and rotated automatically by a mesh or workload-identity system (lifetimes of hours to about a day). Authorization policies then reference identities ("orders may call payments on POST /charge"), not IP addresses. Watch certificate expiry: an expired root or intermediate is a classic outage. **5. Secrets management.** Store secrets in a secrets manager with fine-grained IAM, versioning, audit and **rotation** (the manager or a function rotates the credential in the database, then updates the secret; apps re-read on failure or on a schedule). Deliver at runtime via SDK, sidecar/agent or a CSI-mounted file rather than baking into images or plain environment variables, which leak into crash dumps, \`/proc\`, debug endpoints and logs, and are inherited by child processes. Better still, **eliminate** secrets: IAM database authentication, workload identity to cloud APIs, short-lived dynamic database credentials. Scan repositories and images for committed secrets and treat any hit as compromised. **6. Segmentation.** Layer controls: separate accounts/projects per environment, private subnets with no inbound internet route, security groups that reference other groups rather than CIDRs, private endpoints for managed services so traffic never crosses the internet, egress filtering through proxies or firewalls, and service-level authorization via mTLS identities. Encryption and segmentation are complementary: one protects data if traffic is intercepted, the other limits who can reach it at all.`, components: [ { name: "KMS and KEKs", description: "HSM-backed keys that never leave the service; key policies decide who can encrypt, decrypt and administer; every use is audit-logged." }, { name: "Data encryption keys", description: "Per-object or per-session keys generated by KMS, used locally, stored encrypted next to the data." }, { name: "Rotation and re-wrapping", description: "New key versions for new data; re-wrap DEKs or re-encrypt after compromise; old versions disabled deliberately." }, { name: "TLS 1.3 and mTLS", description: "Encryption and server authentication at the edge; mutual authentication with short-lived workload certificates internally." }, { name: "Secrets manager", description: "Central, audited, versioned storage with automated rotation and runtime delivery; ideally replaced by identity-based access where possible." }, { name: "Segmentation", description: "Account, network, private endpoint and egress controls that limit reachability and blast radius." } ], misconceptions: [ { myth: "Encryption at rest protects our data from an attacker who has stolen cloud credentials.", reality: "Storage services decrypt transparently for any principal allowed to read. Protection comes from controlling **who can use the key** and the data API, with separate keys and narrow key policies." }, { myth: "Enabling automatic key rotation re-encrypts existing data.", reality: "It only creates new key material for future encryptions; old versions stay available to decrypt old ciphertext. Re-encryption or DEK re-wrapping is a separate job." }, { myth: "Environment variables are a secure way to deliver secrets.", reality: "They are better than hardcoding but leak through process listings, crash reports, debug endpoints and child processes, and cannot rotate without restart. Prefer a secrets manager with runtime fetch or mounted files, or no secret at all." }, { myth: "mTLS inside the cluster is redundant if the network is private.", reality: "mTLS gives each call an authenticated identity, which is what allows authorization policy and blocks lateral movement after a single compromise." } ], example: { title: "Envelope encryption flow with per-tenant context", description: `The KMS calls are real AWS CLI operations (other providers have equivalent APIs); local encryption uses a standard AEAD from your crypto library. Note what is stored and what is never stored.`, language: "bash", code: `# 1) Ask KMS for a fresh 256-bit DEK under the tenant's KEK, bound to the tenant aws kms generate-data-key \\ --key-id alias/tenant-data-prod \\ --key-spec AES_256 \\ --encryption-context tenant=t-42 # -> { "Plaintext": "", "CiphertextBlob": "", "KeyId": "arn:..." } # 2) In the app: AES-256-GCM encrypt the object with Plaintext DEK (local, fast) # store: { ciphertext, nonce, auth_tag, encrypted_dek=CiphertextBlob, ctx={tenant:t-42} } # then zero the plaintext DEK in memory. Never log or persist it. # 3) To read: unwrap the DEK (KMS checks key policy + IAM + context, and logs the call) aws kms decrypt \\ --ciphertext-blob fileb://encrypted_dek.bin \\ --encryption-context tenant=t-42 \\ --query Plaintext --output text # wrong tenant context -> decrypt fails (context is authenticated) # Cost/latency: 10,000 objects/s with one KMS call each = 10,000 KMS req/s # -> cache DEKs per tenant for e.g. 5 min, or one DEK per batch/session` }, exercise: { prompt: `A multi-tenant SaaS stores customer documents in object storage with provider-managed encryption and one shared database password in an environment variable. A large customer requires that they can revoke your access to their data and that you can prove every access. Design the changes.`, solution: `- Move to **per-tenant customer-managed KEKs** (optionally keys hosted in the customer's own account/tenancy for bring-your-own-key) with **envelope encryption** and the tenant ID as encryption context. - Revocation: the customer disables the key or removes your grant; all of their data, including backups encrypted under it, becomes unreadable once any cached plaintext DEKs expire, so keep the DEK cache TTL short and state it in the contract (crypto-shredding on deletion). - Proof of access: every decrypt is a KMS call recorded in audit logs with caller identity and context; ship them to an immutable log store and expose a per-tenant access report. - Replace the database password with **IAM database authentication** or dynamic short-lived credentials from a secrets manager; remove it from environment variables; enable rotation. - Add mTLS between services so only the document service identity can request decryption for documents, and scope the key policy to that role.` }, faq: [ { q: "Provider-managed or customer-managed keys?", a: `Provider-managed is fine for baseline at-rest protection. Use customer-managed keys when you need separate access control and audit per dataset, revocation, crypto-shredding, cross-account control or compliance requirements that demand it; they add cost and operational responsibility.` }, { q: "Should the app cache plaintext DEKs?", a: `Briefly and in memory only, bounded by time and number of uses, to reduce KMS cost and latency. The trade-off is a slightly longer window if the host is compromised and slower revocation.` }, { q: "Is client-side encryption worth it?", a: `When the storage operator (or the provider) must not see plaintext, or for end-to-end protection across systems. It costs search/indexing capability and adds key distribution complexity.` } ], keyTerms: ["envelope encryption", "data encryption key (DEK)", "key encryption key (KEK)", "encryption context", "key rotation", "crypto-shredding", "mTLS", "SPIFFE ID", "secrets manager", "network segmentation"], deeper: `Hardware security modules give FIPS-validated key protection; cloud KMS services run on HSMs, with dedicated single-tenant HSM offerings for stricter requirements at much higher cost and operational burden. Confidential computing (memory encryption with hardware-attested enclaves or confidential VMs) extends protection to data in use, relevant when even the host operator must be excluded.`, interview: { seniorAnswer: `A strong answer explains envelope encryption step by step (generate DEK, encrypt locally, store wrapped DEK, decrypt via KMS with policy checks and audit), uses encryption context to bind ciphertext to a tenant, separates keys by environment, classification and tenant, and is precise about rotation (new versions for new data; re-wrap or re-encrypt after compromise). It frames key policy as the real access control, uses TLS 1.3 at the edge and mTLS with short-lived workload certificates internally, moves secrets to a manager with rotation or eliminates them via workload identity, and layers network segmentation and private endpoints for defence in depth.`, followUps: [ { q: "What does encryption at rest with a provider key actually protect against?", a: `Physical media theft and certain provider-side access paths. Not against your own principals or stolen credentials, since the service decrypts for anyone authorized to read.` }, { q: "How do you rotate a database password without downtime?", a: `Use two credentials (or the manager's alternating-user strategy): create the new one, update the secret, let clients pick it up (re-read on auth failure), then revoke the old one after the overlap window.` }, { q: "Where would you terminate TLS?", a: `At the edge load balancer for the public certificate and WAF, then re-encrypt to backends with mTLS; terminate at the service itself when end-to-end encryption is required and the load balancer must not see plaintext (L4 passthrough).` } ], redFlags: [ 'Equating "encryption at rest enabled" with "data is protected".', "Believing key rotation re-encrypts data or fixes a compromise.", "Secrets in images, code, Terraform state without protection, or logs.", "One key for all tenants and environments.", 'Plaintext internal traffic justified by "private network".' ], numbers: [ "DEK: AES-256, usually AES-256-GCM", "KMS direct encrypt payload limit: small (4 KB on AWS KMS, 64 KiB on Google Cloud KMS), hence envelope encryption", "Automatic KEK rotation: commonly yearly by default", "Workload certificates: hours to ~1 day lifetime", "TLS 1.3: 1-RTT full handshake" ] }, references: [ { title: "RFC 8446: TLS 1.3", url: "https://www.rfc-editor.org/rfc/rfc8446" }, { title: "AWS Well-Architected Framework", url: "https://aws.amazon.com/architecture/well-architected/" }, { title: "Azure Well-Architected Framework", url: "https://learn.microsoft.com/en-us/azure/well-architected/" } ] }, { id: "infra-sec-supply-chain", title: "Supply chain security, guardrails and compliance", stage: 5, order: 3, objectives: ["sec-supply-chain", "auto-delivery"], scope: "senior", estMinutes: 35, summary: "The shared responsibility model across IaaS, PaaS and SaaS, SLSA build levels and provenance, SBOMs, keyless signing with Sigstore, vulnerability management with patch SLAs, policy-as-code guardrails and audit logging.", what: `Supply chain security protects everything that goes into what you run: source, dependencies, base images, build systems, artifacts and deployment. Compliance is proving, continuously and with evidence, that controls exist and work. - **Shared responsibility**: what the provider secures versus what you secure, which shifts with the service model. - **Build integrity**: SLSA levels and signed **provenance** describing how an artifact was built. - **Inventory**: **SBOMs** listing components and versions. - **Authenticity**: artifact **signing** (Sigstore / cosign) and verification at deploy time. - **Hygiene**: vulnerability management with patch SLAs; **policy as code** guardrails; tamper-resistant **audit logs**.`, why: `Attacks on build systems, dependencies and package registries (malicious packages, typosquatting, compromised CI, poisoned base images) bypass perimeter controls entirely because the malicious code arrives signed by your own pipeline. Regulators and enterprise customers increasingly ask for SBOMs and provenance. Senior engineers are expected to design a pipeline where only artifacts built by trusted builders from reviewed source can run in production, and to run vulnerability management by risk rather than by CVE count.`, problem: `- Developers build images on laptops and push them directly to the production registry with a shared credential. - Images are referenced by mutable tags like \`:latest\`, so what runs is not what was tested. - A critical vulnerability is announced; nobody can say within a day which services include the affected library. - The vulnerability scanner reports 4,000 findings; teams ignore all of them. - Policies exist in a wiki ("no public buckets") but nothing enforces them, and audit logs live in the same account an attacker would control.`, how: `**1. Shared responsibility by model (NIST SP 800-145 service models).** - **IaaS** (VMs): provider secures facilities, hardware, hypervisor and network; you own guest OS patching, runtime, network configuration, IAM, data and application. - **PaaS** (managed databases, functions, managed Kubernetes control plane): provider also owns OS and runtime patching; you own configuration, identity, network exposure, data and code. - **SaaS**: provider runs nearly everything; you still own **identities, access configuration and your data**. In every model, misconfiguration and access management are yours. **2. SLSA build track.** SLSA v1.x defines build levels: - **L1**: provenance exists, describing how the artifact was built (builder, source, build steps). - **L2**: builds run on a **hosted** build platform that generates and **signs** the provenance, so it cannot be trivially forged after the fact. - **L3**: a **hardened** build platform: builds are isolated from one another and the signing material is not accessible to user-defined build steps, so even a compromised build script cannot forge provenance. Consumers verify provenance at deploy time: expected builder, expected source repository and branch, artifact digest matches. **3. SBOMs.** Generate an SBOM (SPDX or CycloneDX) for each artifact at build time, store and attach it to the image (as an attestation), and index it centrally. When a new CVE lands, query "which deployed digests contain library X version Y" in minutes. An SBOM is inventory, not a security verdict. **4. Signing with Sigstore.** **cosign** signs container images and attestations. In **keyless** mode, the CI job authenticates with its OIDC identity to **Fulcio**, which issues a short-lived signing certificate binding the signature to that identity (e.g. a specific workflow in a specific repository); the signature event is recorded in the **Rekor** transparency log. Verification checks the signature, the certificate identity and issuer, and the log entry. No long-lived signing keys to steal or rotate. **5. Enforce at admission.** Deploy by **digest**, not tag. A Kubernetes admission controller (OPA Gatekeeper, Kyverno, or a cloud's binary authorization feature) rejects images that are not signed by the expected identity, lack provenance from the trusted builder, or violate policy. Have an audited break-glass path. **6. Vulnerability management by risk.** Scan images, dependencies and hosts continuously (new CVEs affect old images). Prioritize by severity **and** exploitability and exposure: known exploited vulnerabilities (e.g. CISA's KEV catalog), exploit-likelihood scores such as EPSS, internet exposure, and whether the vulnerable code is reachable. Set **patch SLAs** by tier, for example: critical and known-exploited on internet-facing systems within days; high within ~30 days; medium within ~90 days; track exceptions with expiry dates. Keep base images minimal (distroless or slim) and rebuild them on a schedule so patching is a rebuild, not a manual fix. **7. Policy as code guardrails.** Express rules as code (OPA/Rego, Kyverno, cloud-native policy services, Terraform policy checks) and enforce in three places: **CI** (fail the plan or build), **admission/deploy** (reject), and **runtime/organization** (preventive guardrails and detective rules that alert or auto-remediate). Version, test and review policies like application code. **8. Audit logging and evidence.** Enable control-plane audit logs everywhere (AWS CloudTrail, Azure Activity Log and Entra ID logs, Google Cloud Audit Logs), centralize them into a separate, restricted log-archive account or project with immutable retention (object lock / immutability policies), and deny disabling them through organization guardrails. Compliance frameworks (SOC 2, ISO 27001, PCI DSS) then draw evidence from these logs and policy reports continuously instead of from screenshots.`, components: [ { name: "Shared responsibility model", description: "Provider vs customer duties shift across IaaS, PaaS and SaaS; identity, configuration and data stay with the customer." }, { name: "SLSA provenance", description: "Signed, verifiable record of builder, source and build process; L1 exists, L2 hosted and signed, L3 hardened and isolated." }, { name: "SBOM", description: 'Machine-readable component inventory (SPDX, CycloneDX) per artifact, indexed for fast "where are we affected?" queries.' }, { name: "Signing and verification", description: "Sigstore cosign keyless signing via OIDC identity, Fulcio short-lived certificates and the Rekor transparency log; verified at admission." }, { name: "Vulnerability management", description: "Continuous scanning, risk-based prioritization (KEV, EPSS, exposure, reachability), tiered patch SLAs and expiring exceptions." }, { name: "Policy as code and audit", description: "Guardrails enforced in CI, at admission and at the organization level; immutable, centralized audit logs as evidence." } ], misconceptions: [ { myth: "Using a managed service means the provider handles security.", reality: "The provider secures the service; you still own identities, access policies, network exposure, encryption choices and your data. Most cloud incidents are customer-side misconfiguration." }, { myth: "An SBOM makes software secure.", reality: "An SBOM is an inventory. Its value is fast impact analysis and licence/vulnerability matching; it must be paired with scanning, prioritization and patching." }, { myth: "Signing images is enough.", reality: "A signature proves who signed, not that the build was trustworthy. Verify the signer identity and the provenance (trusted builder, expected source), and enforce it at admission." }, { myth: "Fix every CVE by CVSS score order.", reality: "Raw counts and CVSS alone bury the urgent few. Prioritize known-exploited, internet-exposed and reachable vulnerabilities first, with SLAs and tracked exceptions." } ], example: { title: "Sign in CI, verify at deploy, reject unpinned images", description: `Keyless signing in CI with cosign, verification that pins the signer identity, and a small Rego admission rule (OPA v1 syntax) requiring digest-pinned images. The organization, repository and image names are placeholders.`, language: "bash", code: `# In CI (GitHub Actions job with id-token: write permission), after pushing by digest IMAGE=registry.example.com/orders@sha256:3f1c...e9 cosign sign --yes "$IMAGE" # keyless: OIDC -> Fulcio cert -> Rekor entry cosign attest --yes --type cyclonedx --predicate sbom.cdx.json "$IMAGE" # At deploy / in an admission controller: verify WHO signed it, not just that it is signed cosign verify "$IMAGE" \\ --certificate-identity-regexp '^https://github.com/acme/orders/\\.github/workflows/release\\.yml@refs/heads/main$' \\ --certificate-oidc-issuer https://token.actions.githubusercontent.com # Rego admission rule: images must be pinned by digest # package k8s.admission # deny contains msg if { # input.request.kind.kind == "Pod" # some c in input.request.object.spec.containers # not contains(c.image, "@sha256:") # msg := sprintf("image %v must be pinned by digest", [c.image]) # } # Example patch SLA policy (internal policy, not a standard): # known-exploited or critical + internet-facing : 7 days # high : 30 days # medium : 90 days # exceptions: owner + compensating control + expiry date` }, exercise: { prompt: `A widely used logging library has a critical remote-code-execution CVE announced this morning, and it is on the known-exploited list. You run ~300 services across Kubernetes and VMs. Walk through the first 24 hours, then the changes that make the next one faster.`, solution: `- **Hour 0\u20132**: declare an incident; query the SBOM index (and running-image inventory) for affected versions; rank by exposure: internet-facing first. Where available, apply a fast mitigation: WAF rules for the known exploit pattern, configuration flags that disable the vulnerable feature, egress restrictions that block the typical callback. - **Hour 2\u201324**: bump the dependency in shared base images and libraries, rebuild through the normal pipeline (signed, with provenance), roll out by priority with canaries; patch VM fleets via image rebuild or configuration management. Track coverage as "% of exposed services patched" and hunt in audit and network logs for exploitation indicators. - **Afterwards**: make SBOMs mandatory at build and indexed centrally; scheduled base-image rebuilds; dependency update bots; admission policy requiring signed, digest-pinned images built by the trusted builder; default-deny egress; documented patch SLAs with known-exploited items at the top.` }, faq: [ { q: "What is the difference between an SBOM and provenance?", a: `An SBOM lists **what** is inside an artifact. Provenance describes **how and where** it was built (builder, source revision, parameters). You want both, attached to the artifact digest.` }, { q: "Preventive or detective guardrails?", a: `Both. Preventive (deny in CI, admission or organization policy) for rules that must never be broken; detective (alert, auto-remediate) for rules with legitimate exceptions or where blocking would break production. Start detective, measure violations, then promote to preventive.` }, { q: "Why keep audit logs in a separate account?", a: `An attacker who gains administrator access in a workload account should not be able to delete or alter the evidence. A separate, locked-down account with immutable retention preserves it.` } ], keyTerms: ["shared responsibility model", "SLSA", "build provenance", "SBOM", "cosign", "keyless signing", "transparency log", "patch SLA", "policy as code", "audit log"], deeper: `Dependency confusion and typosquatting are mitigated by routing all package installs through an internal proxy/registry that pins namespaces to sources, lockfiles with hashes, and allowlisting. For the highest assurance, reproducible builds let independent builders produce bit-identical artifacts so provenance can be cross-checked rather than trusted.`, interview: { seniorAnswer: `A strong answer starts with the shared responsibility model (and that identity, configuration and data are always the customer's), then describes an end-to-end trusted pipeline: reviewed source, hosted hardened builder producing signed SLSA provenance, SBOM per artifact, keyless signing bound to the CI workload identity, digest-pinned deploys, and admission policies that verify signer identity and provenance. It runs vulnerability management by risk with patch SLAs and expiring exceptions, enforces policy as code in CI, at admission and at the organization level, and keeps immutable, centralized audit logs that double as compliance evidence.`, followUps: [ { q: "How do you get from SLSA L1 to L3?", a: `L1: generate provenance in the pipeline. L2: move builds to a hosted CI that signs provenance. L3: use a hardened, isolated builder whose signing keys are inaccessible to build steps (e.g. reusable trusted workflows), then enforce verification at deploy.` }, { q: "What does keyless signing remove, and what does it depend on?", a: `It removes long-lived signing keys. It depends on the OIDC identity provider and the Sigstore infrastructure (Fulcio, Rekor) and on verifying the exact identity and issuer; verifying "any valid signature" is meaningless.` }, { q: "How do you stop the scanner backlog from being ignored?", a: `Prioritize by exploitation and exposure, auto-fix via base-image rebuilds and dependency bots, show each team only actionable items against SLAs, and track exceptions with owners and expiry.` } ], redFlags: [ "Deploying mutable tags such as :latest to production.", "Long-lived signing keys or registry credentials on developer laptops.", "Treating SBOM generation as the whole supply chain programme.", "Prioritizing by raw CVE count or CVSS alone.", "Audit logs stored in the same account they are meant to protect, or deletable by workload admins." ], numbers: [ "SLSA build track: L1 provenance exists, L2 hosted + signed, L3 hardened + isolated", "Example patch SLAs: critical/known-exploited exposed ~7 days, high ~30, medium ~90", "Sigstore keyless certs are short-lived (on the order of minutes)" ] }, references: [ { title: "SLSA: Supply-chain Levels for Software Artifacts", url: "https://slsa.dev/" }, { title: "Sigstore", url: "https://sigstore.dev/" }, { title: "AWS Shared Responsibility Model", url: "https://aws.amazon.com/compliance/shared-responsibility-model/" }, { title: "Open Policy Agent documentation", url: "https://www.openpolicyagent.org/docs/latest/" } ] } ]; // ../../packages/content/src/infra/lessons-3.ts var infraLessons3 = [ // ───────────────────────────── Stage 6 · Automation & Delivery ──────────────────────────── { id: "infra-auto-iac", title: "Infrastructure as code: state, blast radius and policy", stage: 6, order: 1, objectives: ["auto-iac"], scope: "senior", estMinutes: 30, summary: "Declarative IaC turns infrastructure into reviewed diffs. The hard parts are not syntax: they are state ownership, locking, blast radius, drift, secrets and guardrails that scale to many teams.", what: `Infrastructure as code (IaC) describes the **desired state** of infrastructure in versioned files and lets a tool compute and apply the difference against reality. Terraform (and its open-source fork OpenTofu) is the reference model most interviews assume: - **Configuration** \u2013 HCL files declaring resources, data sources, variables and outputs. - **State** \u2013 a JSON document mapping every declared resource address (\`aws_s3_bucket.logs\`) to the real object ID and its last-known attributes. - **Plan** \u2013 refresh state from provider APIs, diff it against configuration, and produce an ordered set of create / update / replace / destroy actions. - **Apply** \u2013 execute that plan through provider APIs, walking the dependency graph in parallel, then write the new state. Cloud-native alternatives (CloudFormation on AWS, Bicep/ARM on Azure, Infrastructure Manager / Config Connector on Google Cloud, Pulumi, Crossplane) share the same core idea: a desired-state model, a diff, and an engine that converges.`, why: `Without IaC every environment is a hand-built snowflake: nobody can say what production *is*, rebuilding a region after a disaster becomes archaeology, and audits rely on screenshots. With IaC, a change to infrastructure is a pull request with a machine-generated plan attached, reviewed like code, applied by a pipeline, and reproducible in another account or region. For a senior engineer the real value is **controlled change at scale**: dozens of teams modifying shared cloud estates without stepping on each other, with guardrails enforced automatically rather than by tribal review.`, problem: `The naive setup is one giant root module with a local state file. It fails in predictable ways: - **Concurrent applies** corrupt or overwrite state because nothing locks it. - **One plan touches everything**, so a typo in a tag can propose replacing a production database; plans take 20 minutes and reviewers stop reading them. - **Console hot-fixes** during incidents create drift that the next apply silently reverts. - **Secrets** (generated DB passwords, private keys) land in plaintext in state that is readable by anyone with bucket access. - **No guardrails**: a public bucket or a \`0.0.0.0/0\` security rule gets merged because a reviewer missed one line in a 900-line plan.`, how: `**State is the source of truth for what the tool manages.** Store it remotely (object storage such as S3 / Azure Blob / GCS, or a managed backend) with versioning enabled and **locking** so only one writer runs at a time (for the S3 backend, historically a DynamoDB lock table; Terraform 1.10+ supports S3-native locking with \`use_lockfile = true\`, and DynamoDB-based locking is now deprecated). Restrict state access as tightly as production credentials, because it contains them. **Split state to limit blast radius.** Organise roots by lifecycle and ownership: \`network\`, \`shared-data\`, \`platform\`, \`service-x\` per environment. Rarely-changing, high-impact layers (VPCs, DNS zones, KMS keys) live apart from frequently-changing app infrastructure. Pass values between layers via outputs read through remote-state data sources or, better, via a published parameter store, so consumers do not need read access to another team's whole state. **Modules with versions.** Shared modules (a "standard service", a "hardened bucket") are published with semantic versions and pinned by consumers. Breaking changes are a major bump; consumers upgrade deliberately. Pin provider versions with a lock file for reproducible plans. **Plan, review, apply the same plan.** CI runs \`terraform plan -out=tfplan\` on the PR, posts the summary, runs policy checks on the JSON plan, and the apply step applies *that saved plan* after approval, so what was reviewed is what runs. **Drift detection.** Schedule \`terraform plan -refresh-only\` (or a full plan with \`-detailed-exitcode\`) per root and alert on non-empty diffs. Then decide: codify the manual change, or revert it. **Import and refactor safely.** Bring existing resources under management with \`import\` blocks (or the older \`terraform import\` command), and rename/move resources with \`moved\` blocks instead of destroy-and-recreate. **Environments.** CLI workspaces share one configuration and backend with separate state; they suit identical, ephemeral copies. For long-lived dev/stage/prod, separate directories (or separate root configs per environment calling the same versioned modules) with separate backends and credentials give clearer isolation: a prod apply cannot happen because someone forgot which workspace was selected. **Policy as code.** Evaluate the plan JSON against rules (OPA/Rego via tools like Conftest, HashiCorp Sentinel, or cloud-native policy such as AWS SCPs / Azure Policy / GCP Organization Policy as a backstop). Typical rules: no public storage, encryption required, mandatory cost tags, allowed instance families, deletion protection on databases. **Immutable over mutable.** Prefer replacing servers from a new image (bake with Packer or build containers) over patching them in place with configuration management; in-place mutation accumulates drift. Mutable updates remain fine for things that are expensive to replace and designed for it (database parameter changes, autoscaling settings).`, components: [ { name: "State backend + lock", description: "Remote, versioned, encrypted storage for state with a mutual-exclusion lock. Losing or corrupting it means the tool no longer knows what it owns; versioning is your undo button." }, { name: "Root modules (stacks)", description: "The unit of plan/apply and therefore the unit of **blast radius**. Sized by ownership and change frequency, not by convenience." }, { name: "Reusable modules", description: "Versioned building blocks that encode the paved road (encryption on, logging on, tags required). Pinned by consumers; upgraded via PRs." }, { name: "Plan pipeline", description: "CI that runs fmt/validate, plan, policy checks and posts results on the PR; applies the saved plan after approval using short-lived credentials (OIDC federation rather than static keys)." }, { name: "Policy engine", description: "OPA/Conftest, Sentinel or similar evaluating plan JSON pre-apply, backed by organisation-level cloud policies that also stop console changes." }, { name: "Drift detector", description: "Scheduled refresh-only plans per root that open tickets or alerts when reality diverges from code." } ], misconceptions: [ { myth: "State is just a cache; you can regenerate it.", reality: "State holds the mapping from addresses to real IDs plus attributes some providers cannot re-read. Losing it means re-importing everything by hand. Treat it as critical data: versioned, backed up, access-controlled." }, { myth: "Marking a variable `sensitive` keeps secrets out of state.", reality: "`sensitive` only redacts CLI output. Values still land in state in plaintext. Keep secrets in a secrets manager and reference them at runtime, generate them outside IaC, use ephemeral values (Terraform 1.10+) and write-only arguments (1.11+) where providers support them, and encrypt and lock down the state backend." }, { myth: "Workspaces are the standard way to separate prod from dev.", reality: "Workspaces share code, backend and usually credentials, so a wrong selection can hit prod. For long-lived environments, separate directories/backends/credentials are the safer default." }, { myth: "One big state is simpler, so it is better.", reality: "It is simpler on day one and dangerous on day 300: slow plans, lock contention between teams and a blast radius equal to the whole estate." } ], example: { title: "Layered roots with a remote, locked backend and a policy gate", description: `A network layer owned by the platform team, consumed by a service layer. The service root reads only the outputs it needs; CI blocks the plan if policy fails.`, language: "bash", code: `# repo layout live/prod/network/ # VPC, subnets, NAT, DNS (changes monthly) live/prod/data/ # databases, KMS keys (changes rarely, deletion_protection on) live/prod/svc-orders/ # ASG/K8s resources, queues (changes daily) modules/service/ v3.2.0 # pinned by svc-* roots # CI for live/prod/svc-orders terraform init -input=false terraform plan -input=false -out=tfplan -detailed-exitcode # exit 2 = changes present terraform show -json tfplan > plan.json conftest test plan.json --policy policy/ # OPA/Rego rules # ...human approval on the PR... terraform apply -input=false tfplan # applies exactly what was reviewed` }, exercise: { prompt: `Your company has a single Terraform state with ~4,000 resources across all services in prod. Plans take 25 minutes, two teams regularly block each other on the lock, and last month a PR proposed replacing the primary database because of a module upgrade. Propose a migration plan.`, solution: `- **Target layout:** split by ownership and change rate: \`network\`, \`data\` (databases, keys), \`platform\` (clusters, shared ingress), then one root per service. Each gets its own backend key and least-privilege CI role. - **Mechanics:** move resources with \`terraform state mv\` or by adding \`import\` blocks in the new root and \`removed\` blocks (with \`lifecycle { destroy = false }\`) in the old one, one layer at a time, verifying each new root plans to **zero changes** before moving on. - **Guardrails:** \`prevent_destroy\` / provider deletion protection on databases; a policy that fails any plan containing \`delete\` or \`replace\` on resources tagged \`tier=data\` unless an override label is present. - **Modules:** version the shared module, pin it, and upgrade service roots independently. - **Outcome to report:** plan time per root drops to about a minute, lock contention disappears, and the worst-case blast radius of a service PR is that service.` }, faq: [ { q: "Terraform vs cloud-native tools (CloudFormation, Bicep)?", a: "Native tools get day-zero support for new services and server-side state, but lock you to one provider. Terraform/OpenTofu gives one workflow across clouds and SaaS (DNS, monitoring, identity). Many orgs pick one per layer and are explicit about why." }, { q: "How do I handle a console change made during an incident?", a: "Drift detection flags it; the incident follow-up either codifies the change in a PR (plan shows no diff afterward) or reverts it deliberately. Never let the next unrelated apply be the thing that silently undoes it." }, { q: "What is the difference between `moved`, `import` and `removed` blocks?", a: "`moved` renames an address without touching the real object; `import` adopts an existing object into state; `removed` drops an object from state, optionally without destroying it. All three make refactors reviewable in a plan." } ], keyTerms: ["desired state", "state file", "state locking", "blast radius", "module versioning", "drift detection", "import block", "policy as code", "immutable infrastructure", "workspaces"], deeper: `**Dependency and ordering traps.** Terraform builds a graph from references; hidden dependencies (an IAM policy that must exist before a function can start) need explicit \`depends_on\`, which also makes plans more conservative. **Create-before-destroy** avoids downtime on replacement but needs unique names. **Provider-side eventual consistency** (IAM propagation can take seconds) causes flaky applies; retries in providers mitigate but do not eliminate it. **Controllers vs CLI.** Reconciling controllers (Crossplane, Config Connector, the Terraform-in-Kubernetes operators) continuously correct drift rather than detecting it on a schedule. That is great for consistency and painful during incidents, when someone's manual fix is reverted within minutes. Decide explicitly which layer is continuously reconciled.`, interview: { seniorAnswer: `A strong answer frames IaC as **change management**, not templating. Cover: state as the record of ownership (remote, versioned, locked, access-controlled because it contains secrets); splitting roots by ownership and change frequency to cap blast radius and lock contention; versioned modules as the paved road; plan-on-PR and apply-the-saved-plan; policy as code on plan JSON with org-level cloud policy as a backstop; drift detection with a clear rule for codify-or-revert; and short-lived CI credentials via OIDC. Mention a failure story: a module bump proposing replacement of a stateful resource, caught by a deny-replace policy and \`prevent_destroy\`.`, followUps: [ { q: "How would you safely rename a resource that holds data?", a: "Use a `moved` block (or `state mv`) so the plan shows a move, not destroy/create. Verify the plan has zero replace actions before applying; keep deletion protection on as a second layer." }, { q: "Two teams need the VPC ID from the network stack. How do you share it?", a: "Publish outputs to a parameter store or registry and read them with a data source, rather than granting full read on the network state. That avoids leaking secrets and coupling to internal addresses." }, { q: "How do you stop someone bypassing IaC in the console?", a: "Read-only console roles for most humans, break-glass roles with alerting, org-level guardrail policies that also apply to API calls, and drift detection to catch what slips through." }, { q: "What goes wrong with workspaces for prod?", a: "Shared backend and credentials mean selecting the wrong workspace can apply to prod; per-environment differences turn into conditionals on `terraform.workspace`. Separate roots/backends per long-lived env are clearer." } ], redFlags: [ "Keeps state locally or in git.", "Believes `sensitive = true` removes secrets from state.", 'One state for the whole company "for simplicity".', "Applies from laptops with long-lived admin keys.", 'No answer for drift beyond "we tell people not to use the console".' ], numbers: [ "Aim for roots whose plan completes in ~1\u20133 minutes; 20+ minute plans signal a split is overdue (rule of thumb).", "Rule of thumb: hundreds, not thousands, of resources per root.", "Drift detection cadence: daily for most roots, more often for security-sensitive layers." ] }, references: [ { title: "Terraform documentation", url: "https://developer.hashicorp.com/terraform/docs" }, { title: "Terraform state", url: "https://developer.hashicorp.com/terraform/language/state" }, { title: "Open Policy Agent documentation", url: "https://www.openpolicyagent.org/docs/latest/" } ] }, { id: "infra-auto-delivery", title: "CI/CD and release safety", stage: 6, order: 2, objectives: ["auto-delivery"], scope: "senior", estMinutes: 30, summary: "Most outages are caused by changes. Release engineering is about making change small, observable and reversible: build once, promote the artifact, expose it progressively, and roll back automatically when SLOs burn.", what: `- **Continuous integration (CI)** \u2013 every change merges to mainline frequently and is built and tested automatically; the main branch stays releasable. - **Continuous delivery (CD)** \u2013 every green build produces a deployable artifact and *could* go to production at the push of a button; the release decision is a business choice. - **Continuous deployment** \u2013 every green build goes to production automatically, with no human gate. - **Progressive delivery** \u2013 exposing a new version to a growing fraction of traffic or users while watching health signals, with automatic halt or rollback. - **GitOps** \u2013 the desired state of each environment lives in git; an agent inside the environment pulls and reconciles it (Argo CD, Flux), rather than CI pushing with admin credentials.`, why: `Industry incident data and every SRE postmortem archive say the same thing: a large share of outages are triggered by deployments or configuration changes. You cannot stop changing, so you reduce the **size** of each change, the **exposure** before you know it is safe, and the **time to undo**. Teams that deploy small batches often have lower change failure rates, not higher, because each change is easy to reason about and revert. The DORA metrics quantify this: deployment frequency, lead time for changes, change failure rate and time to restore service (renamed *failed deployment recovery time* in recent DORA reports, which also added rework rate).`, problem: `A typical fragile pipeline: rebuild the code separately for each environment ("works in staging" but a different dependency resolved in prod), deploy big batches weekly, flip 100% of traffic at once, and discover breakage from customer tickets. Rollback means a new build under pressure. Database migrations that drop columns make rollback impossible, so every bad deploy becomes a forward-fix incident.`, how: `**Build once, promote the artifact.** CI produces one immutable artifact (container image referenced by **digest**, not a mutable tag), signs it and records provenance. Staging and prod deploy that same digest; only configuration differs, and configuration is versioned too. **Choose a rollout strategy per risk:** - **Rolling** \u2013 replace instances in batches (\`maxSurge\`/\`maxUnavailable\`). Cheap, default for stateless services; mixed versions coexist, and rollback is another rolling update. - **Blue/green** \u2013 stand up a full parallel stack, switch traffic at the load balancer or DNS. Near-instant rollback by switching back; costs 2\xD7 capacity during the window; DNS-based switches are slowed by TTLs and cached resolvers. - **Canary** \u2013 send 1% \u2192 5% \u2192 25% \u2192 100% of traffic to the new version, comparing its error rate and latency against the baseline at each step. Catches problems with real traffic while exposing few users; needs enough traffic per step to be statistically meaningful. - **Feature flags** \u2013 decouple *deploy* from *release*: code ships dark and is enabled per tenant/cohort at runtime. Rollback is a flag flip in seconds. Cost: flag debt and combinatorial test states; remove flags after rollout. **Automated analysis and rollback.** Each canary step gates on SLIs (error ratio, p99 latency, saturation) vs baseline and on error-budget burn rate. If the burn rate on the canary exceeds a threshold, the controller (Argo Rollouts, Flagger, Spinnaker, cloud deploy services) aborts and shifts traffic back without a human. **Database migrations: expand/contract.** Never couple a breaking schema change with the code that needs it. (1) **Expand:** add the new column/table, nullable, backward compatible. (2) Deploy code that writes both and reads old. (3) Backfill. (4) Switch reads to new. (5) **Contract:** after the old version can never come back, drop the old column. Every step is independently deployable and reversible. **GitOps pull model.** The cluster agent watches an environment repo and reconciles; CI's only job is to open a PR bumping the image digest. Benefits: no cluster-admin credentials in CI, an audit trail of every prod change, drift is auto-corrected, and rollback is \`git revert\`. **Measure with DORA.** Track deployment frequency, lead time (commit to prod), change failure rate (deploys causing degraded service) and time to restore (now called failed deployment recovery time). Elite teams deploy on demand with lead times under a day; the point is the trend, not the badge.`, components: [ { name: "Pipeline stages", description: "Lint/unit \u2192 build \u2192 scan/sign \u2192 integration \u2192 deploy staging \u2192 automated checks \u2192 progressive prod rollout. Fast feedback first; aim for CI under ~10 minutes." }, { name: "Artifact registry", description: "Immutable images referenced by digest, with signatures and provenance (SLSA-style attestations) verified at admission." }, { name: "Rollout controller", description: "Executes canary/blue-green steps, queries metrics, pauses, promotes or aborts automatically." }, { name: "Feature flag service", description: "Runtime toggles with targeting rules, kill switches for risky features, and an owner + expiry for every flag." }, { name: "GitOps agent", description: "In-cluster reconciler pulling desired state from git; removes push credentials from CI and makes rollback a revert." }, { name: "Release health signals", description: "Per-version SLIs and burn-rate queries the controller can evaluate; without version labels on metrics, canary analysis is blind." } ], misconceptions: [ { myth: "Continuous delivery means every commit goes to production automatically.", reality: "That is continuous *deployment*. Continuous delivery means every build is releasable; a human or business rule may still decide when." }, { myth: "Blue/green gives instant, free rollback.", reality: "Only for stateless tiers. Shared databases, queues with new message formats and DNS caching all break the illusion, and you pay double capacity during the cut-over." }, { myth: "A 1% canary for five minutes proves the release is safe.", reality: "At low traffic, 1% may see a handful of requests: not enough to detect a 0.5% error regression. Size canary steps and bake times to traffic volume, and include time-based failures (cache expiry, cron jobs, memory leaks)." }, { myth: "Rollback is always possible.", reality: "Destructive migrations, message format changes and external side effects (emails sent, payments captured) are one-way. Design for roll-forward safety with expand/contract and versioned payloads." } ], example: { title: "Canary with automated analysis (Argo Rollouts-style)", description: `Traffic steps with pauses; an analysis template compares the canary's 5xx ratio against a threshold and aborts the rollout automatically if it fails twice.`, language: "yaml", code: `apiVersion: argoproj.io/v1alpha1 kind: Rollout metadata: { name: orders } spec: strategy: canary: steps: - setWeight: 5 - pause: { duration: 10m } - analysis: { templates: [{ templateName: error-ratio }] } - setWeight: 25 - pause: { duration: 15m } - setWeight: 50 - pause: { duration: 15m } --- apiVersion: argoproj.io/v1alpha1 kind: AnalysisTemplate metadata: { name: error-ratio } spec: metrics: - name: canary-5xx-ratio interval: 1m failureLimit: 2 successCondition: result[0] < 0.01 provider: prometheus: query: | sum(rate(http_requests_total{app="orders",version="canary",code=~"5.."}[5m])) / sum(rate(http_requests_total{app="orders",version="canary"}[5m]))` }, exercise: { prompt: `You must rename \`users.fullname\` to \`users.display_name\` in a service with 30 replicas, rolling deploys, and a requirement that any deploy can be rolled back within 5 minutes. Lay out the release sequence.`, solution: `- **Release 1 (expand):** migration adds nullable \`display_name\`. Code writes both columns, reads \`fullname\`. Rollback: old code ignores the new column. - **Backfill job:** copy \`fullname\` \u2192 \`display_name\` in batches (throttled, idempotent), verify counts. - **Release 2:** read \`display_name\` (fallback to \`fullname\` if null), still dual-write. Rollback to release 1 is safe because both columns are kept in sync. - **Release 3:** stop writing \`fullname\`. Only after release 2 has been stable and no older version can be deployed. - **Release 4 (contract):** drop \`fullname\`. This is the only irreversible step and it happens when nothing depends on it. - Each release goes through the normal canary; at no point does a rollback require a schema change.` }, faq: [ { q: "Canary or blue/green?", a: "Canary when you have enough traffic to measure and want limited exposure; blue/green when you need an atomic switch (e.g. protocol change) and can afford double capacity. Many teams combine them: blue/green infrastructure with weighted traffic shifting." }, { q: "Where should integration tests run in a GitOps setup?", a: "CI tests the artifact before the PR to the environment repo; post-sync hooks or the rollout controller run smoke and analysis in the environment. Promotion between environments is a PR, gated on those results." }, { q: "How do you avoid feature-flag debt?", a: "Every flag gets an owner, a type (release, ops kill-switch, experiment, permission) and an expiry; CI warns on stale release flags; removing a flag is part of the definition of done." } ], keyTerms: ["continuous delivery", "continuous deployment", "artifact promotion", "blue/green", "canary", "feature flag", "expand/contract", "GitOps", "DORA metrics", "automated rollback"], deeper: `**Bake time and the long tail of failures.** Some defects appear only after hours: memory leaks, certificate or token expiry, daily batch jobs, cache TTLs. Large providers deploy region by region, starting with low-traffic cells, with bake times between waves, so a time-delayed bug hits one cell, not the fleet. **Config is code:** feature-flag and configuration pushes deserve the same progressive rollout as binaries; several famous global outages came from an instantly-propagated config change, not a code deploy.`, interview: { seniorAnswer: `Anchor on "most incidents are changes", then show the system: trunk-based CI with fast feedback; one immutable, signed artifact promoted by digest; rollout strategy chosen per risk (rolling default, canary with automated SLO-based analysis, blue/green for atomic cut-overs, flags to decouple deploy from release); expand/contract migrations so rollback is always possible; GitOps pull model for credentials and auditability; wave-based rollouts across cells/regions with bake time; and DORA metrics to show improvement. Be explicit about failure modes: insufficient canary traffic, config pushes bypassing the pipeline, irreversible migrations.`, followUps: [ { q: "How do you decide canary step sizes and bake times?", a: "From traffic and detection power: each step must see enough requests to distinguish the target error rate from baseline (often thousands), and bake long enough to cover periodic work. Low-traffic services may need synthetic load or longer steps." }, { q: "What metrics would trigger automated rollback?", a: "Canary vs baseline error ratio, p99 latency, saturation (CPU, memory, restarts), and short-window error-budget burn rate. Use relative comparison to baseline to avoid false aborts from global incidents." }, { q: "Why build once rather than per environment?", a: "Rebuilding can resolve different dependencies or compiler versions, so what you tested is not what you run. One digest promoted everywhere makes staging evidence valid for prod and enables provenance verification." }, { q: "Push vs pull deployment?", a: "Push needs CI to hold prod credentials and has no drift correction. Pull (GitOps) keeps credentials inside the cluster, reconciles drift, and gives a git audit trail, at the cost of another controller to operate and slower emergency changes unless you plan for them." } ], redFlags: [ "Rebuilds artifacts per environment or deploys `:latest`.", "Plans rollback without considering the database schema.", "Treats config/flag changes as exempt from progressive rollout.", 'Canary "analysis" is a human watching a dashboard.', "Cannot name the DORA metrics or what they trade off." ], numbers: [ "CI feedback target: under ~10 minutes for the main pipeline (rule of thumb).", "Typical canary ladder: 1\u20135% \u2192 25% \u2192 50% \u2192 100% with 10\u201330 minute bakes.", "DORA elite benchmark: on-demand deploys, lead time under a day, restore under an hour." ] }, references: [ { title: "Google SRE workbook", url: "https://sre.google/workbook/table-of-contents/" }, { title: "SLSA", url: "https://slsa.dev/" }, { title: "The Twelve-Factor App", url: "https://12factor.net/" }, { title: "Alerting on SLOs (SRE workbook)", url: "https://sre.google/workbook/alerting-on-slos/" } ] }, // ───────────────────────────── Stage 7 · Observability & Performance ──────────────────────────── { id: "infra-obs-signals", title: "Signals, alerting and observability cost", stage: 7, order: 1, objectives: ["obs-signals"], scope: "senior", estMinutes: 30, summary: "Metrics tell you that something is wrong, traces tell you where, logs and profiles tell you why. Page on user-visible symptoms via SLO burn, and keep cardinality and volume under control or the bill becomes the incident.", what: `Observability is the ability to answer new questions about a system's behaviour from the telemetry it already emits. The signal types: - **Metrics** \u2013 numeric time series, cheap to store and query, aggregated by labels. Best for dashboards and alerts. - **Logs** \u2013 discrete events with context; expensive per byte, rich for debugging. - **Traces** \u2013 a request's path across services as a tree of spans with timing and attributes; essential in microservices. - **Profiles** \u2013 where CPU time and memory go inside a process, continuously sampled in production. Frameworks for *which* metrics: Google's **four golden signals** (latency, traffic, errors, saturation); **RED** for request-driven services (Rate, Errors, Duration); **USE** for resources (Utilization, Saturation, Errors). OpenTelemetry is the vendor-neutral standard for generating and shipping all of these.`, why: `In a distributed system nobody can hold the whole thing in their head. When p99 latency doubles at 03:00, the on-call engineer needs to know within minutes whether users are affected, which dependency is responsible and what changed. Poor alerting is also a people problem: a team paged 30 times a week stops trusting pages, and the one real outage is acknowledged and ignored.`, problem: `Common failure patterns: - **Cause-based alerts everywhere**: "CPU > 80%", "disk > 70%", "one pod restarted". They fire constantly without user impact and stay silent during real outages caused by something unanticipated. - **Alert fatigue**: dozens of non-actionable pages; responders mute channels. - **Cardinality explosion**: someone adds \`user_id\` or full URL path as a metric label; the time-series database runs out of memory and the monthly bill triples. - **Logs as the only signal**: unstructured text grepped during incidents, 100% retained at great cost, no correlation to requests. - **Broken traces**: context not propagated through a queue or a proxy, so traces stop at the first hop.`, how: `**Instrument with RED + USE.** Every service exports request rate, error rate and a latency **histogram** (not just an average) per endpoint class; every resource (CPU, memory, disk, connection pools, queues, thread pools) exports utilization, saturation (queue length, wait time) and errors. **Alert on symptoms, investigate with causes.** Pages should fire when users are hurt or about to be: SLO burn, availability, latency at the edge. Cause metrics (CPU, replication lag) belong on dashboards and in tickets, with a few exceptions that predict imminent unrecoverable failure (disk will be full in 4 hours, certificate expires in 7 days). **SLO-based alerting with burn rates.** Burn rate = observed error rate / allowed error rate. With a 99.9% SLO over 30 days, a burn rate of 1 consumes the budget exactly in 30 days. The SRE workbook's multiwindow, multi-burn-rate approach pages at about **14.4\xD7 over 1 hour** (2% of budget gone) and **6\xD7 over 6 hours** (5%), each confirmed by a short window (~5 and ~30 minutes) so the alert also resets quickly, and opens a ticket at about **1\xD7 over 3 days** (10%). **Control cardinality.** Series count \u2248 product of label value counts. \`endpoint\` (50) \xD7 \`status\` (5) \xD7 \`pod\` (200) = 50k series per metric, which is fine; add \`customer_id\` (100k) and it is 5 billion, which is not. Keep unbounded identifiers in logs and trace attributes, use route templates (\`/users/{id}\`) not raw paths, and drop or aggregate pod-level labels where not needed. **Tracing and context propagation.** Use W3C Trace Context (\`traceparent\` header) end to end, including through message queues (put it in message attributes) and async jobs. Sample: head-based (decide at the root, e.g. 1\u201310%) is cheap; tail-based (decide after the trace completes, keep all errors and slow traces) is more useful but needs a collector tier that buffers spans. Attach **exemplars** so a latency spike on a metric links to example traces. **Structured logs and sampling.** JSON logs with consistent fields (\`trace_id\`, \`service\`, \`level\`, \`tenant\`), no secrets or PII. Sample high-volume success logs, keep 100% of errors, and set tiered retention (hot for days, cheap archive for months). **Make alerts actionable.** Each page has an owner, a runbook link, a dashboard and a clear "what to do". Review pages weekly; delete or demote any alert that did not lead to action.`, components: [ { name: "Four golden signals", description: 'Latency (split successful vs failed requests), traffic, errors (explicit, implicit and policy failures such as "slow = failed"), saturation (how full the most constrained resource is).' }, { name: "RED / USE", description: 'RED for every service endpoint; USE for every resource. Together they cover "is the service healthy" and "is the box/pool/queue the bottleneck".' }, { name: "Latency histograms", description: "Bucketed distributions that can be aggregated across instances to compute percentiles. Averaging per-instance percentiles is mathematically wrong." }, { name: "OpenTelemetry collector", description: "Agent/gateway that receives, processes (batching, attribute scrubbing, tail sampling) and exports telemetry to one or more backends, decoupling instrumentation from vendor." }, { name: "Burn-rate alerts", description: "Multiwindow alerts on error-budget consumption speed that page for fast burns and ticket for slow burns." }, { name: "Runbooks and dashboards", description: "Linked from every alert: what the alert means, first diagnostic steps, mitigations, escalation." } ], misconceptions: [ { myth: "More alerts mean better coverage.", reality: "Beyond a handful of symptom alerts per service, each extra page reduces the chance any page is taken seriously. Coverage comes from SLOs at the user boundary." }, { myth: "Average latency is a good health indicator.", reality: "Averages hide the tail. A 50 ms mean can coexist with a 2 s p99 that hits every user who loads a page with many calls. Alert on percentiles from histograms." }, { myth: "Observability means collecting everything.", reality: "Telemetry cost often grows faster than traffic. Senior teams budget telemetry, sample, set retention tiers and choose the cheapest signal that answers each question." } ], example: { title: "Multiwindow burn-rate alert (Prometheus rule)", description: `For a 99.9% availability SLO (error budget 0.1%). Pages only when both the long and short window exceed 14.4\xD7 burn, so it fires fast for big outages and clears quickly after recovery.`, language: "yaml", code: `groups: - name: checkout-slo rules: - alert: CheckoutErrorBudgetFastBurn expr: | ( sum(rate(http_requests_total{svc="checkout",code=~"5.."}[1h])) / sum(rate(http_requests_total{svc="checkout"}[1h])) ) > (14.4 * 0.001) and ( sum(rate(http_requests_total{svc="checkout",code=~"5.."}[5m])) / sum(rate(http_requests_total{svc="checkout"}[5m])) ) > (14.4 * 0.001) labels: { severity: page } annotations: summary: "Checkout burning error budget at >14.4x (2% of 30d budget per hour)" runbook: "runbooks/checkout-availability"` }, exercise: { prompt: `A team has 140 alert rules, gets ~25 pages per week, and still learned about last month's checkout outage from Twitter. Their metrics bill grew 3\xD7 after adding per-customer labels. What do you change?`, solution: `- **Inventory pages from the last 30 days:** classify each as actionable/user-impacting or not. Delete or demote (to ticket/dashboard) every non-actionable rule. - **Define SLOs at the edge** for the critical journeys (checkout availability and latency) and add multiwindow burn-rate pages; that is the alert that would have caught the outage. - **Keep a few cause alerts** that predict unrecoverable failure (disk full ETA, cert expiry), as tickets where possible. - **Fix cardinality:** remove \`customer_id\` from metric labels; put it on spans and logs; use route templates; drop unused per-pod series at the collector. - **Process:** every page needs a runbook and owner; a weekly review tracks pages per on-call shift, aiming for a couple per shift at most.` }, faq: [ { q: "Metrics, logs or traces: which first?", a: "Metrics first for detection (cheap, alertable), traces next for localisation in distributed systems, logs for detail. Correlate them via trace IDs and exemplars so you can pivot in one click." }, { q: "Head or tail sampling?", a: "Head sampling is simple and cheap but drops most interesting traces. Tail sampling keeps errors and slow requests but requires a stateful collector tier that sees all spans of a trace. A common compromise is low-rate head sampling plus tail rules for errors and latency outliers." }, { q: "Should I alert on CPU?", a: "Rarely as a page. High CPU without user impact is efficient use; user impact will show up in latency/error SLOs. Use CPU saturation for capacity planning and autoscaling." } ], keyTerms: ["four golden signals", "RED method", "USE method", "symptom-based alerting", "burn rate", "cardinality", "context propagation", "tail sampling", "exemplars", "structured logging"], deeper: `**Black-box vs white-box.** Probes from outside (synthetic checks from several regions) catch DNS, certificate and edge failures that internal metrics cannot see, because a service that receives no traffic reports no errors. Pair them. **Watch the watcher.** If the monitoring pipeline is down, silence looks like health. Use a dead-man's-switch alert (an always-firing heartbeat that pages when it *stops* arriving) and host part of the alerting path outside the failure domain it monitors.`, interview: { seniorAnswer: `Explain the signal roles (metrics detect, traces localise, logs/profiles explain), instrument with RED + USE and latency histograms, and page only on symptoms: SLO burn rate with multiwindow thresholds (~14.4\xD7 over 1h, ~6\xD7 over 6h, ticket at ~1\xD7 over 3d for a 30-day window). Treat telemetry as a cost and reliability problem: cardinality budgets, route templates, sampling (head + tail for errors/slow), tiered log retention. Mention context propagation through async boundaries, runbooks on every page, dead-man's switch for the monitoring stack, and a target of very few pages per shift.`, followUps: [ { q: "Why multiwindow burn-rate alerts instead of a simple threshold?", a: "A single short window is noisy; a single long window is slow to fire and slow to clear. Requiring both a long and short window gives fast detection of serious burns, low false positives, and quick reset after recovery." }, { q: "How do you compute fleet p99 correctly?", a: "Aggregate histogram buckets across instances, then compute the quantile. Averaging per-pod p99 values gives a meaningless number." }, { q: "A trace stops at the queue. Why?", a: "Context is not propagated through the message: the producer must inject `traceparent` into message attributes and the consumer must extract it and start a linked or child span." }, { q: "How do you keep telemetry cost under control?", a: "Per-team budgets and showback, cardinality limits enforced at the collector, sampling, dropping unused metrics, shorter hot retention with cheap archive, and preferring metrics over logs for counting things." } ], redFlags: [ "Pages on CPU or single pod restarts.", "Uses averages for latency SLOs.", "Adds user IDs or raw URLs as metric labels.", 'No runbooks; "the on-call will figure it out".', "Thinks 100% trace sampling is free." ], numbers: [ "99.9% over 30 days \u2248 43 minutes of full-outage budget.", "Burn-rate pages: 14.4\xD7 over 1h (2% budget), 6\xD7 over 6h (5%); ticket at 1\xD7 over 3 days (10%).", "Series per metric = product of label cardinalities; keep per-metric series in the thousands to low hundreds of thousands (rule of thumb).", "On-call health target: no more than a couple of pages per shift (SRE guidance, approximate)." ] }, references: [ { title: "Monitoring distributed systems (SRE book)", url: "https://sre.google/sre-book/monitoring-distributed-systems/" }, { title: "Alerting on SLOs (SRE workbook)", url: "https://sre.google/workbook/alerting-on-slos/" }, { title: "OpenTelemetry documentation", url: "https://opentelemetry.io/docs/" }, { title: "The USE method", url: "https://www.brendangregg.com/usemethod.html" } ] }, { id: "infra-obs-performance", title: "Performance troubleshooting and tail latency", stage: 7, order: 2, objectives: ["obs-performance"], scope: "senior", estMinutes: 30, summary: "Latency lives in the tail, and fan-out makes the tail everyone's problem. Queueing theory explains why 80% utilization feels fine and 95% falls off a cliff; the USE method and a 60-second Linux checklist find the bottleneck.", what: `Performance troubleshooting is a method for going from "it's slow" to a specific saturated resource or code path, using measurements rather than guesses. The core tools: - **Latency percentiles** \u2013 p50 describes the typical request, p99/p99.9 the experience of users who make many requests. - **Little's law** \u2013 \`L = \u03BB \xD7 W\`: items in the system equal arrival rate times time in system. Holds for any stable system. - **Queueing intuition** \u2013 as utilization approaches 100%, waiting time grows non-linearly. - **USE method** \u2013 for every resource, check Utilization, Saturation and Errors. - **Linux observability tools** \u2013 a quick standard sequence of commands, then profilers and flame graphs for CPU-bound problems.`, why: `Senior interviews love "the service is slow, walk me through it" because it reveals whether you have a method. Production loves it too: a methodical engineer finds a saturated connection pool in five minutes, while guessing leads to scaling the wrong tier, restarting things and losing evidence.`, problem: `**Tail at scale.** If a page fans out to 100 backends in parallel and each has a 1% chance of exceeding its p99, the probability that at least one is slow is \`1 \u2212 0.99^100 \u2248 63%\`. The backend's p99 becomes the frontend's typical case. **Utilization lies.** A disk at "60% busy" averaged over a minute may be 100% busy in bursts with a deep queue. A CPU at 50% on a VM may be losing cycles to **steal** from the hypervisor. A container may be **throttled** by its cgroup CPU quota while the node looks idle. **Noisy neighbours.** Shared hosts, shared disks, shared network links and shared databases mean your latency can rise because of someone else's batch job.`, how: `**Start from the symptom.** Which requests, which percentile, since when, what changed (deploy, traffic, dependency)? Compare against the baseline. **Little's law for sizing.** At 2,000 req/s and 50 ms mean latency, \`L = 2000 \xD7 0.05 = 100\` requests are in flight, so a pool of 20 DB connections each held for the whole request caps you near 400 req/s. If latency rises to 250 ms, you need 500 concurrent slots for the same throughput, which is why slow dependencies exhaust thread and connection pools. **Queueing intuition.** For a simple single-server queue (M/M/1) the mean time in system scales like \`service_time / (1 \u2212 \u03C1)\`: at 50% utilization \u2248 2\xD7 service time, at 90% \u2248 10\xD7, at 95% \u2248 20\xD7. Real systems differ in detail but the knee is real; plan headroom so steady state stays well below the knee. **USE checklist per resource:** CPU (utilization per core, run-queue length, throttling), memory (used vs available, swapping, OOM kills, page-fault rate), disk (utilization, await, queue size, errors), network (throughput vs link capacity, retransmits, drops), and software resources (thread pools, connection pools, file descriptors, locks). **The 60-second Linux checklist** (popularised by Brendan Gregg): - \`uptime\` \u2013 load averages; rising or falling trend. - \`dmesg | tail\` \u2013 OOM kills, TCP drops, disk errors. - \`vmstat 1\` \u2013 run queue (\`r\`), free memory, swap in/out, CPU user/system/idle/iowait/**steal**. - \`mpstat -P ALL 1\` \u2013 per-CPU balance; one hot core suggests a single-threaded bottleneck. - \`pidstat 1\` \u2013 per-process CPU over time. - \`iostat -xz 1\` \u2013 per-device \`await\`, queue depth and utilization. - \`free -m\` \u2013 available memory and page cache. - \`sar -n DEV 1\` \u2013 network interface throughput; \`sar -n TCP,ETCP 1\` \u2013 connection rates and retransmits. - \`top\` \u2013 overall check. **Containers and VMs.** Check cgroup CPU throttling (\`nr_throttled\`/\`throttled_usec\` in \`cpu.stat\`) and memory pressure; check steal time on VMs; burstable instance credits on small instance types. **Profile the hot path.** If CPU-bound, sample stacks (\`perf\`, eBPF-based tools, language profilers, continuous profilers) and render a **flame graph**: width is proportion of samples, so look for wide plateaus. Off-CPU analysis finds time spent blocked on locks and I/O. **Mitigate the tail.** Timeouts and budgets per hop, hedged requests (send a second request after the p95 delay, cancel the loser), limiting fan-out, load shedding and caching hot results.`, components: [ { name: "Percentiles and histograms", description: "p50/p95/p99/p99.9 from aggregated histograms; always state the window and the population (all requests, successful only, per endpoint)." }, { name: "Little's law", description: "`L = \u03BBW`. Turns throughput and latency into required concurrency for pools, workers and connection limits." }, { name: "Utilization vs queueing delay", description: "Wait time explodes non-linearly near saturation; averages over long windows hide bursts at 100%." }, { name: "USE method", description: "Systematic per-resource sweep that finds saturated resources quickly and avoids streetlight debugging." }, { name: "Linux 60-second tools", description: "uptime, dmesg, vmstat, mpstat, pidstat, iostat, free, sar, top: a fast first pass before deeper tooling." }, { name: "Profilers and flame graphs", description: "Sampled stack traces visualised by width; on-CPU for compute hot spots, off-CPU for blocking." } ], misconceptions: [ { myth: "Load average equals CPU utilization.", reality: "On Linux, load average counts runnable tasks *and* tasks in uninterruptible sleep (often disk I/O). High load with idle CPUs usually means an I/O or lock problem." }, { myth: "Adding replicas always fixes latency.", reality: "Only if the bottleneck is in that tier. If replicas share a saturated database, more replicas add more contention and make it worse." }, { myth: "A low p50 means the service is fast.", reality: "Users who load pages with many calls experience the tail. With fan-out, the backend p99 dominates end-user latency." }, { myth: "High iowait means the disk is the bottleneck.", reality: "iowait is idle CPU time while I/O is outstanding: it is a hint, not proof. Confirm with per-device `await`, queue depth and utilization." } ], example: { title: "First minute on a slow VM", description: `Reading a \`vmstat\` sample: a run queue well above the vCPU count, almost no idle time and high steal points at the hypervisor (noisy neighbour or exhausted burst credits), not the application.`, language: "bash", code: `$ vmstat 1 3 procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu----- r b swpd free buff cache si so bi bo in cs us sy id wa st 9 0 0 812344 10212 2143220 0 0 4 20 2310 4100 46 11 2 0 41 11 0 0 811980 10212 2143300 0 0 0 16 2290 4050 45 10 2 0 43 10 0 0 811700 10212 2143310 0 0 0 12 2305 4120 45 11 2 0 42 # r=10 runnable on a 4-vCPU VM, st\u224842% steal: the guest is starved of CPU by the host. # Action: check instance type (burstable credits?), move to dedicated/larger instance, # or reschedule; profiling the app would be a waste of time here.` }, exercise: { prompt: `An API's p99 rose from 120 ms to 900 ms after traffic grew from 1,500 to 2,400 req/s. p50 barely moved. App CPU is 45%. Each request holds a DB connection for ~40 ms; the pool has 64 connections per instance across 2 instances. Explain the likely cause and fix.`, solution: `- **Little's law:** required concurrent DB connections \u2248 2,400 \xD7 0.040 = 96 on average, against 128 total, so the pools run around 75% average utilization with bursts well above that. - **Queueing:** near the knee, waits for a free connection grow non-linearly. Most requests still get a connection immediately (p50 flat), but the unlucky ones queue (p99 explodes). App CPU is not the bottleneck. - **Verify:** pool wait-time and active-connection metrics, DB-side active sessions and query latency. - **Fix:** reduce hold time (do not hold connections across remote calls, fix slow queries), size the pool with headroom *if* the database can take more sessions (check DB CPU and max connections; consider a pooler), add instances only with a per-instance pool budget that keeps total connections within the database limit, and add pool-wait timeouts so overload fails fast instead of queueing.` }, faq: [ { q: "Why is p99.9 worth tracking?", a: "At high request rates 0.1% is a lot of users, and for fan-out pages it becomes the common case. It also surfaces GC pauses, retries and cold caches that p99 misses." }, { q: "What is CPU steal?", a: "Time a virtual CPU was ready to run but the hypervisor ran something else. Sustained steal above a few percent means contention on the host or exhausted burst credits." }, { q: "When should I reach for a profiler?", a: "After the USE sweep shows CPU is genuinely saturated by your process (high user time, not steal or throttling). For latency without CPU saturation, look at off-CPU time, locks, pools and dependencies first." } ], keyTerms: ["tail latency", "fan-out", "Little's law", "utilization", "saturation", "USE method", "CPU steal", "CPU throttling", "flame graph", "hedged requests"], deeper: `**Coordinated omission.** Many load generators wait for a response before sending the next request, so when the server stalls they send fewer requests and under-record the latency users would have seen. Use open-loop load generation (fixed arrival rate) when measuring tail latency. **Hedging budget.** Hedged requests cut tail latency dramatically if they are sent only after the p95 delay (adding roughly 5% extra load) and the backend can cancel the loser. Hedging non-idempotent writes or hedging immediately just doubles load during an overload.`, interview: { seniorAnswer: `Show a method: clarify the symptom (which percentile, which endpoint, since when, what changed), then sweep USE across resources, including software resources like pools and queues. Use Little's law to turn throughput and latency into concurrency, and queueing intuition to explain why p99 explodes near saturation while p50 stays flat. Know the Linux first-minute tools and what each reveals (run queue, steal, iowait, await, retransmits), container throttling and noisy neighbours, and when to profile (flame graphs for on-CPU, off-CPU for blocking). Close with tail mitigations: deadlines, hedging, reducing fan-out, load shedding, headroom.`, followUps: [ { q: "Why does fan-out amplify tail latency?", a: "The request completes when the slowest leaf completes. With N independent leaves, P(at least one slow) = 1 \u2212 (1 \u2212 p)^N; at N=100 and p=1%, that is ~63%." }, { q: "Load average is 30 on a 16-core box but CPUs are 60% idle. What next?", a: "Load includes uninterruptible (D-state) tasks, usually disk or NFS I/O. Check `vmstat` `b` column, `iostat -xz` await and queue depth, and `dmesg` for storage errors." }, { q: "How much headroom do you plan for?", a: "Enough that steady-state utilization of the bottleneck stays below the knee (often 60\u201370% for latency-sensitive tiers), plus the capacity to lose an AZ (N+1 or N+2) without crossing it." } ], redFlags: [ 'Immediately suggests "add more servers" without locating the bottleneck.', "Only talks about averages.", "Treats load average as CPU percent.", "Ignores steal, throttling and dependency saturation.", "Restarts processes before capturing evidence." ], numbers: [ "1 \u2212 0.99^100 \u2248 63%: fan-out of 100 makes backend p99 the common case.", "M/M/1 wait multiplier \u2248 1/(1 \u2212 \u03C1): 2\xD7 at 50%, 10\xD7 at 90%, 20\xD7 at 95%.", "~0.5 ms intra-datacenter round trip; ~100 ns main-memory reference (order of magnitude).", "Hedge after p95 \u2248 ~5% extra load." ] }, references: [ { title: "The USE method", url: "https://www.brendangregg.com/usemethod.html" }, { title: "Linux performance (Brendan Gregg)", url: "https://www.brendangregg.com/linuxperf.html" }, { title: "Handling overload (SRE book)", url: "https://sre.google/sre-book/handling-overload/" } ] }, // ───────────────────────────── Stage 8 · Architecture & Cost ──────────────────────────── { id: "infra-arch-frameworks", title: "Well-Architected trade-offs, migrations and multi-cloud", stage: 8, order: 1, objectives: ["arch-frameworks"], scope: "senior", estMinutes: 30, summary: "The Well-Architected frameworks give a shared vocabulary for reviewing designs. The senior skill is naming which pillar you are trading for which, choosing a migration strategy per workload, and resisting multi-region or multi-cloud unless the requirement pays for it.", what: `Each major provider publishes a framework of design pillars and review questions: - **AWS Well-Architected (6 pillars):** operational excellence, security, reliability, performance efficiency, cost optimization, sustainability. - **Azure Well-Architected (5 pillars):** reliability, security, cost optimization, operational excellence, performance efficiency. - **Google Cloud Well-Architected Framework (6 pillars):** operational excellence; security, privacy and compliance; reliability; cost optimization; performance optimization; sustainability. Around them sit adjacent decisions every architect faces: **migration strategy** per workload (the "7 Rs"), **multi-region / multi-cloud** posture, **build vs buy**, and recording decisions in **architecture decision records (ADRs)**.`, why: `Interviewers at senior and staff level want to see that you can evaluate a design across several dimensions at once and articulate costs. "Make it highly available" is not an answer; "active-passive across two regions buys us a 1-hour RTO at roughly 1.4\xD7 infrastructure cost and adds a failover runbook we must exercise quarterly" is. The frameworks also matter practically: many organisations run formal reviews against them before launch.`, problem: `Without explicit trade-off thinking, teams over-build (multi-region active-active for an internal tool with a 99.5% SLO), under-build (single-AZ database behind a "99.99%" promise), or migrate everything with one strategy (lift-and-shift the whole estate and then wonder why the bill went up). Decisions get relitigated every quarter because nobody wrote down why they were made.`, how: `**Pillars trade against each other.** Typical tensions: - Reliability vs cost: each extra AZ or region multiplies baseline spend; standby capacity is paid insurance. - Security vs operational excellence/velocity: stricter change controls and network segmentation slow delivery unless automated. - Performance vs cost: provisioned capacity and caches cost money even when idle. - Sustainability vs reliability: fewer, fuller machines reduce energy but shrink headroom. State which pillar you are optimising for this workload, and the floor you will not go below on the others. **Migration strategies, the 7 Rs** (AWS terminology, widely used): - **Retire** \u2013 turn it off; often 10\u201320% of a legacy portfolio is unused (rough industry anecdote, verify per estate). - **Retain** \u2013 leave it where it is for now (compliance, recent hardware investment, too risky). - **Rehost** \u2013 lift and shift VMs as-is; fastest, least cloud benefit. - **Relocate** \u2013 move at the hypervisor/platform level without changing the workload (e.g. VMware-based offerings). - **Replatform** \u2013 lift, tinker and shift: swap self-managed DB for a managed one, containerise without rewriting. - **Repurchase** \u2013 replace with SaaS. - **Refactor / re-architect** \u2013 rebuild cloud-native; highest effort and highest long-term benefit. Choose per workload by business value, change rate and technical debt; sequence easy wins first to build migration muscle. **Multi-region decision criteria.** Driven by RTO/RPO, regulatory residency, latency to global users and blast-radius isolation. Options: backup-and-restore (hours RTO, cheap), pilot light, warm standby, active-active (seconds RTO, highest cost and data-consistency complexity). Active-active forces you to answer write conflicts: single-writer per region/partition, CRDTs or a globally consistent database with cross-region write latency. **Multi-cloud decision criteria.** Valid reasons: regulatory or customer mandate, acquisitions, a clearly best-of-breed service, negotiating leverage at very large scale. Costs: lowest-common-denominator architecture, duplicated platform teams and skills, egress between clouds, two identity and network models. A pragmatic stance is "portable where cheap" (containers, Terraform, OpenTelemetry) and "native where valuable", rather than abstracting every service. **Build vs buy.** Buy (managed or SaaS) when the capability is not your differentiator and a vendor operates it better; build when it is core to your product, when vendor limits block you, or when scale makes the unit economics favour owning it. Count total cost of ownership: on-call, upgrades, security patching, and the opportunity cost of engineers. **ADRs.** A short document per significant decision: context, decision, alternatives considered, consequences, status. Stored next to the code, immutable once accepted (superseded by a new ADR). Cheap insurance against relitigating.`, components: [ { name: "Pillars", description: "Shared review dimensions (operations, security, reliability, performance, cost, sustainability). Useful as a checklist; the value is in explicit trade-offs." }, { name: "Well-Architected review", description: "Structured question set applied before launch or periodically; outputs a prioritised list of high-risk issues, not a score to maximise." }, { name: "7 Rs", description: "Retire, retain, rehost, relocate, replatform, repurchase, refactor: a per-workload migration decision." }, { name: "DR tiers", description: "Backup/restore \u2192 pilot light \u2192 warm standby \u2192 active-active, trading RTO/RPO against cost and complexity." }, { name: "Build vs buy analysis", description: "Differentiation, TCO including people, vendor risk and exit cost, time to value." }, { name: "ADR", description: "Lightweight, versioned record of a decision and its consequences, so future engineers know why." } ], misconceptions: [ { myth: "Multi-cloud is more reliable than multi-region in one cloud.", reality: "Usually the opposite for a given budget: multi-region within one provider gives most of the isolation with one skill set; multi-cloud adds failure modes in the glue and rarely gets exercised." }, { myth: "Lift-and-shift saves money.", reality: "Rehosting always-on, oversized VMs frequently costs more than on-premises. Savings come later from rightsizing, elasticity, managed services and commitments." }, { myth: "Well-Architected means scoring high on every pillar.", reality: "Pillars conflict. A good review documents conscious trade-offs and fixes high-risk gaps; it does not maximise everything." } ], example: { title: "An ADR for regional posture", description: `A concise ADR showing the format and the trade-off language interviewers want to hear.`, language: "text", code: `ADR-014: Payments API regional posture Status: Accepted (2026-03) Context: SLO 99.95%, RPO <= 1 min, RTO <= 30 min. 92% of users in one geography. Regulator requires data to stay in-country; two regions available in-country. Decision: Warm standby in region B. Async DB replication (lag p99 < 5 s), app tier scaled to 30% in B, failover runbook automated, game-day every quarter. Alternatives: - Active-active: RTO ~0 but needs multi-writer DB; +80% cost; rejected for now. - Backup/restore: RTO hours; violates RTO. Consequences: ~+35% infra cost; we accept up to ~5 s of acknowledged writes at risk on regional failover (documented to product); revisit if SLO -> 99.99%.` }, exercise: { prompt: `A company with 300 on-premises applications must exit its data centre in 18 months. The CTO wants "everything cloud-native". Propose an approach.`, solution: `- **Portfolio discovery:** inventory apps, owners, dependencies, utilisation and business criticality. Expect a meaningful share to be candidates for **retire** or **repurchase** (SaaS). - **Bucket by strategy:** low-change legacy \u2192 **rehost/relocate** to hit the deadline; databases and middleware with managed equivalents \u2192 **replatform**; a few strategic, high-change systems \u2192 **refactor** on their own timeline (possibly after rehost). - **Waves:** start with low-risk apps to build landing zone, networking, identity and migration tooling; move dependency groups together to avoid chatty cross-site traffic. - **Explain to the CTO:** refactoring 300 apps in 18 months is not feasible; rehost-then-modernise meets the hard deadline and lets you spend refactoring effort where it pays. - **Guardrails:** rightsizing and commitments after 1\u20132 months of real usage data; ADRs for each strategic decision.` }, faq: [ { q: "How do I talk about the pillars without sounding like a brochure?", a: 'Use them as a checklist to find gaps, then talk in specifics: "this costs X, buys Y nines, and the failure mode we still accept is Z".' }, { q: "When is active-active worth it?", a: "When the RTO is near zero, the business loss per minute justifies roughly doubling infrastructure plus engineering complexity, and the data model tolerates multi-region writes (partitioned ownership or conflict resolution)." }, { q: "What makes a good ADR?", a: "One decision, the context and constraints at the time, at least two alternatives with why they lost, explicit consequences including what you are giving up, and a trigger for revisiting." } ], keyTerms: ["Well-Architected pillars", "trade-off", "7 Rs", "rehost", "replatform", "refactor", "RTO/RPO", "multi-region", "build vs buy", "ADR"], deeper: `**Cells over regions.** Many large systems reduce blast radius with **cell-based architecture**: independent stacks each serving a slice of customers, routed by a thin layer. A bad deploy or poison request takes out one cell, not a region. Cells also make capacity planning and gradual rollouts more uniform. The cost is a routing layer and cross-cell operations (migrations between cells, global queries).`, interview: { seniorAnswer: `Use the pillars as a lens, then talk in trade-offs with numbers: what reliability tier the SLO actually requires, what each step up (multi-AZ, warm standby, active-active) costs and what new failure modes it introduces (replication lag, split brain, failover that nobody has tested). For migrations, choose among the 7 Rs per workload and sequence them in waves against the deadline. On multi-cloud, give legitimate drivers and real costs and prefer portability where it is cheap. Close with how you record and revisit the decision (ADR with explicit revisit triggers).`, followUps: [ { q: "Name the AWS pillars. How do Azure and Google Cloud differ?", a: "AWS: operational excellence, security, reliability, performance efficiency, cost optimization, sustainability. Azure has five (no separate sustainability pillar). Google Cloud has six, including sustainability, and groups security with privacy and compliance." }, { q: 'Your CEO wants multi-cloud "for resilience". Response?', a: "Ask what failure we are protecting against and what it costs per hour. Usually multi-region in one provider plus tested DR meets the need for far less; if there is a regulatory or concentration-risk mandate, scope multi-cloud to the critical path and keep it exercised." }, { q: "Replatform vs refactor for a monolith on VMs?", a: "Replatform (containers + managed DB) gets operational wins quickly with limited risk. Refactor only the parts with high change rate or scaling pain, ideally strangler-fig style, once the platform is stable." }, { q: "How do you evaluate build vs buy for an internal developer platform?", a: "Differentiation (usually low), TCO including staffing and on-call, integration with existing identity/CI, vendor lock-in and exit cost, and time to value. Often buy/adopt the core and build the thin opinionated layer." } ], redFlags: [ "Proposes active-active multi-region for every workload.", "Treats multi-cloud as free resilience.", "One migration strategy for the whole portfolio.", "Cannot articulate what a design gives up.", "No written record of decisions." ], numbers: [ "AWS: 6 pillars; Azure: 5; Google Cloud: 6.", "7 Rs: retire, retain, rehost, relocate, replatform, repurchase, refactor.", "99.9% \u2248 8.8 h/year; 99.99% \u2248 53 min/year; 99.999% \u2248 5.3 min/year downtime." ] }, references: [ { title: "AWS Well-Architected", url: "https://aws.amazon.com/architecture/well-architected/" }, { title: "Azure Well-Architected Framework", url: "https://learn.microsoft.com/en-us/azure/well-architected/" }, { title: "Google Cloud Well-Architected Framework", url: "https://cloud.google.com/architecture/framework" }, { title: "AWS migration strategies", url: "https://docs.aws.amazon.com/prescriptive-guidance/latest/large-migration-guide/migration-strategies.html" } ] }, { id: "infra-arch-finops", title: "FinOps and cost engineering", stage: 8, order: 2, objectives: ["arch-finops"], scope: "senior", estMinutes: 25, summary: "Cloud cost is an engineering metric. Know the drivers (compute, storage, and especially data transfer), match purchase models to workload shape, measure unit cost, and make spend visible to the teams that cause it.", what: `**FinOps** is the operating practice of bringing financial accountability to variable cloud spend, so engineering, finance and product make trade-offs together. The FinOps Foundation framework describes an iterative lifecycle: - **Inform** \u2013 allocation and visibility: who spends what, on which product, and is it forecastable? - **Optimize** \u2013 reduce waste and improve rates: rightsizing, scheduling, commitments, spot, architecture changes. - **Operate** \u2013 embed it: budgets, anomaly alerts, policies, cost reviews in design and planning. **Cost engineering** is the technical half: designing systems whose cost scales sensibly with the business.`, why: `In the cloud, every engineer is a purchaser: a Terraform PR can add six figures a year. Cost is also a design signal: a service whose cost grows faster than its traffic has an architectural problem. Senior interviewers increasingly ask "what would this cost?" and expect order-of-magnitude reasoning, including the costs people forget.`, problem: `Typical waste and surprises: - **Idle and oversized resources**: dev environments running nights and weekends, instances sized for a peak that happens once a year, unattached volumes and old snapshots. - **Data transfer**: internet egress, **cross-AZ** traffic between chatty services or replicas, NAT gateway processing, cross-region replication. Often invisible until the bill. - **Storage that only grows**: logs and backups with no lifecycle policy, everything on the hottest tier. - **No allocation**: untagged resources mean nobody owns the spend, so nobody optimises it. - **Wrong purchase model**: steady 24/7 baseline on on-demand rates; or commitments bought for workloads that were later decommissioned.`, how: `**Know the drivers.** Compute (instance hours, vCPU-seconds for serverless), storage (GB-month by tier, plus requests), data transfer (per GB, direction- and distance-dependent), managed-service premiums, and licences. Inbound internet traffic is generally free; outbound internet egress commonly costs several cents per GB; cross-AZ traffic is charged in many providers (on AWS, on the order of $0.01/GB in each direction). Approximate and provider-specific: always check current pricing. **Match purchase model to workload shape.** - **On-demand** for spiky, short-lived or unknown workloads. - **Commitments** (AWS Savings Plans / Reserved Instances, Azure reservations / savings plans, Google Cloud committed use discounts) for the steady baseline: commonly 30\u201370% cheaper depending on term and flexibility. Commit to the floor of usage, not the average. - **Spot / preemptible** (AWS Spot, Azure Spot VMs, Google Cloud Spot VMs) for fault-tolerant, interruptible work (batch, CI, stateless workers): deep discounts (often 60\u201390%) with short-notice interruption (about two minutes on AWS, roughly 30 seconds on Azure and Google Cloud). Diversify instance types and handle the interruption signal. **Rightsize** from observed utilization (p95 CPU/memory over weeks), not requested capacity; in Kubernetes, rightsize requests too, since the scheduler packs by requests. Move to newer instance generations and, where supported, ARM-based instances for better price/performance. **Design out transfer costs.** Keep chatty services and their caches in the same AZ where availability allows (zone-aware routing), compress, use a CDN for internet egress, use private endpoints instead of NAT for cloud-service traffic, and avoid cross-region replication you do not need. **Storage lifecycle.** Tier objects by access pattern (hot \u2192 infrequent \u2192 archive), expire logs and temporary data, clean old snapshots, and watch request costs for many tiny objects. **Allocation: tagging, showback, chargeback.** Enforce tags (\`team\`, \`service\`, \`env\`, \`cost-center\`) via policy as code; account-per-team structures make allocation simpler. **Showback** reports costs to teams; **chargeback** bills them internally. Shared costs (platform clusters, networking) are split by a documented key such as requested CPU. **Unit economics.** Track cost per business unit (per 1k requests, per active customer, per order, per GB processed). Absolute spend can rightly grow with the business; unit cost should flatten or fall. This is the metric to put in front of leadership. **Operate.** Budgets and anomaly detection per team, cost visible in PRs (estimation tools), regular reviews of the top cost lines, and engineers empowered to act.`, components: [ { name: "Lifecycle: inform, optimize, operate", description: "Iterative phases: visibility and allocation, then rate and usage optimisation, then continuous governance." }, { name: "Data transfer", description: "Internet egress, cross-AZ, cross-region, NAT processing. The most commonly underestimated cost driver in architecture reviews." }, { name: "Commitments vs spot", description: "Commit to the steady baseline; run interruptible work on spot; leave peaks on on-demand or autoscaled." }, { name: "Rightsizing", description: "Resize from observed p95 utilization; in containers, fix requests so bin-packing reflects reality." }, { name: "Tagging, showback, chargeback", description: "Allocation enforced by policy, reported to owners; shared costs split by a documented key." }, { name: "Unit economics", description: "Cost per business outcome; the metric that separates healthy growth from waste." } ], misconceptions: [ { myth: "Serverless is always cheaper.", reality: "Cheaper for spiky, low-duty-cycle workloads. For a steady high-throughput service, per-invocation pricing can cost several times more than well-utilised instances or containers." }, { myth: "Buy commitments for all current usage.", reality: "Commit to the floor you are confident persists for the term. Over-committing turns elasticity into fixed cost, and architecture changes can strand reservations." }, { myth: "Multi-AZ is free apart from the extra instances.", reality: "Replication and service-to-service traffic across AZs is billed per GB in many providers; a chatty microservice mesh spread across three zones can generate a large transfer bill." }, { myth: "Cost optimisation is a one-off project.", reality: "Without operate-phase controls (tags, budgets, anomaly alerts, reviews) waste returns within months." } ], example: { title: "Back-of-envelope transfer cost", description: `A service sends 2 TB/day to a cache and a database in other AZs, and serves 500 GB/day to the internet without a CDN. Prices are illustrative approximations.`, language: "text", code: `Cross-AZ: 2 TB/day \u2248 60 TB/month = 60,000 GB ~ $0.01/GB out + ~$0.01/GB in \u2248 $0.02/GB \u2192 ~ $1,200 / month Internet egress: 500 GB/day \u2248 15 TB/month = 15,000 GB ~ $0.08/GB (first tiers, approximate) \u2192 ~ $1,200 / month Fixes: - zone-aware routing to same-AZ cache replicas \u2192 cross-AZ traffic down ~2/3 - CDN with high cache-hit ratio for static/media \u2192 origin egress down sharply Unit metric: transfer cost per 1k requests, tracked monthly.` }, exercise: { prompt: `A SaaS company's cloud bill grew 70% year over year while revenue grew 25%. You have one quarter. What do you do?`, solution: `- **Inform first:** enforce tagging and map 90%+ of spend to teams/services; publish a showback dashboard; compute unit cost (per customer, per 1k requests) to show which services are scaling badly. - **Quick wins:** shut down idle/non-prod out of hours, delete unattached volumes and old snapshots, apply storage lifecycle policies, rightsize the top over-provisioned instances and Kubernetes requests. - **Rates:** cover the observed steady baseline with flexible commitments; move CI and batch to spot. - **Architecture:** investigate data transfer lines (cross-AZ chatter, NAT for cloud-service traffic, missing CDN) and the top 3 services by unit-cost growth. - **Operate:** budgets and anomaly alerts per team, cost estimation in IaC PRs, monthly review. Report the delta as unit cost trend, not just absolute spend.` }, faq: [ { q: "Showback or chargeback?", a: "Start with showback: it builds trust in the numbers. Chargeback makes sense once allocation is accurate and teams have the authority to change their spend; otherwise it creates disputes without savings." }, { q: "How do I estimate cost in a system design interview?", a: "Order of magnitude: instance count \xD7 hourly price, storage GB \xD7 tier price, and especially transfer GB \xD7 per-GB price. State assumptions and flag transfer and managed-service premiums as the likely surprises." }, { q: "What is a good unit metric?", a: "Something tied to value that engineering can influence: cost per active customer, per order, per million API calls, per GB ingested. Pick one or two per product and trend them." } ], keyTerms: ["FinOps lifecycle", "data egress", "cross-AZ traffic", "commitments", "spot instances", "rightsizing", "unit economics", "showback", "chargeback", "storage lifecycle"], deeper: `**Kubernetes cost allocation** is hard because many workloads share nodes. Allocate by the larger of requested and used CPU/memory per pod, attribute idle node capacity to the platform (or spread it), and make cluster efficiency (used \xF7 allocatable) a platform KPI. Overstated requests are both a cost problem and a scheduling problem.`, interview: { seniorAnswer: `Treat cost as a design constraint with numbers. Name the drivers including the hidden ones (internet egress, cross-AZ and NAT processing, cross-region replication, log volume), map purchase models to workload shape (commit to the baseline, spot for interruptible, on-demand for peaks), rightsize from observed utilization including container requests, and apply storage lifecycle policies. Explain the FinOps loop (inform, optimize, operate) with tagging enforced by policy, showback before chargeback, budgets and anomaly alerts. Measure success as unit cost per business outcome, not total spend.`, followUps: [ { q: "How do you size a commitment purchase?", a: "Look at 30\u201390 days of hourly usage, commit to roughly the minimum sustained level (the floor), prefer flexible commitment types, ladder purchases over time, and review coverage and utilization monthly." }, { q: "How would you run stateless workers on spot safely?", a: "Diversify across instance types and AZs, handle the interruption notice (drain, checkpoint, stop taking work), keep an on-demand base for minimum capacity, and make jobs idempotent so retries are safe." }, { q: "Where do cross-AZ costs hide in Kubernetes?", a: "Service-to-service calls load-balanced across zones, cross-zone load balancer traffic, and replicated stateful sets. Topology-aware routing and zone-local replicas reduce it, traded against even spread for availability." } ], redFlags: [ "Ignores data transfer when estimating cost.", "Buys commitments for peak usage.", "Runs stateful, non-interruptible work on spot without a plan.", "Optimises total spend while unit cost is rising.", "No allocation, so nobody owns the bill." ], numbers: [ "Commitment discounts commonly ~30\u201370% vs on-demand (term and flexibility dependent).", "Spot discounts often ~60\u201390%; AWS gives ~2 minutes interruption notice, Azure and Google Cloud ~30 seconds.", "Cross-AZ transfer on AWS \u2248 $0.01/GB each direction; internet egress several cents per GB (approximate).", "1 TB/day \u2248 30 TB/month: multiply per-GB prices by ~30,000." ] }, references: [ { title: "FinOps Framework", url: "https://www.finops.org/framework/" }, { title: "AWS Well-Architected", url: "https://aws.amazon.com/architecture/well-architected/" }, { title: "Google Cloud Well-Architected Framework", url: "https://cloud.google.com/architecture/framework" } ] }, // ───────────────────────────── Stage 9 · Interview Craft ──────────────────────────── { id: "infra-craft-system-design", title: "A 45-minute system design method", stage: 9, order: 1, objectives: ["craft-system-design"], scope: "senior", estMinutes: 30, summary: "System design interviews score how you think, not which boxes you draw. Use a repeatable structure, quantify early, drive the conversation, go deep where it matters, and close with failure modes, trade-offs and evolution.", what: `A system design interview is a 45\u201360 minute collaborative exercise: you are given a vague product ("design a URL shortener", "design a metrics pipeline", "design a multi-region rate limiter") and must produce a reasoned architecture while thinking aloud. A reliable framework: - **Clarify (5 min)** \u2013 functional requirements (what it does), non-functional requirements (scale, latency, availability, consistency, durability, cost, compliance), and what is out of scope. - **Estimate (3\u20135 min)** \u2013 QPS (peak vs average), storage growth, bandwidth, memory for hot data. - **API and data model (5 min)** \u2013 core endpoints or events, entities, access patterns, partition keys. - **High-level design (10 min)** \u2013 clients, edge, services, data stores, async paths. Walk a request end to end. - **Deep dives (10\u201315 min)** \u2013 the 1\u20132 hardest parts, often chosen with the interviewer. - **Bottlenecks and failure modes (5 min)** \u2013 hot keys, overload, dependency failure, AZ/region loss, data corruption. - **Trade-offs and evolution (3\u20135 min)** \u2013 what you would change at 10\xD7 scale, what you deliberately did not build.`, why: `At senior level, the interview is a proxy for how you would lead a real design review: do you find the actual requirements, size the problem, make defensible choices, and know where it will break? Candidates with deep knowledge still fail because they jump to components, never quantify, or spend 30 minutes on one box. Structure frees your attention for judgment.`, problem: `Common failure patterns: - **Diving into technology** ("we'll use Kafka and Cassandra") before knowing scale or access patterns. - **No numbers**, so no way to justify sharding, caching or a queue. - **Passive candidate** waiting for prompts; the interviewer has to drive. - **Breadth with no depth**: twelve boxes, nothing explained below the label. - **Happy path only**: no mention of what happens when a dependency is slow, a region fails or a hot key appears. - **Running out of time** before trade-offs, which is where senior signal lives.`, how: `**Clarify like an owner.** Ask who the users are, the read/write ratio, peak vs average traffic, latency targets (p99, not "fast"), consistency needs per operation (balance must be strongly consistent; a like counter need not), data retention, and multi-region requirements. Write the requirements visibly and confirm them. **Back-of-envelope numbers to keep handy (order of magnitude):** - 1 day \u2248 86,400 s \u2248 10^5 s. So 1M requests/day \u2248 12 req/s; 100M/day \u2248 1,200 req/s average; plan peak at 2\u201310\xD7 average. - Main memory reference ~100 ns; SSD random read ~tens to ~100 \xB5s; round trip within a datacenter ~0.5 ms; cross-continent round trip ~100\u2013150 ms. - Reading 1 MB sequentially: ~microseconds from memory, ~ms from SSD. - A single well-tuned relational primary can typically handle thousands to low tens of thousands of simple writes/s; a Redis-class cache node ~100k ops/s (rough rules of thumb, workload dependent). - Storage: 100M records \xD7 1 KB = 100 GB; times replication factor 3; times retention. **API and data first, then boxes.** The access pattern determines the store: key-value lookups, range scans by time, secondary indexes, full-text, graph traversal. State the partition key and why it avoids hot spots. **High-level design, then walk a request.** Narrate a write and a read through the system, naming where state lives and what is synchronous vs async. **Drive the deep dive.** Offer choices: "The interesting parts are the fan-out on write for timelines and the hot-key problem for celebrities; which would you like me to go into?" Then go to mechanism level: data layout, consistency, caching strategy and invalidation, idempotency, backpressure. **Failure modes and operability.** For each critical component: what if it is slow, down, or returns wrong data? Timeouts, retries with jitter, circuit breakers, load shedding, multi-AZ, backups and restore tests, the SLOs you would set and the alerts you would page on, how you would deploy safely. **Trade-offs and evolution.** Summarise the key decisions and their costs, and what changes at 10\xD7 (sharding, cells, moving to async, regional deployment). **What interviewers score.** At **senior**: requirements gathering, sound estimates, correct use of building blocks, depth in at least one area, awareness of failure modes and trade-offs, clear communication. At **staff**: framing the problem in business terms, identifying the few decisions that really matter, reasoning about org and operational cost (who runs this, migration path from today's system), multi-year evolution, and making the interviewer feel they were in a good design review.`, components: [ { name: "Requirements", description: "Functional, non-functional with numbers, and explicit non-goals. Everything later is justified against these." }, { name: "Estimation", description: "QPS, storage, bandwidth and memory to order of magnitude; drives sharding, caching and queue decisions." }, { name: "API and data model", description: "Endpoints/events, entities, access patterns and partition keys; chooses the data store for you." }, { name: "High-level architecture", description: "Edge, services, stores, async paths; a narrated request walk-through." }, { name: "Deep dives", description: "One or two hard problems to mechanism depth, chosen with the interviewer." }, { name: "Failure modes, trade-offs, evolution", description: "What breaks, how it degrades, what you chose not to do, and what changes at 10\xD7." } ], misconceptions: [ { myth: "There is a correct answer the interviewer is waiting for.", reality: "Multiple designs pass. Interviewers score the reasoning: requirements, numbers, justified choices, awareness of costs and failure." }, { myth: "Naming more technologies shows more experience.", reality: "Unjustified components are a negative signal. Fewer boxes, each explained, beats a buzzword map." }, { myth: "The interviewer should guide the discussion.", reality: "Seniors drive: propose the agenda, check in at transitions, and invite the interviewer to steer deep dives." }, { myth: "Precise arithmetic matters.", reality: "Order of magnitude matters. Round aggressively, state assumptions, and show how the number changes the design." } ], example: { title: 'Opening five minutes for "design a URL shortener"', description: `Clarifying questions and a quick estimate that already shapes the design (read-heavy, small dataset, cache-friendly).`, language: "text", code: `Clarify: - Create short links and redirect. Custom aliases? Expiry? Analytics? -> aliases yes, analytics async - Scale: 100M new links/month, 100:1 read:write - Redirect latency p99 < 50 ms at edge; availability 99.99% for redirects, 99.9% for create Estimate: writes: 100M / (30 * 1e5 s) \u2248 40/s avg, ~400/s peak reads: ~4,000/s avg, ~40,000/s peak storage: 100M * 12 months * 5 years * ~500 B \u2248 3 TB (+ replicas) hot set: top 20% of links serve most reads -> fits comfortably in memory cache Implications: - KV store keyed by short code; ID generation without coordination (range allocation / random + check) - redirects served from cache/CDN; analytics via async event stream, never in the redirect path` }, exercise: { prompt: `Practise the framework on "design a metrics ingestion pipeline for 50k hosts, each sending 500 series every 10 s, with 30-day retention and dashboards that must load in under 2 s". Produce requirements, estimates and the two deep dives you would propose.`, solution: `- **Estimates:** 50k \xD7 500 = 25M active series; 25M / 10 s = 2.5M samples/s. At ~1\u20132 bytes/sample compressed (Gorilla-style compression, approximate) that is ~2.5\u20135 MB/s, roughly 6.5\u201313 TB over 30 days before replication; raw ingest bandwidth before compression is far higher. - **High level:** agents \u2192 regional ingest gateways (stateless, batching) \u2192 durable log (partitioned by series hash) \u2192 ingesters building compressed blocks in memory \u2192 object storage for blocks + index \u2192 query layer with caching and downsampled rollups. - **Deep dive 1: cardinality and partitioning.** Hash series to partitions, per-tenant series limits, hot-tenant isolation, what happens when a deploy changes a label and doubles series. - **Deep dive 2: query performance.** Pre-aggregated rollups (1 m, 1 h) for long ranges, query result caching, limits on series per query, fan-out and tail latency across shards. - **Failure modes:** ingester crash (replay from the log), backpressure when the log lags, and dropping or delaying low-priority tenants under overload rather than failing everyone.` }, faq: [ { q: "How much should I write vs talk?", a: "Keep a visible list of requirements and numbers and a simple diagram; talk continuously about why. The written artefacts let the interviewer follow and let you refer back when justifying choices." }, { q: "What if I do not know a technology the interviewer mentions?", a: 'Say so, reason from first principles about what it must do (e.g. "a log-structured store optimised for writes"), and compare to something you know. Honesty plus reasoning scores better than bluffing.' }, { q: "How do I recover if I realise a mistake mid-way?", a: 'Name it and fix it: "Given the 100:1 read ratio I under-weighted caching; let me revise." Self-correction is a positive senior signal.' } ], keyTerms: ["functional requirements", "non-functional requirements", "back-of-envelope estimation", "access patterns", "partition key", "deep dive", "failure modes", "trade-offs", "evolution", "driving the interview"], deeper: `**Infrastructure-flavoured variants.** Platform and SRE loops often swap product questions for infrastructure ones: design a deployment system, a multi-tenant Kubernetes platform, a global load-balancing layer, a log pipeline, or a secrets service. The framework is the same, but the non-functional requirements dominate: blast radius, tenancy isolation, upgrade strategy, failure of the control plane vs data plane (data plane should keep working when the control plane is down: static stability), and the operational cost of the platform team.`, interview: { seniorAnswer: `Show the structure explicitly at the start ("I'll clarify, estimate, sketch the API and data model, do a high-level design, then go deep on two areas and finish with failure modes and trade-offs"), then execute it with numbers. Tie every component to a requirement or estimate, pick data stores by access pattern, go to mechanism depth on the hardest part, and proactively cover overload, dependency failure, AZ/region loss, deployment and observability. Keep time; reserve the last minutes for trade-offs and 10\xD7 evolution. For staff, add business framing, migration from today's system and who operates it.`, followUps: [ { q: 'The interviewer says "assume 10\xD7 the traffic". What do you revisit?', a: "The estimates first, then whichever component crosses a limit: single-writer database (shard or partition), cache memory, fan-out costs, cross-AZ transfer cost, and whether synchronous paths should become async." }, { q: "How do you choose between SQL and NoSQL in an interview?", a: "From access patterns and consistency: relational for multi-entity transactions, ad-hoc queries and moderate write scale; key-value/wide-column for very high write throughput with known access patterns by key. State the trade-off and migration path." }, { q: "How do you handle a hot key?", a: "Detect it (per-key metrics), cache with request coalescing, replicate hot entries across cache nodes, shard the key (key#N with fan-in on read), and rate-limit pathological clients." } ], redFlags: [ "Starts drawing before asking any questions.", "No numbers anywhere in the design.", "Picks technologies by name without justification.", "Never mentions failures, overload or deployment.", "Runs out of time with no trade-off discussion." ], numbers: [ "1 day \u2248 10^5 s; 1M/day \u2248 12/s; peak \u2248 2\u201310\xD7 average.", "Memory ~100 ns, SSD ~10\u2013100 \xB5s, intra-DC RTT ~0.5 ms, cross-continent ~100\u2013150 ms.", "Time budget: clarify 5, estimate 5, API/data 5, high level 10, deep dives 10\u201315, failures + trade-offs 5\u201310 minutes." ] }, references: [ { title: "System Design Primer", url: "https://github.com/donnemartin/system-design-primer" }, { title: "High Performance Browser Networking", url: "https://hpbn.co/" }, { title: "Amazon Builders' Library", url: "https://aws.amazon.com/builders-library/" }, { title: "Static stability using Availability Zones", url: "https://aws.amazon.com/builders-library/static-stability-using-availability-zones/" } ] }, { id: "infra-craft-behavioral", title: "Senior behavioural interviews", stage: 9, order: 2, objectives: ["craft-behavioral"], scope: "senior", estMinutes: 25, summary: "Behavioural rounds decide levelling as often as technical ones. Prepare a bank of quantified STAR+L stories that show scope, ownership, influence, judgment under ambiguity and growth from failure, and map each to the themes interviewers probe.", what: `Behavioural interviews ask about past situations ("tell me about a time...") on the premise that past behaviour predicts future behaviour. For senior and staff roles they are a primary **levelling** signal: the same story told at team scope reads as mid-level, told at multi-team scope with business impact reads as senior or staff. **STAR+L** gives each story a shape: - **Situation** \u2013 the context in one or two sentences: system, team, stakes. - **Task** \u2013 your responsibility or goal, and why it was hard. - **Action** \u2013 what *you* did, specifically, including decisions and trade-offs. The bulk of the story. - **Result** \u2013 the measurable outcome. - **Learning** \u2013 what you would do differently and what you changed afterwards.`, why: `Infrastructure work is high-leverage and high-blast-radius: interviewers need evidence you can lead an incident, drive a migration across teams, push back on an unsafe deadline and mentor others. Many strong engineers under-level because their stories are vague ("we improved reliability"), use "we" throughout, or describe tasks instead of decisions.`, problem: `Common failure patterns: - **Rambling situation**, little action: five minutes of context and one sentence of what you did. - **"We" not "I"**: the interviewer cannot tell your contribution. - **No numbers**: no before/after, no scale, no business impact. - **Wrong scope** for the level: a senior candidate whose biggest story is a single ticket. - **Fake failures**: "my weakness is I work too hard"; or failure stories that blame others. - **No preparation**: improvising stories under pressure, repeating the same story for every question.`, how: `**Build a story bank.** Write 8\u201312 stories from the last few years, each in STAR+L form in a few bullet points. Tag each with the themes it demonstrates. Aim for every theme to be covered by at least two stories so you never repeat within a loop. **Themes to cover (senior signals):** - **Scope** \u2013 work that spanned teams, systems or quarters. - **Ownership** \u2013 you saw a problem nobody owned and fixed it end to end, including the unglamorous parts. - **Influence without authority** \u2013 convincing peer teams or leadership with data, prototypes, or by reducing their cost of saying yes. - **Ambiguity** \u2013 turning a vague goal into a plan with milestones and decision points. - **Mentoring and multiplying** \u2013 making others better: reviews, docs, paved roads, on-call training. - **Judgment** \u2013 a trade-off where you chose speed vs safety, build vs buy, or pushed back on a risky plan. - **Conflict and disagreement** \u2013 disagreeing well, committing once decided. - **Failure** \u2013 a real mistake, owned, with systemic follow-up. **Quantify impact.** Before and after numbers: "pages per week from 30 to 4", "p99 from 900 ms to 180 ms", "deploy lead time from 3 days to 2 hours", "cut $40k/month in transfer costs", "migrated 120 services across 6 teams in two quarters with zero customer-facing incidents". If exact numbers are confidential, use relative ones (percentages, orders of magnitude). **Balance the time.** Roughly 10\u201315% situation and task, 60\u201370% action, 15\u201320% result and learning. Aim for 2\u20133 minutes per story, then let the interviewer probe; follow-ups are where depth and authenticity show. **Say "I" for your decisions, "we" for team outcomes.** Name the specific choices you made and the alternatives you rejected. **Handling "tell me about a failure".** Pick a real failure with real consequences, where you were the cause or the owner (not a teammate). Structure: what happened, your part in it, how you detected and mitigated it, the impact, the blameless systemic fix (process, tooling, guardrail) and evidence it worked. Show you changed something durable, not only that you "learned to be more careful". **Calibrate to level.** Senior: you led a significant project or incident and made the key technical calls. Staff: you set direction across teams, changed how the organisation works, and dealt with org-level trade-offs. Choose stories accordingly.`, components: [ { name: "STAR+L", description: "Situation, Task, Action, Result, Learning. Action is the centre of gravity; Learning separates senior from mid-level." }, { name: "Story bank", description: "8\u201312 prepared stories, each tagged with themes, covering every theme at least twice." }, { name: "Senior signals", description: "Scope, ownership, influence without authority, ambiguity, mentoring, judgment." }, { name: "Impact quantification", description: "Before/after metrics, scale, business outcome; relative numbers when absolute ones are confidential." }, { name: "Failure story", description: "Real, owned, with blameless systemic fixes and evidence they worked." } ], misconceptions: [ { myth: "Behavioural rounds are a formality after the technical ones.", reality: "They frequently decide the level and sometimes the hire. Under-prepared behavioural answers are a common reason strong engineers get down-levelled." }, { myth: 'Saying "we" shows you are a team player.', reality: "It hides your contribution. Credit the team for outcomes, but be specific about your own decisions and actions." }, { myth: "A failure story should end with a positive spin quickly.", reality: "Interviewers want depth on cause, ownership and systemic change. Rushing past the failure looks evasive." } ], example: { title: "A quantified STAR+L story (influence without authority)", description: `Condensed bullet form, as it would appear in a story bank.`, language: "text", code: `Themes: influence without authority, scope, judgment S: 40 services on 6 teams deployed via hand-run scripts; change failure rate ~25%, two Sev-1s in a quarter from bad deploys. T: I was a senior SRE with no authority over product teams; goal: progressive delivery for all tier-1 services within two quarters. A: - Pulled deploy and incident data to show 70% of Sev-1/2s were deploy-triggered. - Built a canary template with automated rollback; migrated my own team first. - Paired with one product team per week; removed their cost to adopt (PRs written for them). - Negotiated a staged policy with eng leadership: required for tier-1 only. R: 34/40 services migrated in 5 months; change failure rate 25% -> 8%; zero deploy-caused Sev-1s in the following two quarters. L: I underinvested in docs early and became a bottleneck; next time I'd train two champions per team in month one.` }, exercise: { prompt: `Draft your story bank: list 8 stories with one-line STAR summaries, tag each with themes from the list (scope, ownership, influence, ambiguity, mentoring, judgment, conflict, failure), and check that every theme has at least two stories. Then write the full STAR+L for your failure story with at least two numbers.`, solution: `- A good bank has a mix: an incident you led, a migration across teams, a cost or performance win, a disagreement with a manager or peer team, someone you mentored to promotion or on-call readiness, a project you killed or descoped, and a real failure. - **Check the grid:** every theme at least twice; no story carries more than 3\u20134 themes (it becomes vague). - **Failure story checklist:** you caused or owned it; impact quantified (e.g. "40 minutes of checkout errors for ~8% of users"); your detection and mitigation; the systemic fix (e.g. "added a deny-replace policy on stateful resources and a pre-apply plan review"); evidence (e.g. "it blocked three similar changes in the next six months"). - **Rehearse aloud** to 2\u20133 minutes each and practise answering two follow-ups per story ("what would you do differently?", "how did you get the other team to agree?").` }, faq: [ { q: "How many stories do I really need?", a: "Eight to twelve well-prepared stories cover most loops, because each can answer several questions. Breadth of themes matters more than count." }, { q: "What if my best work is confidential?", a: "Abstract the specifics (no customer or product names), keep the shape and relative numbers. Interviewers care about your reasoning and impact, not secrets." }, { q: "How do I show staff-level scope if my title was senior?", a: "Choose stories where you set direction across teams, changed a process or standard others adopted, or made an org-level trade-off. Scope of impact matters more than title." } ], keyTerms: ["STAR+L", "story bank", "scope", "ownership", "influence without authority", "ambiguity", "judgment", "quantified impact", "failure story", "levelling"], deeper: `**Blameless framing transfers.** The same culture that makes good postmortems (focus on systems and incentives, not individual fault) makes good failure stories: explain the conditions that made the mistake possible and how you changed them. It signals that you would make the team safer, not just yourself more careful.`, interview: { seniorAnswer: `Come with a prepared, theme-mapped bank of 8\u201312 STAR+L stories. In each answer, spend most of the time on your actions and decisions (including alternatives you rejected), state measurable before/after results, and finish with a genuine learning and what you changed because of it. Match the scope to the level you are targeting: cross-team, multi-quarter, business-relevant. For failure questions, own a real mistake, describe impact honestly, and show the systemic, blameless fix and evidence it worked.`, followUps: [ { q: "Tell me about a time you disagreed with your manager.", a: "Show that you disagreed with data, proposed an alternative, escalated proportionately, and committed once a decision was made, plus how it turned out and what you learned about influencing." }, { q: "What would you do differently?", a: 'Always have a concrete answer prepared for each story: a decision you would make earlier, a stakeholder you would involve sooner, or a guardrail you would add. "Nothing" is a red flag.' }, { q: "How did you measure success?", a: 'Name the metric before and after, how it was measured, and the time frame, e.g. "change failure rate from DORA-style tracking, 25% to 8% over two quarters".' } ], redFlags: [ 'Uses "we" throughout; personal contribution unclear.', "No numbers in any story.", "Failure story blames others or is a disguised strength.", "Same story reused for every question.", "Stories at task scope for a senior/staff role." ], numbers: [ "8\u201312 stories; every theme covered at least twice.", "2\u20133 minutes per story before follow-ups.", "Time split: ~15% situation/task, ~65% action, ~20% result and learning." ] }, references: [ { title: "Tech Interview Handbook: behavioral interviews", url: "https://www.techinterviewhandbook.org/behavioral-interview/" }, { title: "Postmortem culture (SRE book)", url: "https://sre.google/sre-book/postmortem-culture/" } ] } ]; // ../../packages/content/src/infra/questions-1.ts var R = { hpbn: { title: "High Performance Browser Networking (Ilya Grigorik)", url: "https://hpbn.co/" }, tcp: { title: "RFC 9293: Transmission Control Protocol (TCP)", url: "https://www.rfc-editor.org/rfc/rfc9293" }, tls13: { title: "RFC 8446: The Transport Layer Security (TLS) Protocol Version 1.3", url: "https://www.rfc-editor.org/rfc/rfc8446" }, quic: { title: "RFC 9000: QUIC: A UDP-Based Multiplexed and Secure Transport", url: "https://www.rfc-editor.org/rfc/rfc9000" }, http3: { title: "RFC 9114: HTTP/3", url: "https://www.rfc-editor.org/rfc/rfc9114" }, dns: { title: "RFC 1034: Domain Names - Concepts and Facilities", url: "https://www.rfc-editor.org/rfc/rfc1034" }, rfc1918: { title: "RFC 1918: Address Allocation for Private Internets", url: "https://www.rfc-editor.org/rfc/rfc1918" }, vpc: { title: "Amazon VPC User Guide: What is Amazon VPC?", url: "https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html" }, awsWa: { title: "AWS Well-Architected Framework", url: "https://aws.amazon.com/architecture/well-architected/" }, azureWa: { title: "Azure Well-Architected Framework", url: "https://learn.microsoft.com/en-us/azure/well-architected/" }, gcpWa: { title: "Google Cloud Well-Architected Framework", url: "https://cloud.google.com/architecture/framework" }, gcpArch: { title: "Google Cloud Architecture Center", url: "https://cloud.google.com/architecture" }, azurePatterns: { title: "Azure Architecture Center: Cloud design patterns", url: "https://learn.microsoft.com/en-us/azure/architecture/patterns/" }, primer: { title: "The System Design Primer", url: "https://github.com/donnemartin/system-design-primer" }, builders: { title: "AWS Builders' Library", url: "https://aws.amazon.com/builders-library/" }, staticStability: { title: "AWS Builders' Library: Static stability using Availability Zones", url: "https://aws.amazon.com/builders-library/static-stability-using-availability-zones/" }, overload: { title: "Google SRE book: Handling Overload", url: "https://sre.google/sre-book/handling-overload/" }, cascading: { title: "Google SRE book: Addressing Cascading Failures", url: "https://sre.google/sre-book/addressing-cascading-failures/" }, sreBook: { title: "Google SRE book (free online)", url: "https://sre.google/sre-book/table-of-contents/" }, twelveFactor: { title: "The Twelve-Factor App", url: "https://12factor.net/" }, k8sTenancy: { title: "Kubernetes docs: Multi-tenancy", url: "https://kubernetes.io/docs/concepts/security/multi-tenancy/" }, useMethod: { title: "Brendan Gregg: The USE Method", url: "https://www.brendangregg.com/usemethod.html" }, linuxPerf: { title: "Brendan Gregg: Linux Performance", url: "https://www.brendangregg.com/linuxperf.html" }, pgHa: { title: "PostgreSQL docs: High Availability, Load Balancing, and Replication", url: "https://www.postgresql.org/docs/current/high-availability.html" }, jepsen: { title: "Jepsen: Consistency Models", url: "https://jepsen.io/consistency" }, finops: { title: "FinOps Framework", url: "https://www.finops.org/framework/" } }; var infraQuestions1 = [ // ───────────────────────── net-fundamentals ───────────────────────── { id: "iq-net-fundamentals-001", domain: "networking", objective: "net-fundamentals", lessonId: "infra-net-fundamentals", difficulty: 2, type: "single", prompt: "Your team replicates backups between two regions over a dedicated 1 Gbps path with an 80 ms RTT. Packet loss is ~0%, yet a single TCP stream plateaus at ~50 Mbps. What is the most likely cause and fix?", choices: [ "The effective TCP window is ~500 KB while the bandwidth-delay product is ~10 MB; raise socket buffers / window-scaling limits (or use parallel streams).", "The link is saturated by other tenants; upgrade the path to 10 Gbps.", "Nagle's algorithm is delaying segments; set TCP_NODELAY on the sender.", "TCP slow start never finishes on long paths; switch the transfer to plain UDP." ], answer: [0], explanation: "Single-stream TCP throughput is capped at window / RTT. The BDP is 1 Gbps x 0.08 s = 80 Mbit = ~10 MB, but 50 Mbps x 0.08 s is only ~500 KB in flight, so the window, not the link, is the limit. Raising receive/send buffer maxima (window scaling must be enabled) or running several parallel streams fills the pipe; buying bandwidth changes nothing when the window is the bottleneck.", choiceRationale: [ "Correct: 50 Mbps x 80 ms = ~500 KB in flight versus a ~10 MB BDP, so the window is the binding constraint.", "With no loss and a flat 50 Mbps ceiling there is no sign of contention, and more bandwidth does not enlarge the window.", "Nagle affects small interactive writes, not bulk transfers that already fill full-size segments.", "Slow start ends quickly without loss; replacing TCP with raw UDP throws away congestion control and reliability rather than fixing the window." ], references: [R.hpbn, R.tcp], tags: ["tcp", "bandwidth-delay-product", "throughput"] }, { id: "iq-net-fundamentals-002", domain: "networking", objective: "net-fundamentals", lessonId: "infra-net-fundamentals", difficulty: 3, type: "single", prompt: "You must move `api.example.com` to a new load balancer next Tuesday. The A record currently has a TTL of 86400 s. Which plan minimises the window in which clients hit the old endpoint?", choices: [ "Change the record and lower the TTL to 60 s at the same moment on Tuesday.", "At least 24 h before Tuesday, lower the TTL to ~60 s; cut over on Tuesday; keep the old endpoint serving (or proxying) until its traffic decays; then raise the TTL again.", "Set the TTL to 0 permanently so future migrations are instant.", "Cut over on Tuesday and ask the major public resolvers to flush their caches." ], answer: [1], explanation: "Resolvers cache a record for the TTL they saw when they fetched it, so a TTL change only takes effect after the old TTL expires. Lowering it one full old-TTL in advance means that by cutover every cache holds at most a 60 s copy. Some clients and resolvers ignore TTLs, so the old endpoint must keep serving until its traffic actually drains; a permanently tiny TTL adds resolver load and latency for no lasting benefit.", choiceRationale: [ "Caches that fetched the record before the change keep the 86400 s copy, so stragglers can hit the old endpoint for up to a day.", "Correct: pre-lowering by one old TTL bounds staleness, and keeping the old endpoint alive covers resolvers that ignore TTLs.", "TTL 0 forces a lookup on nearly every connection, increasing latency and DNS dependency, and some resolvers clamp it anyway.", "You cannot flush the long tail of ISP and enterprise resolvers, so this leaves stale clients unhandled." ], references: [R.dns, R.hpbn], tags: ["dns", "ttl", "migration"] }, { id: "iq-net-fundamentals-003", domain: "networking", objective: "net-fundamentals", lessonId: "infra-net-fundamentals", difficulty: 2, type: "single", prompt: "After moving a mobile API from HTTP/1.1 (6 connections per client) to HTTP/2 (one multiplexed connection), median latency improved but p99 got worse for users on lossy cellular networks (~2% loss). What best explains this?", choices: [ "HTTP/2 header compression (HPACK) is CPU-bound on low-end phones.", "HTTP/2 requires TLS 1.3, which adds an extra round trip per request.", "With one TCP connection, a single lost packet stalls every multiplexed stream until it is retransmitted (transport head-of-line blocking); HTTP/3 over QUIC recovers loss per stream.", "HTTP/2 server push floods the radio link with unused resources." ], answer: [2], explanation: "HTTP/2 removes application-level head-of-line blocking but TCP still delivers bytes in order, so one loss blocks all streams on that connection; with six HTTP/1.1 connections a loss only stalled one. On lossy links this shows up in the tail, not the median. QUIC (HTTP/3) runs streams independently over UDP, so loss on one stream does not delay the others.", choiceRationale: [ "HPACK is cheap and would affect all users, not specifically lossy networks at p99.", "HTTP/2 does not mandate TLS 1.3, and the TLS handshake is per connection, not per request.", "Correct: transport-level HOL blocking on a single TCP connection amplifies loss into tail latency.", "Server push is rarely used and largely deprecated by browsers; it would not explain a loss-correlated p99 regression." ], references: [R.http3, R.quic], tags: ["http2", "http3", "quic", "tail-latency"] }, { id: "iq-net-fundamentals-004", domain: "networking", objective: "net-fundamentals", lessonId: "infra-net-fundamentals", difficulty: 1, type: "single", prompt: "A client 100 ms RTT away opens a brand-new HTTPS connection (TCP + full TLS 1.3 handshake, no session resumption or 0-RTT) and sends one GET. Ignoring server processing time, roughly when does the first response byte arrive?", choices: ["~400 ms", "~100 ms", "~200 ms", "~300 ms"], answer: [3], explanation: "TCP needs one RTT for SYN/SYN-ACK, TLS 1.3 a full handshake of one RTT (the client can send the request right after its Finished), and the request/response one more RTT: ~3 RTT = ~300 ms. TLS 1.2 would add another RTT. This is why connection reuse, resumption and edge termination close to users matter so much for latency.", choiceRationale: [ "Four RTTs matches TCP plus a TLS 1.2 handshake, not TLS 1.3.", "One RTT is only the request/response on an already-established, already-secured connection.", "Two RTTs would require 0-RTT resumption or skipping the TCP handshake (e.g. QUIC).", "Correct: 1 RTT TCP + 1 RTT TLS 1.3 + 1 RTT request/response = ~300 ms." ], references: [R.tls13, R.hpbn], tags: ["tls", "latency", "handshake"] }, { id: "iq-net-fundamentals-005", domain: "networking", objective: "net-fundamentals", lessonId: "infra-net-fundamentals", difficulty: 3, type: "multi", prompt: "A fleet of workers calls one upstream service through a single egress NAT IP. Under peak load, connections fail with address/port allocation errors and hosts show tens of thousands of sockets in TIME_WAIT. Select TWO changes that address the root cause.", choices: [ "Reuse connections via HTTP keep-alive and client-side pooling instead of opening a connection per request.", "Increase the upstream server's listen backlog (`somaxconn`).", "Increase the number of distinct 4-tuples available, e.g. more NAT egress IPs or more upstream destination IPs.", "Disable TCP timestamps on the workers to shorten TIME_WAIT." ], answer: [0, 2], explanation: "Each connection to the same destination IP:port through one NAT IP consumes a source port, and closed connections hold that 4-tuple in TIME_WAIT for tens of seconds, so connection-per-request churn exhausts the ephemeral port range (at most ~64k per 4-tuple prefix, and only ~28k with the Linux default 32768-60999 range). Pooling removes the churn, and adding source or destination IPs multiplies the available 4-tuples. Backlog tuning helps accept queues, not client port exhaustion, and disabling timestamps actually prevents safe TIME_WAIT reuse.", choiceRationale: [ "Correct: connection reuse eliminates most new 4-tuple allocations and TIME_WAIT churn.", "The listen backlog governs pending accepts on the server, not ephemeral port exhaustion on the client/NAT side.", "Correct: each extra source or destination IP adds another full port range of usable 4-tuples.", "Timestamps are what make TIME_WAIT reuse safe; disabling them does not shorten TIME_WAIT and can make things worse." ], references: [R.tcp, R.hpbn], tags: ["tcp", "nat", "port-exhaustion", "connection-pooling"] }, { id: "iq-net-fundamentals-006", domain: "networking", objective: "net-fundamentals", lessonId: "infra-net-fundamentals", difficulty: 2, type: "single", prompt: "During a period of mild packet loss between two services, the latency histogram for new connections shows distinct spikes at almost exactly ~1 s and ~3 s above normal. What is the most likely mechanism?", choices: [ "Lost SYNs being retransmitted after the initial ~1 s retransmission timeout, then again after an exponentially backed-off ~2 s (cumulative ~3 s).", "DNS resolver timeouts on the client, which default to exactly 1 s and 3 s.", "Garbage-collection pauses on the server that happen to align with packet loss.", "Nagle and delayed ACK interacting, which adds up to 1 s per request." ], answer: [0], explanation: "Before the handshake completes there is no RTT sample, so the sender uses an initial RTO of about 1 s and doubles it on each retry. A lost SYN or SYN-ACK therefore produces quantised delays of ~1 s, ~3 s, ~7 s. Seniors recognise these quantised spikes and fix them with connection reuse, connect timeouts shorter than the first retry plus a retry to another endpoint, or by removing the loss source.", choiceRationale: [ "Correct: initial RTO of ~1 s with exponential backoff yields spikes at ~1 s and ~3 s cumulative.", "Resolver timeouts vary by stub configuration and would hit even when the TCP path is healthy; they do not track packet loss on the service link.", "GC pauses would not produce consistent quantised delays tied only to new connections.", "The Nagle/delayed-ACK stall is typically tens to a few hundred ms and affects established connections, not connection setup." ], references: [R.tcp, R.hpbn], tags: ["tcp", "retransmission", "tail-latency"] }, // ───────────────────────── net-cloud ───────────────────────── { id: "iq-net-cloud-001", domain: "networking", objective: "net-cloud", lessonId: "infra-net-cloud", difficulty: 2, type: "single", prompt: "Your Kubernetes clusters use VPC-native pod networking, so every pod takes a subnet IP. Each AZ needs a private subnet for up to ~4,000 pods and nodes, and the provider reserves 4-5 addresses per subnet. What is the smallest subnet prefix per AZ that fits?", choices: ["/21", "/20", "/19", "/22"], answer: [1], explanation: "A /20 has 4,096 addresses, leaving ~4,091 after reservations, which fits 4,000 with little headroom; a /21 (2,048) does not. In practice a senior would also plan for growth and surge during node upgrades and might choose a /19 or a secondary range, but the smallest that fits is /20. Undersizing pod subnets is a common cause of failed scale-outs that are painful to fix later.", choiceRationale: [ "A /21 provides only 2,048 addresses, roughly half of what is needed.", "Correct: /20 = 4,096 addresses, ~4,091 usable after reservations.", "A /19 fits comfortably but is not the smallest prefix that meets the requirement.", "A /22 provides only 1,024 addresses." ], references: [R.vpc, R.rfc1918], tags: ["cidr", "ip-planning", "subnets"] }, { id: "iq-net-cloud-002", domain: "networking", objective: "net-cloud", lessonId: "infra-net-cloud", difficulty: 3, type: "single", prompt: "After an acquisition, the acquired company runs in a VPC using 10.0.0.0/16, the same CIDR as your main VPC. Within two weeks, their apps must call one internal API of yours over private networking. Re-addressing either side will take quarters. Which design best meets this?", choices: [ "Peer the two VPCs and rely on longest-prefix routing to disambiguate.", "Attach both VPCs to a transit hub and add static routes for 10.0.0.0/16 in both directions.", "Expose the API through a private endpoint service (e.g. PrivateLink / Private Service Connect / Private Link) behind a load balancer, consumed via an endpoint IP in their VPC.", "Route their traffic over the public internet with an IP allow-list on your API." ], answer: [2], explanation: "Peering and transit routing both require non-overlapping address space, so identical CIDRs cannot be routed between. A private endpoint service presents your API as an IP inside the consumer VPC and NATs the traffic, so overlap does not matter and only that one service is exposed, which also shrinks blast radius. It is a tactical fix; the long-term answer is still an enterprise IP plan.", choiceRationale: [ "Peering between overlapping CIDRs is rejected or unroutable; longest-prefix match cannot pick between identical ranges.", "A transit hub has the same overlap problem: it cannot route a prefix that exists on both sides.", "Correct: endpoint services are consumed via local IPs, so overlapping CIDRs are irrelevant and exposure is limited to one service.", "Public exposure violates the private-networking requirement and widens the attack surface." ], references: [R.vpc, R.awsWa], tags: ["vpc", "overlapping-cidr", "private-endpoint"] }, { id: "iq-net-cloud-003", domain: "networking", objective: "net-cloud", lessonId: "infra-net-cloud", difficulty: 2, type: "single", prompt: "A team adds a subnet-level network ACL that allows inbound TCP 443 from anywhere and outbound TCP 443 to anywhere. The instance security group already allows inbound 443. Clients now time out connecting to the web tier. Why?", choices: [ "Security groups and NACLs cannot both be applied to the same traffic.", "NACLs are evaluated after security groups, so the security group must also allow outbound 443.", "The NACL needs an explicit allow for ICMP so path MTU discovery works.", "NACLs are stateless: responses to clients go to their ephemeral ports (e.g. 1024-65535), which the outbound rule does not allow." ], answer: [3], explanation: "Security groups are stateful, so return traffic is implicitly allowed; subnet ACLs are stateless and evaluate each direction independently. The server replies from 443 to the client ephemeral port, so the outbound rule must allow that range. This is why most teams keep NACLs coarse and do fine-grained control in stateful security groups.", choiceRationale: [ "Both layers apply together routinely; that is the normal defence-in-depth arrangement.", "Security groups are stateful, so they already allow the return traffic for an accepted inbound connection.", "Blocking ICMP can break PMTUD for large packets, but it would not make every TCP connection time out.", "Correct: the stateless ACL drops return packets to client ephemeral ports." ], references: [R.vpc], tags: ["nacl", "security-groups", "stateless"] }, { id: "iq-net-cloud-004", domain: "networking", objective: "net-cloud", lessonId: "infra-net-cloud", difficulty: 1, type: "single", prompt: "The monthly bill shows a large NAT gateway data-processing charge. Investigation shows private-subnet batch jobs pull ~200 TB/month from the same cloud's object storage in-region. What is the best fix?", choices: [ "Add a private/gateway endpoint for the object storage service so that traffic bypasses the NAT gateway.", "Move the batch jobs to public subnets with public IPs.", "Replace the managed NAT gateway with self-managed NAT instances.", "Compress objects before upload to reduce bytes transferred." ], answer: [0], explanation: "Managed NAT charges per GB processed, so in-region traffic to a provider service is pure waste when a private endpoint exists. A gateway or private endpoint keeps the traffic on the provider network without NAT and also lets you apply endpoint policies. Public subnets widen exposure, and self-managed NAT trades a bill for an operational and availability burden.", choiceRationale: [ "Correct: private endpoints remove the NAT hop and its per-GB processing fee for that traffic.", "This avoids NAT fees but exposes the workloads directly to the internet, a poor security trade.", "NAT instances can be cheaper but add patching, scaling and single-point-of-failure risk while the traffic still does not need NAT.", "Compression may help somewhat but leaves an unnecessary per-GB path in place and requires changing every producer." ], references: [R.vpc, R.finops], tags: ["nat", "cost", "private-endpoint"] }, { id: "iq-net-cloud-005", domain: "networking", objective: "net-cloud", lessonId: "infra-net-cloud", difficulty: 3, type: "multi", prompt: "Your on-prem data centre must reach the cloud with ~5 Gbps sustained throughput, predictable latency, and no outage if any single circuit, device or provider facility fails. Select TWO design elements that are required.", choices: [ "A single dedicated interconnect port with two logical attachments (VLANs) for redundancy.", "Dedicated interconnect circuits terminating at two different provider locations, on diverse on-prem routers.", "Static routes on both paths, with operators switching preference during an outage.", "Dynamic routing (BGP) across all links, with tuned timers or BFD so failover is automatic." ], answer: [1, 3], explanation: "Dedicated interconnects give predictable latency and bandwidth that internet VPN cannot, but resilience requires physical diversity: separate facilities, circuits and routers. BGP lets routes withdraw automatically when a link fails, and BFD or tuned timers bring detection down from minutes toward about a second. Logical redundancy on one port and manual static failover both leave a single failure causing an outage.", choiceRationale: [ "Two VLANs on one port share the same physical port, circuit and facility, so one failure takes both down.", "Correct: facility and device diversity removes single physical failure points.", "Manual static failover turns a link failure into an outage that lasts until a human responds.", "Correct: BGP with fast failure detection reroutes automatically without human action." ], references: [R.awsWa, R.gcpArch], tags: ["hybrid", "interconnect", "bgp", "resilience"] }, { id: "iq-net-cloud-006", domain: "networking", objective: "net-cloud", lessonId: "infra-net-cloud", difficulty: 2, type: "single", prompt: "Your organisation has 30 VPCs/VNets that all need to talk to each other and to on-prem. Today they use pairwise peering. How many peerings does a full mesh need, and what is the better design?", choices: [ "60 peerings; keep the mesh but automate it with IaC.", "435 peerings; move to a hub-and-spoke transit hub (e.g. Transit Gateway / Virtual WAN or hub VNet / Network Connectivity Center) with central route tables.", "435 peerings; keep the mesh because peering is transitive and on-prem traffic will flow through it.", "900 peerings; merge everything into one VPC to remove peering entirely." ], answer: [1], explanation: "A full mesh needs n(n-1)/2 = 30 x 29 / 2 = 435 links, and peering is non-transitive, so on-prem reachability would also have to be built per VPC. A transit hub gives O(n) attachments, central routing and segmentation, and one place for inspection. The trade-off is an extra hop, per-GB processing charges and a shared component whose route tables need careful change control.", choiceRationale: [ "60 is 2n, not n(n-1)/2, and automating a 435-edge mesh still leaves a hard-to-reason-about routing estate.", "Correct: 435 is the mesh size, and a transit hub scales linearly with central control.", "The count is right but peering is not transitive, so on-prem traffic cannot ride through peers.", "900 is n squared, and collapsing into one VPC destroys account and blast-radius isolation." ], references: [R.vpc, R.azureWa], tags: ["peering", "transit-hub", "network-topology"] }, // ───────────────────────── net-edge ───────────────────────── { id: "iq-net-edge-001", domain: "networking", objective: "net-edge", lessonId: "infra-net-edge", difficulty: 2, type: "single", prompt: "A gRPC service sits behind an L4 (TCP) load balancer. After scaling from 3 to 10 replicas during a traffic surge, the 7 new replicas receive almost no requests and the original 3 stay hot. What is the best fix?", choices: [ "Lower the L4 load balancer idle timeout so connections recycle faster.", "Switch the L4 balancer from round-robin to least-connections.", "Balance per request with an L7 (HTTP/2-aware) load balancer or client-side balancing, optionally also capping connection age on the server.", "Increase the CPU request on the old replicas so the scheduler moves them." ], answer: [2], explanation: "gRPC multiplexes many requests over a few long-lived HTTP/2 connections, and an L4 balancer only makes a decision when a connection opens. New replicas see traffic only when clients reconnect. An L7 proxy or client-side balancer distributes individual requests across all backends; setting a maximum connection age forces gradual rebalancing as a complement.", choiceRationale: [ "Active gRPC connections rarely go idle, so an idle timeout barely recycles them.", "Least-connections still balances connections, and the existing connections stay pinned to the old replicas.", "Correct: per-request balancing spreads multiplexed streams across all replicas.", "Resource requests do not change how traffic is distributed over existing connections." ], references: [R.primer, R.hpbn], tags: ["load-balancing", "grpc", "l7"] }, { id: "iq-net-edge-002", domain: "networking", objective: "net-edge", lessonId: "infra-net-edge", difficulty: 2, type: "single", prompt: "During a 40-second database failover, the load balancer marked every web instance unhealthy and returned errors for 4 minutes, even for pages that don't touch the database. The health check endpoint queries the database. What is the best redesign?", choices: [ "Increase the health check interval to 5 minutes so blips are ignored.", "Remove health checks and rely on autoscaling to replace bad instances.", "Point the health check at the database directly instead of the app.", "Make the LB health check shallow (process up and able to serve), report dependency health separately, and degrade gracefully, ideally with the LB failing open when all targets look unhealthy." ], answer: [3], explanation: "A deep check that includes a shared dependency turns one dependency blip into a correlated fleet-wide removal, so the LB has nothing left to send traffic to. Shallow checks answer the question the LB actually asks: can this instance serve requests? Dependency problems should drive degraded responses and alerts, and failing open (sending to all targets when all are unhealthy) avoids self-inflicted total outages.", choiceRationale: [ "A 5-minute interval delays detection of truly dead instances and does not remove the shared-fate coupling.", "Without health checks the LB keeps sending traffic to crashed instances until autoscaling eventually notices.", "Checking the database tells the LB nothing about individual instances and makes the shared-fate coupling worse.", "Correct: shallow checks plus graceful degradation and fail-open prevent dependency-induced mass ejection." ], references: [R.builders, R.cascading], tags: ["health-checks", "load-balancing", "cascading-failure"] }, { id: "iq-net-edge-003", domain: "networking", objective: "net-edge", lessonId: "infra-net-edge", difficulty: 3, type: "single", prompt: "An L7 load balancer has a 60 s idle timeout and reuses backend connections. The backend app server uses a 5 s keep-alive timeout. You see a low but steady rate of 502s on quiet endpoints, with no errors in app logs. What is the most likely cause and fix?", choices: [ "The backend closes idle connections first, racing with the LB reusing them; set the backend keep-alive timeout longer than the LB's idle timeout.", "The LB idle timeout is too long; reduce it to 1 s.", "The backend is overloaded on quiet endpoints; add replicas.", "TLS session tickets are expiring; disable TLS between the LB and backend." ], answer: [0], explanation: "When the backend closes an idle keep-alive connection at 5 s, the LB can still send a request on it at the same moment and gets a reset, which surfaces as a 502 that never reaches app logs. The rule is that the backend's keep-alive timeout must exceed the LB's idle timeout (with margin), so the LB, which initiates reuse, always closes first. Quiet endpoints show it most because their connections sit idle long enough to hit the timeout.", choiceRationale: [ "Correct: the backend-closes-first race explains low-rate 502s with no app-side errors.", "A 1 s LB timeout would technically close first, but it forces constant reconnects and extra handshake latency; lengthening the backend keep-alive fixes the race without that cost.", "Quiet endpoints are the least loaded, and overload would appear in app logs and metrics.", "Session ticket expiry triggers a full handshake, not a 502, and removing TLS is a security regression." ], references: [R.hpbn, R.primer], tags: ["keep-alive", "502", "load-balancing", "timeouts"] }, { id: "iq-net-edge-004", domain: "networking", objective: "net-edge", lessonId: "infra-net-edge", difficulty: 1, type: "single", prompt: "You are choosing between anycast IPs and DNS-based global traffic management for a latency-sensitive global API. What is the main operational advantage of anycast during a regional failure?", choices: [ "Anycast guarantees each client always reaches the geographically closest region.", "Failover happens via BGP route withdrawal within seconds and is not delayed by resolver and client DNS caching.", "Anycast removes the need for health checks on regional backends.", "Anycast lets you weight traffic per region more precisely than DNS can." ], answer: [1], explanation: "With DNS-based steering, clients keep using cached answers until TTLs expire, and some ignore TTLs, so failover takes minutes for a long tail. Anycast advertises the same IP from many locations, and withdrawing a route shifts traffic at the network layer quickly. The trade-off is coarser control: routing follows BGP paths, not exact geography or fine weights.", choiceRationale: [ "BGP picks the best path by routing policy, which is usually but not always the closest location.", "Correct: route withdrawal moves traffic quickly without waiting on DNS caches.", "You still need health checks to decide when to withdraw a location or shift traffic behind it.", "Fine-grained weighting is a strength of DNS-based steering, not anycast." ], references: [R.primer, R.dns], tags: ["anycast", "gslb", "failover"] }, { id: "iq-net-edge-005", domain: "networking", objective: "net-edge", lessonId: "infra-net-edge", difficulty: 2, type: "single", prompt: "Your CDN serves 100k req/s with a 90% cache hit ratio. Better cache keys (ignoring tracking query parameters) would raise the hit ratio to 98%. What happens to origin request load?", choices: [ "It drops by ~8%, from 10k to ~9.2k req/s.", "It drops by ~50%, from 10k to 5k req/s.", "It drops by ~80%, from 10k to 2k req/s.", "It stays the same, because hit ratio only affects edge latency." ], answer: [2], explanation: "Origin load is the miss ratio times total traffic: 10% x 100k = 10k req/s becomes 2% x 100k = 2k req/s, a 5x reduction. Small changes in hit ratio near the top produce large changes in origin load, which is why seniors talk about miss ratio. Normalising cache keys is often the cheapest large win, but you must avoid collapsing variants that really differ, such as language or auth.", choiceRationale: [ "This applies the 8-point change to total traffic incorrectly instead of to the miss ratio.", "Halving would correspond to going from a 10% to a 5% miss ratio, i.e. a 95% hit ratio.", "Correct: misses go from 10% to 2% of traffic, a 5x drop in origin load.", "Every miss is an origin request, so the hit ratio directly drives origin load." ], references: [R.hpbn, R.primer], tags: ["cdn", "cache-hit-ratio", "capacity"] }, { id: "iq-net-edge-006", domain: "networking", objective: "net-edge", lessonId: "infra-net-edge", difficulty: 3, type: "multi", prompt: "Your search endpoint is hit by an L7 flood: valid-looking HTTPS GETs with random query strings from tens of thousands of rotating residential IPs. The database behind search is near saturation. Select TWO responses that best protect the service.", choices: [ "Apply edge WAF rate-based rules keyed on client fingerprint/IP/session, plus bot challenges, for the search path.", "Rely on origin autoscaling to absorb the traffic until the attack ends.", "Block the attacking IPs one by one with subnet network ACL rules.", "Protect the origin by shedding load and degrading search (e.g. cached or limited results, a concurrency cap on DB queries) when saturation is detected." ], answer: [0, 3], explanation: "L7 floods with random query strings bypass caching and look like real traffic, so they need filtering at the edge, where WAF rate limits and challenges absorb volume before it reaches the origin. Defence in depth means the origin must also protect its scarce resource, the database, by shedding and degrading rather than queueing until it collapses. Autoscaling moves the bottleneck to the database and increases cost, and per-IP ACLs cannot keep up with rotating botnets or their rule limits.", choiceRationale: [ "Correct: edge rate limiting and challenges stop most attack traffic before it reaches origin capacity.", "Scaling stateless tiers just pushes more load onto the saturated database and inflates cost.", "ACL rule limits are small and tens of thousands of rotating IPs make per-IP blocking futile.", "Correct: load shedding and graceful degradation keep the database from tipping into a cascading failure." ], references: [R.overload, R.awsWa], tags: ["ddos", "waf", "load-shedding"] }, // ───────────────────────── compute-models ───────────────────────── { id: "iq-compute-models-001", domain: "compute", objective: "compute-models", lessonId: "infra-compute-models", difficulty: 2, type: "single", prompt: "An internal API serves a flat ~2,000 req/s 24/7, each request taking ~50 ms of mostly CPU. It currently runs as serverless functions and is now the largest line in the compute bill. Which move best balances cost and operability?", choices: [ "Keep functions but raise their memory size so each request runs faster.", "Move to provisioned (pre-warmed) function concurrency to remove cold starts.", "Rewrite as a batch job that processes requests every minute.", "Run it as containers on an autoscaled service (or managed container platform) sized for the steady load, keeping functions for spiky or event-driven paths." ], answer: [3], explanation: "Serverless pricing per invocation and per GB-second is excellent for spiky or low-duty-cycle work but usually costs more than well-utilised containers or VMs for a high, flat baseline. Little's law says ~100 requests are in flight at any time (2,000 x 0.05 s), which a handful of right-sized containers can serve at high utilisation. You give up some operational simplicity, so keep functions where scale-to-zero and burst elasticity actually pay off.", choiceRationale: [ "More memory can shorten duration but rarely changes the unfavourable economics for a constant high baseline.", "Provisioned concurrency fixes latency, not cost, and you pay for it continuously.", "Batching changes the API contract and latency, which breaks a synchronous API.", "Correct: steady, high-utilisation load is cheaper on containers, while functions remain for bursty work." ], references: [R.awsWa, R.finops], tags: ["serverless", "containers", "cost"] }, { id: "iq-compute-models-002", domain: "compute", objective: "compute-models", lessonId: "infra-compute-models", difficulty: 2, type: "multi", prompt: "Your team wants to move a 6-hour nightly batch pipeline (thousands of independent tasks) to spot/preemptible capacity to cut cost by ~60-80%. Select TWO practices that make this robust.", choices: [ "Pin all workers to the single cheapest instance type in one zone to maximise savings.", "Checkpoint task progress to durable storage so interrupted work resumes instead of restarting.", "Diversify across several instance types/sizes and zones so one capacity pool reclaim does not stall the job.", "Treat interruptions as rare and rerun the whole pipeline if it fails." ], answer: [1, 2], explanation: "Spot capacity can be reclaimed with short notice, and reclaims are correlated within a capacity pool (an instance type in one zone). Diversification reduces the chance that a single pool reclaim takes everything, and checkpointing bounds lost work to one checkpoint interval. Rerunning a 6-hour job on failure can wipe out the savings and miss the deadline.", choiceRationale: [ "A single pool maximises correlated interruption risk and capacity shortages.", "Correct: checkpointing turns interruptions into small, bounded rework.", "Correct: diversification spreads risk across uncorrelated capacity pools.", "Interruptions are a normal occurrence on spot, and whole-job reruns can cost more than on-demand." ], references: [R.awsWa, R.finops], tags: ["spot", "batch", "cost"] }, { id: "iq-compute-models-003", domain: "compute", objective: "compute-models", lessonId: "infra-compute-models", difficulty: 1, type: "single", prompt: "During an incident, half of a VM fleet behaves differently from the other half because engineers SSH-ed in over months to apply hot fixes. What practice best prevents this class of problem?", choices: [ "Immutable infrastructure: bake versioned images in a pipeline and replace instances instead of modifying them in place.", "Require a change ticket before anyone SSHs into a production host.", "Run a nightly configuration-management agent that reverts unknown changes.", "Take daily snapshots of every VM so you can compare them." ], answer: [0], explanation: "Snowflake servers come from in-place mutation; immutable images make every instance of a version identical and make rollback a redeploy of the previous image. Config management reduces drift but still mutates live hosts and leaves windows of divergence. Seniors pair immutability with no human shell access by default, which also removes a security risk.", choiceRationale: [ "Correct: replacing rather than patching eliminates drift by construction.", "Process controls slow mutation but do not stop drift from accumulating.", "Periodic convergence narrows drift but still allows divergence between runs and mutable state.", "Snapshots help forensics but do nothing to prevent divergence." ], references: [R.twelveFactor, R.awsWa], tags: ["immutable-infrastructure", "drift"] }, { id: "iq-compute-models-004", domain: "compute", objective: "compute-models", lessonId: "infra-compute-models", difficulty: 2, type: "single", prompt: "A JVM caching service runs on 40 compute-optimised instances. Dashboards show memory at ~90% and CPU at ~20% across the fleet, and it scales out whenever memory pressure triggers. Which change is most likely to cut cost without hurting performance?", choices: [ "Switch to burstable instances, since CPU is mostly idle.", "Move to a memory-optimised family (more GiB per vCPU) and run fewer instances.", "Increase JVM heap on the current instances to reduce GC.", "Buy a 3-year commitment for the current 40 compute-optimised instances." ], answer: [1], explanation: "The workload is memory-bound, so the fleet is paying for idle vCPUs to get RAM. A memory-optimised family has a higher GiB-per-vCPU ratio, so the same memory fits on fewer, cheaper instances while CPU utilisation rises to a healthier level. Committing before right-sizing locks in waste, and burstable instances risk throttling under sustained load.", choiceRationale: [ "Burstable instances do not fix the memory ratio and can be throttled when credits run out.", "Correct: matching the instance family to the binding resource reduces instance count and cost.", "With memory already at 90%, a larger heap risks OOM and does not change the ratio being paid for.", "Committing to the wrong shape locks in waste; right-size first, then commit." ], references: [R.awsWa, R.useMethod], tags: ["right-sizing", "instance-families", "cost"] }, { id: "iq-compute-models-005", domain: "compute", objective: "compute-models", lessonId: "infra-compute-models", difficulty: 3, type: "single", prompt: "Your platform will run untrusted, customer-supplied code (arbitrary binaries) on shared hosts. The current proposal is standard containers with seccomp and a non-root user. Which isolation design best fits the threat model?", choices: [ "Standard containers are enough if you also drop all Linux capabilities.", "Run each customer in a separate Kubernetes namespace with NetworkPolicies.", "Use a sandboxed runtime with a strong kernel boundary (microVMs or a user-space kernel such as gVisor) per tenant workload, plus network egress controls.", "Use one VM per customer with full OS images, provisioned on demand." ], answer: [2], explanation: "Containers share the host kernel, so one kernel exploit escapes every tenant on that host; hardening reduces the attack surface but does not change the boundary. MicroVMs or user-space kernels give a VM-like boundary with container-like startup and density, which is the established pattern for multi-tenant code execution. Full VMs per customer are secure but slow and costly at fine granularity, and namespaces are an organisational boundary rather than a security one.", choiceRationale: [ "Dropping capabilities shrinks the attack surface but the shared kernel remains the single boundary against hostile code.", "Namespaces and NetworkPolicies isolate names and network paths, not the kernel.", "Correct: a per-workload kernel boundary matches hostile multi-tenancy with acceptable density and startup time.", "Secure, but heavyweight per-customer VMs cost more and start slower than sandboxed runtimes for the same boundary strength." ], references: [R.k8sTenancy, R.awsWa], tags: ["isolation", "multi-tenancy", "sandboxing"] }, { id: "iq-compute-models-006", domain: "compute", objective: "compute-models", lessonId: "infra-compute-models", difficulty: 3, type: "single", prompt: "A serverless function writes to a relational database that allows 500 connections. A marketing campaign drives the function to ~1,200 concurrent executions, each opening its own connection; the database starts rejecting connections and existing services that share it fail too. Which fix best addresses this?", choices: [ "Raise the database max_connections to 2,000.", "Add retries with exponential backoff to connection attempts in the function.", "Move the function to a larger memory size so each execution finishes faster.", "Cap function concurrency to what the database can absorb and put a connection pooler/proxy between the functions and the database (or buffer writes through a queue)." ], answer: [3], explanation: "Serverless scales faster and wider than most stateful backends, so the bottleneck and shared-fate risk move to the database. A concurrency limit bounds the blast radius, and a pooler multiplexes many short-lived executions onto a small set of server connections; a queue decouples bursty writes entirely. Raising max_connections costs memory per connection and often reduces throughput, and retries amplify load during the overload.", choiceRationale: [ "Each connection consumes database memory and CPU, so more connections usually worsens contention rather than adding capacity.", "Retries add load at exactly the wrong moment and can turn an overload into a sustained outage.", "Shorter executions help a little but do not bound concurrency against a fixed connection limit.", "Correct: bounding concurrency and pooling or queueing protects the shared database." ], references: [R.overload, R.builders], tags: ["serverless", "connection-pooling", "backpressure"] }, // ───────────────────────── compute-scaling ───────────────────────── { id: "iq-compute-scaling-001", domain: "compute", objective: "compute-scaling", lessonId: "infra-compute-scaling", difficulty: 2, type: "single", prompt: "Traffic rises 5x within 2 minutes at the top of every hour when a partner batch fires. Target-tracking autoscaling on CPU needs ~1 minute to react, and new instances take ~3 minutes to boot and warm up, so each hour starts with 4-5 minutes of errors. What is the best fix?", choices: [ "Scheduled or predictive scale-out a few minutes before each hour, plus a warm pool of pre-initialised instances to cut launch time.", "Lower the CPU target from 60% to 30% so scaling triggers earlier.", "Switch the scaling metric from CPU to memory.", "Increase the maximum instance count of the group." ], answer: [0], explanation: "Reactive scaling cannot beat a ramp that is faster than metric delay plus boot time (~4 minutes here). The spike is predictable, so capacity should arrive before demand; scheduled or predictive scaling handles that, and warm pools shrink launch time for the unpredictable remainder. A lower CPU target permanently over-provisions and still lags a 5x ramp.", choiceRationale: [ "Correct: pre-provisioning for a predictable spike plus warm pools removes the reaction gap.", "A lower target pays for idle capacity all day and still cannot absorb a 5x jump in 2 minutes.", "Changing the metric does not remove the metric delay and boot latency.", "The ceiling is not being reached; the problem is how fast capacity arrives." ], references: [R.awsWa, R.overload], tags: ["autoscaling", "warm-pools", "predictive-scaling"] }, { id: "iq-compute-scaling-002", domain: "compute", objective: "compute-scaling", lessonId: "infra-compute-scaling", difficulty: 3, type: "single", prompt: "A service must handle 2,000 req/s at an average latency of 200 ms. Load tests show each instance stays within SLO up to 50 concurrent in-flight requests. It runs across 3 AZs and must keep serving full load if one AZ is lost. What is the minimum total instance count?", choices: ["8", "12", "9", "24"], answer: [1], explanation: "By Little's law, in-flight requests = 2,000 x 0.2 s = 400, which needs 400 / 50 = 8 instances. To survive the loss of one of 3 AZs, the remaining 2 AZs must still hold 8, so each AZ needs 4, for 12 in total (50% overprovision). This static-stability approach avoids depending on scaling during an AZ failure, when the control plane may be impaired.", choiceRationale: [ "8 covers steady state but loses a third of capacity in an AZ outage.", "Correct: 8 needed in 2 surviving AZs means 4 per AZ times 3 AZs = 12.", "N+1 instances protects against a single instance failure, not a whole AZ.", "24 doubles the requirement and pays for far more redundancy than one AZ loss needs." ], references: [R.staticStability, R.useMethod], tags: ["capacity-planning", "littles-law", "multi-az"] }, { id: "iq-compute-scaling-003", domain: "compute", objective: "compute-scaling", lessonId: "infra-compute-scaling", difficulty: 2, type: "single", prompt: "An API that mostly waits on downstream calls autoscales on CPU at 60%. During a slowdown, p99 latency triples and requests queue, but CPU sits at 25%, so no scale-out happens. What is the best scaling signal for this service?", choices: [ "Network bytes in per instance.", "Memory utilisation per instance.", "In-flight requests (concurrency) or queue depth per instance, with a check on whether the bottleneck is the downstream itself.", "Request count per minute across the whole fleet." ], answer: [2], explanation: "For I/O-bound services, CPU does not track saturation; concurrency and queue depth do, because they rise as latency rises. A senior also asks whether scaling helps: if the downstream is the bottleneck, adding callers only increases pressure on it, so the right response may be backpressure or a concurrency limit. Pick the signal that best reflects the resource that saturates first.", choiceRationale: [ "Network throughput may even fall during a slowdown and does not reflect queueing.", "Memory rarely tracks request saturation for this kind of service.", "Correct: concurrency and queue depth measure saturation for I/O-bound work and reveal when the bottleneck is downstream.", "Request rate ignores latency, so it misses saturation when the same rate takes longer to serve." ], references: [R.useMethod, R.overload], tags: ["autoscaling", "saturation", "signals"] }, { id: "iq-compute-scaling-004", domain: "compute", objective: "compute-scaling", lessonId: "infra-compute-scaling", difficulty: 1, type: "single", prompt: "A single-writer relational primary runs at 85% CPU, with growth of ~5% per month. The team needs headroom this quarter and has no sharding layer. What is the most pragmatic first step?", choices: [ "Shard the database by customer ID this sprint.", "Add more application replicas to spread the load.", "Migrate to a NoSQL store that scales horizontally.", "Scale the primary vertically to a larger instance (during a planned failover), and offload reads to replicas while planning longer-term partitioning." ], answer: [3], explanation: "Vertical scaling is the fastest, lowest-risk way to buy headroom for a single writer; managed databases usually do it with a short failover. Offloading reads reduces primary load further. Sharding or a datastore migration is a large architectural change that should be planned on the runway that vertical scaling buys, not rushed under pressure.", choiceRationale: [ "Sharding in a sprint under pressure is high-risk and requires application-level routing changes.", "More app replicas send more queries to the same primary and make the problem worse.", "A datastore migration is a quarters-long project with different consistency semantics.", "Correct: scale up for immediate headroom, offload reads, then plan horizontal partitioning." ], references: [R.primer, R.pgHa], tags: ["vertical-scaling", "databases", "capacity"] }, { id: "iq-compute-scaling-005", domain: "compute", objective: "compute-scaling", lessonId: "infra-compute-scaling", difficulty: 3, type: "multi", prompt: "Before Black Friday you are asked to certify that checkout can take 4x normal peak. Select TWO practices that make the load-test results trustworthy.", choices: [ "Use an open-model (arrival-rate) load generator so slow responses do not reduce offered load, avoiding coordinated omission, and report latency percentiles.", "Test with production-like data volumes, cache state and real downstream dependencies (or faithful limits on them).", "Use a closed-loop generator with a fixed number of threads and report average latency.", "Test a single instance and multiply its throughput by the planned instance count." ], answer: [0, 1], explanation: "Closed-loop generators slow down when the system slows, hiding exactly the queueing you want to find, and averages hide tail latency. Empty caches, small datasets and stubbed dependencies make results optimistic or pessimistic in ways that do not reflect production. Linear extrapolation from one instance ignores shared bottlenecks such as databases, locks and load balancers, which usually break first.", choiceRationale: [ "Correct: arrival-rate load exposes queueing and tail latency honestly.", "Correct: realistic data and dependencies surface the shared bottlenecks that limit real capacity.", "Closed-loop load suffers coordinated omission, and averages hide the tail that SLOs care about.", "Shared resources do not scale linearly, so single-instance extrapolation overstates capacity." ], references: [R.overload, R.linuxPerf], tags: ["load-testing", "capacity-planning", "latency"] }, { id: "iq-compute-scaling-006", domain: "compute", objective: "compute-scaling", lessonId: "infra-compute-scaling", difficulty: 2, type: "single", prompt: "An autoscaling group scales out at 60% CPU and in at 55%, with no cooldown. Every few minutes it adds and removes instances, causing cache warm-up latency spikes and connection churn. What is the best fix?", choices: [ "Widen the hysteresis (e.g. out at 60%, in at 35-40%) and add a scale-in stabilisation window longer than the warm-up time.", "Raise the scale-out threshold to 80% so it triggers less often.", "Disable scale-in entirely and keep peak capacity all day.", "Scale on memory instead of CPU because it changes more slowly." ], answer: [0], explanation: "In a modest-sized group, adding one instance drops average CPU by more than 5 points (e.g. 10 instances at 60% become 11 at ~55%), which immediately trips the scale-in rule, so the system oscillates. Wider hysteresis plus a scale-in stabilisation window (scale out fast, scale in slowly) damps the loop. Disabling scale-in solves flapping by paying for peak capacity around the clock.", choiceRationale: [ "Correct: hysteresis and an asymmetric stabilisation window stop oscillation without losing elasticity.", "An 80% threshold leaves less headroom for spikes and does not address the narrow gap.", "This trades flapping for permanent overspend.", "Memory may not track load at all, and switching metrics leaves the control-loop flaw unfixed." ], references: [R.awsWa, R.overload], tags: ["autoscaling", "hysteresis", "flapping"] }, // ───────────────────────── compute-platform ───────────────────────── { id: "iq-compute-platform-001", domain: "compute", objective: "compute-platform", lessonId: "infra-compute-platform", difficulty: 2, type: "single", prompt: "Your platform team will host ~25 internal, trusted product teams on shared Kubernetes clusters. The goal is fair resource use and limited blast radius without running a cluster per team. Which baseline design fits best?", choices: [ "One namespace per team, and rely on teams to self-police resource use.", "Namespace per team with RBAC scoped to it, ResourceQuota and LimitRange, default-deny NetworkPolicies, and Pod Security admission at a restricted level.", "A separate cluster per team so there is no sharing at all.", "One shared namespace with labels identifying each team." ], answer: [1], explanation: "For trusted internal tenants, namespace-based soft multi-tenancy is the standard pattern: RBAC limits who can change what, quotas stop one team from starving others, and NetworkPolicies and Pod Security limit lateral movement. A cluster per team gives the strongest isolation but multiplies upgrade, cost and fleet overhead for 25 teams. Hostile or regulated tenants change the calculus toward dedicated clusters or sandboxed runtimes.", choiceRationale: [ "Without quotas and policies, one team can exhaust resources or reach other teams by accident.", "Correct: the namespace isolation primitives together give fair sharing and contained blast radius for trusted tenants.", "Strong isolation, but 25 clusters multiply operational cost far beyond what trusted tenants need.", "Labels are not a security or quota boundary, so there is no isolation between teams." ], references: [R.k8sTenancy], tags: ["kubernetes", "multi-tenancy", "quotas"] }, { id: "iq-compute-platform-002", domain: "compute", objective: "compute-platform", lessonId: "infra-compute-platform", difficulty: 2, type: "single", prompt: "During a node-pool upgrade, node drains hang for hours. The blocking pods belong to several single-replica Deployments, each with a PodDisruptionBudget of `minAvailable: 1`. What is the right fix?", choices: [ "Force-delete the pods during upgrades so drains always complete.", "Delete all PodDisruptionBudgets in the cluster.", "Run those workloads with at least 2 replicas spread across nodes (or accept downtime with a PDB that allows 1 disruption), and add policy checks that reject PDBs that can never be satisfied.", "Increase the drain timeout to 24 hours." ], answer: [2], explanation: "A PDB of minAvailable: 1 on a single replica can never allow a voluntary eviction, so drains wait forever. The fix is to make the workload actually tolerate disruption (multiple replicas with spread) or to state honestly that it tolerates downtime. Platform teams should catch unsatisfiable PDBs with admission policy because they block every upgrade.", choiceRationale: [ "Force deletion bypasses the protection PDBs exist to provide and can cause real outages.", "Removing all PDBs throws away legitimate protections for correctly configured workloads.", "Correct: fix the replica/PDB mismatch and prevent it with policy.", "A longer timeout only delays the stall; the eviction is never allowed." ], references: [R.k8sTenancy, R.sreBook], tags: ["kubernetes", "upgrades", "pdb"] }, { id: "iq-compute-platform-003", domain: "compute", objective: "compute-platform", lessonId: "infra-compute-platform", difficulty: 3, type: "single", prompt: "You run one very large shared production cluster for 40 teams in one region. A bad admission webhook rollout once took down scheduling for everyone, and one team now needs PCI-scoped isolation. Which topology change best balances blast radius and operational cost?", choices: [ "Keep one cluster but add more control-plane replicas.", "Give every one of the 40 teams its own cluster.", "Keep one cluster and put the PCI team in a dedicated namespace with stricter NetworkPolicies.", "Split into a small number of clusters per region (e.g. by criticality or compliance tier, with a dedicated PCI cluster), managed as a fleet with shared templates and staged rollouts across clusters." ], answer: [3], explanation: "A single cluster makes cluster-scoped components such as webhooks, CRDs and upgrades shared fate for every tenant. A handful of clusters partitioned by risk or compliance tier contains blast radius and lets you stage changes cluster by cluster, while fleet tooling keeps the per-cluster cost manageable. Per-team clusters overshoot on cost and drift, and namespaces alone do not satisfy compliance scoping for the PCI workload.", choiceRationale: [ "More control-plane replicas do not protect against a bad cluster-wide config change.", "40 clusters multiply upgrades, cost and drift far beyond what the risk requires.", "Namespaces share nodes, control plane and cluster-scoped config, which usually does not meet PCI scope reduction.", "Correct: a few tiered clusters with staged fleet rollouts contain blast radius at acceptable cost." ], references: [R.k8sTenancy, R.gcpWa], tags: ["kubernetes", "cluster-topology", "blast-radius"] }, { id: "iq-compute-platform-004", domain: "compute", objective: "compute-platform", lessonId: "infra-compute-platform", difficulty: 1, type: "single", prompt: 'Cluster nodes average 25% real CPU usage, yet new pods stay Pending with "Insufficient cpu" and the cluster autoscaler keeps adding nodes. What is the most likely cause?', choices: [ "Pods request far more CPU than they use; the scheduler bin-packs on requests, not actual usage, so requests need right-sizing.", "CPU limits are set too low, so the scheduler cannot place pods.", "The node pool uses the wrong CPU architecture.", "The cluster autoscaler is misconfigured and ignores real utilisation." ], answer: [0], explanation: "The scheduler places pods by summing requests against allocatable capacity; actual utilisation does not factor in. Inflated requests make nodes look full while they idle, and the autoscaler then adds more of them. Right-sizing requests from observed usage (for example with recommendations from a vertical autoscaler) is one of the biggest Kubernetes cost levers.", choiceRationale: [ "Correct: scheduling and autoscaling act on requests, so over-requesting strands capacity.", "Limits do not affect scheduling decisions; requests do.", 'An architecture mismatch causes image pull or exec errors, not "Insufficient cpu".', "The autoscaler is working as designed by reacting to unschedulable pods based on requests." ], references: [R.k8sTenancy, R.finops], tags: ["kubernetes", "requests", "bin-packing"] }, { id: "iq-compute-platform-005", domain: "compute", objective: "compute-platform", lessonId: "infra-compute-platform", difficulty: 2, type: "multi", prompt: "You are adding an expensive GPU node pool to a shared cluster. General workloads keep landing on GPU nodes and blocking ML jobs, and the pool never scales down. Select TWO changes that fix this.", choices: [ "Label the GPU nodes and rely on teams to add node selectors.", "Give ML jobs a higher PriorityClass so they preempt anything on GPU nodes.", "Taint the GPU nodes and add matching tolerations plus node affinity only to GPU workloads.", "Run GPUs as a separate autoscaled node pool that can scale to zero when no GPU pods are pending." ], answer: [2, 3], explanation: "Labels only attract pods that opt in; taints repel everything that does not tolerate them, which is how you keep general pods off scarce hardware. Pairing tolerations with affinity ensures GPU jobs both may and must land there. A dedicated autoscaled pool that scales to zero stops paying for idle GPUs, which general pods were previously pinning.", choiceRationale: [ "Labels without taints do not stop other pods from scheduling onto GPU nodes.", "Preemption churns other workloads and still lets them land there first; it treats the symptom.", "Correct: taints plus tolerations and affinity reserve GPU nodes for GPU workloads.", "Correct: an isolated, scale-to-zero pool controls cost for expensive hardware." ], references: [R.k8sTenancy, R.finops], tags: ["kubernetes", "node-pools", "gpu", "taints"] }, { id: "iq-compute-platform-006", domain: "compute", objective: "compute-platform", lessonId: "infra-compute-platform", difficulty: 3, type: "single", prompt: "A latency-sensitive service has a CPU request and limit of 1 core. Node CPU is ~30%, yet p99 latency shows periodic spikes of tens of milliseconds, and container metrics show a high throttled-periods ratio. What is the best explanation and fix?", choices: [ "The node is overcommitted; move the pod to a dedicated node pool.", "CFS quota enforcement throttles the container when bursts (e.g. many threads or GC) exhaust its quota within a scheduling period; raise or remove the CPU limit while keeping an accurate request.", "The service needs more memory; increase the memory limit.", "Increase replicas so each pod gets fewer requests." ], answer: [1], explanation: "CPU limits are enforced as a quota per period (100 ms by default); a multi-threaded burst can burn the whole quota early and then sit throttled for the rest of the period, even on an idle node. That shows up as tail-latency spikes, not high average CPU. Many teams remove CPU limits for latency-sensitive services and rely on requests for fair share, keeping limits where hard caps are truly needed.", choiceRationale: [ "At 30% node CPU there is no contention; the throttling is self-imposed by the limit.", "Correct: quota throttling causes periodic stalls, so raising or removing the limit fixes the tail.", "Memory pressure shows up as OOM kills or paging, not CPU throttling metrics.", "More replicas may dilute bursts but leave the throttling mechanism in place and cost more." ], references: [R.linuxPerf, R.useMethod], tags: ["kubernetes", "cpu-throttling", "tail-latency"] }, // ───────────────────────── storage-types ───────────────────────── { id: "iq-storage-types-001", domain: "storage-data", objective: "storage-types", lessonId: "infra-storage-types", difficulty: 2, type: "single", prompt: "A legacy CMS needs 20 replicas across 3 AZs to read and write the same directory tree with POSIX semantics (renames, file locks). Which storage choice best fits?", choices: [ "A single block volume attached to all 20 replicas.", "Object storage mounted via a FUSE adapter.", "A managed, multi-AZ network file service (e.g. EFS / Azure Files / Filestore) mounted by all replicas.", "Local instance disks synchronised with rsync every minute." ], answer: [2], explanation: "Shared POSIX access across many clients and AZs is what managed file storage is for. Block volumes are typically single-AZ and single-writer, and object stores lack atomic rename and locking, so FUSE adapters break POSIX expectations in subtle ways. The trade-off is higher latency per operation and per-GB cost than block storage, so it suits shared content better than databases.", choiceRationale: [ "Block volumes are AZ-scoped and generally single-attach; multi-attach needs a cluster-aware file system.", "FUSE over object storage lacks atomic renames and locks, which breaks POSIX-dependent apps.", "Correct: managed file storage provides shared POSIX semantics across AZs.", "Periodic rsync creates conflicts and lost writes when multiple replicas write." ], references: [R.awsWa, R.gcpArch], tags: ["file-storage", "block-storage", "posix"] }, { id: "iq-storage-types-002", domain: "storage-data", objective: "storage-types", lessonId: "infra-storage-types", difficulty: 2, type: "single", prompt: "A director argues that because object storage offers ~11 nines of durability, separate backups of the bucket are unnecessary. What is the strongest senior response?", choices: [ "Agree; durability that high makes data loss statistically impossible.", "Disagree only because the durability figure is marketing and not real.", "Agree, as long as the bucket is replicated to a second region.", "Durability covers hardware loss, not deletion, overwrites, ransomware or a compromised credential; add versioning, object lock/immutability and a copy in a separate account with restricted access." ], answer: [3], explanation: "Durability measures the probability of losing an object because of infrastructure faults; it says nothing about a valid request that deletes or encrypts the data. Replication faithfully copies deletions too. Protection against human and adversarial failure needs versioning, retention locks and an isolated copy with separate credentials, which is a different failure domain.", choiceRationale: [ "High durability does not stop authorised deletes or overwrites.", "The durability design is real; the flaw is that it addresses a different failure mode.", "Cross-region replication also replicates deletes and corruption.", "Correct: logical and adversarial failures need versioning, immutability and account isolation." ], references: [R.awsWa, R.azureWa], tags: ["durability", "backups", "ransomware"] }, { id: "iq-storage-types-003", domain: "storage-data", objective: "storage-types", lessonId: "infra-storage-types", difficulty: 3, type: "single", prompt: "You store 500 TB of logs, queried often in the first 30 days and deleted at day 60. Illustrative prices per TB-month: standard 20, infrequent-access 10 (30-day minimum), archive 4 with a 90-day minimum and multi-hour, paid restores. Which lifecycle is cheapest per TB while meeting needs?", choices: [ "Standard for 30 days, then infrequent-access until deletion at day 60 (~30 per TB).", "Standard for all 60 days (~40 per TB).", "Standard for 30 days, then archive until deletion (~32 per TB).", "Write directly to archive from day 0 (~12 per TB)." ], answer: [0], explanation: "Minimum storage durations bill you for the full minimum even if you delete early: moving to archive at day 30 costs 20 + 4 x 3 = 32, not 24, before transition and request fees. Infrequent-access costs 20 + 10 = 30 and its 30-day minimum is exactly met. Writing straight to archive looks cheapest but makes the hot 30-day query window impossible with multi-hour paid restores.", choiceRationale: [ "Correct: 20 + 10 = 30 per TB, with the minimum duration exactly met and data still readable.", "Two months of standard costs 40, more than tiering after day 30.", "The 90-day minimum bills 3 months of archive (12) on top of 20, about 32 plus transition fees.", "Cheapest storage, but frequent queries in the first 30 days would incur slow, expensive restores." ], references: [R.finops, R.awsWa], tags: ["storage-classes", "lifecycle", "cost"] }, { id: "iq-storage-types-004", domain: "storage-data", objective: "storage-types", lessonId: "infra-storage-types", difficulty: 1, type: "single", prompt: "An AZ is degraded, and you need to bring up a VM that used a network block volume in that AZ in a different AZ. What is the standard approach?", choices: [ "Detach the volume and attach it to a VM in the other AZ.", "Restore a new volume in the target AZ from the latest snapshot (snapshots are stored regionally), accepting data loss back to that snapshot.", "Use a cross-AZ volume peering connection.", "Copy the volume block by block over the network with dd from the degraded AZ." ], answer: [1], explanation: "Network block volumes are typically replicated within a single AZ and can attach only to instances in that AZ. Snapshots live in regional object storage, so they are the portable copy, and RPO equals the time since the last snapshot. If that RPO is unacceptable, the data layer needs application-level replication across AZs, or a regional/zone-redundant disk type where offered.", choiceRationale: [ "Block volumes are AZ-scoped and cannot attach to instances in another AZ.", "Correct: regional snapshots are the cross-AZ recovery path, with RPO equal to snapshot age.", "There is no such feature as cross-AZ volume peering.", "Copying from a degraded AZ is slow, unreliable and may not be possible at all." ], references: [R.awsWa, R.gcpWa], tags: ["block-storage", "snapshots", "availability-zones"] }, { id: "iq-storage-types-005", domain: "storage-data", objective: "storage-types", lessonId: "infra-storage-types", difficulty: 2, type: "multi", prompt: "A self-managed database on a network block volume shows rising write latency at peak, and the volume metrics show it pinned at a flat ceiling. Select TWO checks or changes most likely to resolve it.", choices: [ "Check whether the volume is hitting its provisioned IOPS/throughput, and move to a volume tier (or setting) with higher provisioned performance.", "Increase the file system block size to 64 KB.", "Check whether the instance's own block-storage bandwidth/IOPS limit is the cap, and move to an instance size with more storage bandwidth if so.", "Move the database files to object storage for unlimited throughput." ], answer: [0, 2], explanation: "A flat ceiling indicates a hard limit, and there are two common ones: the volume tier limit and the per-instance limit on storage bandwidth/IOPS. Raising one without checking the other often yields no improvement. File system block size tweaks rarely remove a provisioned cap, and object storage does not provide the low-latency random I/O a database needs.", choiceRationale: [ "Correct: volume-level provisioned limits are a classic flat ceiling.", "Block size changes are risky and do not lift a provisioned IOPS or throughput cap.", "Correct: instances have their own storage bandwidth limits that can cap even fast volumes.", "Object storage has high per-request latency and no in-place random writes, so it is unsuitable for database files." ], references: [R.useMethod, R.awsWa], tags: ["block-storage", "iops", "performance"] }, { id: "iq-storage-types-006", domain: "storage-data", objective: "storage-types", lessonId: "infra-storage-types", difficulty: 3, type: "single", prompt: "A self-managed database stripes its data across 4 block volumes, and the WAL lives on a 5th. Backups are scheduled snapshots of each volume, taken independently. A restore test fails with corruption. What is the best fix?", choices: [ "Take snapshots more frequently so they are closer together in time.", "Snapshot only the WAL volume, since it can rebuild data.", "Use crash-consistent multi-volume snapshots taken at the same point in time (or quiesce the DB), and prefer database-native backup plus WAL archiving for point-in-time recovery, with regular restore tests.", "Switch to a larger single volume so there is only one snapshot." ], answer: [2], explanation: "Independent snapshots capture each volume at a slightly different moment, so the combined image never existed on disk and may not be recoverable. Multi-volume crash-consistent snapshots or quiescing give one coherent point; database-native backups with WAL archiving go further, giving point-in-time recovery the DB itself understands. A backup is only real once a restore has been tested.", choiceRationale: [ "Closer timing still leaves the volumes inconsistent with each other.", "A WAL alone cannot rebuild data files without a consistent base backup.", "Correct: consistent multi-volume capture or DB-native backup, verified by restore tests, fixes the root cause.", "A single volume may hit size or performance limits and still gives only crash-consistent, untested backups." ], references: [R.pgHa, R.awsWa], tags: ["snapshots", "backups", "consistency"] }, // ───────────────────────── data-databases ───────────────────────── { id: "iq-data-databases-001", domain: "storage-data", objective: "data-databases", lessonId: "infra-data-databases", difficulty: 2, type: "single", prompt: 'After routing all reads to asynchronous read replicas to offload the primary, users report that profile edits "do not save": the page reloads showing old values, then corrects itself a second later. What is the best fix?', choices: [ "Switch all replicas to synchronous replication.", "Add a 2-second sleep after each write.", "Move all reads back to the primary.", "Provide read-your-writes: route a user's reads to the primary for a short window after their write, or read from a replica only once it has replayed past the write's log position." ], answer: [3], explanation: "Asynchronous replicas lag the primary, so a read straight after a write can miss it; users see this as a lost write. Read-your-writes consistency only needs to hold for the writing session, so session pinning or log-position (LSN) tracking fixes it while keeping most reads on replicas. Making every replica synchronous adds commit latency and reduces availability for a problem that affects a small fraction of reads.", choiceRationale: [ "Synchronous replication to all replicas adds write latency and couples availability to the slowest replica.", "A fixed sleep adds latency to every write and still fails when lag exceeds it.", "This removes the offload benefit entirely to fix a narrow consistency need.", "Correct: session-scoped read-your-writes fixes the anomaly while keeping replica offload." ], references: [R.jepsen, R.pgHa], tags: ["replication", "read-replicas", "consistency"] }, { id: "iq-data-databases-002", domain: "storage-data", objective: "data-databases", lessonId: "infra-data-databases", difficulty: 3, type: "single", prompt: "Your primary commits ~3,000 transactions/s and replicates asynchronously to a standby that typically lags ~2 s at peak. If the primary is lost unrecoverably at peak and you promote the standby, roughly what is the impact?", choices: [ "About 6,000 acknowledged transactions are lost (RPO ~2 s), so you need reconciliation for those writes or synchronous replication if that is unacceptable.", "No data loss, because the standby will catch up from the primary after promotion.", "About 3,000 transactions are lost, since only the last second is in flight.", "About 1,500 transactions are lost, since half of the lag is network transit that the standby already holds." ], answer: [0], explanation: "With async replication, anything committed on the primary but not yet shipped is lost when the primary dies: 3,000 tx/s x 2 s = ~6,000 acknowledged transactions. That is your effective RPO, and it grows exactly when load and lag peak. If the business cannot tolerate it, use synchronous or semi-synchronous replication for that data, at the cost of commit latency, or design idempotent reconciliation from upstream sources.", choiceRationale: [ "Correct: lag times write rate gives the lost-write count, which is the real RPO.", "A dead primary cannot ship the missing log, so the standby has nothing to catch up from.", "This halves the lag without justification.", "Data in transit but not received and persisted by the standby is lost too." ], references: [R.pgHa, R.jepsen], tags: ["replication-lag", "rpo", "failover"] }, { id: "iq-data-databases-003", domain: "storage-data", objective: "data-databases", lessonId: "infra-data-databases", difficulty: 2, type: "single", prompt: "A service runs 200 pods, each with an application connection pool of 20, against a PostgreSQL primary configured for 500 connections. During a deploy (old and new pods overlap), connections are refused and the database slows. What is the best fix?", choices: [ "Raise max_connections to 10,000 to cover the worst case.", "Put a connection pooler (e.g. PgBouncer in transaction mode) in front of the database and shrink per-pod pools so total server connections stay well below the limit.", "Reduce the number of pods to 25.", "Add read replicas so connections spread out." ], answer: [1], explanation: "The maximum demand is 200 x 20 = 4,000 connections, and up to 8,000 while old and new pods fully overlap during a deploy, against 500. Each PostgreSQL connection is a backend process with memory overhead, and throughput usually peaks at a few times the core count, so more connections mostly add contention. A transaction-mode pooler multiplexes thousands of client connections onto a small server pool; note that it constrains session features such as session-level prepared statements and advisory locks.", choiceRationale: [ "Thousands of backend processes waste memory and increase contention, often lowering throughput.", "Correct: pooling decouples client fan-out from server connections and bounds load on the database.", "This cuts application capacity to fit a connection limit instead of fixing connection management.", "Writes still go to the primary, and the fan-out problem repeats on each replica." ], references: [R.pgHa, R.primer], tags: ["postgresql", "connection-pooling", "deploys"] }, { id: "iq-data-databases-004", domain: "storage-data", objective: "data-databases", lessonId: "infra-data-databases", difficulty: 3, type: "single", prompt: "A multi-tenant SaaS is sharding its main database. 95% of tenants are small, but three enterprise tenants each generate ~10% of total traffic and keep growing. Most queries are scoped to one tenant. Which sharding design is best?", choices: [ "Hash-shard by row ID to spread load perfectly evenly.", "Range-shard by tenant creation date.", "Shard by tenant ID with a directory (lookup) layer, so tenants can be moved individually and the largest tenants placed on dedicated shards.", "Shard by tenant ID using a fixed hash modulo N, with no ability to move tenants." ], answer: [2], explanation: "Tenant ID keeps most queries single-shard and preserves transactional locality, which row-ID hashing destroys. A directory layer adds one lookup but allows rebalancing and isolating noisy, fast-growing tenants on their own shards. Fixed modulo hashing makes resharding painful and gives no way to deal with a whale tenant that outgrows a shard.", choiceRationale: [ "Even load comes at the cost of scatter-gather queries and cross-shard transactions for every tenant request.", "New tenants all land on the newest shard, which creates a moving hotspot.", "Correct: tenant-scoped locality plus a movable directory handles whales and rebalancing.", "Fixed modulo cannot move or isolate a growing large tenant and makes adding shards expensive." ], references: [R.primer, R.azurePatterns], tags: ["sharding", "multi-tenancy", "hot-partitions"] }, { id: "iq-data-databases-005", domain: "storage-data", objective: "data-databases", lessonId: "infra-data-databases", difficulty: 1, type: "single", prompt: "You must rename a heavily used column with zero downtime while old and new application versions run side by side during a rolling deploy. Which approach is correct?", choices: [ "Run ALTER TABLE ... RENAME COLUMN during a low-traffic window.", "Deploy the new app version first, then rename the column.", "Create a new table and switch over with a single deploy.", "Expand/contract: add the new column, dual-write, backfill, switch reads, stop writing the old column, then drop it in a later release." ], answer: [3], explanation: "During a rolling deploy, two app versions coexist, so every schema state must work with both. Expand/contract makes each step backward compatible and individually reversible. A direct rename breaks whichever version expects the other name, and backfills on large tables should be batched to avoid long locks and replication lag.", choiceRationale: [ "Old pods still reference the old name and fail immediately after the rename.", "The new version would fail until the rename happens, and the old version would fail after it.", "A big-bang table switch is hard to roll back and still breaks the coexisting version.", "Correct: expand/contract keeps both versions working at each step." ], references: [R.twelveFactor, R.primer], tags: ["schema-migrations", "zero-downtime", "expand-contract"] }, { id: "iq-data-databases-006", domain: "storage-data", objective: "data-databases", lessonId: "infra-data-databases", difficulty: 2, type: "multi", prompt: "The payments ledger requires RPO = 0 if any single AZ fails, with bounded write latency. Select TWO statements that are part of a correct design.", choices: [ "An asynchronous cross-region read replica gives RPO = 0.", "Use synchronous (or quorum) replication to a standby in a different AZ before acknowledging commits.", "Nightly snapshots plus WAL archiving every 5 minutes gives RPO = 0.", "Accept that commit latency increases by at least one cross-AZ round trip (typically around 1-2 ms within a region, order of magnitude) and that commits stall or degrade if the synchronous standby is unavailable." ], answer: [1, 3], explanation: "RPO = 0 means no acknowledged write may exist on only one failure domain, which requires synchronous or quorum replication before acknowledging. That costs at least one cross-AZ round trip per commit and creates a choice when the standby is down: block writes or fall back to async and lose the RPO guarantee, so multiple synchronous candidates are common. Async replicas and periodic archiving both have non-zero RPO.", choiceRationale: [ "Async replication always has a lag window, so RPO is greater than zero.", "Correct: synchronous or quorum commit across AZs is required for RPO = 0.", "WAL archiving every 5 minutes means up to ~5 minutes of loss.", "Correct: honest designs state the latency cost and the standby-down behaviour." ], references: [R.pgHa, R.jepsen], tags: ["synchronous-replication", "rpo", "multi-az"] }, // ───────────────────────── data-caching ───────────────────────── { id: "iq-data-caching-001", domain: "storage-data", objective: "data-caching", lessonId: "infra-data-caching", difficulty: 2, type: "single", prompt: "A read path serves 50k req/s with a 95% cache hit ratio; the database can sustain ~5k req/s. One of four cache nodes fails, its keys rehash to the others, and the hit ratio drops to 80% while they refill. What happens to the database?", choices: [ "Load rises from 2.5k to 10k req/s, 4x and twice its capacity; without coalescing, rate limits or shedding, the database overloads.", "Load rises by 15%, from 2.5k to ~2.9k req/s, which is within capacity.", "Load rises from 2.5k to 5k req/s, exactly at capacity.", "Load is unchanged because the remaining cache nodes absorb the requests." ], answer: [0], explanation: "Database load is the miss rate times traffic: 5% x 50k = 2.5k becomes 20% x 50k = 10k req/s. The cache had become a load-bearing part of capacity, so its failure is a database outage unless the system protects itself. Seniors size the database for realistic cache-degraded modes or add request coalescing, admission control and gradual warm-up.", choiceRationale: [ "Correct: the miss ratio quadruples from 5% to 20%, so database load reaches 10k against a 5k limit.", "This misapplies the 15-point drop to the existing load instead of to total traffic.", "Doubling would correspond to a 90% hit ratio, not 80%.", "Remaining nodes do not have the failed node's keys yet, so those requests miss to the database." ], references: [R.cascading, R.primer], tags: ["caching", "hit-ratio", "capacity", "cascading-failure"] }, { id: "iq-data-caching-002", domain: "storage-data", objective: "data-caching", lessonId: "infra-data-caching", difficulty: 2, type: "single", prompt: 'Every 10 minutes, a hot "homepage feed" cache entry expires and ~3,000 concurrent requests miss simultaneously, each running the same expensive query, briefly spiking database CPU to 100%. What is the best fix?', choices: [ "Increase the TTL to 24 hours.", "Request coalescing (single-flight or a short lock) so one caller recomputes while others wait or get the stale value, plus stale-while-revalidate or early refresh and jittered TTLs.", "Add more database read replicas.", "Remove the TTL and invalidate only on deploys." ], answer: [1], explanation: "This is a cache stampede (thundering herd): synchronized misses on one key multiply backend work by the number of concurrent callers. Coalescing reduces 3,000 recomputes to one, and serving stale while refreshing in the background removes the latency hit; jitter prevents many keys from expiring together. Longer TTLs trade freshness for fewer stampedes but do not eliminate them.", choiceRationale: [ "Long TTLs reduce frequency but still stampede at expiry and serve very stale data.", "Correct: coalescing plus stale-while-revalidate turns N recomputes into one without user-visible misses.", "Replicas add capacity but still execute the redundant query thousands of times.", "Data changes between deploys would go stale with no bound." ], references: [R.cascading, R.primer], tags: ["caching", "stampede", "thundering-herd"] }, { id: "iq-data-caching-003", domain: "storage-data", objective: "data-caching", lessonId: "infra-data-caching", difficulty: 3, type: "single", prompt: "A celebrity's profile key receives ~200k reads/s during a live event. It lives on one shard of a distributed cache, which saturates its network and CPU while the other shards are idle. Which approach best fixes this hot-key problem?", choices: [ "Add more shards to the cache cluster.", "Move the key to a larger cache node with more memory.", "Add a short-TTL in-process (L1) cache on application servers for hot keys, and/or replicate the key under several suffixed copies that readers pick at random.", "Switch the key to a write-through policy." ], answer: [2], explanation: "A single key always hashes to one shard, so adding shards does nothing for it. A local L1 cache with a TTL of a second or so absorbs nearly all reads in-process at the cost of brief staleness, and key splitting spreads reads across shards at the cost of more invalidation work. Detection matters too: track per-key request rates so hot keys can be promoted automatically.", choiceRationale: [ "Resharding cannot split a single key; it still maps to one shard.", "The bottleneck is network and CPU on one node, not memory.", "Correct: L1 caching or key replication spreads or absorbs hot-key reads.", "Write policy affects how writes propagate, not read concentration on one shard." ], references: [R.primer, R.azurePatterns], tags: ["caching", "hot-keys", "sharding"] }, { id: "iq-data-caching-004", domain: "storage-data", objective: "data-caching", lessonId: "infra-data-caching", difficulty: 1, type: "single", prompt: "With a cache-aside pattern, which write path minimises the chance of the cache holding stale data indefinitely?", choices: [ "Update the cache first, then the database.", "Write the new value into the cache after updating the database.", "Delete the cache key first, then update the database.", "Update the database, then delete (invalidate) the cache key, with a TTL as a safety net." ], answer: [3], explanation: "Writing values into the cache from the write path races with concurrent readers and writers and can leave an older value in place indefinitely. Deleting after the database commit means the next reader repopulates from the source of truth; a TTL bounds any remaining race. Updating the cache before the database risks caching a value that never commits.", choiceRationale: [ "If the database write fails, the cache holds a value that does not exist in the source of truth.", "Two concurrent writers can set the cache in the reverse order of their database commits, leaving a stale value.", "A reader can repopulate the old value between the delete and the database update.", "Correct: invalidate after commit and bound residual races with a TTL." ], references: [R.azurePatterns, R.primer], tags: ["caching", "cache-aside", "invalidation"] }, { id: "iq-data-caching-005", domain: "storage-data", objective: "data-caching", lessonId: "infra-data-caching", difficulty: 3, type: "multi", prompt: "You must replace the entire production cache cluster (new engine version) for a service whose database can only handle ~30% of read traffic uncached. Select TWO practices that prevent an outage during cutover.", choices: [ "Warm the new cluster before cutover (replay hot keys or dual-write), then shift read traffic to it gradually.", "Flush the old cluster first so both clusters start from the same state.", "Increase all TTLs on the new cluster to 24 hours.", "Protect the database during the cold period with request coalescing and admission control/rate limits on the miss path." ], answer: [0, 3], explanation: "A cold cache sends nearly all reads to the database, here more than 3x what it can handle. Pre-warming and gradual traffic shifting keep the miss rate within database capacity, and coalescing plus admission control cap the damage if warm-up is incomplete. Flushing makes things worse, and longer TTLs do not help a cache that has no entries yet.", choiceRationale: [ "Correct: warming and gradual shifting keep misses within what the database can serve.", "Flushing the old cluster removes your only warm cache.", "TTL length is irrelevant when the cache is empty.", "Correct: coalescing and admission control stop a cold cache from overloading the database." ], references: [R.cascading, R.builders], tags: ["caching", "cache-warming", "migration"] }, { id: "iq-data-caching-006", domain: "storage-data", objective: "data-caching", lessonId: "infra-data-caching", difficulty: 2, type: "single", prompt: "To cut write latency on an account-balance service, a developer proposes a write-back (write-behind) cache: acknowledge writes once they are in the cache and flush to the database asynchronously. What is the best senior response?", choices: [ "Reject it for balances: a cache node failure loses acknowledged writes; keep the database as the synchronous system of record and reserve write-back for loss-tolerant data such as view counters.", "Accept it, as long as the cache cluster has replicas.", "Accept it, but flush every 100 ms to bound the loss.", "Use write-through instead, because it makes writes faster than write-back." ], answer: [0], explanation: "Write-back acknowledges before durability, so any crash or failover before the flush loses data the client believes is committed, which is unacceptable for balances. Cache replication is usually asynchronous and does not give database-grade durability guarantees. Write-back is a good fit for aggregatable, loss-tolerant data; write-through keeps the cache fresh but adds latency rather than removing it.", choiceRationale: [ "Correct: financial data needs synchronous durability, and write-back fits only loss-tolerant workloads.", "Cache replicas are typically async and can still lose recent writes on failover.", "A smaller loss window is still loss of acknowledged financial writes.", "Write-through writes to both synchronously, so it is slower than write-back, not faster." ], references: [R.primer, R.jepsen], tags: ["caching", "write-back", "durability"] } ]; // ../../packages/content/src/infra/questions-2.ts var R2 = { raft: { title: "The Raft Consensus Algorithm", url: "https://raft.github.io/" }, jepsen: { title: "Jepsen: Consistency Models", url: "https://jepsen.io/consistency" }, primer: { title: "The System Design Primer", url: "https://github.com/donnemartin/system-design-primer" }, retries: { title: "Amazon Builders' Library: Timeouts, retries and backoff with jitter", url: "https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/" }, idempotent: { title: "Amazon Builders' Library: Making retries safe with idempotent APIs", url: "https://aws.amazon.com/builders-library/making-retries-safe-with-idempotent-APIs/" }, backlogs: { title: "Amazon Builders' Library: Avoiding insurmountable queue backlogs", url: "https://aws.amazon.com/builders-library/avoiding-insurmountable-queue-backlogs/" }, staticStability: { title: "Amazon Builders' Library: Static stability using Availability Zones", url: "https://aws.amazon.com/builders-library/static-stability-using-availability-zones/" }, builders: { title: "Amazon Builders' Library", url: "https://aws.amazon.com/builders-library/" }, breaker: { title: "Martin Fowler: CircuitBreaker", url: "https://martinfowler.com/bliki/CircuitBreaker.html" }, overload: { title: "Google SRE Book: Handling Overload", url: "https://sre.google/sre-book/handling-overload/" }, cascading: { title: "Google SRE Book: Addressing Cascading Failures", url: "https://sre.google/sre-book/addressing-cascading-failures/" }, kafka: { title: "Apache Kafka documentation", url: "https://kafka.apache.org/documentation/" }, azPatterns: { title: "Azure Architecture Center: Cloud design patterns", url: "https://learn.microsoft.com/en-us/azure/architecture/patterns/" }, slo: { title: "Google SRE Book: Service Level Objectives", url: "https://sre.google/sre-book/service-level-objectives/" }, alertSlo: { title: "Google SRE Workbook: Alerting on SLOs", url: "https://sre.google/workbook/alerting-on-slos/" }, workbook: { title: "Google SRE Workbook", url: "https://sre.google/workbook/table-of-contents/" }, sreBook: { title: "Google SRE Book", url: "https://sre.google/sre-book/table-of-contents/" }, monitoring: { title: "Google SRE Book: Monitoring Distributed Systems", url: "https://sre.google/sre-book/monitoring-distributed-systems/" }, postmortem: { title: "Google SRE Book: Postmortem Culture", url: "https://sre.google/sre-book/postmortem-culture/" }, toil: { title: "Google SRE Book: Eliminating Toil", url: "https://sre.google/sre-book/eliminating-toil/" }, awsWa: { title: "AWS Well-Architected Framework", url: "https://aws.amazon.com/architecture/well-architected/" }, azWa: { title: "Azure Well-Architected Framework", url: "https://learn.microsoft.com/en-us/azure/well-architected/" }, gcpFw: { title: "Google Cloud Architecture Framework", url: "https://cloud.google.com/architecture/framework" }, chaos: { title: "Principles of Chaos Engineering", url: "https://principlesofchaos.org/" }, pgHa: { title: "PostgreSQL: High Availability, Load Balancing, and Replication", url: "https://www.postgresql.org/docs/current/high-availability.html" }, zeroTrust: { title: "NIST SP 800-207: Zero Trust Architecture", url: "https://csrc.nist.gov/pubs/sp/800/207/final" }, shared: { title: "AWS Shared Responsibility Model", url: "https://aws.amazon.com/compliance/shared-responsibility-model/" }, k8sTenancy: { title: "Kubernetes: Multi-tenancy", url: "https://kubernetes.io/docs/concepts/security/multi-tenancy/" }, tls13: { title: "RFC 8446: TLS 1.3", url: "https://www.rfc-editor.org/rfc/rfc8446" }, owasp: { title: "OWASP Top Ten", url: "https://owasp.org/www-project-top-ten/" }, slsa: { title: "SLSA: Supply-chain Levels for Software Artifacts", url: "https://slsa.dev/" }, sigstore: { title: "Sigstore", url: "https://sigstore.dev/" }, opa: { title: "Open Policy Agent documentation", url: "https://www.openpolicyagent.org/docs/latest/" }, cis: { title: "CIS Benchmarks", url: "https://www.cisecurity.org/cis-benchmarks" } }; var DOMAIN = { "dist-theory": "distributed", "dist-patterns": "distributed", "dist-messaging": "distributed", "rel-slo": "reliability", "rel-incidents": "reliability", "rel-resilience": "reliability", "sec-identity": "security", "sec-data": "security", "sec-supply-chain": "security" }; var mk = (topic, n, body) => ({ id: `iq-${topic}-${String(n).padStart(3, "0")}`, domain: DOMAIN[topic], objective: topic, lessonId: `infra-${topic}`, ...body }); var infraQuestions2 = [ // ---------------------------------------------------------------- dist-theory mk("dist-theory", 1, { difficulty: 1, type: "single", prompt: "A leaderless key-value store keeps N = 5 replicas per key. Writes are acknowledged after W = 3 replicas confirm. What is the **smallest read quorum R** that guarantees every read overlaps at least one replica holding the latest acknowledged write?", choices: ["R = 1", "R = 2", "R = 3", "R = 5"], answer: [2], explanation: "Read and write quorums are guaranteed to intersect when **R + W > N**. With N = 5 and W = 3, R must be at least 3 (3 + 3 = 6 > 5). Overlap alone does not give linearizability under concurrent writes and sloppy quorums, but it is the precondition for reading the latest acknowledged value.", choiceRationale: [ "R + W = 4, not greater than 5; a read can hit only the two stale replicas.", "R + W = 5 equals N; the read set and write set can be disjoint.", "Correct: 3 + 3 = 6 > 5, so every read set shares at least one replica with every write set.", "Works but is not the minimum, and reading all 5 makes reads unavailable when any single replica is down." ], references: [R2.primer, R2.jepsen], tags: ["quorum", "calculation", "replication"] }), mk("dist-theory", 2, { difficulty: 2, type: "single", prompt: "A user-profile service must accept writes in three regions with **local write latency under 10 ms** (cross-region round trips are ~70\u2013150 ms). In PACELC terms, what is the team implicitly signing up for?", choices: [ "Choosing latency over consistency even when there is no partition, so they need a conflict-resolution strategy (version vectors, CRDTs or application merge) for concurrent writes.", "Choosing consistency over availability during partitions, so writes will block when a region is cut off.", "Nothing special: a consensus protocol like Raft across regions can commit in under 10 ms if the leader is nearby.", "Strong consistency is preserved as long as clocks are synchronized with NTP and last-write-wins is used." ], answer: [0], explanation: "A 10 ms local commit is impossible if the write must reach another region first, so the system is **EL** (else, latency) in PACELC and almost certainly **PA** during partitions. That means concurrent writes to the same key in two regions will diverge and must be reconciled. A senior answer names the merge strategy and which fields tolerate it, rather than pretending replication is free.", choiceRationale: [ "Correct: local-latency writes mean asynchronous replication, so divergence is normal operation, not just a partition edge case.", "Blocking during partitions is the PC choice; the requirement explicitly prioritizes local latency and availability.", "Raft commits require a majority round trip; with replicas in three regions that is at least one cross-region RTT.", "NTP-based last-write-wins silently drops concurrent updates and gives no strong consistency; clock skew makes it worse." ], references: [R2.jepsen, R2.primer], tags: ["pacelc", "multi-region", "consistency"] }), mk("dist-theory", 3, { difficulty: 2, type: "single", prompt: 'A team runs etcd with **3 members across 3 AZs**. To "add redundancy" they propose **4 members across 2 AZs (2 + 2)**, dropping the third AZ to save cost. What is the most accurate assessment?', choices: [ "The 4-node cluster is strictly better because it tolerates two node failures.", "The 4-node cluster needs a majority of 3, so losing either AZ loses quorum; the current 3-node, 3-AZ layout survives a full AZ loss.", "Both layouts tolerate exactly one AZ failure, so the change only affects cost.", "The 4-node cluster is safer because an even number of members prevents split brain." ], answer: [1], explanation: "Majority quorum for 4 members is 3, so a 4-node cluster tolerates only **one** member failure, the same as 3 members. Placed 2 + 2, losing either AZ leaves 2 of 4 and the cluster stops accepting writes. Even member counts add replication cost without adding fault tolerance; what matters is spreading an odd number of members across at least three failure domains.", choiceRationale: [ "Wrong: with 4 members the majority is 3, so only one failure is tolerated.", "Correct: 2 survivors out of 4 is not a majority, while 2 of 3 is.", "The 2-AZ layout cannot survive any AZ loss; the 3-AZ layout can.", "Split brain is prevented by majority quorums for any size; even sizes simply waste a member." ], references: [R2.raft], tags: ["consensus", "quorum", "failure-domains"] }), mk("dist-theory", 4, { difficulty: 3, type: "single", prompt: "An inventory service stores each item's count with **last-write-wins using the writer node's wall-clock timestamp**. Nodes are NTP-synced but skew of up to ~100 ms has been observed. Occasionally a decrement made 20 ms after another update disappears. What is the best fix?", choices: [ "Tighten NTP polling so skew stays below 20 ms.", "Move all writes to a single node so only one clock is used.", "Add a random tiebreaker to timestamps so ties are resolved deterministically.", "Replace timestamp LWW with conditional writes on a per-item version (compare-and-set), or with a counter type that merges increments and decrements." ], answer: [3], explanation: "Wall-clock LWW orders writes by clocks that do not reflect causality, so a causally later write from a node with a lagging clock loses and is **silently discarded**. Tightening NTP only shrinks the window; it never closes it. Conditional writes on a version number make conflicts explicit (retry on mismatch), and a counter CRDT avoids conflicts for commutative operations.", choiceRationale: [ "Reduces frequency but skew can never be bounded to zero, so updates are still lost.", "Removes the symptom by creating a single point of failure and a throughput ceiling; it is a trade, not a fix.", "Tiebreakers only matter for equal timestamps; the problem is wrong ordering, not ties.", "Correct: version-based CAS or a commutative counter type preserves every update regardless of clock skew." ], references: [R2.jepsen], tags: ["clocks", "lww", "conflict-resolution"] }), mk("dist-theory", 5, { difficulty: 3, type: "single", prompt: "A job scheduler elects a leader with a **30 s lease** in a coordination service. The leader hits a 45 s stop-the-world GC pause; a new leader is elected; the old leader resumes and writes a stale schedule to shared storage. What prevents this class of bug?", choices: [ "Shorten the lease to 5 s so the pause is detected faster.", "Have the old leader check the system clock after resuming and stop if the lease has expired.", "Issue a monotonically increasing fencing token with each lease and have the storage layer reject writes carrying an older token.", "Run two leaders in parallel and have storage keep whichever write arrives last." ], answer: [2], explanation: "A paused process cannot know it was paused, and any check it performs can itself be followed by another pause before the write lands. The only robust defense is for the **resource** to reject stale leaders: a fencing token (epoch) that increases with every lease grant and is compared on each write. Shorter leases only change how often the race occurs.", choiceRationale: [ "A shorter lease makes failover faster but a pause longer than the lease still produces two writers.", "The pause can occur between the clock check and the write, so a self-check is not safe.", "Correct: storage enforces ordering, so a resumed stale leader is rejected no matter how long it paused.", "Dual leaders with last-arrival-wins is exactly the split-brain scenario being avoided." ], references: [R2.raft, R2.jepsen], tags: ["leader-election", "fencing", "failure-detection"] }), mk("dist-theory", 6, { difficulty: 2, type: "multi", prompt: "A Raft-backed configuration store must serve **linearizable reads**. Select TWO approaches that provide them without relying on bounded clock drift.", choices: [ "Serve the read from any follower's locally applied state.", "Have the leader record its commit index, confirm it is still leader via a heartbeat round to a majority, wait until that index is applied, then answer (ReadIndex).", "Serve the read from the leader's local state immediately, without any check.", "Append the read as an entry to the log and answer once that entry is committed and applied." ], answer: [1, 3], explanation: "A node that believes it is leader may have been deposed by a partition, so a linearizable read must confirm leadership with a majority. ReadIndex does that with a heartbeat round and no log write; routing the read through the log does it at the cost of a log append. Lease-based reads are faster but depend on bounded clock drift, which the prompt excludes.", choiceRationale: [ "Followers may lag the leader, so reads can be stale.", "Correct: the majority heartbeat proves leadership at the moment of the read.", "A deposed leader in a minority partition would return stale data.", "Correct: commit through a majority orders the read after all earlier writes." ], references: [R2.raft, R2.jepsen], tags: ["raft", "linearizability", "select-two"] }), // -------------------------------------------------------------- dist-patterns mk("dist-patterns", 1, { difficulty: 1, type: "single", prompt: "After a 30-second database blip, thousands of clients using **exponential backoff without jitter** keep hitting the database in synchronized spikes for minutes afterward. What does adding jitter change?", choices: [ "It lengthens each client's wait so the database gets more time to recover.", "It caps the maximum number of retries per client.", "It guarantees each retry goes to a different replica.", "It spreads retries randomly across the backoff window so clients stop arriving in synchronized waves." ], answer: [3], explanation: "Clients that failed at the same moment compute identical backoff schedules and retry in lockstep, recreating the overload each time. Randomizing the delay (for example full jitter: a random value between 0 and the exponential cap) decorrelates them so load arrives as a smooth stream the recovering service can absorb.", choiceRationale: [ "Jitter does not lengthen waits (full jitter actually lowers the average delay); its value is decorrelating arrival times.", "Retry caps are a separate control; jitter does not limit attempts.", "Jitter is about timing, not routing.", "Correct: decorrelating retry times removes the synchronized spikes." ], references: [R2.retries], tags: ["retries", "jitter", "thundering-herd"] }), mk("dist-patterns", 2, { difficulty: 2, type: "single", prompt: "A request flows edge \u2192 API \u2192 order service \u2192 database. **Each of the three caller layers makes up to 3 attempts** (1 try + 2 retries) on failure. The database is hard-down. In the worst case, how many database calls does one user request generate?", choices: ["9", "6", "27", "81"], answer: [2], explanation: "Retries multiply across layers: 3 attempts at the edge \xD7 3 at the API \xD7 3 at the order service = **27** calls reaching the database for one user action. That amplification hits exactly when the dependency is weakest. The usual fix is to retry at a single layer, give other layers retry budgets (e.g. retries capped at ~10% of requests), and fail fast once a circuit breaker is open.", choiceRationale: [ "Counts only two layers of multiplication (3 \xD7 3).", "Adds retries per layer instead of multiplying them.", "Correct: 3 \xD7 3 \xD7 3 = 27.", "Assumes four retrying layers; only three layers call downstream here." ], references: [R2.retries, R2.cascading], tags: ["retry-amplification", "calculation", "cascading-failure"] }), mk("dist-patterns", 3, { difficulty: 2, type: "single", prompt: "A mobile client calls `POST /payments`. The server charges the card, but the response is lost and the client times out and retries, double-charging the customer. Which design fixes this most robustly?", choices: [ "The client sends a unique idempotency key per logical payment; the server stores key \u2192 result atomically with the charge and returns the stored result for any repeat of that key.", "The server deduplicates requests that have the same amount and card within 60 seconds.", "Disable client retries for payment calls and show an error instead.", "Increase the client timeout to 60 seconds so the response is rarely lost." ], answer: [0], explanation: "Only the client knows that two requests are the same logical intent, so it must supply the identity. The server records the key and its outcome in the **same transaction** as the side effect, so a retry returns the original result instead of charging again. Keys need a retention window longer than the client's retry horizon, and a request with a reused key but different parameters should be rejected.", choiceRationale: [ "Correct: client-generated keys stored atomically with the effect make retries safe.", "Heuristic dedupe blocks legitimate identical purchases and misses retries outside the window.", "Pushes the ambiguity onto the user, who will retry manually and hit the same problem.", "Lower probability, same bug; any network failure after the charge still causes a duplicate." ], references: [R2.idempotent], tags: ["idempotency", "payments", "retries"] }), mk("dist-patterns", 4, { difficulty: 3, type: "single", prompt: "A service queues incoming requests in an **unbounded FIFO**. Clients give up after 2 s. During a traffic surge, queue wait reaches 5 s; CPU is at 100%, yet the success rate is near zero. What is the best change?", choices: [ "Increase the client timeout to 10 s so queued requests complete.", "Bound the queue (or a concurrency limit) and reject excess immediately with 429/503, and drop queued requests whose deadline has already passed before doing any work.", "Add more worker threads on the same instances so the queue drains faster.", "Switch to an unbounded LIFO queue so every request is eventually served." ], answer: [1], explanation: "Every request served is one its client already abandoned, so all CPU is spent on **wasted work** (goodput collapse). Bounding admission keeps queue wait under the client deadline so the requests that are accepted succeed, and fast rejections let clients back off or fail over. Checking the propagated deadline before processing stops burning capacity on dead requests; LIFO can help but only together with bounds.", choiceRationale: [ "Longer timeouts increase in-flight work and latency; they do not add capacity.", "Correct: bounded admission plus deadline-aware dropping restores goodput.", "CPU is already saturated; more threads add contention, not throughput.", "LIFO favors fresh requests, but unbounded it still accumulates hopeless work and memory." ], references: [R2.overload, R2.backlogs], tags: ["load-shedding", "backpressure", "overload"] }), mk("dist-patterns", 5, { difficulty: 3, type: "single", prompt: "Service A must answer its client within **1,000 ms**. It makes one call to service B, whose latency is p99 = 180 ms and p99.9 = 900 ms. Which timeout policy for A \u2192 B is best?", choices: [ "Timeout 1,000 ms, no retries, so B always has the full budget.", "Timeout 100 ms with up to 3 retries, to keep each attempt short.", "No explicit timeout; rely on TCP keepalive to detect dead connections.", "Timeout ~250\u2013300 ms (just above p99) with at most one jittered retry, issued only if the remaining propagated deadline allows it." ], answer: [3], explanation: "Setting the timeout slightly above p99 cuts off the slow tail where a fresh attempt is likely to be fast, while keeping false timeouts around 1%. One retry fits inside the 1 s budget; more would amplify load during a B brownout. Propagating the deadline lets B and the retry logic know how much time is left instead of each hop using its own fixed timeout.", choiceRationale: [ "A single slow call can consume the entire budget, and hung calls tie up A's resources for a full second.", "100 ms is below p99, so a large share of healthy calls time out and the retries multiply load on B.", "Keepalive detects dead peers on a scale of minutes or more, not request-level slowness.", "Correct: tail-cutting timeout, bounded retry and deadline awareness fit the budget." ], references: [R2.retries, R2.cascading], tags: ["timeouts", "deadlines", "tail-latency"] }), mk("dist-patterns", 6, { difficulty: 2, type: "multi", prompt: "In a multi-tenant API, one tenant's nightly batch job saturates the shared worker pool and database connection pool, causing timeouts for every other tenant. Select TWO changes that most directly contain the blast radius.", choices: [ "Enforce per-tenant rate limits or concurrency quotas at admission.", "Partition worker and connection pools (bulkheads) so batch or noisy tenants cannot exhaust capacity reserved for others.", "Double the size of the shared connection pool.", "Have all clients retry with exponential backoff." ], answer: [0, 1], explanation: "The failure is one consumer exhausting a shared resource. Per-tenant quotas stop the excess at the door, and bulkheads ensure that even admitted work from one class cannot drain the pool others depend on. Enlarging the shared pool just moves the saturation point (and may overload the database), and retries add load.", choiceRationale: [ "Correct: caps any single tenant's share of capacity.", "Correct: isolates resource pools so saturation stays within one compartment.", "The batch job will fill a bigger pool too, and more connections can overload the database.", "Retries increase load during saturation; they do not isolate tenants." ], references: [R2.azPatterns, R2.overload], tags: ["bulkhead", "rate-limiting", "multi-tenancy", "select-two"] }), // ------------------------------------------------------------- dist-messaging mk("dist-messaging", 1, { difficulty: 1, type: "single", prompt: "A consumer processes an event (sends a welcome email) and then commits its offset. It occasionally crashes between the two steps, and some users get two emails. What is the appropriate fix?", choices: [ "Make the handler idempotent, e.g. record processed event IDs (or use an upsert keyed on the event) and skip duplicates.", "Commit the offset before processing so duplicates cannot happen.", "Switch to a broker that guarantees exactly-once network delivery.", "Increase the consumer session timeout so crashes are rarer." ], answer: [0], explanation: "Committing after processing gives **at-least-once** delivery: a crash in between replays the message. The durable answer is idempotent processing so a replay has no extra effect. Committing first converts duplicates into lost messages (at-most-once), which is usually worse for side effects users care about.", choiceRationale: [ "Correct: idempotent handling makes redelivery harmless.", "Trades duplicates for silently dropped messages on crash.", "Brokers can offer exactly-once within their own system, but an external side effect like email still needs idempotency.", "Reduces frequency, not the possibility, of a crash between steps." ], references: [R2.kafka, R2.idempotent], tags: ["delivery-semantics", "idempotency", "consumers"] }), mk("dist-messaging", 2, { difficulty: 2, type: "single", prompt: "A Kafka topic has **12 partitions** keyed by customer ID. Consumer lag is growing, so the team scales the consumer group from 12 to **24 instances**. What happens?", choices: [ "Throughput roughly doubles because each partition is now split between two consumers.", "Ordering per customer breaks because two consumers read each partition.", "Twelve consumers sit idle; within one group a partition is assigned to at most one consumer, so parallelism is capped by partition count.", "Kafka automatically creates 12 more partitions to match the consumer count." ], answer: [2], explanation: "Within a classic consumer group each partition is owned by a single consumer (Kafka's newer share groups, KIP-932, are a separate queue-style model), so the 13th through 24th instances get no assignment. To scale further you add partitions, which changes the key-to-partition mapping for new messages and needs care if per-key ordering matters during the transition. Alternatively, increase per-consumer throughput (batching, async I/O with per-key ordering preserved).", choiceRationale: [ "Partitions are not split across consumers in the same group.", "Ordering is preserved precisely because only one consumer owns each partition.", "Correct: parallelism per group is bounded by the number of partitions.", "Partition count is an explicit topic setting; it does not change with consumers." ], references: [R2.kafka], tags: ["partitions", "consumer-groups", "ordering"] }), mk("dist-messaging", 3, { difficulty: 2, type: "single", prompt: "An order service writes the order row to its database and then publishes `OrderCreated` to a broker. When the broker is briefly unavailable, orders exist with no event, and downstream fulfilment never sees them. Which pattern fixes this?", choices: [ "Publish the event first, then write the database row.", "Write the event into an outbox table in the same database transaction as the order, and have a relay or change-data-capture process publish outbox rows to the broker.", "Wrap the database write and the broker publish in a distributed two-phase commit.", "Retry the publish in-process up to five times before giving up." ], answer: [1], explanation: "Two separate writes to two systems cannot be made atomic by ordering them; one can always succeed while the other fails. The **transactional outbox** turns it into one local transaction, then delivers the event at-least-once from the outbox, so consumers must be idempotent. 2PC across a database and a broker is rarely supported and couples availability of both.", choiceRationale: [ "Reverses the failure: events for orders that were never saved.", "Correct: atomic local write plus asynchronous relay guarantees the event is eventually published.", "Most brokers do not participate in XA transactions, and 2PC adds blocking and coupling.", "A crash after the DB commit loses the in-memory retry, so the gap remains." ], references: [R2.azPatterns, R2.kafka], tags: ["outbox", "dual-write", "consistency"] }), mk("dist-messaging", 4, { difficulty: 3, type: "single", prompt: "A malformed message in partition 7 makes the consumer throw on every attempt. Because offsets are committed in order, partition 7 has been stuck for an hour while lag grows. Per-account ordering matters. What is the best design?", choices: [ "Skip and commit past any message that fails once, logging the error.", "Restart the consumer automatically on every failure until the message succeeds.", "Increase partition count so the bad message affects fewer accounts.", "After a bounded number of retries, move the message to a dead-letter/parking topic with alerting and replay tooling, and also park later messages for the same key until it is resolved." ], answer: [3], explanation: "A poison message must not block everything behind it, but blindly skipping it loses data and can break per-key invariants. Bounded retries followed by parking in a DLQ unblock the partition, and parking subsequent messages for the **same key** preserves ordering for that account while all other accounts flow. Alerting plus replay tooling makes the DLQ an operational process rather than a black hole.", choiceRationale: [ "Loses data on transient errors and lets later messages for the same account apply out of order.", "A deterministic failure will never succeed; this just crash-loops.", "Repartitioning does not remove the poison message and reshuffles key mapping.", "Correct: unblocks the partition while preserving per-key ordering and recoverability." ], references: [R2.kafka, R2.backlogs], tags: ["dead-letter-queue", "poison-message", "ordering"] }), mk("dist-messaging", 5, { difficulty: 2, type: "single", prompt: "After an outage, a queue has a backlog of **2,000,000 messages**. New messages arrive at **5,000/s**, and the consumer fleet processes **7,000/s** in total. Roughly how long until the backlog is drained?", choices: ["~4.8 minutes", "~16.7 minutes", "~6.7 minutes", "It never drains"], answer: [1], explanation: "Only the **surplus** capacity drains the backlog: 7,000 \u2212 5,000 = 2,000 messages/s. 2,000,000 / 2,000 = 1,000 s, about 16.7 minutes. If message age matters (e.g. time-sensitive notifications), consider scaling consumers temporarily or processing newest-first, since every queued message is also getting older.", choiceRationale: [ "Divides by total throughput (7,000/s) and ignores that new arrivals keep coming.", "Correct: 2,000,000 / (7,000 \u2212 5,000) = 1,000 s.", "Divides by the arrival rate, which is not the drain rate.", "Consumers outpace arrivals, so the backlog shrinks steadily." ], references: [R2.backlogs], tags: ["backlog", "calculation", "capacity"] }), mk("dist-messaging", 6, { difficulty: 3, type: "multi", prompt: "A team is choosing between a work queue and a partitioned log (Kafka-style) for an event platform where several teams consume the same events and a new analytics consumer must backfill the last 7 days. Select TWO statements that are correct.", choices: [ "A log retains messages after consumption, so a new consumer group can start from an older offset and replay history.", "A log provides native per-message acknowledgement and individual redelivery, making it the better fit for tasks with widely varying durations.", "Global ordering across all partitions of a log is guaranteed, so partition count does not affect ordering design.", "Consumer parallelism within one group in a log is bounded by the partition count, so partitions must be sized for peak consumer parallelism." ], answer: [0, 3], explanation: "Logs decouple retention from consumption, which is exactly what multi-consumer fan-out and backfill need. The price is that parallelism per consumer group is bounded by partitions and that ordering is only per partition. Per-message acks and visibility timeouts are the strength of work queues, which suit independent tasks of uneven duration (Kafka share groups add queue-style acks on top of a log, but classic consumer groups behave as described).", choiceRationale: [ "Correct: retention-based replay is a defining property of logs.", "This describes work queues; logs track a committed offset per partition, so one slow message holds up later ones in that partition.", "Ordering is guaranteed only within a partition.", "Correct: one consumer per partition per group caps parallelism." ], references: [R2.kafka, R2.primer], tags: ["queue-vs-log", "replay", "select-two"] }), // -------------------------------------------------------------------- rel-slo mk("rel-slo", 1, { difficulty: 1, type: "single", prompt: "A service has an availability SLO of **99.9% over a 30-day window**, measured in time. How much full downtime does the error budget allow per window?", choices: ["~4.3 minutes", "~43.2 minutes", "~7.2 hours", "~8.8 hours"], answer: [1], explanation: "30 days \xD7 24 h \xD7 60 min = 43,200 minutes; 0.1% of that is **43.2 minutes**. Each additional nine divides the budget by ten (99.99% \u2248 4.3 minutes per 30 days), which is why each nine typically costs disproportionately more engineering effort.", choiceRationale: [ "That is the budget for 99.99%.", "Correct: 43,200 \xD7 0.001 = 43.2 minutes.", "That is the budget for 99% over 30 days.", "That is roughly 99.9% over a full year, not 30 days." ], references: [R2.slo], tags: ["error-budget", "calculation", "availability"] }), mk("rel-slo", 2, { difficulty: 2, type: "single", prompt: "A checkout service runs at **99.95%** availability on its own and calls three **hard, serial dependencies**, each at **99.9%**. Failures are independent. What is the best estimate of checkout's achievable availability?", choices: ["99.95%", "99.9%", "~99.65%", "~99.85%"], answer: [2], explanation: "Serial dependencies multiply: 0.9995 \xD7 0.999\xB3 \u2248 0.9995 \xD7 0.9970 \u2248 **0.9965**. A service cannot be more available than the product of its hard dependencies, so promising 99.9% here is not credible without making dependencies soft (cache, degrade, async) or more available.", choiceRationale: [ "Ignores the dependencies entirely.", "Assumes the weakest dependency sets the ceiling; in series, all of them subtract.", "Correct: product of four serial availabilities \u2248 99.65%.", "Counts only one dependency: 0.9995 \xD7 0.999 \u2248 99.85%." ], references: [R2.slo, R2.awsWa], tags: ["composite-availability", "calculation", "dependencies"] }), mk("rel-slo", 3, { difficulty: 3, type: "single", prompt: "A service runs active-active in **two independent regions, each 99.5%** available, behind a **global load balancer at 99.99%**. Assume failover is instant and either region can carry full load. What is the approximate overall availability?", choices: ["99.5%", "~99.75%", "~99.9975%", "~99.99%"], answer: [3], explanation: "The two regions are in parallel: 1 \u2212 (0.005)\xB2 = 0.999975. The global load balancer is in series with that pair: 0.999975 \xD7 0.9999 \u2248 **0.999875**, about 99.99%. The lesson is that redundancy pushes availability up only until a shared serial component (DNS, global LB, control plane, deploy pipeline) dominates, and that real failover is rarely instant or perfectly independent.", choiceRationale: [ "Treats the regions as if redundancy added nothing.", "Averages the components; availabilities do not average.", "Correct for the regions alone, but ignores the serial load balancer.", "Correct: parallel pair (\u224899.9975%) in series with the LB (99.99%) \u2248 99.99%." ], references: [R2.slo, R2.gcpFw], tags: ["composite-availability", "calculation", "multi-region"] }), mk("rel-slo", 4, { difficulty: 3, type: "single", prompt: "A service has a **99.9% request-success SLO over 30 days**. For the past hour the error rate has been **1.44%**. What is the burn rate, and what fraction of the 30-day error budget did that hour consume?", choices: [ "Burn rate 14.4\xD7; about 2% of the budget", "Burn rate 1.44\xD7; about 0.2% of the budget", "Burn rate 14.4\xD7; about 20% of the budget", "Burn rate 144\xD7; about 2% of the budget" ], answer: [0], explanation: "Burn rate is observed error rate divided by the budget rate: 1.44% / 0.1% = **14.4\xD7**. One hour is 1/720 of 30 days, so the hour consumed 14.4 / 720 = **2%** of the budget; sustained, the whole budget would be gone in about 2 days. This is why 14.4\xD7 over 1 hour (2% budget) is a common fast-burn paging threshold in multi-window alerting.", choiceRationale: [ "Correct: 1.44 / 0.1 = 14.4; 14.4 / 720 = 0.02.", "Divides by 1% instead of the 0.1% budget.", "Correct burn rate, but miscounts hours in the window by a factor of 10.", "Correct fraction, but the burn rate is off by 10\xD7." ], references: [R2.alertSlo], tags: ["burn-rate", "calculation", "alerting"] }), mk("rel-slo", 5, { difficulty: 2, type: "single", prompt: "You are defining the primary SLI for a customer-facing checkout API. Which SLI best reflects user experience?", choices: [ "The proportion of valid checkout requests that return a non-5xx response within 500 ms, measured at the load balancer or edge.", "Average CPU utilization of checkout pods staying below 70%.", "Percentage of time all checkout pods report Ready.", "Success rate of a synthetic ping to `/healthz` every minute." ], answer: [0], explanation: "Good SLIs are **ratios of good events to valid events**, measured as close to the user as practical, and combine correctness with latency. Resource metrics and pod readiness are causes, not symptoms; a fleet can be all Ready with low CPU while every request fails. Synthetic health checks are useful supplements but sample a trivial path rather than real traffic.", choiceRationale: [ "Correct: request-based, user-facing, combines availability and latency.", "CPU is a saturation signal, not a measure of user success.", "Pods can be Ready while returning errors or timing out.", "Exercises a trivial endpoint, missing failures in the real checkout path." ], references: [R2.slo, R2.monitoring], tags: ["sli", "slo-design", "golden-signals"] }), mk("rel-slo", 6, { difficulty: 2, type: "multi", prompt: "Mid-month, a service has exhausted its 30-day error budget, mostly from two incidents caused by risky deploys. Select TWO actions consistent with a sound error budget policy.", choices: [ "Pause non-critical feature releases until the service is back within budget, allowing urgent security and reliability fixes.", "Lower the SLO to the level actually achieved this month so releases can continue.", "Redirect engineering effort to the postmortem action items for the largest budget consumers, such as safer deploy and rollback.", "Page the on-call for every individual failed request until the window resets." ], answer: [0, 2], explanation: "The point of an error budget is to make the reliability-versus-velocity trade explicit: when the budget is gone, risk-taking slows and effort shifts to what consumed it. Retroactively lowering the SLO defeats the agreement; SLOs should be revisited deliberately, not to escape a policy. Paging on individual errors produces noise, not reliability.", choiceRationale: [ "Correct: a release freeze with exceptions is the classic budget-exhausted response.", "Moving the target after missing it removes the policy's meaning.", "Correct: fixing the top budget consumers addresses the cause.", "Per-request paging causes alert fatigue; alerting should be on burn rate." ], references: [R2.slo, R2.workbook], tags: ["error-budget-policy", "release-velocity", "select-two"] }), // -------------------------------------------------------------- rel-incidents mk("rel-incidents", 1, { difficulty: 1, type: "single", prompt: "A SEV1 starts 10 minutes after a deploy: error rates jumped from 0.1% to 15%. Engineers want to find the faulty line of code first. As incident commander, what do you prioritize?", choices: [ "Have the team reproduce the bug in staging so the root cause is confirmed.", "Wait for the full metric picture over the next 30 minutes before acting.", "Start writing the postmortem timeline so nothing is forgotten.", "Mitigate first: roll back (or disable the feature flag) now, and investigate root cause after impact stops." ], answer: [3], explanation: "Strong correlation with a recent change makes rollback the fastest, lowest-risk mitigation, and restoring service beats understanding it. Root cause analysis can happen once users are no longer affected, using the bad build in a safe environment. Rolling back a change that turns out to be innocent costs little; delaying mitigation costs real impact.", choiceRationale: [ "Diagnosis before mitigation extends user impact.", "Waiting while 15% of requests fail burns budget with no benefit.", "Timeline capture matters but is a scribe task, not the IC's first priority.", "Correct: mitigation before root cause." ], references: [R2.sreBook, R2.postmortem], tags: ["mitigation", "rollback", "incident-command"] }), mk("rel-incidents", 2, { difficulty: 2, type: "single", prompt: "Forty minutes into a major incident, the incident commander is debugging the database personally, executives are pinging three different engineers for status, and two people have made conflicting config changes. What is the most important correction?", choices: [ "The IC steps back from hands-on debugging, assigns an operations lead to own changes and a communications lead to own stakeholder updates, and coordinates.", "Ask executives to stop messaging until the incident is resolved.", "Add more engineers to the bridge so the problem is solved faster.", "Lock all production changes until the root cause is found." ], answer: [0], explanation: "The symptoms are coordination failures, not a lack of skill. Separating roles (IC coordinates, ops lead is the single point for production changes, comms lead sends regular updates) stops conflicting changes and frees responders from status requests. More people without structure adds noise, and a total change freeze can block the mitigation itself.", choiceRationale: [ "Correct: explicit roles restore a single line of control and communication.", "Stakeholders legitimately need information; give them a channel instead of silence.", "Unstructured headcount increases conflicting actions.", "Mitigation often requires changes; the fix is one owner for changes, not none." ], references: [R2.sreBook], tags: ["incident-command", "roles", "communication"] }), mk("rel-incidents", 3, { difficulty: 2, type: "single", prompt: "An on-call engineer notices that ~3% of checkout attempts in one region are failing. It might be a client bug, so they hesitate to declare an incident and wake people up. What is the best practice?", choices: [ "Wait an hour to see whether the error rate grows before declaring anything.", "Open a low-priority ticket for the owning team to look at during business hours.", "Declare an incident at an appropriate severity now; it is cheap to downgrade or close if it turns out minor.", "Silently restart the regional checkout pods and monitor." ], answer: [2], explanation: "Revenue-affecting user errors meet most severity criteria, and the cost asymmetry favors declaring early: a downgraded incident costs a few minutes, while a late one loses coordination, communication and timeline data. Clear, written severity criteria remove the hesitation by turning a judgement call into a lookup.", choiceRationale: [ "Delays coordination while customers are failing to pay.", "Checkout failures are not a business-hours problem.", "Correct: declare early and adjust severity as facts emerge.", "Unrecorded changes during an unacknowledged problem make diagnosis harder and may not help." ], references: [R2.sreBook, R2.workbook], tags: ["severity", "declaring-incidents", "on-call"] }), mk("rel-incidents", 4, { difficulty: 3, type: "single", prompt: 'A draft postmortem says: *"Root cause: engineer ran the cleanup script against production instead of staging. Action item: retrain the engineer."* As the senior reviewer, what is the best feedback?', choices: [ "Approve it; the cause is clear and training addresses it.", "Reframe it blamelessly: ask why the system allowed it and add guardrails, such as environment-scoped credentials, a dry-run default, explicit target confirmation and a safer tool path.", "Add an action item requiring two-person approval for every production command.", "Remove the engineer's production access permanently." ], answer: [1], explanation: "Blameless postmortems treat human error as a symptom of a system that made the wrong action easy. Durable action items change the system (credentials that cannot reach production from a staging workflow, safe defaults, clear prompts), so the next person cannot make the same mistake. Blame-focused outcomes also discourage the honest reporting postmortems depend on.", choiceRationale: [ "Training does not prevent the next person from making the same mistake.", "Correct: fix the conditions that made the error possible and likely.", "Blanket two-person rules add toil and friction everywhere for one failure mode; targeted guardrails are better.", "Punitive and does not change the system." ], references: [R2.postmortem], tags: ["postmortem", "blameless", "guardrails"] }), mk("rel-incidents", 5, { difficulty: 3, type: "single", prompt: "An on-call rotation receives ~40 pages per week. About 70% resolve on their own within 5 minutes, and engineers now acknowledge pages without looking. What is the best plan?", choices: [ "Add a second on-call engineer so each person handles 20 pages.", "Add a 10-minute delay to every alert so self-resolving ones never fire.", "Keep the alerts but require a written note for each page so they are taken seriously.", "Audit alerts: delete or convert non-actionable ones to tickets or dashboards, and page primarily on user-facing symptoms such as SLO burn rate." ], answer: [3], explanation: "Every page should be urgent, actionable and require human judgement; pages that self-resolve train people to ignore the pager, which hides the real incident. Symptom-based alerting on SLO burn rate catches what users feel while ignoring harmless cause-level fluctuations. Blanket delays hide fast, severe problems along with the noise.", choiceRationale: [ "Spreads the noise across more people without removing it.", "A uniform delay also delays real fast-burn incidents.", "Adds toil to noise rather than removing it.", "Correct: remove non-actionable alerts and page on symptoms." ], references: [R2.monitoring, R2.toil], tags: ["alert-fatigue", "toil", "on-call"] }), mk("rel-incidents", 6, { difficulty: 2, type: "multi", prompt: "You are the communications lead for an ongoing customer-facing outage. Select TWO items that belong in every stakeholder update.", choices: [ "The suspected root cause and the name of the engineer whose change triggered it.", "Current customer impact in plain language: who is affected, which functions, and since when.", "The full stack trace and raw log excerpts from the failing service.", "What is being done now and when the next update will be sent." ], answer: [1, 3], explanation: "Stakeholders need to know the impact and whether to act, and they need a predictable cadence so they stop interrupting responders. Speculative cause and names are unverified and violate blameless norms; raw technical detail belongs in the responder channel, not the update.", choiceRationale: [ "Unverified and blaming; root cause belongs in the postmortem.", "Correct: impact and scope in non-technical terms.", "Too detailed for stakeholders and may leak sensitive data.", "Correct: current actions plus a committed next-update time." ], references: [R2.sreBook], tags: ["communication", "stakeholders", "select-two"] }), // ------------------------------------------------------------- rel-resilience mk("rel-resilience", 1, { difficulty: 1, type: "single", prompt: 'The business says of the order database: "We can afford to lose at most 5 minutes of orders, and it must be back within 1 hour." How do these map to recovery objectives?', choices: [ "RTO = 5 minutes, RPO = 1 hour", "RPO = 5 minutes, MTBF = 1 hour", "RPO = 5 minutes, RTO = 1 hour", "RTO = 5 minutes, MTTR = 1 hour" ], answer: [2], explanation: "**RPO** (recovery point objective) is how much data loss is tolerable, measured back in time from the failure; **RTO** (recovery time objective) is how long restoration may take. A 5-minute RPO rules out nightly backups and points to continuous replication or log shipping.", choiceRationale: [ "Swaps the two objectives.", "MTBF measures time between failures, not recovery.", "Correct: data loss tolerance is RPO, downtime tolerance is RTO.", "Confuses RTO with RPO and introduces MTTR, a measured average rather than an objective." ], references: [R2.awsWa, R2.azWa], tags: ["rpo", "rto", "disaster-recovery"] }), mk("rel-resilience", 2, { difficulty: 2, type: "single", prompt: "An internal reporting system has an agreed **RPO of 24 hours and RTO of 8 hours** in a regional disaster. Which DR strategy fits best?", choices: [ "Backup and restore: daily backups copied to another region, with infrastructure as code to rebuild there on demand.", "Pilot light: a continuously replicated database in a second region with minimal compute.", "Warm standby: a scaled-down but running copy of the full stack in a second region.", "Active-active across two regions with global traffic routing." ], answer: [0], explanation: "The cheapest strategy that meets the objectives is the right one. Daily cross-region backups meet a 24-hour RPO, and an 8-hour RTO leaves time to rebuild from IaC and restore, provided the restore is rehearsed and timed. Pilot light, warm standby and active-active buy minutes-level RPO/RTO at increasing standing cost that this system does not need.", choiceRationale: [ "Correct: lowest cost that still meets both objectives, if restores are tested.", "Continuous replication pays for an RPO far tighter than required.", "Standing compute in a second region is unnecessary for an 8-hour RTO.", "Highest cost and complexity for a system that tolerates a day of data loss." ], references: [R2.awsWa, R2.azWa], tags: ["dr-strategy", "cost", "rpo-rto"] }), mk("rel-resilience", 3, { difficulty: 3, type: "single", prompt: "Leadership wants the payments ledger to be **active-active in two regions** so either region can accept writes. Balances must never go negative or double-spend. Which design best meets this?", choices: [ "Asynchronous bidirectional replication with last-write-wins conflict resolution.", "Both regions accept writes and a nightly reconciliation job corrects conflicting balances.", "Read replicas in the second region with writes forwarded to the primary only during business hours.", "Assign each account a single home region that owns its writes (other regions forward to it), with controlled failover of ownership, or use a consensus-replicated database and accept cross-region commit latency." ], answer: [3], explanation: 'Invariants like "balance never negative" require a single serialization point per account. Partitioning ownership by account keeps writes local for most users while preserving that invariant, at the cost of a careful ownership failover process. A consensus-replicated store also works, but every commit pays at least one cross-region round trip; asynchronous multi-writer designs cannot enforce the invariant.', choiceRationale: [ "Concurrent debits in two regions can both succeed, and LWW silently drops one, allowing double spends.", "Reconciling after money has moved is too late for a ledger invariant.", "Not active-active and leaves writes unavailable much of the time.", "Correct: one owner per account, or synchronous consensus with known latency cost." ], references: [R2.jepsen, R2.awsWa], tags: ["active-active", "multi-region", "consistency"] }), mk("rel-resilience", 4, { difficulty: 2, type: "single", prompt: "A service needs **60 instances** at peak and runs across **3 AZs**. You want it to be **statically stable**: survive the loss of any one AZ at peak without launching new instances. What is the minimum total you should run?", choices: ["60", "80", "90", "120"], answer: [2], explanation: "With one AZ lost, the remaining two must carry all 60, so each AZ needs 30; across 3 AZs that is **90** instances (150% of peak). Relying on autoscaling during the failure assumes the control plane and spare capacity are available exactly when many customers are also trying to scale, which is a correlated risk.", choiceRationale: [ "Losing one AZ leaves only 40, a third short at peak.", "Leaves about 53 after losing an AZ; still short.", "Correct: 30 per AZ, so 60 remain after any single AZ loss.", "Over-provisions: 40 per AZ leaves 80 after one AZ loss, a third more than needed (and it still could not survive two AZ losses)." ], references: [R2.staticStability], tags: ["static-stability", "calculation", "multi-az"] }), mk("rel-resilience", 5, { difficulty: 2, type: "single", prompt: "Nightly database backups have reported success for a year, but nobody has restored one. A ransomware review asks whether you can recover. What is the most important improvement?", choices: [ "Increase backup frequency to hourly.", "Run regular automated restores into an isolated environment that verify data integrity and measure restore time against RTO, and keep copies immutable or in a separate account.", "Add a second backup tool from a different vendor.", "Store backups in the same account with versioning enabled." ], answer: [1], explanation: "A backup is unproven until it has been restored; jobs that report success can still produce unusable or incomplete data, and restore time is often far longer than assumed. Ransomware and compromised credentials can delete backups, so copies need immutability (object lock or equivalent) or isolation in a separate account with separate credentials.", choiceRationale: [ "Improves RPO but does nothing to prove backups are restorable.", "Correct: tested restores plus immutable or isolated copies.", "Two untested tools are still untested.", "An attacker with account access can still delete versions." ], references: [R2.awsWa, R2.gcpFw], tags: ["backup", "restore-testing", "ransomware"] }), mk("rel-resilience", 6, { difficulty: 3, type: "multi", prompt: "A team proposes moving a large multi-tenant service to a **cell-based architecture**, where each cell is a complete, independent copy of the stack serving a subset of customers. Select TWO accurate statements.", choices: [ "A bad deploy, poison request or noisy tenant is contained to the customers in one cell, limiting blast radius.", "Each cell can drop multi-AZ redundancy because other cells provide the redundancy.", "Cross-cell queries and transactions become cheap because all cells share the same database.", "It requires a thin, highly available routing layer that maps customers to cells, and it must be kept simple since it is shared by all cells." ], answer: [0, 3], explanation: "Cells shrink blast radius by giving each subset of customers fully independent infrastructure, which also enables staged deploys cell by cell. The trade-off is a routing layer that every request depends on, so it must be minimal and very reliable, plus extra work for anything that spans cells. Cells do not replace in-cell redundancy: a customer pinned to a cell still needs that cell to survive an AZ failure.", choiceRationale: [ "Correct: failure is bounded to one cell's customers.", "Customers are pinned to a cell, so a single-AZ cell is an outage for them.", "Cells do not share data stores; cross-cell operations get harder, not easier.", "Correct: the cell router is the shared dependency and must stay simple." ], references: [R2.builders, R2.awsWa], tags: ["cell-architecture", "blast-radius", "select-two"] }), // ---------------------------------------------------------------- sec-identity mk("sec-identity", 1, { difficulty: 1, type: "single", prompt: "A CI pipeline deploys to the cloud using a **long-lived access key** stored as a CI secret. What is the preferred replacement?", choices: [ "Federate the CI system's OIDC identity to a cloud role (AWS IAM role via OIDC, Azure workload identity federation, Google Cloud Workload Identity Federation) and issue short-lived credentials per job.", "Rotate the access key every 90 days via a scheduled job.", "Encrypt the access key with a second key stored in the repository.", "Create a separate access key for each developer who triggers pipelines." ], answer: [0], explanation: "Long-lived keys can leak through logs, forks or compromised runners and remain valid until someone notices. OIDC federation removes the stored secret entirely: each job exchanges a signed token for credentials that expire within minutes to hours, and the trust policy can be scoped to a specific repository and branch.", choiceRationale: [ "Correct: no stored secret, short-lived and scoped credentials.", "Rotation shortens exposure but the key is still a standing secret.", "The decryption key sits next to the ciphertext, adding no protection.", "Multiplies the number of long-lived secrets." ], references: [R2.zeroTrust, R2.awsWa], tags: ["workload-identity", "oidc", "short-lived-credentials"] }), mk("sec-identity", 2, { difficulty: 2, type: "single", prompt: 'A platform team\'s deployment role has `*:*` permissions because "it needs lots of services." You are asked to get it to least privilege without breaking deploys. What is the most practical approach?', choices: [ "Replace `*:*` with a hand-written policy based on what the team thinks it needs, and fix breakages as they appear in production.", "Keep `*:*` but require MFA for the role.", "Split it into one role per cloud service, each with full access to that service.", "Use access logs and last-accessed data to generate a scoped policy from actual usage, apply it in a pre-production environment first, and add a permissions boundary or organization guardrail as a ceiling." ], answer: [3], explanation: "Least privilege is easiest to reach empirically: observed usage over a representative period shows what the role actually calls. Validating in a lower environment avoids production breakage, and a permissions boundary or organization policy caps what the role could ever be granted. Splitting by service still leaves full access to each, and MFA does not reduce what an authenticated caller can do.", choiceRationale: [ "Guesswork tends to either break deploys or creep back to broad grants.", "MFA protects authentication, not authorization scope; pipelines also rarely use MFA.", "Service-level `*` is still far broader than needed.", "Correct: data-driven scoping, safe rollout and a hard ceiling." ], references: [R2.awsWa, R2.azWa], tags: ["least-privilege", "iam", "policy"] }), mk("sec-identity", 3, { difficulty: 2, type: "single", prompt: "In a shared Kubernetes cluster, all pods read cloud resources through the **node's instance identity**, so any pod can access any team's buckets. What is the best fix?", choices: [ "Use NetworkPolicies to block pods from reaching the cloud APIs.", "Use per-workload identity (e.g. EKS Pod Identity or IRSA, AKS Workload Identity, GKE Workload Identity) that maps each Kubernetes service account to its own narrowly scoped cloud role, and block pod access to the node metadata credentials.", "Put each team's pods on dedicated nodes with different node roles.", "Store a separate access key for each team in Kubernetes Secrets." ], answer: [1], explanation: "Node-level identity gives every pod on the node the union of all permissions it needs. Workload identity binds short-lived cloud credentials to a Kubernetes service account, so each workload gets only its own permissions. Blocking or limiting pod access to the instance metadata endpoint prevents falling back to the node role.", choiceRationale: [ "Pods often legitimately need cloud APIs; this breaks them without granting least privilege.", "Correct: per-service-account credentials scoped to each workload.", "Works but wastes capacity and is coarse; any pod scheduled on those nodes still shares the role.", "Introduces long-lived secrets that must be rotated and can leak." ], references: [R2.k8sTenancy, R2.zeroTrust], tags: ["workload-identity", "kubernetes", "least-privilege"] }), mk("sec-identity", 4, { difficulty: 3, type: "single", prompt: "An attacker phished an employee's VPN credentials, connected to the corporate network, and moved laterally to internal admin tools that trusted any request from the internal network range. Which change best reflects a zero-trust architecture?", choices: [ "Add a second VPN concentrator and stricter firewall rules at the perimeter.", "Require VPN users to change passwords monthly.", "Put each resource behind a policy enforcement point that authenticates the user and device on every request, evaluates context (identity, device posture, risk) and grants least-privilege, per-session access, regardless of network location.", "Move the admin tools to a separate subnet reachable only from the VPN." ], answer: [2], explanation: 'Zero trust (NIST SP 800-207) removes implicit trust based on network location: being "inside" grants nothing by itself. Every access decision is made per request by a policy decision point using identity, device health and context, enforced close to the resource. Phishing-resistant MFA strengthens the identity signal, but the architectural change is removing network-based trust.', choiceRationale: [ "Strengthens the perimeter but keeps the implicit trust that enabled lateral movement.", "Does nothing against phished credentials used immediately.", "Correct: per-request, identity- and device-aware authorization at each resource.", "Still trusts anyone on the VPN, which is what the attacker had." ], references: [R2.zeroTrust], tags: ["zero-trust", "lateral-movement", "nist-800-207"] }), mk("sec-identity", 5, { difficulty: 3, type: "single", prompt: "Your SaaS product assumes a role in each **customer's AWS account** to read their resources. A security reviewer warns that one customer could trick your service into accessing another customer's account (a confused-deputy attack). What mitigates this?", choices: [ "Use a single shared role name across all customers so access is consistent.", "Require customers to send you long-lived access keys instead of roles.", "Have your service validate that the target account ID looks well-formed before assuming the role.", "Generate a unique external ID per customer, store it server-side, and require customers to add an `sts:ExternalId` condition to the trust policy; your service always passes the external ID it holds for that tenant." ], answer: [3], explanation: "The confused deputy problem arises when your service has permission to act in many accounts and a customer can make it act on someone else's behalf by supplying another role ARN. An external ID that your service generates per tenant (customers cannot choose or override it) and always attaches for that tenant ensures the role can be assumed only in the context of the customer who configured it. Format checks do not establish ownership.", choiceRationale: [ "Predictable role names make cross-tenant misuse easier.", "Long-lived keys are worse to manage and still allow mix-ups.", "A syntactically valid ARN says nothing about who owns it.", "Correct: the external ID binds each trust relationship to the right tenant." ], references: [R2.awsWa, R2.shared], tags: ["confused-deputy", "cross-account", "iam"] }), mk("sec-identity", 6, { difficulty: 2, type: "multi", prompt: "You are designing privileged access for production. Select TWO practices that reduce standing privilege while still allowing emergency response.", choices: [ "A small number of break-glass accounts with strong MFA, credentials held in a vault, and alerting plus mandatory review on every use.", "Shared administrator credentials documented in the team wiki for fast access.", "Just-in-time elevation for routine admin work: time-bound, approved, logged, and automatically revoked.", "Permanent administrator rights for everyone on the on-call rotation." ], answer: [0, 2], explanation: "Standing privilege is the risk: any compromised account with permanent admin is a full compromise. Just-in-time elevation grants rights only when needed and only for a short time, and break-glass covers the case where the normal path is broken, with alerting to keep it honest. Shared or permanent admin rights remove accountability and maximize blast radius.", choiceRationale: [ "Correct: tightly controlled, audited emergency access.", "Shared credentials have no individual accountability and leak easily.", "Correct: removes standing privilege for day-to-day work.", "Every on-call laptop becomes a production admin credential." ], references: [R2.zeroTrust, R2.awsWa], tags: ["privileged-access", "jit", "select-two"] }), // -------------------------------------------------------------------- sec-data mk("sec-data", 1, { difficulty: 1, type: "single", prompt: "Why do cloud KMS-based designs use **envelope encryption** (a local data key encrypted by a KMS-held key) rather than sending every object to KMS for encryption?", choices: [ "KMS cannot encrypt data at all; it only stores keys.", "Bulk data is encrypted locally with a data key, so large payloads never travel to KMS and per-request limits and latency are avoided, while the master key never leaves KMS.", "Envelope encryption removes the need for any access control on the KMS key.", "It allows the data key to be stored in plaintext next to the data for faster reads." ], answer: [1], explanation: "KMS services typically limit direct encryption payloads to small sizes and are rate-limited, so encrypting bulk data through them is impractical. With envelope encryption the data key encrypts data locally, and only the small data key is wrapped by the KMS key and stored alongside the ciphertext. Access to data is then controlled by access to the KMS decrypt operation, which is logged.", choiceRationale: [ "KMS services can encrypt small payloads directly; the issue is size and throughput.", "Correct: local bulk encryption with a centrally protected key-encryption key.", "The KMS key policy is precisely the access control that protects all wrapped data keys.", "Only the encrypted (wrapped) data key is stored with the data." ], references: [R2.awsWa, R2.gcpFw], tags: ["envelope-encryption", "kms", "encryption-at-rest"] }), mk("sec-data", 2, { difficulty: 2, type: "single", prompt: "An auditor requires annual rotation of the KMS key protecting a 2 PB data lake. An engineer plans a months-long job to re-encrypt all objects. What is the most accurate response?", choices: [ "The re-encryption job is required; rotation is meaningless otherwise.", "Rotation is unnecessary because data at rest is already encrypted.", "Enable the KMS key's automatic rotation: new encryptions use the new key version while prior versions are retained to decrypt existing data, so routine rotation needs no bulk re-encryption. Re-encrypt only if a key is suspected compromised.", "Delete the old key after rotation to force all clients to the new version." ], answer: [2], explanation: "Managed KMS rotation creates new key material for future operations and keeps older versions available for decryption, which satisfies routine rotation policies without touching existing ciphertext. With envelope encryption, even re-wrapping data keys is far cheaper than re-encrypting objects. Bulk re-encryption is reserved for compromise scenarios, where the old material must no longer be trusted.", choiceRationale: [ "Overkill for routine rotation; managed rotation handles it.", "Rotation limits how much data one key version protects; auditors legitimately require it.", "Correct: versioned rotation without bulk re-encryption.", "Deleting old key material makes existing data permanently unreadable." ], references: [R2.awsWa, R2.azWa], tags: ["key-rotation", "kms", "compliance"] }), mk("sec-data", 3, { difficulty: 2, type: "single", prompt: "A service's database password is in a `.env` file baked into its container image and copied into three environments. What is the best target state?", choices: [ "The workload authenticates with its own identity to a secrets manager at runtime and retrieves short-lived or automatically rotated database credentials; nothing secret is stored in the image or repository.", "Keep the password in the image but encrypt the `.env` file with a key stored in the same image.", "Move the password to a Kubernetes ConfigMap so it is outside the image.", "Use a different password per environment but keep them in the image." ], answer: [0], explanation: "Secrets in images spread to every registry, cache and developer machine that pulls them, and cannot be rotated without rebuilding. Fetching at runtime via workload identity means no bootstrap secret is needed, and dynamic or rotated credentials limit the value of any leak. Separate credentials per environment are still good practice, but only once they live in a secrets manager.", choiceRationale: [ "Correct: runtime retrieval with workload identity and rotation.", "The decryption key ships alongside the ciphertext.", "ConfigMaps are not intended for secrets and are readable by anyone with ConfigMap access.", "Still baked in, still unrotatable without rebuilds." ], references: [R2.owasp, R2.awsWa], tags: ["secrets-management", "rotation", "workload-identity"] }), mk("sec-data", 4, { difficulty: 3, type: "single", prompt: "A team rolled out a service mesh with **mTLS between all services** and now proposes removing network segmentation and Kubernetes NetworkPolicies as redundant. What is the best response?", choices: [ "Agree; mTLS encrypts all traffic, so segmentation adds nothing.", "Agree, but keep TLS at the ingress only.", "Disagree; mTLS should be removed instead because network policies are sufficient.", "Disagree; mTLS gives authenticated, encrypted connections, but you still need authorization policies on top of identity, and segmentation limits reachability if a workload or the mesh is compromised or bypassed." ], answer: [3], explanation: "mTLS proves who is calling and protects the channel, but by itself it does not decide whether caller A may call service B; that requires explicit authorization policies. Segmentation is an independent layer that limits what a compromised pod can even reach, including workloads outside the mesh. Defense in depth means each control covers failure modes of the others.", choiceRationale: [ "Encryption and authentication are not authorization or reachability control.", "Weakens the internal posture further.", "Network policies cannot provide workload identity or encryption.", "Correct: identity, authorization and segmentation are complementary layers." ], references: [R2.zeroTrust, R2.k8sTenancy], tags: ["mtls", "segmentation", "defense-in-depth"] }), mk("sec-data", 5, { difficulty: 3, type: "single", prompt: "An object storage bucket is encrypted at rest with **provider-managed keys**. An attacker steals an application's cloud credentials that have read access to the bucket. How much does at-rest encryption protect the data, and what would actually limit the exposure?", choices: [ "Fully protected; the attacker sees only ciphertext.", "Not protected; at-rest encryption is transparent to any authorized principal. Limiting exposure needs least-privilege access, a customer-managed key whose key policy restricts decrypt to specific principals and conditions, and alerting on unusual access.", "Partially protected; the attacker can list objects but cannot download them.", "Protected as long as TLS is enforced on the bucket." ], answer: [1], explanation: "Server-side encryption at rest defends against threats like lost or improperly decommissioned media, not against callers the service treats as authorized. Stolen valid credentials decrypt transparently. A customer-managed key adds a second, independently controlled permission (and audit trail) on decrypt, and least privilege plus anomaly detection limit what any one credential can read.", choiceRationale: [ "Decryption happens automatically for authorized reads.", "Correct: at-rest encryption does not stop authorized principals; access control and key policy do.", "Read permission includes downloading decrypted objects.", "TLS protects data in transit, not against an authorized reader." ], references: [R2.shared, R2.awsWa], tags: ["encryption-at-rest", "threat-model", "cmk"] }), mk("sec-data", 6, { difficulty: 2, type: "multi", prompt: "TLS terminates at an L7 load balancer, and traffic to backends is plain HTTP inside a private network. A new compliance requirement mandates encryption in transit all the way to the backend. Select TWO approaches that satisfy it.", choices: [ "Rely on the private network being isolated from the internet.", "Re-encrypt: the load balancer terminates client TLS and opens a new TLS connection to the backend.", "Use TLS passthrough on an L4 load balancer so TLS terminates on the backend itself.", "Base64-encode request bodies between the load balancer and backend." ], answer: [1, 2], explanation: "Re-encryption keeps L7 features (routing, WAF, header manipulation) and adds a TLS hop to the backend; passthrough gives true end-to-end TLS but loses L7 inspection at the load balancer. Which to choose depends on whether the LB must see plaintext. Network isolation is not encryption, and encoding is not encryption.", choiceRationale: [ "Private networking reduces exposure but is not encryption in transit.", "Correct: TLS on both hops, with L7 features retained.", "Correct: end-to-end TLS with the backend holding the certificate.", "Base64 is a reversible encoding with no confidentiality." ], references: [R2.tls13, R2.zeroTrust], tags: ["tls", "encryption-in-transit", "select-two"] }), // ------------------------------------------------------------ sec-supply-chain mk("sec-supply-chain", 1, { difficulty: 1, type: "single", prompt: "A team runs workloads on IaaS virtual machines (e.g. EC2, Azure VMs, Compute Engine). A critical kernel vulnerability is announced. Under the shared responsibility model, who patches the guest operating system?", choices: [ "The cloud provider, automatically, because it owns the hypervisor.", "Nobody; VMs are isolated, so guest vulnerabilities do not matter.", "The customer, because the guest OS and everything above it are the customer's responsibility on IaaS.", "The provider for the kernel, the customer for user-space packages." ], answer: [2], explanation: "On IaaS the provider secures the physical infrastructure and virtualization layer; the guest OS, its patches, configuration and the applications above it belong to the customer. Responsibility shifts toward the provider as you move to managed platforms and serverless, which is part of the trade-off when choosing compute models.", choiceRationale: [ "Providers patch the host and hypervisor, not your guest OS.", "Guest OS vulnerabilities are exploitable from the network and from workloads.", "Correct: guest OS patching is a customer responsibility on IaaS.", "The kernel is part of the guest OS, which the customer owns." ], references: [R2.shared], tags: ["shared-responsibility", "patching", "iaas"] }), mk("sec-supply-chain", 2, { difficulty: 2, type: "single", prompt: 'A critical vulnerability is disclosed in a popular logging library on a Friday afternoon. Leadership asks, "Which of our 400 services are affected?" What capability answers this fastest and most reliably?', choices: [ "Ask every team to check their dependency files and reply by Monday.", "Run a fresh full vulnerability scan of every repository and image.", "Search the source code for the library's import statements.", "Query an inventory of SBOMs generated at build time and stored for every deployed artifact, mapped to where each artifact runs." ], answer: [3], explanation: "An SBOM records the components, including transitive dependencies, that actually ended up in each built artifact. With SBOMs indexed and linked to deployment inventory, the question becomes a query that runs in minutes. Source searches miss transitive and vendored dependencies, and manual surveys are slow and inconsistent.", choiceRationale: [ "Slow and error-prone, and misses transitive dependencies.", "Useful but slower, and scanning repositories may not reflect what is deployed.", "Misses transitive, shaded and vendored copies.", "Correct: build-time SBOMs plus deployment mapping give a fast, accurate answer." ], references: [R2.slsa, R2.owasp], tags: ["sbom", "vulnerability-response", "inventory"] }), mk("sec-supply-chain", 3, { difficulty: 2, type: "single", prompt: "An attacker with leaked registry credentials pushed a malicious image tagged `api:latest`, which production pulled on the next rollout. Which control best prevents a repeat?", choices: [ "Sign images in CI (e.g. Sigstore cosign with keyless signing bound to the pipeline identity) and enforce signature verification at cluster admission, deploying by digest rather than mutable tags.", "Rotate the registry password monthly.", "Scan every image for CVEs before deployment.", "Make the registry private so it is not reachable from the internet." ], answer: [0], explanation: "Registry credentials prove someone could push, not that an artifact came from your trusted build. Admission-time signature verification only admits images signed by the expected pipeline identity, and pinning by digest stops a tag being re-pointed. Vulnerability scanning would not flag purpose-built malware with no known CVEs.", choiceRationale: [ "Correct: verifies origin at deploy time, independent of registry access.", "Reduces the window but a leaked credential still works until rotation.", "Scanners detect known vulnerabilities, not malicious intent.", "The attacker already had valid credentials, so private reachability does not help." ], references: [R2.sigstore, R2.slsa], tags: ["image-signing", "admission-control", "supply-chain"] }), mk("sec-supply-chain", 4, { difficulty: 3, type: "single", prompt: "Your build system now emits SLSA provenance attestations for every artifact. In a design review, which claim about what provenance gives you is accurate?", choices: [ "It proves the artifact contains no known vulnerabilities.", "It records verifiable metadata about how the artifact was built (which builder, from which source revision, with which inputs), so consumers can check it came from the expected pipeline and source.", "It guarantees that the source code was reviewed by two people.", "It replaces the need for an SBOM because it lists all runtime dependencies." ], answer: [1], explanation: `Provenance answers "where and how was this built?" and, at higher SLSA build levels, makes that record hard to forge. It lets a deployment policy reject artifacts not built by the trusted builder from the expected repository. It says nothing about whether the code is correct or vulnerability-free, and dependency inventory is the SBOM's job.`, choiceRationale: [ "Vulnerability status comes from scanning and SBOM analysis, not provenance.", "Correct: provenance is build metadata that can be verified.", "Code review practices are separate controls from build provenance.", "SBOMs and provenance are complementary; provenance may list build inputs but is not a complete component inventory of the artifact." ], references: [R2.slsa], tags: ["slsa", "provenance", "attestation"] }), mk("sec-supply-chain", 5, { difficulty: 3, type: "single", prompt: "A new container scanner reports **3,000 CVEs** across production images. Teams are overwhelmed and are ignoring the reports. What is the best senior-level program?", choices: [ "Prioritize by real risk (known exploitation, exploit likelihood, reachability and exposure of the workload), fix most findings by rebuilding on maintained minimal base images, and set remediation SLAs by risk tier.", "Block every deployment that contains any CVE until the count reaches zero.", "Fix CVEs in order of CVSS score from highest to lowest.", 'Suppress all findings below "critical" permanently to reduce noise.' ], answer: [0], explanation: "Raw CVE counts mix exploitable issues in internet-facing code with unreachable packages in internal batch jobs. Risk-based prioritization (for example using known-exploited catalogs and exploit-prediction scores) focuses effort where it matters, and most findings disappear by rebuilding on a patched, smaller base image. SLAs per tier give accountability without halting delivery.", choiceRationale: [ "Correct: risk-based triage, base image hygiene and tiered SLAs.", "Halts delivery, including security fixes, and incentivizes disabling scanners.", "CVSS alone ignores exploitability and exposure.", "Permanent suppression hides lower-rated issues that may be actively exploited." ], references: [R2.owasp, R2.cis], tags: ["vulnerability-management", "prioritization", "base-images"] }), mk("sec-supply-chain", 6, { difficulty: 2, type: "multi", prompt: "You want **preventive** guardrails, not just detection, so teams cannot create risky configurations. Select TWO controls that prevent rather than detect.", choices: [ "Organization-level policies that deny creating publicly accessible storage (e.g. AWS SCPs, Azure Policy with deny effect, Google Cloud Organization Policy).", "A weekly report listing misconfigured resources sent to each team.", "A quarterly manual compliance audit against CIS Benchmarks.", "Kubernetes admission control (e.g. OPA Gatekeeper or Kyverno) that rejects privileged pods and images from untrusted registries." ], answer: [0, 3], explanation: "Preventive controls stop a bad change at the moment it is requested: organization policies deny the cloud API call, and admission controllers reject the Kubernetes object. Reports and audits are detective; they are valuable but leave a window in which the risky configuration exists. Mature programs pair both, with prevention for high-severity, well-understood rules.", choiceRationale: [ "Correct: denied at the cloud control plane.", "Detective; the misconfiguration already exists.", "Detective and infrequent.", "Correct: rejected at cluster admission." ], references: [R2.opa, R2.cis], tags: ["policy-as-code", "guardrails", "select-two"] }) ]; // ../../packages/content/src/infra/questions-3.ts var DOMAIN2 = { "auto-iac": "automation", "auto-delivery": "automation", "obs-signals": "observability", "obs-performance": "observability", "arch-frameworks": "architecture-cost", "arch-finops": "architecture-cost", "craft-system-design": "interview-craft", "craft-behavioral": "interview-craft" }; var R3 = { tfDocs: { title: "Terraform documentation", url: "https://developer.hashicorp.com/terraform/docs" }, tfState: { title: "Terraform state", url: "https://developer.hashicorp.com/terraform/language/state" }, opa: { title: "Open Policy Agent documentation", url: "https://www.openpolicyagent.org/docs/latest/" }, twelve: { title: "The Twelve-Factor App", url: "https://12factor.net/" }, slsa: { title: "SLSA framework", url: "https://slsa.dev/" }, builders: { title: "Amazon Builders\u2019 Library", url: "https://aws.amazon.com/builders-library/" }, sreBook: { title: "Google SRE book", url: "https://sre.google/sre-book/table-of-contents/" }, sreWorkbook: { title: "Google SRE workbook", url: "https://sre.google/workbook/table-of-contents/" }, monitoring: { title: "SRE book: Monitoring distributed systems", url: "https://sre.google/sre-book/monitoring-distributed-systems/" }, sloAlerting: { title: "SRE workbook: Alerting on SLOs", url: "https://sre.google/workbook/alerting-on-slos/" }, slo: { title: "SRE book: Service level objectives", url: "https://sre.google/sre-book/service-level-objectives/" }, otel: { title: "OpenTelemetry documentation", url: "https://opentelemetry.io/docs/" }, use: { title: "Brendan Gregg: The USE method", url: "https://www.brendangregg.com/usemethod.html" }, linuxPerf: { title: "Brendan Gregg: Linux performance", url: "https://www.brendangregg.com/linuxperf.html" }, overload: { title: "SRE book: Handling overload", url: "https://sre.google/sre-book/handling-overload/" }, awsWa: { title: "AWS Well-Architected", url: "https://aws.amazon.com/architecture/well-architected/" }, azWa: { title: "Azure Well-Architected Framework", url: "https://learn.microsoft.com/en-us/azure/well-architected/" }, gcpFw: { title: "Google Cloud Architecture Framework", url: "https://cloud.google.com/architecture/framework" }, migration: { title: "AWS migration strategies", url: "https://docs.aws.amazon.com/prescriptive-guidance/latest/large-migration-guide/migration-strategies.html" }, staticStab: { title: "Static stability using Availability Zones", url: "https://aws.amazon.com/builders-library/static-stability-using-availability-zones/" }, finops: { title: "FinOps Framework", url: "https://www.finops.org/framework/" }, vpc: { title: "What is Amazon VPC?", url: "https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html" }, primer: { title: "System Design Primer", url: "https://github.com/donnemartin/system-design-primer" }, behavioral: { title: "Tech Interview Handbook: Behavioral interviews", url: "https://www.techinterviewhandbook.org/behavioral-interview/" }, cascading: { title: "SRE book: Addressing cascading failures", url: "https://sre.google/sre-book/addressing-cascading-failures/" }, postmortem: { title: "SRE book: Postmortem culture", url: "https://sre.google/sre-book/postmortem-culture/" } }; var q = (topic, n, d) => ({ id: `iq-${topic}-${String(n).padStart(3, "0")}`, domain: DOMAIN2[topic], objective: topic, lessonId: `infra-${topic}`, type: d.answer.length > 1 ? "multi" : "single", ...d }); var infraQuestions3 = [ // ---------------------------------------------------------------- auto-iac q("auto-iac", 1, { difficulty: 2, prompt: "All production infrastructure (shared network, databases and 40 services) lives in one Terraform root module with a single state. Plans take 25 minutes, and last week a typo in one service's module produced a plan that would have replaced a shared route table. What is the best structural fix?", choices: [ "Require engineers to run `terraform apply -target` for the resources they changed", "Split into separate root modules and states by lifecycle and blast radius (network, data, per-service), passing values via outputs or data sources", "Increase `-parallelism` so plans finish faster and reviewers have more time to read them", "Add `prevent_destroy` to every resource in the configuration" ], answer: [1], explanation: "A single state couples every change to every resource: plans are slow, locks are contended and any mistake can touch shared foundations. Splitting states along lifecycle and ownership boundaries shrinks the blast radius of each apply and makes plans fast enough to review. Stable layers (network) change rarely and are consumed read-only by faster-moving service stacks.", choiceRationale: [ "Routine `-target` use is documented as an exceptional tool; it hides dependency changes and lets state drift from config.", "Correct: state boundaries are the primary blast-radius control in Terraform.", "Faster plans do not reduce what a single apply can break.", "Blocks destruction but also blocks legitimate replacements, and does nothing for in-place damaging updates." ], references: [R3.tfState, R3.tfDocs], tags: ["terraform", "state", "blast-radius"] }), q("auto-iac", 2, { difficulty: 3, prompt: "During an incident an on-call engineer opened a security group rule in the console to restore traffic from a new partner CIDR. The scheduled drift-detection plan now shows Terraform will remove that rule on the next apply. What is the best next step?", choices: [ "Add `lifecycle { ignore_changes = all }` to the security group so console fixes are never reverted", "Run a refresh-only apply so state matches reality and close the ticket", "Codify the rule in the Terraform config through a reviewed PR, apply so plan returns to no-op, and record the break-glass change in the incident follow-ups", "Revoke console write access immediately, then let the next apply remove the rule so config stays the source of truth" ], answer: [2], explanation: "Drift after a break-glass fix is expected; the goal is to reconcile intent back into code without re-breaking production. Updating config via PR makes the emergency change reviewed, durable and visible, and a clean plan proves convergence. Ignoring changes or only refreshing state leaves code that no longer describes the system, which is how the next rebuild silently loses the fix.", choiceRationale: [ "Hides all future drift on a security-critical resource; IaC stops being authoritative.", "State would record the rule, but config still lacks it, so a later plan or rebuild will remove it.", "Correct: reconcile in code, prove a no-op plan, and track the break-glass usage.", "Reverting a live mitigation would re-cause the outage; tightening access is a separate follow-up." ], references: [R3.tfState, R3.tfDocs], tags: ["terraform", "drift", "break-glass"] }), q("auto-iac", 3, { difficulty: 2, prompt: "Your Terraform state lives in an object-storage bucket and several CI pipelines can apply concurrently. Select TWO practices that most reduce risk.", choices: [ "Enable state locking so two applies cannot write the same state at once", "Commit a copy of the state file to Git after every apply for auditability", "Mark secret outputs as `sensitive`, which keeps them out of the state file", "Encrypt the state at rest, enable bucket versioning, and restrict read access, because state can contain secrets in plaintext" ], answer: [0, 3], explanation: "Concurrent writers without a lock can corrupt state or lose resources from tracking. State frequently contains secret values (generated passwords, keys), so it must be treated as a secret itself: encrypted, access-controlled and versioned for recovery. `sensitive` only redacts values from CLI output; they are still stored in state.", choiceRationale: [ "Correct: locking serialises writers to one state.", "Spreads secrets into Git history and creates a second, stale source of truth.", "Incorrect: `sensitive` affects display only; the value is still persisted in state.", "Correct: protects confidentiality and enables rollback of a bad state write." ], references: [R3.tfState], tags: ["terraform", "state", "secrets"] }), q("auto-iac", 4, { difficulty: 1, prompt: "You want policy as code (for example OPA/Rego rules) to stop a publicly readable storage bucket before it is ever created. Where should the check run?", choices: [ "In CI against the machine-readable plan output, failing the pipeline before apply", "Only in a nightly cloud scanner that flags public buckets after creation", "Only as variable validation blocks inside the bucket module", "In a pre-commit hook on developer laptops" ], answer: [0], explanation: "Evaluating the plan JSON in CI sees the exact resources and attributes about to be created, regardless of which module produced them, and blocks before anything exists. Runtime scanners are a valuable second layer but detect after exposure. Module validation is bypassed by anyone who does not use the module, and laptop hooks are optional.", choiceRationale: [ "Correct: preventive, central and independent of module choice.", "Detective only; the bucket is already exposed when flagged.", "Only covers callers of that module and only its inputs.", "Easily skipped; not an enforcement point." ], references: [R3.opa, R3.tfDocs], tags: ["policy-as-code", "opa", "guardrails"] }), q("auto-iac", 5, { difficulty: 3, prompt: "A refactor moves `aws_db_instance.main` into a new `module.database`. The plan now shows the production database will be destroyed and recreated. What is the safest correct fix?", choices: [ "Add `create_before_destroy` so a new database exists before the old one is removed", "Add `prevent_destroy` and apply; Terraform will then update in place", "Take a snapshot, apply during a maintenance window, and restore data into the new instance", "Declare a `moved` block (or run a state move) from the old address to the new module address so Terraform treats it as the same object" ], answer: [3], explanation: "The resource did not change; only its address did, and Terraform keys objects by address. A `moved` block records the rename in code so every environment applying the refactor migrates state consistently and the plan becomes a no-op. Lifecycle flags address replacement behaviour, not identity.", choiceRationale: [ "Still replaces the database, with a new endpoint and empty data.", "Makes the plan fail rather than fixing the address mismatch.", "Turns a refactor into a risky data migration with downtime.", "Correct: maps the old address to the new one; reviewable and repeatable across environments." ], references: [R3.tfState, R3.tfDocs], tags: ["terraform", "refactoring", "state"] }), q("auto-iac", 6, { difficulty: 2, prompt: "You manage dev, staging and prod for the same platform. Prod needs bigger instances and multi-AZ databases. Which layout best balances consistency and safety?", choices: [ "Copy-paste a directory per environment and edit each one independently", "One root module and one state, with `count` per environment on every resource", "Versioned shared modules, one thin root config and separate state per environment with environment-specific variables, promoted through the pipeline", "One root module using `terraform.workspace` conditionals throughout resources to express prod-only differences" ], answer: [2], explanation: "Shared versioned modules keep environments structurally identical, while separate states isolate blast radius so a dev apply can never touch prod. Differences live in explicit variables, and promoting a module version dev to staging to prod mirrors artifact promotion. Copy-paste diverges silently; scattered conditionals make prod behaviour impossible to test elsewhere.", choiceRationale: [ "Environments drift apart and fixes must be repeated by hand.", "One state couples all environments; a dev mistake can destroy prod.", "Correct: consistency from modules, isolation from state, differences as data.", "Hidden branching means staging no longer exercises prod code paths." ], references: [R3.tfDocs, R3.twelve], tags: ["terraform", "environments", "modules"] }), // ----------------------------------------------------------- auto-delivery q("auto-delivery", 1, { difficulty: 3, prompt: "A service handles 2,000 rps with a 0.1% baseline error rate. You run a 1% canary for 10 minutes. Roughly how many requests and expected baseline errors does the canary see, and what does that imply?", choices: [ "~12,000 requests and ~12 expected errors; only large regressions are statistically detectable, so lengthen the bake or raise the canary weight for subtle ones", "~120,000 requests and ~120 errors; a 10% regression is easily detectable", "~1,200 requests and ~1 error; canaries are useless below 10% traffic", "~12,000 requests; any single extra error proves a regression and should trigger rollback" ], answer: [0], explanation: "2,000 x 1% = 20 rps, x 600 s = 12,000 requests; at 0.1% that is about 12 errors. Poisson noise on 12 is about \xB13.5 (sqrt 12), so a 25% regression (15 errors) is invisible and only roughly a doubling (about 24, ~3 sigma) stands out; detecting subtle regressions needs more samples: longer bake, staged weights, or comparing against a concurrent baseline cohort. Seniors size canaries from traffic and SLO, not by habit.", choiceRationale: [ "Correct arithmetic and the right conclusion about statistical power.", "Off by 10x on traffic.", "Off by 10x, and small canaries still catch crashes and gross regressions.", "Single-error triggers produce constant false rollbacks given Poisson noise." ], references: [R3.sreWorkbook, R3.builders], tags: ["canary", "progressive-delivery", "statistics"] }), q("auto-delivery", 2, { difficulty: 2, prompt: "A release renames a database column from `addr` to `address`. You deploy with blue/green and want instant rollback. Which approach preserves that?", choices: [ "Run the rename in the same deploy; blue/green switches traffic atomically so both versions are fine", "Deploy the code first and run the rename after green is healthy", "Take a snapshot before cutover and restore it if rollback is needed", "Expand/contract: add `address`, dual-write and backfill, switch reads, and only drop `addr` after the old version can no longer return" ], answer: [3], explanation: "Blue/green only swaps compute; both colours share the same database, so every schema state must work with both N and N-1 code. Expand/contract spreads a breaking change across several backward-compatible deploys. Restoring snapshots loses writes made since the cutover, which is not a rollback.", choiceRationale: [ "Blue (old code) breaks the instant the column disappears.", "Green breaks until the rename runs, and rollback after it breaks blue.", "Data loss and long RTO; not an instant rollback.", "Correct: each step is compatible with the adjacent code versions." ], references: [R3.builders, R3.twelve], tags: ["blue-green", "schema-migration", "rollback"] }), q("auto-delivery", 3, { difficulty: 2, prompt: "You are shipping a rewritten checkout flow. Product wants it live for internal users first, then 5% of customers, with the ability to turn it off in seconds without a deploy. What do you use?", choices: [ "Blue/green deploy with a full traffic switch", "Deploy the code dark behind a feature flag, ramp by cohort, and keep a kill switch", "A long-lived release branch merged when QA signs off", "A pod-level canary at 5% of replicas" ], answer: [1], explanation: "Flags decouple deploy from release: code ships continuously, exposure is targeted by user cohort, and disabling is a config change measured in seconds. Pod-level canaries cannot target internal users and give inconsistent experiences across requests without stickiness. The cost is flag debt, so flags need owners and removal dates.", choiceRationale: [ "All-or-nothing; no cohort targeting.", "Correct: cohort targeting plus seconds-to-disable.", "Increases merge risk and still releases all at once.", "Splits by replica, not user, and rollback still needs a deploy." ], references: [R3.builders, R3.sreWorkbook], tags: ["feature-flags", "progressive-delivery", "release"] }), q("auto-delivery", 4, { difficulty: 1, prompt: "Which practice best guarantees that what you tested in staging is exactly what runs in production?", choices: [ "Rebuild the image in each environment from the same Git tag", "Pin base images by tag such as `:latest-stable`", "Build once, then promote the same immutable artifact digest through environments, injecting config at deploy time", "Run the full test suite again in production after deploy" ], answer: [2], explanation: "Rebuilds can pull different dependencies or base layers, so the same tag can yield different bits. Promoting a single digest, with environment config supplied separately, makes staging evidence apply to prod and supports provenance attestations. This is the twelve-factor separation of build, release and run.", choiceRationale: [ "Non-reproducible builds can differ between environments.", "Mutable tags can move underneath you.", "Correct: same bits everywhere; only config differs.", "Late detection, not a guarantee of sameness." ], references: [R3.twelve, R3.slsa], tags: ["artifacts", "promotion", "immutability"] }), q("auto-delivery", 5, { difficulty: 3, prompt: "Your platform team is adopting pull-based GitOps (for example Argo CD or Flux). Select TWO statements that are accurate.", choices: [ "Rollback is always instant, because `git revert` bypasses the reconciliation loop", "An in-cluster agent continuously reconciles live state to Git, so manual `kubectl` drift is detected and reverted", "CI no longer needs cluster-admin credentials, since the cluster pulls changes rather than CI pushing them", "GitOps removes the need for a separate secrets-management solution" ], answer: [1, 2], explanation: "Pull-based GitOps moves deploy credentials inside the cluster boundary and makes Git the desired state that an agent converges on, which also corrects drift. Rollback still goes through reconciliation and is only as safe as the change being reverted (schemas, data migrations). Secrets must not be stored in plaintext in Git; you still need sealed or external secrets.", choiceRationale: [ "A revert is reconciled like any commit and cannot undo data or schema side effects.", "Correct: continuous reconciliation is the core mechanism.", "Correct: shrinks the credential blast radius of CI.", "Plaintext secrets in Git are a serious leak; you still need a secrets solution." ], references: [R3.slsa, R3.builders], tags: ["gitops", "kubernetes", "security"] }), q("auto-delivery", 6, { difficulty: 3, prompt: "Version 2 of a producer started emitting a new message format to a queue. Errors spiked, you rolled producers back to v1, but consumers that were also upgraded to v2 now fail on old messages, and v1 consumers fail on the v2 messages still in the queue. What practice would have prevented this?", choices: [ "Purging the queue before every rollback", "Making consumers tolerant of both formats first, then switching producers in a later release, so N and N-1 are always mutually compatible", "Deploying producers and consumers together in one atomic release", "Pausing consumers during deploys until the queue drains" ], answer: [1], explanation: "Asynchronous systems have data in flight, so a deploy is never atomic across producers, consumers and stored messages. Readers must accept old and new formats before any writer emits the new one, and writers keep N-1 compatibility until rollback is no longer possible. This makes both roll-forward and rollback safe.", choiceRationale: [ "Destroys business data to fix a compatibility bug.", "Correct: tolerant reader first, then writer, makes every step reversible.", "There is no atomic deploy across services and in-flight messages.", "Adds downtime and backlog without fixing format incompatibility." ], references: [R3.builders, R3.cascading], tags: ["rollback", "compatibility", "messaging"] }), // ------------------------------------------------------------- obs-signals q("obs-signals", 1, { difficulty: 2, prompt: "A request-count metric has labels endpoint (20 values), status (5) and pod (50). A developer wants to add `user_id` (2 million active users) to debug per-customer issues. What is the right response?", choices: [ "Fine: series grow linearly by 2 million, which modern TSDBs handle", "Add it but lower the scrape interval to compensate", "Add it, but only on error responses", "Reject it: today ~5,000 series could become millions or more; put `user_id` on traces and structured logs (linking via exemplars) instead" ], answer: [3], explanation: "Series count is the product of label cardinalities: 20 x 5 x 50 = 5,000 today. Multiplying by an unbounded user dimension can produce millions to billions of series, blowing up memory, query latency and cost. High-cardinality identifiers belong in traces and logs, which are indexed per event rather than per series.", choiceRationale: [ "Growth is multiplicative, not additive.", "Scrape interval does not change series count.", "Errors across 2 million users still explode cardinality.", "Correct: keep metrics low-cardinality; use events for identifiers." ], references: [R3.monitoring, R3.otel], tags: ["metrics", "cardinality", "cost"] }), q("obs-signals", 2, { difficulty: 2, prompt: "You are cleaning up a noisy pager rotation. Which alert most deserves to page a human at 3 a.m.?", choices: [ "Fast and slow error-budget burn on the checkout availability SLO are both above threshold", "CPU above 90% on any node for 5 minutes", "A single pod restarted", "Disk on a log host is 70% full" ], answer: [0], explanation: "Pages should fire on user-visible symptoms that need urgent human action. Multiwindow burn-rate alerts tie paging to SLO impact and filter short blips. Cause-based signals such as CPU or restarts belong on dashboards or tickets unless they reliably predict imminent user harm.", choiceRationale: [ "Correct: symptom-based, SLO-aligned and noise-filtered.", "High CPU may be healthy utilisation; not a user symptom.", "Self-healing event; ticket or dashboard at most.", "Slow-moving; a ticket, not a page." ], references: [R3.sloAlerting, R3.monitoring], tags: ["alerting", "slo", "on-call"] }), q("obs-signals", 3, { difficulty: 3, prompt: "A service has a 99.9% availability SLO over 30 days. Your fast-burn page fires when 2% of the monthly error budget is consumed in 1 hour. What burn rate and sustained error rate does that threshold correspond to?", choices: [ "Burn rate 2, error rate 0.2%", "Burn rate 14.4, error rate 14.4%", "Burn rate 14.4, error rate about 1.44%", "Burn rate 720, error rate 72%" ], answer: [2], explanation: "A 30-day window has 720 hours. Spending 2% of the budget in 1 hour means burning 0.02 x 720 = 14.4 times faster than sustainable. With a 0.1% budget, the error rate is 14.4 x 0.1% = 1.44%. At that pace the whole month of budget is gone in about 50 hours.", choiceRationale: [ "Confuses the budget fraction with the burn rate.", "Right burn rate, but forgets to multiply by the 0.1% budget.", "Correct: 0.02 x 720 = 14.4; 14.4 x 0.1% = 1.44%.", "Uses 720 as the rate rather than scaling by 2%." ], references: [R3.sloAlerting, R3.slo], tags: ["burn-rate", "slo", "computation"] }), q("obs-signals", 4, { difficulty: 3, prompt: "Your tracing uses 1% head-based sampling and keeps missing the rare slow or failed requests. You evaluate tail-based sampling in the collector. Select TWO accurate statements.", choices: [ "Tail sampling removes all instrumentation overhead from application processes", "The keep/drop decision is made after spans for a trace are collected, so policies can keep all errors and slow traces", "Request-rate metrics computed from the sampled traces remain accurate without adjustment", "Collectors must buffer spans and route all spans of a trace to the same instance, which adds memory cost and stateful scaling" ], answer: [1, 3], explanation: "Head sampling decides at the root before outcome is known, so rare failures are dropped at the sampling rate. Tail sampling decides with the full trace in view, but every span must still be exported and held until the decision, and the trace must land on one collector (trace-ID-aware load balancing). Biased sampling also distorts rate metrics, so derive RED metrics before sampling.", choiceRationale: [ "Applications still create and export every span; overhead moves, it does not disappear.", "Correct: outcome-aware retention is the main benefit.", "Keeping all errors biases the sample; rates need pre-sampling metrics.", "Correct: the operational cost of tail sampling." ], references: [R3.otel], tags: ["tracing", "sampling", "opentelemetry"] }), q("obs-signals", 5, { difficulty: 1, prompt: "Which pairing of method to target is most appropriate?", choices: [ "USE (utilisation, saturation, errors) for request-driven services; RED for disks", "RED (rate, errors, duration) for request-driven services; USE for resources such as CPU, disks and connection pools", "RED only for databases; USE only for load balancers", "Both methods measure the same things, so pick one org-wide" ], answer: [1], explanation: "RED describes what a service delivers to its callers and maps directly to SLIs. USE describes the health of each resource and is the fastest way to find a saturated bottleneck. In practice you alert on RED symptoms and diagnose with USE.", choiceRationale: [ "Reversed.", "Correct: RED for services, USE for resources.", "Arbitrary split; both apply more broadly.", "They answer different questions and are complementary." ], references: [R3.use, R3.monitoring], tags: ["red", "use-method", "golden-signals"] }), q("obs-signals", 6, { difficulty: 2, prompt: "Log ingestion cost tripled in two quarters; most volume is INFO request logs and load-balancer health-check lines. Select TWO changes with the highest leverage.", choices: [ "Drop or sample health-check and debug lines at the agent or collector before they reach the paid backend", "Move all logs to a longer hot-retention tier for faster search", "Switch from structured JSON to free text to save bytes", "Replace per-request INFO logs used only for counting with metrics, keeping full logs for errors and sampled successes" ], answer: [0, 3], explanation: "The cheapest log line is the one never ingested, so filter low-value lines at the edge. When logs exist only to count things, a metric gives the same answer at a tiny fraction of the cost and query time. Structure should be kept, because it makes the remaining logs useful.", choiceRationale: [ "Correct: removes noise before it is billed.", "Increases cost.", "Saves little and destroys queryability.", "Correct: aggregates are far cheaper as metrics." ], references: [R3.monitoring, R3.otel], tags: ["logging", "cost", "telemetry-pipeline"] }), // ---------------------------------------------------------- obs-performance q("obs-performance", 1, { difficulty: 2, prompt: "An API serves a steady 1,200 rps with a mean latency of 250 ms. By Little\u2019s law, how many requests are in flight across the system on average?", choices: ["30", "300", "4.8", "3,000"], answer: [1], explanation: "Little\u2019s law: L = lambda x W = 1,200 /s x 0.25 s = 300 concurrent requests. This sizes worker threads, connection pools and concurrency limits. If latency doubles under a slow dependency, in-flight work doubles too, which is how pools exhaust and failures cascade.", choiceRationale: [ "Off by 10x; perhaps a per-instance figure for 10 instances.", "Correct: 1,200 x 0.25 = 300.", "Divides instead of multiplying.", "Uses 2.5 s instead of 0.25 s." ], references: [R3.overload, R3.cascading], tags: ["littles-law", "concurrency", "computation"] }), q("obs-performance", 2, { difficulty: 3, prompt: "A frontend request fans out in parallel to 50 backend shards and waits for all of them. Each shard independently exceeds its p99 latency on 1% of calls. Roughly what fraction of frontend requests see at least one shard above its p99?", choices: ["1%", "50%", "5%", "About 40%"], answer: [3], explanation: "P(no slow shard) = 0.99^50, about 0.605, so about 39.5% of requests wait on at least one tail response. Fan-out turns a 1-in-100 backend event into something roughly 4 in 10 frontend requests experience. Mitigations include hedged or backup requests, tighter backend tail control, partial results and reducing fan-out width.", choiceRationale: [ "Ignores the fan-out.", "Adds probabilities naively (50 x 1%), which overestimates.", "Underestimates by an order of magnitude.", "Correct: 1 - 0.99^50 is about 0.395." ], references: [R3.primer, R3.builders], tags: ["tail-latency", "fan-out", "computation"] }), q("obs-performance", 3, { difficulty: 2, prompt: "A 16-core Linux host shows a load average of 40 while CPU utilisation is 35% and latency is poor. What is the most likely explanation and next check?", choices: [ "Many threads are blocked in uninterruptible I/O wait, which Linux counts in load average; check `vmstat 1`, `iostat -x 1` and per-process D-state", "The CPU is saturated; add cores", "The load average is wrong when utilisation is under 50%; ignore it", "Memory is leaking; restart the service" ], answer: [0], explanation: "Linux load average counts runnable tasks plus those in uninterruptible sleep (usually disk or NFS I/O). High load with low CPU therefore points at I/O or lock contention, not CPU. Following USE, check disk utilisation, queue depth and await before scaling CPU.", choiceRationale: [ "Correct: load includes D-state tasks; USE says check disk saturation next.", "CPU at 35% contradicts CPU saturation.", "Load average is valid; it simply measures more than CPU.", "No evidence of memory pressure; restarting hides the cause." ], references: [R3.use, R3.linuxPerf], tags: ["linux", "load-average", "use-method"] }), q("obs-performance", 4, { difficulty: 3, prompt: "To cut cost, a team proposes running a latency-sensitive service at 90% average CPU instead of 50%. Using a simple single-server queue model (M/M/1), what happens to mean queueing delay?", choices: [ "It rises about 1.8x, in proportion to utilisation", "It is unchanged until utilisation reaches 100%", "It rises about 9x, because queueing delay scales with rho/(1 - rho), going from 1 to 9; tail latency degrades even more", "It falls, because busier caches are warmer" ], answer: [2], explanation: "In M/M/1, mean waiting time is proportional to rho/(1 - rho): 0.5/0.5 = 1 versus 0.9/0.1 = 9. Latency is non-linear in utilisation, which is why latency-sensitive tiers keep headroom while batch tiers can run hot. Real systems with bursty arrivals behave worse than the model.", choiceRationale: [ "Assumes linear behaviour, which queueing theory refutes.", "Queues form well before 100%.", "Correct: the hockey-stick of rho/(1 - rho).", "Cache effects do not offset queueing growth." ], references: [R3.overload, R3.use], tags: ["queueing", "utilisation", "computation"] }), q("obs-performance", 5, { difficulty: 3, prompt: "A multithreaded service in a container with a 2-CPU limit shows p99 spikes of roughly 50 to 100 ms while average CPU usage is only 60% of the limit and p50 is flat. What should you check first?", choices: [ "DNS resolution latency on the node", "Garbage-collection logs only, since CPU is not the problem", "Disk IOPS on the node", "CFS quota throttling: `nr_throttled` and throttled time in the cgroup `cpu.stat`, since bursts can exhaust the quota early in each 100 ms period" ], answer: [3], explanation: "CPU limits are enforced per scheduling period (100 ms by default). Many threads bursting together can use the whole quota in the first part of the period, then sit throttled for the rest, adding tens of ms to unlucky requests even though average usage looks low. Fixes include raising or removing the limit, reducing thread counts, or right-sizing requests.", choiceRationale: [ "Possible, but does not match the period-shaped spikes under a CPU limit.", "GC can cause pauses, but average CPU hides throttling, so averages do not rule CPU out.", "No evidence of I/O involvement.", "Correct: classic averaged-out throttling under quota." ], references: [R3.linuxPerf, R3.use], tags: ["containers", "cpu-throttling", "tail-latency"] }), q("obs-performance", 6, { difficulty: 2, prompt: "You need an accurate fleet-wide p99 latency across 20 hosts. Select TWO valid approaches.", choices: [ "Sum histogram bucket counts across hosts, then compute the percentile from the merged histogram", "Average the 20 per-host p99 values", "Merge per-host mergeable quantile sketches (for example t-digest or DDSketch-style) and query p99", "Take the maximum of the per-host p99 values" ], answer: [0, 2], explanation: "Percentiles are not additive: averaging or taking the max of per-host p99s gives a number that does not correspond to any real distribution, and hosts with different traffic volumes skew it further. Histograms with shared bucket boundaries and mergeable sketches preserve enough of the distribution to compute a correct aggregate percentile within known error.", choiceRationale: [ "Correct: bucket counts add, so the merged histogram represents the fleet.", "Ignores traffic weighting and distribution shape.", "Correct: sketches are designed to merge.", "An upper bound at best, often badly pessimistic." ], references: [R3.monitoring, R3.otel], tags: ["percentiles", "histograms", "aggregation"] }), // ---------------------------------------------------------- arch-frameworks q("arch-frameworks", 1, { difficulty: 2, prompt: "Your data-centre lease ends in 9 months. One of 300 applications is a vendor product with no source code, a licence that permits virtual machines, and a stable workload. Which migration strategy fits best?", choices: [ "Rehost (lift and shift) onto cloud VMs, then optimise later", "Refactor into microservices on Kubernetes", "Rebuild it as serverless functions", "Retain it on premises indefinitely, regardless of the lease" ], answer: [0], explanation: "With no source code and a hard deadline, rehosting is the fastest low-risk path and is common for the bulk of a large migration. Deep modernisation is reserved for apps where business value justifies it. Retain is a valid strategy, but the lease end removes it here unless a colocation option exists.", choiceRationale: [ "Correct: fits deadline, licensing and lack of source.", "Impossible without source and unnecessary for a stable app.", "Same problem: no source code.", "The lease end makes indefinite retention impractical." ], references: [R3.migration, R3.awsWa], tags: ["migration", "7rs", "trade-offs"] }), q("arch-frameworks", 2, { difficulty: 3, prompt: "Leadership asks for active-active across two cloud providers to achieve 99.99% availability for a service that currently runs in a single region of one provider. What is the strongest senior recommendation?", choices: [ "Agree; multi-cloud active-active is the only way to exceed 99.9%", "First go multi-AZ and then multi-region within one provider, with tested failover; consider multi-cloud only for specific drivers such as regulation or concentration risk, and quantify its cost", "Refuse; 99.99% is not achievable in the cloud", "Use two providers in active-passive with manual DNS failover and no regular drills" ], answer: [1], explanation: "Most outages come from your own changes (contained by progressive, zone-by-zone and region-by-region rollout) and zonal or regional faults (handled by multi-AZ and multi-region), all achievable within one provider at a fraction of the complexity. Multi-cloud doubles tooling, skills and data-replication problems and pushes you towards lowest-common-denominator services. A senior ties the choice to stated drivers and shows the cost.", choiceRationale: [ "Overstates; multi-region designs commonly target 99.99%.", "Correct: incremental, evidence-based and cost-aware.", "Incorrect; well-designed multi-region systems can achieve it.", "Untested manual failover rarely meets its RTO." ], references: [R3.awsWa, R3.gcpFw], tags: ["multi-cloud", "multi-region", "availability"] }), q("arch-frameworks", 3, { difficulty: 2, prompt: "A request path depends serially on three independent components with availabilities of 99.95%, 99.9% and 99.99%. What is the approximate best-case availability of the path?", choices: ["99.99%", "99.9%", "99.95%", "About 99.84%"], answer: [3], explanation: "Serial dependencies multiply: 0.9995 x 0.999 x 0.9999 is about 0.9984. A chain is always weaker than its weakest link. Seniors use this to argue for fewer hard dependencies, redundancy (parallel components combine as 1 - product of unavailabilities) and graceful degradation.", choiceRationale: [ "Takes the best component, not the product.", "Takes the weakest link, ignoring the others.", "Takes the middle value.", "Correct: product of availabilities." ], references: [R3.slo, R3.awsWa], tags: ["availability", "computation", "dependencies"] }), q("arch-frameworks", 4, { difficulty: 2, prompt: "A four-person platform team needs an event streaming backbone. Event streaming is not a product differentiator. They are debating self-managing Kafka on VMs versus a managed streaming service. What is the best default?", choices: [ "Self-manage; it is always cheaper", "Build a custom log on object storage", "Use the managed service, verify limits and cost at projected scale, and keep clients on standard protocols to preserve an exit path", "Delay the decision until traffic justifies streaming" ], answer: [2], explanation: "For a small team, the dominant cost of self-managing is engineering time for upgrades, rebalancing, capacity and on-call. Buying non-differentiating capability frees the team for product work. Due diligence on quotas, pricing at scale and portability addresses the main risks of buying.", choiceRationale: [ "Ignores labour and operational risk; frequently false at this team size.", "Building core infrastructure from scratch is the highest-risk option.", "Correct: buy the undifferentiated, with explicit checks.", "Ignores an existing need." ], references: [R3.azWa, R3.awsWa], tags: ["build-vs-buy", "managed-services", "trade-offs"] }), q("arch-frameworks", 5, { difficulty: 1, prompt: "What is the primary output of a Well-Architected style review of a workload?", choices: [ "A certification that the workload is compliant", "A prioritised list of risks and improvement actions with explicit trade-offs across the pillars", "A guarantee of a specific availability SLA", "An automatic remediation of all findings" ], answer: [1], explanation: "The frameworks from AWS, Azure and Google Cloud are structured ways to surface risks against pillars such as reliability, security, cost and performance. The value is a prioritised improvement plan and conscious trade-off decisions, not a certificate or guarantee.", choiceRationale: [ "Not a compliance attestation.", "Correct: risks, priorities and trade-offs.", "Reviews do not create SLAs.", "Remediation is the team\u2019s follow-up work." ], references: [R3.awsWa, R3.azWa], tags: ["well-architected", "review", "pillars"] }), q("arch-frameworks", 6, { difficulty: 3, prompt: "You want a three-AZ service to survive the loss of one zone without depending on any recovery actions. Select TWO design choices that provide static stability.", choices: [ "Rely on autoscaling to launch replacement capacity in the surviving zones when a zone fails", "Pre-provision enough capacity in each zone that two zones alone can carry peak load", "Keep the failure path free of control-plane calls, for example no need to launch instances, change DNS or update configuration to stay up", "Run the database primary in one zone and restore from backup elsewhere on failure" ], answer: [1, 2], explanation: "Static stability means the system keeps working in a degraded state without making changes, because control planes are often impaired during the same event. That requires headroom already in place (about 50% extra with three zones sized for N-1) and data-plane-only failover. Restore-based designs have long RTOs and depend on extra operations.", choiceRationale: [ "Depends on a control plane that may be degraded or capacity-constrained during the event.", "Correct: pre-provisioned N-1 capacity.", "Correct: avoid control-plane dependencies during recovery.", "Single-zone primary with restore is neither fast nor static." ], references: [R3.staticStab, R3.awsWa], tags: ["static-stability", "multi-az", "resilience"] }), // -------------------------------------------------------------- arch-finops q("arch-finops", 1, { difficulty: 2, prompt: "Private-subnet workloads pull about 50,000 GB per month from object storage in the same region through a NAT gateway billed at roughly $0.045 per GB processed (approximate, provider-dependent). What is the best fix and approximate monthly saving?", choices: [ "Move the workloads to public subnets with public IPs; saves about $2,250 but widens exposure", "Add a second NAT gateway per AZ; saves about $1,000", "Route storage traffic through a gateway or private endpoint for the storage service, removing NAT processing; saves about $2,250 per month", "Compress objects; saves about $225" ], answer: [2], explanation: "50,000 GB x $0.045 is about $2,250 per month of pure NAT processing for traffic that never leaves the provider. Private connectivity to the storage service, such as a gateway endpoint on AWS or Private Google Access or a private endpoint on other providers, removes that path and keeps traffic off the internet route. Always check endpoint pricing for your provider, as some endpoint types carry their own per-GB charge.", choiceRationale: [ "Saves money by giving up the private-subnet security posture.", "More NAT gateways add cost; this does not save.", "Correct: private path for in-region service traffic.", "Marginal and invasive compared with fixing the route." ], references: [R3.vpc, R3.finops], tags: ["nat", "egress", "computation"] }), q("arch-finops", 2, { difficulty: 3, prompt: "A fleet runs a steady 400 vCPU all day and peaks at 1,000 vCPU for 4 hours daily. Commitments give a 40% discount on committed vCPU whether used or not. Relative to all on-demand (normalised to 500 vCPU-equivalents per hour on average), which commitment is cheapest?", choices: [ "Commit 400 vCPU: about 340 (240 committed + 100 on-demand), roughly 32% savings", "Commit 500 vCPU (the daily average): about 300", "Commit 1,000 vCPU (the peak): about 600", "No commitment: about 500" ], answer: [0], explanation: "Average usage is 400 + 600 x 4/24 = 500 vCPU. Committing at the floor: 400 x 0.6 = 240, plus peak overflow 600 x 4/24 = 100 on demand, totalling 340. Committing 500 costs 300 plus 500 x 4/24, about 83, so roughly 383, because 100 vCPU sit idle 20 hours a day. Commit to the reliable floor and serve peaks with on-demand, spot or autoscaling.", choiceRationale: [ "Correct: covering the baseline maximises utilisation of the commitment.", "Ignores the on-demand overflow during peaks; the true total is about 383.", "Paying for 600 idle vCPU for 20 hours a day costs more than on-demand.", "Baseline, but leaves the discount unused." ], references: [R3.finops], tags: ["commitments", "coverage", "computation"] }), q("arch-finops", 3, { difficulty: 2, prompt: "The CFO flags that the cloud bill grew 30% quarter over quarter. Over the same period, orders grew 50%. What is the most accurate framing?", choices: [ "Efficiency worsened by 30%; freeze new spend", "Efficiency is unchanged because both numbers grew", "The bill should have grown 50%, so the team underspent", "Cost per order fell about 13% (1.3 / 1.5 is about 0.87); report unit cost alongside the total and watch for components where it is rising" ], answer: [3], explanation: "Unit economics separate growth from efficiency. Cost per order went from 1.0 to 1.3/1.5, about 0.87, a 13% improvement despite the larger bill. FinOps practice reports unit cost trends to engineering and finance together, then digs into the services where unit cost is moving the wrong way.", choiceRationale: [ "Ignores the denominator.", "Different growth rates mean efficiency changed.", "Spend is not a target to hit.", "Correct: unit cost improved and is the right metric." ], references: [R3.finops], tags: ["unit-economics", "finops", "computation"] }), q("arch-finops", 4, { difficulty: 1, prompt: "35% of monthly cloud spend cannot be attributed to any team. What is the best first move?", choices: [ "Immediately charge back the untagged cost to every team equally", "Enforce required ownership tags at provisioning via policy, align accounts or projects to owners, and start with showback before chargeback", "Ask each team to tag resources manually by the end of the quarter", "Delete untagged resources after 24 hours" ], answer: [1], explanation: "Allocation needs prevention (policy-enforced tags and account or project structure) and visibility (showback) before financial accountability (chargeback). Equal splits remove incentives, manual cleanup decays, and deleting untagged resources risks outages.", choiceRationale: [ "Unfair and gives no signal about who is driving the cost.", "Correct: enforce at creation, structure by owner, show back first.", "No enforcement; coverage erodes again.", "Dangerous; can delete production resources." ], references: [R3.finops], tags: ["tagging", "showback", "allocation"] }), q("arch-finops", 5, { difficulty: 2, prompt: "Chatty microservices spread across three AZs exchange about 200 TB per month across zones. Assume cross-AZ transfer costs roughly $0.01/GB in each direction (approximate). What is the best mitigation?", choices: [ "Prefer same-zone endpoints with topology-aware routing, falling back to other zones only when local capacity is unhealthy, which can save a large share of roughly $4,000 per month", "Move everything into a single AZ to eliminate the charge", "Compress payloads; this removes the charge entirely", "Ignore it; data transfer is always negligible" ], answer: [0], explanation: "200,000 GB x $0.02 (both directions) is about $4,000 per month. Zone-aware routing keeps most traffic local while retaining multi-AZ resilience, as long as each zone has enough capacity and failover remains automatic. Consolidating into one zone trades a cost line for a large availability risk.", choiceRationale: [ "Correct: cuts cross-zone traffic without giving up zone redundancy.", "Saves money by removing AZ fault tolerance.", "Reduces bytes, not the per-GB charge on what remains.", "At this volume transfer is a material line item." ], references: [R3.finops, R3.vpc], tags: ["data-transfer", "cross-az", "computation"] }), q("arch-finops", 6, { difficulty: 2, prompt: "Spot or preemptible capacity is 60 to 90% cheaper but can be reclaimed with short notice. Select TWO workloads that are good fits.", choices: [ "Stateless batch rendering jobs that checkpoint progress and can retry", "The single primary node of a production relational database", "CI build and test runners that can simply rerun interrupted jobs", "A latency-critical stateful singleton with no replica" ], answer: [0, 2], explanation: "Spot suits work that is interruption-tolerant: stateless, retryable, checkpointed or horizontally redundant. Losing a database primary or an unreplicated singleton causes an outage or data risk. Diversifying instance types and zones improves spot availability further.", choiceRationale: [ "Correct: checkpoints bound lost work.", "Interruption causes failover or downtime on the most critical node.", "Correct: reruns are cheap.", "No redundancy; interruption is an outage." ], references: [R3.finops, R3.awsWa], tags: ["spot", "preemptible", "workload-fit"] }), // ------------------------------------------------------ craft-system-design q("craft-system-design", 1, { difficulty: 1, prompt: 'The interviewer says: "Design a URL shortener." What is the best next step?', choices: [ "Start drawing the database schema", "Pick the tech stack so the interviewer knows you are hands-on", "Clarify functional scope and non-functional requirements (scale, read/write ratio, latency, availability, retention) and agree on them before designing", "Jump to a deep dive on hash collision handling" ], answer: [2], explanation: "Senior candidates scope the problem first: what is in and out, the scale and the quality bar. These drive every later decision, and stating assumptions out loud shows judgement. Schemas, technologies and deep dives come after a shared understanding exists.", choiceRationale: [ "Premature; the schema depends on requirements.", "Technology choices without requirements look like pattern matching.", "Correct: clarify and agree first.", "Deep dives belong after the high-level design." ], references: [R3.primer], tags: ["interview-method", "requirements", "scoping"] }), q("craft-system-design", 2, { difficulty: 2, prompt: 'After you present your design, the interviewer asks: "What happens if the cache cluster goes down?" Which response is strongest?', choices: [ "It will not; the cache is replicated", "Quantify the impact (for example a 95% hit rate means the database suddenly sees about 20x the load), then describe mitigations such as request coalescing, load shedding and a staged warm-up, and the trade-off of each", "Add a second cache cluster in another region", "Say you would look at the dashboards and decide then" ], answer: [1], explanation: "Interviewers probe failure modes to see whether you reason about blast radius and degradation. Quantifying the impact (a miss rate going from 5% to 100% is 20x origin load) shows the cascading-failure risk, and naming mitigations with costs shows operational maturity. Dismissing or deferring the question is a red flag.", choiceRationale: [ "Dismisses the failure mode; replicated systems still fail.", "Correct: impact, mechanism, mitigations, trade-offs.", "Adds cost without addressing the thundering-herd risk.", "Defers rather than reasoning." ], references: [R3.primer, R3.cascading], tags: ["interview-method", "failure-modes", "caching"] }), q("craft-system-design", 3, { difficulty: 2, prompt: "You estimate 100 million daily active users each making about 10 writes per day. Which capacity statement is the most reasonable to say out loud?", choices: [ "About 1 billion writes per day, roughly 12k writes per second on average; I will plan for about 2 to 3x that at peak, so around 30k per second", "About 100k writes per second on average", "About 1,200 writes per second, so a single database is plenty", "Exact numbers do not matter in system design interviews" ], answer: [0], explanation: "100M x 10 = 1B per day; dividing by about 86,400 seconds gives about 11.6k per second. Real traffic is diurnal and bursty, so a stated peak multiplier is expected. Rounded numbers with explicit assumptions are what interviewers want, because they drive sharding and storage decisions.", choiceRationale: [ "Correct: right arithmetic and an explicit peak factor.", "Overestimates by roughly 10x.", "Underestimates by 10x and draws the wrong conclusion.", "Estimates justify the architecture; skipping them is a red flag." ], references: [R3.primer], tags: ["estimation", "capacity", "computation"] }), q("craft-system-design", 4, { difficulty: 3, prompt: "Halfway through, the interviewer adds that users in three continents must be able to write with low latency. Your design uses a single-leader database in one region. What is the best move?", choices: [ "Keep the design and say read replicas in each region will handle it", "Silently redraw the diagram with a different database", "Ask the interviewer to drop the requirement because it is out of scope", "Say explicitly that the single-leader choice no longer meets the requirement, present options (home-region partitioning by user, multi-leader with conflict resolution, or a globally consistent database with higher write latency), pick one with trade-offs, and update the design" ], answer: [3], explanation: "Requirements changing mid-interview is often a deliberate test of adaptability. Naming the broken assumption, laying out options and their consistency and latency costs, then committing to one shows senior judgement. Read replicas do not address write latency, and hiding the change loses the reasoning signal.", choiceRationale: [ "Replicas help reads, not cross-continent writes.", "Loses the signal; the interviewer wants to hear the reasoning.", "Avoids the test rather than engaging with it.", "Correct: acknowledge, compare options, decide, adapt." ], references: [R3.primer, R3.gcpFw], tags: ["interview-method", "trade-offs", "multi-region"] }), // -------------------------------------------------------- craft-behavioral q("craft-behavioral", 1, { difficulty: 2, prompt: "Which STAR answer best demonstrates influence without authority?", choices: [ "I escalated to our VP, who directed the other team to adopt our logging standard", "I quietly rewrote the other team\u2019s pipeline myself over a weekend so they would not have to", "The other team agreed because I was the most senior engineer in the room", "I measured how many incidents traced back to inconsistent logging, prototyped the standard with one willing team, addressed the main objection (migration effort) with a tool, and three teams adopted it voluntarily within a quarter" ], answer: [3], explanation: "Influence without authority shows up as data, empathy for the other side\u2019s constraints, a low-friction path and voluntary adoption with a measured result. Escalation and title-based persuasion are authority, and doing others\u2019 work unasked does not change minds or scale.", choiceRationale: [ "Uses someone else\u2019s authority; escalation should be a last resort.", "Bypasses ownership and builds no buy-in.", "Relies on seniority as authority.", "Correct: evidence, pilot, objection handling and measurable voluntary adoption." ], references: [R3.behavioral], tags: ["behavioral", "influence", "star"] }), q("craft-behavioral", 2, { difficulty: 2, prompt: '"Tell me about a time you failed." Which answer is strongest for a senior role?', choices: [ "I pushed a config change without a staged rollout and caused a 40-minute partial outage; I led the mitigation, wrote the blameless postmortem, and drove a change requiring progressive rollout for config, which has since caught two bad changes", "I work too hard and sometimes take on too much", "A project failed because another team missed their deadline", "I have not really failed at anything significant" ], answer: [0], explanation: "Interviewers look for genuine ownership, quantified impact, what you did in the moment and a durable systemic fix with evidence that it worked. Disguised strengths, blaming others or claiming no failures all signal low self-awareness.", choiceRationale: [ "Correct: real mistake, impact, ownership, systemic fix and proof.", "A disguised strength; not a failure.", "Externalises blame and shows no learning.", "Signals low self-awareness or low risk-taking." ], references: [R3.behavioral, R3.postmortem], tags: ["behavioral", "failure", "ownership"] }), q("craft-behavioral", 3, { difficulty: 1, prompt: 'While telling an incident story you keep saying "we". The interviewer asks, "What did you specifically do?" What is the best response?', choices: [ "Repeat that it was a team effort and everyone contributed equally", "Take credit for the whole outcome to sound senior", "State your own decisions and actions concretely (for example, I took incident command, chose to roll back rather than patch forward, and ran the comms), while crediting others for their parts", "Change to a different story" ], answer: [2], explanation: "The interviewer needs to evaluate you, not the team. Naming your specific decisions and why you made them gives that signal, and crediting others shows collaboration without claiming their work. Overclaiming is often exposed by follow-up questions.", choiceRationale: [ "Leaves the interviewer unable to assess you.", "Overclaiming erodes credibility.", "Correct: clear personal contribution with honest credit.", "Avoids the question." ], references: [R3.behavioral], tags: ["behavioral", "star", "ownership"] }), q("craft-behavioral", 4, { difficulty: 3, prompt: 'For a staff-level loop, which "Result" statement best signals staff scope?', choices: [ "We shipped the feature on time because I worked several weekends", "Sev-1 incidents across six teams fell from 9 to 2 per quarter after I proposed and drove adoption of a deploy-safety standard, which is now part of the org\u2019s golden path", "I fixed a tricky production bug in under an hour", "Everyone was happy with how it turned out" ], answer: [1], explanation: "Staff scope means multi-team impact through durable mechanisms, with a measured outcome. The strongest result shows breadth (six teams), a metric with a before and after, and institutionalisation (golden path). Heroics, individual fixes and vague sentiment show task-level scope.", choiceRationale: [ "Heroics are not sustainable and show individual scope.", "Correct: cross-team, measured, durable mechanism.", "Valuable but individual and tactical.", "No measurable result." ], references: [R3.behavioral], tags: ["behavioral", "scope", "impact"] }) ]; // ../../packages/content/src/infra/design-1.ts var designCases1 = [ // --------------------------------------------------------------------------- // 1. Multi-region web application // --------------------------------------------------------------------------- { id: "sd-multi-region-web", title: "Highly available multi-region SaaS web application", difficulty: "senior", topics: ["rel-resilience", "net-edge", "data-databases", "dist-theory", "rel-slo", "sec-data"], prompt: `"We run a B2B SaaS product: a web app plus a public API. Customers are global, roughly 40% North America, 35% Europe, 25% Asia-Pacific. Today everything sits in one region and last year a regional outage took us down for most of an afternoon. Leadership has committed to **99.99% availability**, we must survive the loss of an entire region, and our European customers contractually require their data to stay in the EU. Design the target architecture and tell me how you would get there."`, clarifyingQuestions: [ "What exactly does 99.99% measure: the API, the web UI, specific critical user journeys, per tenant or aggregate, and over what window?", "What are the read/write ratio and peak request rate, and which operations must be strongly consistent (billing, permissions) versus tolerant of seconds of staleness?", "What does data residency cover: primary data only, or also backups, logs, support tooling, and derived analytics? Can EU metadata (tenant name, routing key) be global?", "What RPO and RTO are acceptable on a full region loss: is losing a few seconds of writes acceptable for normal SaaS data?", "Is a tenant ever global (a multinational with users on several continents), and how do we handle a user in Asia belonging to an EU tenant?", "What third-party dependencies sit on the critical path (identity provider, payment, email) and are they themselves multi-region?", "What is the budget tolerance: is roughly doubling infrastructure spend acceptable, and how big is the platform team?", "Are there existing constraints such as a single relational database monolith that we have to migrate incrementally?" ], requirements: { functional: [ "Serve web UI and public API to global users with authentication, tenant isolation and per-tenant configuration.", "Pin each tenant to a home geography (EU, US, APAC); EU tenant data at rest and in backups stays in EU regions.", "Survive the complete loss of any one region with automatic or one-command failover of traffic.", "Global control-plane functions: sign-up, tenant directory and routing, billing aggregation.", "Support planned regional evacuation for maintenance and game days." ], nonFunctional: [ "Availability 99.99% for critical journeys (login, core read/write API), measured monthly: about 4.3 minutes of error budget per month.", "Region-loss RTO under 5 minutes for traffic; RPO of seconds for ordinary tenant data, zero for billing ledger entries.", "p99 latency under 300 ms for API calls from the tenant home geography.", "Blast radius: a bad deploy or poison tenant affects at most one cell (a small fraction of tenants).", "Compliance: data residency, encryption at rest and in transit, auditable access.", "Cost: multi-region overhead within roughly 1.6\u20132x of single-region spend." ] }, estimates: `Assume 5,000 tenants, 2 million monthly active users, about 300k daily active. - **Traffic**: 300k DAU x ~200 API calls/day = 60M calls/day, about 700 req/s average. Peaks are business-hours and regional, so assume a 4x peak in the busiest geography: **~3k req/s** globally at peak, under 1.5k req/s in any one region. Read:write roughly 9:1. - **Error budget**: 99.99% of a 30-day month = 43,200 min x 0.0001 = **~4.3 min**. A single DNS-based failover with a 60 s TTL plus detection time can consume a full month of budget, so failover must be fast and rare, and most failures must be absorbed without failover at all (multi-AZ inside the region). - **Composite availability**: three serial dependencies at 99.95% each give about 99.85%. Hitting 99.99% requires redundancy (two independent regions at 99.9% each, failing independently, give about 99.9999% in theory; correlated failures and failover time make the real figure far lower), so the design must remove serial single-region dependencies. - **Storage**: 5,000 tenants x average 20 GB = **~100 TB total** relational plus object data, split by geography (EU ~35 TB). Replicating each geography to a second region doubles storage: ~200 TB. - **Replication bandwidth**: writes are ~10% of 3k req/s = 300 writes/s x ~2 KB including WAL overhead = ~0.6 MB/s, around 50 GB/day (~1.5 TB/month) of cross-region transfer per direction. At an order-of-magnitude ~$0.02/GB inter-region, database replication is tens of dollars a month; even with object-storage replication and cross-region reads it stays in the low thousands at most: negligible versus compute. - **Cost order of magnitude**: if the single-region footprint is ~$150k/month, active-active pairs per geography with ~50\u201360% headroom (each region must absorb its partner) land at **$240k\u2013300k/month**. The headroom is the real cost, not bandwidth.`, architecture: `The reference design is **geography-pinned cells with a paired-region standby per geography**, plus a thin global control plane. 1. **Global edge**: a global CDN and WAF (anycast or DNS-steered, depending on provider) in front of everything (CloudFront + Shield / Azure Front Door / Cloud CDN + Cloud Armor). TLS terminates at the edge; static assets are cached there. Dynamic requests go to the tenant's home geography. 2. **Routing**: the edge resolves the tenant from the hostname (tenant.example.com) or a signed token claim and looks up a small, globally replicated **tenant directory** (tenant id to geography, cell, active region). The directory is read-mostly, cached at the edge for 30\u201360 s, and must keep working when its own write path is down (static stability). 3. **Geographies and regions**: each geography (EU, US, APAC) has two regions, for example EU-West and EU-Central. Both regions run the full stateless stack; one region is the **write primary** per cell and the other is a warm, scaled standby that serves reads. 4. **Cells**: inside each region tenants are partitioned into cells of ~200\u2013500 tenants, each with its own app tier, database cluster, cache and queue. Cells are the unit of deploy, blast radius and capacity. 5. **Data tier**: per cell, a relational database with synchronous multi-AZ replication inside the region and **asynchronous replication** to the paired region (seconds of lag). Object storage uses cross-region replication within the same geography. Backups are copied to a third location inside the geography, never outside it. 6. **Global control plane**: sign-up, billing aggregation and the tenant directory. It stores only non-residency-scoped metadata, runs active-active across geographies, and is **not on the request path** except through cached directory reads. 7. **Failover**: health is judged per cell from synthetic probes and SLI burn rates across several vantage points. Failover promotes the standby database and flips the directory entry; the edge picks it up within its cache TTL. \`\`\` users --> anycast edge (CDN/WAF, TLS) --> tenant directory (cached) | | | EU geo US geo APAC geo +---------------+ (same shape) (same shape) | EU-West (RW) |<-- async repl --> | EU-Central (RO/standby) | | cells 1..N | | cells 1..N | | app, cache, | | app (warm), replica DB, | | DB primary | | object repl | +---------------+ +-------------------------+ global control plane: signup, billing, directory writes (metadata only) \`\`\``, deepDives: [ { title: "Why not active-active writes everywhere", body: `Multi-master across regions means concurrent writes to the same row in two places, so you need conflict resolution (last-writer-wins silently loses data; CRDTs fit only some data types) or a globally consistent database that pays a cross-region round trip on every write (~10\u201330 ms between nearby regions, ~60\u2013150 ms across a large continent or an ocean, order of magnitude). For B2B SaaS the natural shard key is the tenant, and a tenant's users cluster in one geography, so **single-writer per tenant with fast failover** gives most of the availability benefit without conflicts. Reserve globally consistent storage (distributed SQL such as Spanner, CockroachDB or similar) for the small global control plane where correctness matters more than write latency.` }, { title: "Failover mechanics and avoiding split brain", body: `The dangerous failure is a partial one: the primary region is reachable from some vantage points but not others. Rules: - Decide from **multiple independent observers** (probes from other regions and the edge), requiring a quorum before declaring a region unhealthy. - **Fence the old primary** before promoting the new one: revoke its write credentials or flip it read-only via the control plane, so a recovering zombie cannot accept writes. - Prefer **human-approved, one-command failover** for the data tier and automatic failover for stateless traffic. Automatic database promotion on flaky signals causes more outages than it prevents. - After failover, the old primary rejoins as a replica; any unreplicated writes (the RPO window) are written to a quarantine table and reconciled, not discarded silently.` }, { title: "Data residency done properly", body: `Residency is a data-flow problem, not only a database-placement problem. Inventory every sink: primary DB, replicas, backups, search indexes, caches, logs, traces, analytics exports, support tooling and LLM or third-party processors. Patterns: - Keep the global tier limited to **pseudonymous metadata** (tenant id, geography, plan); anything personal stays in-geo. - Scrub or tokenise personal data before logs and traces leave the geography, or run per-geography observability stacks. - Enforce with policy: organisation-level region restrictions (AWS SCPs / Azure Policy allowed locations / GCP resource-location constraint) and per-geography encryption keys whose key policies forbid use from outside the geography. - A multinational tenant still has one home; remote users pay the latency or get read-only edge caching of non-personal content.` }, { title: "Static stability and dependency hygiene", body: `Failover must not depend on the thing that failed. The failover path should need only data-plane operations that are already provisioned: pre-scaled standby capacity (or capacity reservations), pre-created DNS records, warm connection pools. Control-plane calls in the failing region (create instances, modify load balancers) are the first to break during regional events. Likewise, authentication must not depend on a single-region identity provider: cache signing keys (JWKS) and allow token validation offline for the session lifetime.` } ], tradeoffs: [ { decision: "Regional topology per geography", options: "Active-passive (cold/pilot light) vs warm standby vs active-active with single writer per tenant vs multi-master", choice: `**Warm standby that serves reads, single writer per tenant.** Cold standby cannot meet a 5-minute RTO because scaling from zero under a regional event is unreliable; multi-master adds conflict resolution for little gain when tenants are geographically clustered. Keeping the standby serving real read traffic proves it works every day.` }, { decision: "Traffic steering mechanism", options: "DNS-based failover (health-checked records) vs anycast edge with origin failover vs client-side region lists", choice: `**Anycast edge with origin selection from the tenant directory.** DNS TTLs are not honoured uniformly by resolvers and clients, so DNS failover has a long tail of minutes. Steering at an edge you control shifts traffic in seconds. Keep DNS failover as the backstop if the edge provider itself fails.` }, { decision: "Replication mode to the paired region", options: "Synchronous cross-region commit vs asynchronous replication", choice: `**Asynchronous for tenant data, synchronous only for the billing ledger.** Synchronous commit adds a cross-region round trip (~10\u201330 ms between paired regions in one geography) to every write and couples the primary's availability to the standby. Seconds of RPO is acceptable for ordinary SaaS records if it is written into the SLA; the ledger gets its own quorum-replicated store.` }, { decision: "Cell size", options: "Few large cells vs many small cells", choice: `**Many small cells (hundreds of tenants each).** Smaller blast radius and easier per-cell evacuation, at the cost of more fixed overhead per cell and a routing layer. Large enterprise tenants can get dedicated cells.` }, { decision: "Who triggers failover", options: "Fully automatic vs human-in-the-loop vs hybrid", choice: `**Hybrid.** Stateless traffic shifts automatically on clear signals; database promotion is a single pre-approved command an on-call engineer runs after checking the runbook signals. Budget: detection 1\u20132 min, decision 1 min, execution 1\u20132 min.` } ], failureModes: [ { failure: "Full regional outage of the EU write region", mitigation: `Probes and burn-rate alerts fire; on-call runs the cell-evacuation command: fence the old primary, promote replicas in EU-Central, flip directory entries. Standby already serves reads and is pre-scaled, so only writes see an interruption of a few minutes. Unreplicated writes go to quarantine for reconciliation.` }, { failure: "Partial or grey failure: elevated latency and 5% errors in one AZ", mitigation: `Handled inside the region, not with a regional failover: load balancers eject unhealthy targets via outlier detection, zonal shift drains the AZ, and services are provisioned so the remaining AZs carry full load (static stability: N+1 AZ capacity).` }, { failure: "Bad deploy breaks one cell", mitigation: `Deploys roll cell by cell with bake time and automatic rollback on SLI regression. Only the first (canary) cell is exposed; blast radius is a few percent of tenants.` }, { failure: "Tenant directory write path down", mitigation: `Edges serve the last-known directory from cache and the directory replicas are read-only-capable. New sign-ups queue; existing traffic is unaffected. The directory is designed so stale data is safe for minutes.` }, { failure: "Split brain after a network partition between paired regions", mitigation: `Fencing via the control plane (read-only flag plus credential revocation) before promotion; database writes require a valid lease token checked on commit. Replication monitors alert if two primaries ever exist for one cell.` }, { failure: "Replication lag grows to minutes under a write burst", mitigation: `Alert on lag versus the RPO objective; throttle bulk jobs (imports, migrations) that cause bursts; failover runbook states the expected data-loss window before promotion so the decision is informed.` } ], followUps: [ { q: "How would you prove you meet 99.99%?", a: `Define SLIs per critical journey from the edge (successful requests / valid requests, plus latency-qualified success) and compute availability per tenant cohort, not just aggregate, so a dead cell is not hidden by healthy ones. Alert on multi-window burn rates. Run quarterly regional evacuation game days in production and measure the actual RTO and RPO achieved.` }, { q: "An EU customer\u2019s user travels to Singapore. What happens?", a: `The edge in Singapore terminates TLS and forwards to the EU home region, adding ~150\u2013200 ms round trip, order of magnitude. Static content is cached at the edge. Their data is never stored in APAC; if latency is unacceptable we can optimise the protocol (fewer round trips, HTTP/2 or HTTP/3 to the edge with pooled connections behind it), not move the data.` }, { q: "How do you migrate from today\u2019s single region without a big bang?", a: `First move to multi-AZ and cells inside the current region, introducing the tenant directory and routing layer. Then stand up the paired region as a read replica target and run read traffic there. Then migrate EU tenants cell by cell to EU regions using logical replication and a short per-tenant write freeze. Finally rehearse failover per cell before declaring the SLO.` }, { q: "What if the CDN/edge provider itself has an outage?", a: `It is now a serial dependency, so it needs a fallback: keep regional load balancer endpoints with valid certificates, and a pre-tested DNS change (low TTL on the apex record) that bypasses the edge, accepting lost WAF/caching for the duration. Some companies run two CDN providers with DNS steering; that doubles configuration complexity and is only justified at large scale.` }, { q: "How do you keep the standby region from rotting?", a: `Make it serve production reads, deploy to it in the same pipeline, include it in every config change, and periodically flip the primary for a few cells so both directions are exercised. Capacity drift is caught by load tests that replay the partner region\u2019s peak.` } ], rubric: [ { area: "Requirements & scoping", signals: [ "Converts 99.99% into ~4.3 minutes per month and notes that failover time itself consumes budget.", "Asks what residency covers beyond the primary database (backups, logs, support tooling).", "Separates data needing RPO 0 (ledger) from data that tolerates seconds." ] }, { area: "Architecture", signals: [ "Uses tenant as the partition key with a home geography and single writer per tenant.", "Introduces cells to bound blast radius and a cached, statically stable routing directory.", "Keeps the global control plane off the hot path." ] }, { area: "Reliability & failure", signals: [ "Distinguishes AZ-level handling from regional failover; does not fail over regions for grey failures.", "Addresses split brain with fencing and multi-vantage health decisions.", "Pre-provisions standby capacity rather than relying on control-plane scale-up during an event." ] }, { area: "Security & compliance", signals: [ "Enforces residency with organisation policies and geography-scoped encryption keys.", "Treats observability data and third-party processors as residency scope." ] }, { area: "Operations & cost", signals: [ "Identifies headroom (not bandwidth) as the dominant cost of multi-region.", "Plans game days that measure actual RTO/RPO.", "Gives an incremental migration path with checkpoints." ] }, { area: "Communication", signals: [ "States the chosen design first, then defends it against alternatives.", "Quantifies latency and cost claims as order-of-magnitude estimates." ] } ], references: [ { title: "AWS Builders\u2019 Library: Static stability using Availability Zones", url: "https://aws.amazon.com/builders-library/static-stability-using-availability-zones/" }, { title: "Google SRE Book: Service Level Objectives", url: "https://sre.google/sre-book/service-level-objectives/" }, { title: "AWS Well-Architected Framework", url: "https://aws.amazon.com/architecture/well-architected/" }, { title: "Azure Architecture Center: Cloud design patterns", url: "https://learn.microsoft.com/en-us/azure/architecture/patterns/" } ] }, // --------------------------------------------------------------------------- // 2. Observability pipeline // --------------------------------------------------------------------------- { id: "sd-observability-pipeline", title: "Centralized observability platform for 500 services", difficulty: "staff", topics: ["obs-signals", "dist-messaging", "storage-types", "arch-finops", "compute-scaling"], prompt: `"We have about 500 microservices across several Kubernetes clusters and some VMs. Every team ships logs, metrics and traces differently, our vendor bill doubled last year, and during the last big incident our logging system fell over exactly when we needed it. We ingest roughly **2 TB of logs a day**. Design a centralized observability platform: logs, metrics and traces, with sensible retention, cost control, and protection against cardinality explosions."`, clarifyingQuestions: [ "What are the query patterns: incident debugging over the last few hours, compliance search over a year, or analytics? Who are the users and how many concurrent queries?", "What retention is required by compliance (audit/security logs) versus what teams want for debugging?", "How many active metric time series do we have today, and what scrape interval? Do we know the top offenders?", "Do we want to build on open source, stay with a vendor, or a hybrid (self-hosted for logs, vendor for APM)?", "Is there sensitive data in logs (PII, tokens) that must be redacted before storage?", "What is the freshness requirement: how quickly must a log line or metric be queryable after it is emitted?", "Is the platform multi-region, and must telemetry stay in region for residency?", "What is the cost target: a percentage of infrastructure spend, or an absolute budget?" ], requirements: { functional: [ "Collect logs, metrics and traces from Kubernetes, VMs and managed services through one standard (OpenTelemetry SDKs and collectors).", "Query recent logs by service, time, trace id and free text; query metrics with a PromQL-compatible language; view traces and jump between signals via trace and exemplar links.", "Alerting on metrics (SLO burn rates) and log-derived metrics, routed to owning teams.", "Tiered retention: hot, warm, archive; legal hold for audit logs.", "Per-team quotas, cost showback, and guardrails against cardinality explosions." ], nonFunctional: [ "Ingest available 99.9%+ and decoupled from query: the pipeline must not drop data during incidents when volume spikes 3\u20135x.", "Freshness: logs searchable within ~30 s, metrics within ~1 scrape interval, traces within ~1 min.", "Query: recent-window log search p95 under 5 s; dashboard queries under 2 s.", "Cost: total observability spend under ~10% of infrastructure spend (a common rule of thumb target).", "Security: PII redaction at the edge, per-team access control, immutable audit logs." ] }, estimates: `- **Logs**: 2 TB/day / 86,400 s = **~23 MB/s average**; incident peaks of 3x give ~70 MB/s. At ~500 bytes per line that is ~46k lines/s average, ~140k lines/s peak. - **Log storage**: typical compression for logs on columnar or chunked storage is ~5\u201315x; assume 8x, so ~250 GB/day compressed. Hot 7 days on fast storage = ~1.75 TB (x replication factor 2\u20133 = ~3.5\u20135 TB). Warm to 30 days in object storage = ~7.5 TB. Archive 1 year of audit/security logs only (say 10% of volume) = ~9 TB in cold object storage. - **Metrics**: 500 services x ~20 instances x ~1,000 series each = **~10M active series**. At a 30 s scrape that is ~330k samples/s. With compressed TSDB encoding at roughly 1\u20132 bytes per sample, that is ~30\u201360 GB/day before downsampling. - **Traces**: assume 20k req/s at the edge, ~10 spans per request, ~1 KB/span = 200 MB/s unsampled, which is 17 TB/day: more than all the logs. Tail-based sampling keeping errors, slow requests and ~1% of normal traffic brings it to **~3\u20135 MB/s**, a few hundred GB/day. - **Buffer**: a Kafka-style buffer sized for 6 h of peak log ingest = 70 MB/s x 21,600 s = ~1.5 TB per replica, ~4.5 TB at replication factor 3. - **Cost order of magnitude**: object storage at ~$0.02/GB-month for ~20 TB is ~$400/month; the expense is compute for indexing and query, plus the buffer. A self-hosted stack at this scale is plausibly **$30k\u201380k/month** all-in; a per-GB-ingest commercial tool at list prices is often several times that, which is why volume reduction pays off before anything else.`, architecture: `The platform is a **collect, buffer, process, store, query** pipeline per signal, with a common OpenTelemetry front end. 1. **Collection**: services use OpenTelemetry SDKs; a node-level collector (DaemonSet) tails container stdout, receives OTLP, adds Kubernetes metadata (cluster, namespace, pod, team label), and does **first-pass redaction and drop rules**. Metrics are scraped or pushed via OTLP; managed cloud services export via their native log/metric sinks. 2. **Gateway collectors**: a horizontally scaled gateway tier per cluster or region enforces per-team rate limits and quotas, performs tail-based trace sampling (all spans of a trace must reach the same gateway, so route by trace id), and writes to the buffer. 3. **Buffer**: a durable log (Kafka or a managed equivalent: Amazon MSK / Azure Event Hubs / Google Cloud Managed Service for Apache Kafka or Pub/Sub) with topics per signal and team tier. It absorbs incident spikes and decouples ingest from storage outages. 4. **Processing**: stream processors parse, enrich, derive metrics from logs (error counts per service), route audit logs to an immutable store, and route by retention class. 5. **Storage**: - Logs: a label-indexed, chunk-on-object-storage store (Loki-style) for most logs, or a search index (OpenSearch/Elasticsearch-style) only for the subset needing full-text search; chunks live in object storage. - Metrics: Prometheus-compatible long-term store with object-storage blocks (Thanos/Mimir/Cortex-style). Where the backend supports downsampling (e.g. the Thanos compactor), keep 5 min resolution after ~2 weeks and 1 h after ~3 months; otherwise use recording rules for long-range aggregates. - Traces: span store on object storage indexed by trace id, with exemplars linking metrics to traces. - Archive: compressed Parquet or raw files in cold object storage with lifecycle policies. 6. **Query and alerting**: a query frontend with caching, per-tenant query limits and result-size caps; dashboards; rule evaluation for alerts, separated from ad-hoc query capacity. 7. **Meta-monitoring**: the platform is watched by a small, independent stack (different cluster, minimal dependencies), because it cannot alert on its own death. \`\`\` apps (OTel SDK) -> node collector -> gateway (quota, sampling) -> buffer (Kafka) redact/drop by trace id | +---------------+-------------+ v v v log ingesters metric ingesters trace ingesters \\_______ object storage (hot cache + blocks) ___/ | query frontend / rules / alerting -> on-call independent meta-monitoring watches pipeline lag, drops, ingest errors \`\`\``, deepDives: [ { title: "Cardinality control", body: `Metric cost scales with **active series**, and a series is a unique combination of label values. One engineer adding a user_id or request path label to a histogram with 10 buckets across 200 pods can create millions of series in minutes and take down ingesters. Controls, layered: - **Prevention**: lint instrumentation in CI (no unbounded labels), and an allow-list of labels per metric for high-volume services. - **Enforcement**: per-team series limits at the gateway and ingesters; reject new series beyond the limit while keeping existing ones flowing, and alert the owning team. - **Visibility**: a daily top-N report of series by metric and label, attributed to teams; showback of series counts. - **Redirection**: high-cardinality questions (per-user, per-request) belong in traces or logs, which are priced per event not per series.` }, { title: "Surviving the incident spike", body: `Telemetry volume is correlated with outages: error logs multiply, retries amplify, and engineers start running heavy queries simultaneously. Design for it: - Buffer sized for hours of peak so storage can fall behind without losing data; alert on consumer lag rather than dropping. - **Priority classes**: audit and error-level logs in a protected tier; debug-level logs from a misbehaving service are rate-limited first. - Separate **write path and read path** capacity, so a thundering herd of queries cannot starve ingest; per-user query concurrency limits and query cost estimation reject accidental full-scans. - Log sampling or deduplication for identical repeated lines (counts instead of copies) at the collector.` }, { title: "Retention tiers and the cost model", body: `Most log reads happen within hours of writing; most stored bytes are never read. So pay for indexing only where it is used: - **Hot** (1\u20137 days): fast storage and caches, full query capability. - **Warm** (to 30 days): object storage with label indexes; slower queries are acceptable. - **Archive** (to 1\u20137 years, audit only): object storage cold tiers with rehydration in hours; legal hold via object lock (S3 Object Lock / Azure immutable blob storage / GCS retention policies and bucket lock). Default retention is short; longer retention is an explicit, charged choice per stream. The biggest single lever is usually **not ingesting** low-value data: debug logs in production, health-check access logs, and duplicate logging of the same event by sidecars and apps.` }, { title: "Tail-based sampling at scale", body: `Head sampling (decide at the root span) is cheap but discards the rare interesting traces. Tail sampling waits until a trace completes, then keeps errors, slow traces and a baseline percentage. The constraint is that all spans of a trace must meet in one place: route spans by trace id hash to a sampling tier, hold traces in memory for a decision window (~10\u201330 s), and size memory for spans/s x window. Late spans after the decision are dropped or kept by a cached decision. Keep a consistent probability-based baseline so you can still compute rates from sampled data.` } ], tradeoffs: [ { decision: "Log storage engine", options: "Full-text inverted index for all logs vs label index plus chunked object storage vs columnar analytics store", choice: `**Label-indexed chunks on object storage as the default, full-text index for a small, high-value subset** (security, audit). Full-text indexing everything at 2 TB/day multiplies storage and compute several times; most debugging starts from service, time and trace id. A columnar store (ClickHouse-style) is a strong alternative when teams run aggregations over logs.` }, { decision: "Build versus buy", options: "Commercial SaaS for everything vs self-hosted open source vs hybrid", choice: `**Hybrid with OpenTelemetry as the contract.** Standardising on OTel collectors makes the backend swappable. Self-host high-volume, low-value-per-byte logs and metrics; consider a vendor for APM/tracing UX where engineer time matters more. Self-hosting needs a team of several engineers, which must be in the cost comparison.` }, { decision: "Buffer between collectors and storage", options: "Direct write from collectors vs durable log buffer", choice: `**Durable buffer.** It adds latency (seconds) and an operationally heavy component, but it is what keeps data during storage outages and spikes and allows replay after a bad processor deploy.` }, { decision: "Where to drop and redact", options: "At the source/collector vs centrally in processing", choice: `**As close to the source as possible.** Every byte dropped at the node saves network, buffer and storage, and PII redacted at the node never lands anywhere. Central processing still applies a second, policy-driven redaction pass.` }, { decision: "Metrics scrape interval", options: "10 s vs 30 s vs 60 s", choice: `**30 s default, 10 s opt-in for critical SLIs.** Moving from 30 s to 10 s triples samples and storage for marginal benefit on most dashboards; alerting windows are minutes anyway.` } ], failureModes: [ { failure: "Cardinality explosion from one deploy", mitigation: `Per-team series limits reject new series beyond quota; ingesters stay healthy; the owning team gets an alert naming the metric and label. Existing series and other teams are unaffected.` }, { failure: "Log storage backend unavailable for an hour", mitigation: `Buffer holds hours of peak ingest; consumers resume and catch up at a rate higher than ingest (size consumers for ~2x peak). Alert on lag; query users are told data is delayed, not lost.` }, { failure: "Runaway query scans 30 days of logs during an incident", mitigation: `Query frontend estimates cost and rejects or splits it; per-user concurrency limits; read path is isolated from ingest so writes keep flowing.` }, { failure: "Collector DaemonSet crash-loops after a config change", mitigation: `Roll collector config progressively by cluster; collectors buffer to local disk; the kubelet keeps rotated container log files on node disk so tailing resumes from the last checkpoint, but rotation limits (a few files of ~10 MiB by default) mean chatty pods can lose lines during a long outage.` }, { failure: "Secrets or PII leak into logs", mitigation: `Redaction rules at the collector for known patterns (tokens, card numbers, emails); detection jobs scan stored logs and alert; access to raw log streams is per team; deletion runbook for purging affected chunks.` }, { failure: "The observability platform itself fails silently", mitigation: `Independent meta-monitoring on separate infrastructure tracks end-to-end freshness by injecting synthetic canary log lines and metrics and alerting if they do not appear within the freshness SLO.` } ], followUps: [ { q: "How do you cut the bill by 40% next quarter?", a: `Measure first: top 20 log streams and metrics by volume per team. Then the usual order of impact: drop debug and health-check logs in production, deduplicate sidecar plus app logging, shorten default hot retention, turn high-cardinality metric labels into trace attributes, tail-sample traces, and downsample old metrics. Showback per team makes the reductions stick.` }, { q: "Logs, metrics or traces: which do you alert on?", a: `Primarily metrics, specifically SLO burn rates on symptoms users feel, because they are cheap to evaluate and stable. Log-derived metrics fill gaps for systems without instrumentation. Traces are for diagnosis, not alerting. Alerting on raw log patterns is brittle and noisy.` }, { q: "How do you make the platform multi-tenant across 500 services?", a: `Tenant equals team: every signal carries a team label injected from namespace metadata at the collector, not trusted from the app. Quotas, retention classes, access control and showback are per tenant. Query isolation through per-tenant limits in the query frontend.` }, { q: "What SLOs would you set for the observability platform itself?", a: `Ingest availability (accepted / sent), end-to-end freshness (p99 time from emit to queryable under 60 s), query availability and latency for the hot window, and alert evaluation delay. Freshness matters most: stale data during an incident is worse than slow queries.` } ], rubric: [ { area: "Estimation", signals: [ "Converts 2 TB/day to ~23 MB/s and plans for 3\u20135x incident peaks.", "Estimates active series and recognises traces unsampled can exceed log volume.", "Applies compression ratios and tiering to storage estimates." ] }, { area: "Architecture", signals: [ "Uses OpenTelemetry as a vendor-neutral collection contract.", "Places a durable buffer between collection and storage.", "Separates read and write paths and uses object storage as the durable tier." ] }, { area: "Reliability & failure", signals: [ "Designs for telemetry spikes that coincide with outages.", "Adds independent meta-monitoring with synthetic freshness canaries.", "Handles cardinality explosion without impacting other tenants." ] }, { area: "Operations & cost", signals: [ "Identifies volume reduction at the source as the biggest cost lever.", "Proposes per-team quotas and showback.", "Includes team headcount in build versus buy." ] }, { area: "Security", signals: [ "Redacts PII at the collector and controls access per team.", "Uses immutable storage for audit logs with legal hold." ] } ], references: [ { title: "OpenTelemetry documentation", url: "https://opentelemetry.io/docs/" }, { title: "Google SRE Book: Monitoring Distributed Systems", url: "https://sre.google/sre-book/monitoring-distributed-systems/" }, { title: "Google SRE Workbook: Alerting on SLOs", url: "https://sre.google/workbook/alerting-on-slos/" }, { title: "FinOps Framework", url: "https://www.finops.org/framework/" } ] }, // --------------------------------------------------------------------------- // 3. CI/CD platform // --------------------------------------------------------------------------- { id: "sd-ci-cd-platform", title: "Internal CI/CD and deployment platform for 200 teams", difficulty: "staff", topics: ["auto-delivery", "sec-supply-chain", "compute-scaling", "compute-platform", "arch-finops"], prompt: `"We have about 200 engineering teams, a mix of monorepo and polyrepo, deploying to Kubernetes and some serverless. Today every team maintains its own Jenkins and scripts, builds are slow, nobody can tell me what is actually running in production, and the security team is worried after a few public supply-chain attacks. Design an internal CI/CD and deployment platform: build isolation, caching, supply-chain security and progressive delivery."`, clarifyingQuestions: [ "How many engineers, commits and pipeline runs per day, and what is the current median and p95 build time?", "Which languages and build systems, and is there a monorepo with a hermetic build tool (Bazel-style) or many repos with heterogeneous tooling?", "What are the deployment targets and how many environments (dev, staging, prod, per region)?", "What compliance regime applies (SOC 2, PCI, FedRAMP-like): is two-person review and provenance required for production?", "Do builds need access to internal networks or secrets, and do any teams build on special hardware (GPUs, macOS, ARM)?", "Is the platform a mandate or must it win adoption? What is the migration timeline?", "Do we use a hosted SCM (GitHub/GitLab-style) and is a hosted runner offering acceptable, or must runners be in our cloud accounts?", "What is the target for deployment frequency and change failure rate?" ], requirements: { functional: [ "Pipeline-as-code templates (golden paths) teams can extend but not bypass for required controls.", "Ephemeral, isolated build runners with autoscaling; remote build cache and dependency proxy.", "Artifact registry for images and packages with signing, SBOMs and build provenance attestations.", "Admission policy that only signed, provenance-verified artifacts from the platform reach production.", "Progressive delivery: canary or blue/green with automated analysis and rollback; GitOps-based deployment state per environment.", "Inventory: which commit, image and config is running in every cluster and region." ], nonFunctional: [ "Median CI time under 10 minutes for a typical service; queue time p95 under 1 minute.", "Platform availability 99.9% during business hours; deploys must not be blocked for long by platform outages (break-glass path).", "Isolation: one team\u2019s build cannot read another team\u2019s secrets or poison shared caches.", "Supply chain: aim for SLSA Build Level 3-style properties (hardened, isolated build platform producing non-forgeable provenance).", "Cost visibility per team; compute cost per build tracked." ] }, estimates: `- **Load**: 200 teams x ~8 engineers = ~1,600 engineers. ~4 pushes per engineer per day = ~6,400 pipeline runs/day, plus main-branch and scheduled runs, call it **~8k pipelines/day**. Average 6 jobs per pipeline = ~50k jobs/day. - **Concurrency**: work concentrates in ~8 business hours; 50k jobs / 8 h = ~6k jobs/h average, and the peak hour is ~2x that, ~12k jobs/h. With an average job of 6 minutes, peak concurrency (Little's law) = 12k x 0.1 h = **~1,200 concurrent jobs**; plan for ~2k to absorb release-day and merge-queue bursts. - **Compute**: at 4 vCPU per job that is ~5\u20138k vCPU at peak and much less overnight, which suits autoscaled, largely spot/preemptible capacity. ~50k jobs x 6 min x 4 vCPU = ~20k vCPU-hours/day. At an order-of-magnitude ~$0.02\u20130.04 per vCPU-hour on spot, that is **~$400\u2013800/day**, roughly $12\u201324k/month; on-demand is ~2\u20133x. - **Cache and artifacts**: remote build cache sized ~5\u201320 TB with LRU eviction; images ~8k builds/day x a few hundred MB of new layers would be large, but layer deduplication keeps net growth to perhaps 100\u2013300 GB/day; retention policies prune untagged images after 30\u201390 days. - **Egress**: dependency downloads dominate; a pull-through proxy with ~90% hit ratio cuts external egress and protects against upstream outages. - **Value**: shaving 5 minutes off 8k pipelines/day saves 40k engineer-minutes of waiting per day if someone waits on each, which dwarfs runner cost. This is the argument for paying for caching and bigger runners.`, architecture: `1. **Source and triggers**: the SCM sends webhooks to a pipeline orchestrator (GitHub Actions, GitLab CI, Buildkite, Tekton or similar). Pipelines are defined in repo but must **include platform-owned templates** for build, test, scan, sign and publish; required checks are enforced by branch protection. 2. **Runner fleet**: ephemeral runners, one job per fresh VM or microVM (or a Kubernetes pod in a dedicated, hardened build cluster with sandboxed runtimes), autoscaled from queue depth. Separate pools per trust level: untrusted (forks, PRs), trusted (main branch, release) and privileged (signing). No long-lived runners, no Docker socket sharing. 3. **Identity**: runners get short-lived credentials through OIDC federation with the cloud (AWS IAM roles for OIDC / Azure workload identity federation / GCP Workload Identity Federation), scoped by repo, branch and environment. No static cloud keys in CI secrets. 4. **Caching**: remote build cache (content-addressed) with write access only from trusted main-branch builds, read for everyone; dependency pull-through proxies for language registries and base images; per-pool layer caches. 5. **Supply chain**: builds produce an image, an SBOM, vulnerability scan results and **signed provenance** (who built what, from which commit, with which builder). Signing uses keyless Sigstore-style signing tied to the workload identity, or KMS-held keys. Artifacts land in a registry (ECR / ACR / Artifact Registry) with immutable tags. 6. **Deployment**: the pipeline does not push to clusters. It opens a change to an environment config repo (GitOps); an in-cluster agent (Argo CD / Flux) reconciles. A progressive delivery controller (Argo Rollouts / Flagger) runs canaries with metric analysis against SLOs. 7. **Admission**: cluster admission policy (Kyverno, OPA Gatekeeper or the provider's binary authorization feature) verifies the signature and provenance and rejects unsigned images or images from outside the platform registry. 8. **Inventory and audit**: deployment events and the GitOps repos give a queryable record of what runs where. \`\`\` dev push -> SCM -> orchestrator -> ephemeral runner (OIDC creds, sandbox) | build/test (remote cache, dep proxy) | SBOM + scan + sign + provenance v registry (immutable) --> env config repo (PR) | cluster: GitOps agent -> rollout controller (canary, analysis) admission policy verifies signature + provenance \`\`\``, deepDives: [ { title: "Build isolation and trust tiers", body: `CI is remote code execution as a service. A pull request from any contributor runs arbitrary code, so: - **Ephemeral per-job environments**: a fresh VM or microVM (Firecracker-style) or sandboxed pod per job; nothing persists between jobs except through explicit, verified caches. - **Trust tiers**: PR builds run without secrets and without write access to caches or registries; main-branch builds can publish; signing and production deploy credentials live in a separate, minimal pool. - **Network egress control**: builds reach the internet only through the dependency proxy, which blocks exfiltration paths and pins what comes in. - **Credential scoping**: OIDC tokens carry repo, ref and workflow claims so a cloud role trusts only main branch of one repo. A common mistake is trusting the whole organisation in the federation condition.` }, { title: "Supply-chain security end to end", body: `Map controls to where attacks happen: source (compromised account, malicious commit), build (tampered builder, poisoned cache), dependencies (typosquats, compromised packages), and distribution (registry tampering). - Source: mandatory review, signed commits or verified SCM identity, protected branches. - Build: platform-owned hardened builders producing provenance the tenant job cannot forge, which is the essence of SLSA Build L3. - Dependencies: lockfiles, pull-through proxy with allow/deny policy, SBOMs, and continuous scanning so new CVEs against already-deployed images raise alerts. - Distribution: signatures and attestations verified at admission; immutable tags; deploy by digest. Prioritise by risk: OIDC instead of static keys and admission verification usually deliver more than perfect SBOM coverage.` }, { title: "Caching without poisoning", body: `A shared cache is a shared attack surface: if a PR build can write a cache entry keyed by an action's inputs, it can plant a malicious artifact for main. Rules: cache entries are content-addressed by hashed inputs; **only trusted builders write**; PR builds read from the trusted cache and write to a per-PR scratch namespace. Hermetic builds make caching correct; non-hermetic steps (network fetches, timestamps) must be excluded or the cache hit rate collapses and correctness suffers. Track hit rate per repo; a falling hit rate is the leading indicator of slower builds.` }, { title: "Progressive delivery with automated analysis", body: `For a typical service: deploy to one region's canary at ~5% of traffic, compare error rate and latency of canary versus baseline (not versus a fixed threshold, because absolute values move with load), bake for 10\u201330 minutes, then step to 25%, 50%, 100%, region by region. Rollback is automatic on analysis failure. Prerequisites teams forget: backward-compatible database migrations (expand then contract), feature flags to separate deploy from release, and enough traffic in the canary for statistical signal; low-traffic services need longer bakes or synthetic load.` } ], tradeoffs: [ { decision: "Runner isolation unit", options: "Long-lived shared VMs vs container per job on shared nodes vs VM/microVM per job", choice: `**VM or microVM per job for untrusted and trusted tiers**, accepting ~10\u201360 s boot overhead (mitigated by warm pools). Containers on shared nodes share a kernel, and privileged Docker-in-Docker builds are effectively host access. Long-lived runners leak state between jobs.` }, { decision: "Push-based deploys from CI vs GitOps pull", options: "CI holds cluster credentials and applies manifests vs in-cluster agent reconciles from a config repo", choice: `**GitOps pull.** CI never holds production cluster credentials, desired state is auditable and diffable, and drift is corrected. Cost: an extra hop and some latency, plus secret handling in Git needs encryption or external secret references.` }, { decision: "Central templates vs team freedom", options: "Fully standardised pipelines vs fully custom vs required-steps-plus-extension", choice: `**Required platform steps with extension points.** Compliance controls (scan, sign, provenance) are non-bypassable; teams customise test stages. A mandate with no flexibility drives shadow pipelines.` }, { decision: "Hosted runners vs self-hosted in our accounts", options: "Vendor-hosted runners vs self-hosted autoscaled fleet", choice: `**Self-hosted for builds needing internal network access or large volume; hosted for public/open-source repos.** Self-hosting gives network control, spot pricing and larger machines but adds an ops burden for the fleet.` }, { decision: "Blocking on vulnerability scans", options: "Block on any CVE vs block on critical exploitable vs report only", choice: `**Block new critical/high vulnerabilities with a fix available in production paths; report the rest with SLAs.** Blocking on everything trains teams to bypass; report-only never fixes anything.` } ], failureModes: [ { failure: "Orchestrator or SCM outage blocks all deploys, including an urgent fix", mitigation: `Documented break-glass path: an audited, two-person-approved manual promotion of an already-built, signed artifact via the GitOps repo. Rollbacks are a revert in the config repo and do not need CI.` }, { failure: "Runner fleet cannot scale (spot capacity exhausted)", mitigation: `Diversify across instance types and zones, fall back to on-demand for the trusted and release tiers, and keep a small warm pool. Queue time is an SLI with alerts.` }, { failure: "Poisoned cache or compromised dependency", mitigation: `Trusted-writer-only caches, content addressing, proxy allow-lists, SBOM search to find every image containing a bad package within minutes, and the ability to purge cache namespaces.` }, { failure: "Leaked CI credential", mitigation: `Short-lived OIDC tokens limit the window; roles scoped to repo and branch limit blast radius; secret scanning on logs and commits; audit trail of every assume-role.` }, { failure: "Canary passes, then failure at 100% (load-dependent bug)", mitigation: `Step-wise rollout with analysis at each step, region-by-region waves, and quick rollback by revert. Long-tail metrics (memory growth, saturation) included in analysis, not only error rate.` }, { failure: "Admission policy blocks all deploys after a signing key or policy change", mitigation: `Roll policy changes in audit mode first, then enforce per cluster; monitor admission denials; keep a time-boxed emergency exemption controlled by the platform team with audit.` } ], followUps: [ { q: "How do you measure whether the platform is succeeding?", a: `DORA-style metrics per team (deployment frequency, lead time for changes, change failure rate, time to restore), plus platform SLIs: queue time, median build time, cache hit rate, and adoption percentage. Survey developer satisfaction quarterly. Cost per pipeline run tracked over time.` }, { q: "How do you migrate 200 teams off their own Jenkins?", a: `Start with a few willing teams and make the golden path visibly faster. Provide automated converters for common pipeline shapes, keep a compatibility period, and then make the new admission policy (signed artifacts only) the forcing function for production, with clear dates and office hours. Retire old infrastructure per team, not all at once.` }, { q: "Monorepo: how do you keep CI time flat as it grows?", a: `Build only what changed using a dependency graph (Bazel/Pants/Nx-style affected-target detection), remote caching and remote execution for parallelism, test sharding, and a merge queue that batches commits to keep main green without serialising every PR.` }, { q: "What does SLSA actually buy you here?", a: `A shared vocabulary for build integrity. Build L1 is provenance existing; L2 is signed provenance from a hosted build platform; L3 adds hardened builders where tenant jobs cannot tamper with provenance or each other. The Build track does not by itself cover source review (SLSA's separate, newer Source track addresses that) or dependency trust, so it is one layer, not the whole programme.` } ], rubric: [ { area: "Requirements & scoping", signals: [ "Asks about compliance, trust model for contributors and deployment targets before designing.", "Defines success with delivery metrics and build/queue SLIs." ] }, { area: "Estimation", signals: [ "Derives peak concurrent jobs from pipelines/day and job duration.", "Compares runner cost to engineer waiting time.", "Sizes caches and registry growth with retention." ] }, { area: "Architecture", signals: [ "Ephemeral per-job isolation with trust tiers.", "GitOps pull-based deployment with progressive delivery controller.", "Admission-time verification of signatures and provenance." ] }, { area: "Security", signals: [ "Uses OIDC federation scoped to repo and branch instead of static keys.", "Prevents cache poisoning by restricting cache writes to trusted builds.", "Maps controls to source, build, dependency and distribution threats." ] }, { area: "Operations & cost", signals: [ "Plans a break-glass deploy path for platform outages.", "Uses spot capacity with fallbacks and warm pools.", "Has an adoption and migration plan, not just a target state." ] } ], references: [ { title: "SLSA: Supply-chain Levels for Software Artifacts", url: "https://slsa.dev/" }, { title: "Sigstore", url: "https://sigstore.dev/" }, { title: "Open Policy Agent documentation", url: "https://www.openpolicyagent.org/docs/latest/" }, { title: "AWS Builders\u2019 Library", url: "https://aws.amazon.com/builders-library/" } ] }, // --------------------------------------------------------------------------- // 4. Multi-tenant Kubernetes // --------------------------------------------------------------------------- { id: "sd-k8s-multitenant", title: "Secure multi-tenant Kubernetes platform", difficulty: "staff", topics: ["compute-platform", "sec-identity", "net-cloud", "arch-finops", "auto-iac"], prompt: `"Our platform team runs Kubernetes for about 150 internal product teams, and we are now asked to also run workloads for some external customers who bring their own code. Today it is a handful of big shared clusters with namespaces per team and not much else. Design a secure multi-tenant Kubernetes platform. I want to hear how you decide between namespaces and dedicated clusters, how you enforce policy, how you handle upgrades, and how you allocate cost."`, clarifyingQuestions: [ "Which tenants are trusted (internal teams, same security boundary) and which are untrusted (external customer code)? Is untrusted code expected to be actively hostile?", "How many tenants, workloads and nodes, and how fast is it growing?", "Do tenants need cluster-scoped resources: CRDs, operators, admission webhooks, cluster roles?", "What compliance requirements apply (PCI, HIPAA, customer contracts requiring dedicated infrastructure)?", "Do tenants need network isolation from each other and controlled access to shared services or on-prem networks?", "What is the upgrade tolerance: can tenants accept a platform-driven upgrade window, and how much do workloads rely on deprecated APIs?", "Do we use a managed control plane (EKS/AKS/GKE) or run our own?", "Should cost be shown back or charged back, and at what granularity?" ], requirements: { functional: [ "Self-service tenant onboarding: create namespace(s) or cluster, quotas, RBAC, network policy and identity bindings from a declarative request.", "Two isolation tiers: soft multi-tenancy for internal teams, hard isolation for untrusted external workloads.", "Central policy enforcement: pod security, image provenance, resource limits, allowed registries, labelling.", "Fleet management: provisioning, upgrades and add-on lifecycle for many clusters through GitOps and IaC.", "Per-tenant cost allocation including shared overhead." ], nonFunctional: [ "Security: a compromised internal tenant cannot escalate to cluster admin or reach other tenants\u2019 secrets; an untrusted tenant cannot escape to the node or reach other tenants\u2019 network.", "Noisy-neighbour control: one tenant cannot exhaust API server, node or network capacity for others.", "Upgrades: stay within the supported Kubernetes minor versions, upgrading each cluster at least every few months without tenant downtime.", "Platform API availability 99.9%; workload availability depends on tenants spreading across zones.", "Cost overhead of the platform under ~15% of tenant compute." ] }, estimates: `- **Fleet**: 150 internal teams averaging ~40 pods = ~6k pods; with ~30 pods per node (well below the default 110 max pods per node, because CPU/memory bind first), that is ~200 nodes. Kubernetes' documented scalability envelope is up to ~5,000 nodes and ~150,000 pods per cluster, so size is not what forces multiple clusters; blast radius, upgrades and isolation are. - **External tenants**: say 50 customers growing to 500. Cluster-per-tenant at ~3 small nodes plus a managed control plane fee (order of ~$70/month per cluster on standard managed tiers, several times that on extended-support or premium tiers; provider-dependent) costs ~$500\u20131,500/month per tenant floor; 500 tenants is ~$250k\u2013750k/month before real workload. Virtual clusters or sandboxed node pools reduce the floor substantially. - **API server load**: each controller, operator and CI system watches the API. 150 teams each running a few operators can be thousands of watches; API priority and fairness and per-tenant client rate limits matter more than node count. - **IP space**: 6k pods plus headroom with VPC-native pod IPs need a /19 or larger for pods (8k addresses) per cluster; plan CIDRs early, because exhausting pod IP space is a common scaling wall. Size by nodes x per-node allocation, not pod count: many CNIs reserve a block per node (GKE reserves a /24 per node at the default 110 max pods), so 200 nodes can need a /16 of pod range. - **Cost allocation**: allocate node cost by max(requests, usage) per pod; idle capacity (often 20\u201340% in poorly tuned clusters) and system overhead are distributed proportionally or charged to the platform budget.`, architecture: `The design is a **tiered fleet**: shared clusters with namespace tenancy for trusted internal teams, and hard-isolated capacity for untrusted tenants, all managed as one fleet. 1. **Tenant model**: a tenant is a declarative object in Git (team, cost centre, tier, quotas, allowed namespaces, network exposure). A platform controller or IaC pipeline renders it into namespaces, RBAC RoleBindings, ResourceQuota, LimitRange, NetworkPolicy, cloud identity bindings and cost labels. 2. **Tier 1, soft multi-tenancy (internal)**: a few shared clusters per region and environment. Isolation per namespace: restricted Pod Security Standard enforced by Pod Security Admission, default-deny NetworkPolicy, namespace-scoped RBAC only, per-namespace workload identity (IRSA or EKS Pod Identity / Microsoft Entra Workload ID / Workload Identity Federation for GKE) so pods get only their own cloud permissions, quotas on CPU, memory, pods, services and load balancers. 3. **Tier 2, hard multi-tenancy (untrusted)**: either **cluster per tenant** for high-value or compliance-bound customers, or **dedicated node pools per tenant with sandboxed runtimes** (gVisor or Kata Containers via RuntimeClass), taints and tolerations, no shared nodes, strict egress policy, and no access to the Kubernetes API from tenant pods unless explicitly needed. Where tenants need their own CRDs or admin experience, virtual control planes (vCluster-style) on a host cluster give API-level isolation at lower cost than full clusters. 4. **Policy layer**: admission policies (Kyverno or OPA Gatekeeper, or built-in ValidatingAdmissionPolicy) for allowed registries, signed images, required labels, no hostPath/hostNetwork/privileged, required requests and limits. Policies ship from a central repo in audit mode first, then enforce. 5. **Fleet management**: clusters defined in Terraform or Cluster API; add-ons (CNI, ingress, cert manager, policy engine, observability agents) deployed by GitOps with fleet-wide rollout waves. 6. **Networking**: CNI with NetworkPolicy enforcement, per-tenant ingress hostnames, egress gateways or firewall rules per tier, private endpoints to cloud services. 7. **Cost**: a cost allocation tool (OpenCost/Kubecost-style or provider split-cost features) attributes node cost via labels and namespaces to tenants. \`\`\` tenant requests (Git) -> platform controller / IaC | | Tier 1: shared clusters (internal) Tier 2: hard isolation (external) +-------------------------------------+ +-----------------------------------+ | ns team-a | ns team-b | ns team-c | | cluster-per-tenant (regulated) | | PSA restricted, default-deny netpol | | or host cluster + virtual CPs, | | quotas, RBAC, workload identity | | dedicated node pools, gVisor/Kata | +-------------------------------------+ +-----------------------------------+ policy engine + GitOps add-ons + cost allocation across the fleet \`\`\``, deepDives: [ { title: "Namespace vs virtual cluster vs dedicated cluster", body: `Choose by trust and by what the tenant needs from the API: - **Namespace**: cheapest, densest, but shares the kernel (unless sandboxed), the API server, cluster-scoped resources and admission webhooks. Fine for teams inside one company security boundary with good guardrails. - **Virtual cluster**: each tenant gets its own API server and can install CRDs and cluster roles, while pods are synced to a host namespace. Solves API-level conflicts and admin needs; does not by itself solve node or kernel isolation. - **Dedicated cluster**: strongest isolation and independent upgrades, simplest compliance story, but per-cluster fixed cost and fleet management overhead scale linearly with tenants. The senior move is to not pick one: define tiers and let the risk profile choose the tier, with the same tenant API on top.` }, { title: "Hardening the shared kernel and node", body: `Containers on a shared node share the Linux kernel; a kernel exploit or a privileged pod breaks isolation. Layers: - Enforce the restricted Pod Security Standard: no privileged, no host namespaces, no hostPath, drop capabilities, run as non-root, seccomp RuntimeDefault. - Sandboxed runtimes (gVisor intercepts syscalls in user space; Kata runs pods in lightweight VMs) for untrusted code, at a CPU and I/O overhead cost. - Dedicated node pools for untrusted tenants so a node compromise exposes only that tenant. - Block pod access to the cloud instance metadata endpoint (or require hardened metadata modes) so pods cannot steal node credentials. - Minimise what the node identity can do; kubelet credentials scoped by the node authorizer.` }, { title: "Noisy neighbours at every layer", body: `Compute: ResourceQuota per namespace plus LimitRange defaults so pods without requests cannot be scheduled carelessly; PriorityClasses so platform components preempt tenants, not the reverse. API server: API Priority and Fairness FlowSchemas map tenant service accounts to a bounded priority level, and fair queuing by user or namespace within that level stops one runaway controller starving others or the platform's own controllers. Network: NetworkPolicy does not limit bandwidth, so bandwidth-heavy tenants go to dedicated pools. Storage: per-namespace PVC and storage quotas. Object counts: quotas on ConfigMaps, Secrets and Services prevent etcd bloat.` }, { title: "Upgrades across a fleet", body: `Kubernetes ships roughly three minor releases a year and the upstream project supports the most recent three minors, so a cluster that is not upgraded for about a year falls out of support. Process: scan for deprecated API usage before each upgrade; upgrade the control plane, then node pools with surge and PodDisruptionBudgets respected; roll in waves (dev clusters, then low-risk prod, then the rest), with bake time. Alternatively replace clusters blue/green for major add-on changes. Tenants own PDBs and multi-replica deployments; the platform publishes upgrade calendars and refuses to be blocked indefinitely by one tenant.` } ], tradeoffs: [ { decision: "Isolation model for external, untrusted tenants", options: "Namespace on shared nodes vs dedicated node pools + sandboxed runtime vs virtual clusters vs dedicated clusters", choice: `**Dedicated node pools with sandboxed runtimes by default, dedicated clusters for regulated or large customers.** Shared nodes with untrusted code rely on the kernel as the only boundary. Full cluster-per-tenant for every small customer makes fixed cost and fleet toil dominate.` }, { decision: "Number of internal shared clusters", options: "One giant cluster vs a few per region/environment vs cluster per team", choice: `**A few per region and environment**, sized well below scalability limits. One giant cluster concentrates blast radius and makes upgrades terrifying; cluster per team multiplies upgrades and idle capacity.` }, { decision: "Policy engine", options: "Kyverno vs OPA Gatekeeper vs built-in ValidatingAdmissionPolicy", choice: `**Use built-in CEL-based admission policy for simple validations and one engine for mutation and complex rules.** Webhook-based engines are an availability dependency of the API server; run them highly available and decide fail-open versus fail-closed per policy.` }, { decision: "Cost allocation basis", options: "Allocate by requests vs by actual usage vs by max(requests, usage)", choice: `**max(requests, usage)**: requests reserve capacity others cannot use, and usage above requests consumes shared slack. Idle and overhead are reported separately so teams see their efficiency.` } ], failureModes: [ { failure: "Container escape from an untrusted tenant pod", mitigation: `Sandboxed runtime makes escape reach a sandbox, not the host; dedicated node pool limits exposure to that tenant; minimal node IAM and blocked metadata endpoint prevent lateral movement to the cloud account; runtime threat detection alerts.` }, { failure: "Policy webhook outage blocks all pod creation", mitigation: `Run the policy engine with multiple replicas across zones and PDBs, exclude system namespaces from the webhook, and choose failure policy per rule: fail-closed for security-critical checks in the untrusted tier, fail-open with alerting for hygiene rules.` }, { failure: "Tenant controller floods the API server", mitigation: `API Priority and Fairness isolates the tenant's flow; per-tenant client rate limits; alert on request rate per service account; the platform can scale the offending deployment to zero.` }, { failure: "Cluster upgrade breaks workloads using removed APIs", mitigation: `Pre-upgrade scan of manifests and audit logs for deprecated API use; block upgrades until resolved; upgrade non-prod first; blue/green cluster replacement when risk is high.` }, { failure: "Pod IP exhaustion stops scaling", mitigation: `Plan large pod CIDRs or use overlay/secondary ranges, monitor IP utilisation per subnet, and alert at 70%.` }, { failure: "Cross-tenant secret access via over-broad RBAC", mitigation: `Only namespace-scoped RoleBindings for tenants, generated from templates; periodic RBAC audits; external secret managers with per-tenant cloud identity so even a leaked Kubernetes token does not grant cloud secret access.` } ], followUps: [ { q: "Is a namespace a security boundary?", a: `On its own, no. It is a scope for RBAC, quotas and policy. Combined with restricted pod security, network policy, per-namespace identity and admission control it is an adequate boundary for mutually trusted internal teams. For hostile tenants you need a stronger boundary underneath: sandboxed runtimes, dedicated nodes or separate clusters.` }, { q: "A tenant wants to install their own operator with CRDs.", a: `CRDs are cluster-scoped and can conflict across tenants, and operators often want cluster-wide permissions. Options: the platform curates and installs the operator once for all tenants, the tenant gets a virtual cluster, or a dedicated cluster. Do not grant cluster-admin in a shared cluster.` }, { q: "How do you handle 500 clusters operationally?", a: `Treat clusters as cattle: declarative definitions, identical add-on bundles versioned together, GitOps fleet rollout in waves, automated conformance tests after each change, and a fleet inventory dashboard showing version skew. Avoid per-cluster snowflake configuration.` }, { q: "How do you reduce cost on the shared clusters?", a: `Right-size requests using usage data, autoscale nodes with bin-packing-friendly settings, consolidate underused nodes, run batch and dev on spot capacity, and show each team its idle percentage. Requests far above usage are the usual largest waste.` } ], rubric: [ { area: "Requirements & scoping", signals: [ "Separates trusted from untrusted tenants before choosing an isolation model.", "Asks whether tenants need cluster-scoped resources." ] }, { area: "Architecture", signals: [ "Proposes tiers with a common tenant API rather than one model for all.", "Lists the concrete isolation controls: PSA restricted, NetworkPolicy default-deny, RBAC, quotas, workload identity.", "Knows virtual clusters isolate the API but not the kernel." ] }, { area: "Security", signals: [ "Addresses kernel sharing with sandboxed runtimes or dedicated nodes.", "Blocks metadata endpoint credential theft and scopes node identity.", "Treats admission webhooks as an availability dependency." ] }, { area: "Operations & cost", signals: [ "Explains the upgrade cadence and the supported-version window.", "Plans fleet management with GitOps waves and deprecated API scanning.", "Allocates cost by max(requests, usage) and surfaces idle capacity." ] }, { area: "Reliability & failure", signals: [ "Addresses noisy neighbours at API server, compute, network and storage layers.", "Mentions IP exhaustion and API priority and fairness." ] } ], references: [ { title: "Kubernetes documentation: Multi-tenancy", url: "https://kubernetes.io/docs/concepts/security/multi-tenancy/" }, { title: "Open Policy Agent documentation", url: "https://www.openpolicyagent.org/docs/latest/" }, { title: "CIS Benchmarks", url: "https://www.cisecurity.org/cis-benchmarks" }, { title: "FinOps Framework", url: "https://www.finops.org/framework/" } ] }, // --------------------------------------------------------------------------- // 5. Payments disaster recovery // --------------------------------------------------------------------------- { id: "sd-payments-dr", title: "Disaster recovery for a payments system", difficulty: "staff", topics: ["rel-resilience", "data-databases", "dist-theory", "rel-incidents", "sec-data"], prompt: `"We process card and bank payments for merchants, about **2,000 transactions per second at peak**. The core is a ledger database, a payment orchestration service, and integrations to card networks and banks. Regulators and our largest merchants require that we never lose an acknowledged payment and that we are back within **15 minutes** of losing a region. Design the disaster recovery strategy: database, failover, runbooks, and how you test it."`, clarifyingQuestions: [ "Does RPO zero apply to everything or only to acknowledged ledger entries and payment state? Can analytics, reporting and notifications lag?", "Is the RTO 15 minutes for full service, or for accepting new authorisations while some functions (refunds, reporting) come later?", "Where are the external dependencies: are card network and bank connections reachable from both regions, with separate circuits and credentials?", "What is the current database (single-primary relational, distributed SQL) and what write latency budget does the authorisation path have?", "Which disasters are in scope: region loss, data corruption, ransomware, bad deploy, cloud account compromise, provider-wide failure?", "Are there regulatory constraints on where data and keys live (PCI DSS scope, data residency)?", "How often are we allowed to perform live failovers in production?" ], requirements: { functional: [ "Authorise, capture, refund and settle payments with an append-only double-entry ledger.", "Every acknowledged payment is durable in at least two regions (or a quorum spanning regions) before the client receives success.", "Resume accepting payments in a surviving region within 15 minutes of a regional loss.", "Exactly-once effect toward merchants and external networks through idempotency keys and reconciliation.", "Recover from logical corruption (bad migration, bug, malicious deletion) to a point in time." ], nonFunctional: [ "RPO \u2248 0 for acknowledged ledger writes; RTO \u2264 15 min for authorisation; RTO of hours acceptable for reporting.", "Authorisation p99 latency budget under ~500 ms end to end, including network calls.", "Availability 99.99%+ for authorisations.", "PCI DSS-aligned controls: encryption, key management, segregation, audited access.", "DR plan tested regularly with measured RTO/RPO; evidence retained for auditors." ] }, estimates: `- **Write rate**: 2,000 TPS peak; each payment produces ~3\u20135 ledger rows plus state transitions, so **~6\u201310k row writes/s** at peak, roughly 2\u20134k database transactions/s if each payment step commits its rows in one transaction. - **Data volume**: ~2 KB per payment including ledger rows and indexes x average ~600 TPS x 86,400 s = **~100 GB/day**, ~36 TB/year before archiving. - **Replication bandwidth**: 2,000 TPS x 2 KB x 2\u20133x WAL overhead = ~10 MB/s peak per replica stream; trivial for inter-region links. - **Synchronous latency cost**: a commit that must be acknowledged by a replica in another region adds at least one inter-region round trip: ~5\u201315 ms between nearby regions in the same geography, ~60\u2013100 ms+ across a continent, order of magnitude. Within a ~500 ms authorisation budget dominated by network calls to card networks, a ~10 ms commit penalty is acceptable; 80 ms across an ocean on every write is not. - **RTO budget**: detection 2\u20133 min, decision 2 min, database promotion or quorum re-election under 1 min, traffic shift 2\u20133 min, external connectivity checks 2\u20133 min, leaving ~3\u20135 min slack in 15 minutes. Anything requiring provisioning (scaling up compute, issuing certificates) during the event breaks the budget. - **Cost**: a full hot standby region with pre-scaled compute roughly doubles compute and database spend; a three-region quorum adds a third copy of storage. For a payments company this is typically small against what is at risk: 15 minutes down at a 2,000 TPS peak x an assumed average $50 ticket is ~$90M of payment volume not processed. At an assumed take rate well under 1% the direct fee revenue lost is under ~$1M, but merchant churn, contractual penalties and regulatory consequences usually dominate.`, architecture: `The core idea: **acknowledge a payment only after it is durable across failure domains that include another region**, and keep everything needed to resume pre-provisioned in that region. 1. **Regions**: two primary regions close together within the same geography (e.g. ~10 ms apart) plus a third region or a lightweight witness for quorum. Each region has a full, pre-scaled stack: API gateway, orchestration, ledger service, HSM/KMS access, and its own connections to card networks and bank partners. 2. **Ledger database**, two viable options: - **Option A, distributed SQL with consensus** (Spanner multi-region configurations, CockroachDB, YugabyteDB or similar): replicas in three regions, Raft/Paxos majority commit. Loss of one region keeps a majority; leaders re-elect in seconds; RPO 0 by construction. - **Option B, relational primary with synchronous cross-region standby**: e.g. PostgreSQL synchronous replication (synchronous_commit with a standby in region B), plus asynchronous replicas for reads. RPO 0 only while the synchronous standby is attached; you must decide what happens when it is not. PostgreSQL itself blocks commits when no listed synchronous standby is available; the silent downgrade usually comes from an HA manager or an operator editing synchronous_standby_names (Patroni, for example, needs synchronous_mode_strict to keep blocking). 3. **Payment state machine**: every payment has an idempotency key from the merchant and an internal payment id. The orchestrator writes intent before calling the card network and records the outcome after, so recovery can resume or reconcile every in-flight payment. 4. **Outbox and events**: state changes are written with an outbox row in the same transaction; a relay publishes to a replicated event log for downstream consumers (notifications, reporting), which can lag and replay. 5. **Traffic**: merchants hit a global endpoint with health-based routing; the payment API is active in one region per merchant shard or active-active over the consensus database. 6. **Backups for corruption**: continuous WAL/changelog archiving and point-in-time recovery to an isolated, separately-credentialed backup account with immutability; replication does not protect against logical corruption, because it replicates the corruption. 7. **Control and runbooks**: a DR controller exposes declared, audited actions (fence region, promote, shift traffic, verify external links) used by on-call. \`\`\` merchants -> global endpoint (health-routed) | | Region A (active) Region B (active/hot) Region C (witness/replica) API, orchestrator API, orchestrator ledger replica / voter ledger replica (voter) <==== consensus / sync commit ====> ledger replica (voter) network + bank links network + bank links \\________ outbox -> replicated event log -> reporting, notifications isolated backup account: PITR archive, object lock, separate credentials \`\`\``, deepDives: [ { title: "What RPO zero really requires", body: `RPO 0 means the client is told "success" only after the write survives the loss of the primary failure domain. With asynchronous replication the window between commit and replication is lost on region failure, so it cannot be zero. Two ways to get it: majority consensus across three regions, or a synchronous standby. With synchronous replication, the hard question is **degraded mode**: if region B's standby becomes unreachable, either the primary stops accepting writes (availability hit, RPO preserved) or it continues alone (availability preserved, RPO zero silently lost). For payments, write it down: either block, or continue only after automatically attaching another synchronous standby in a different region, never silently downgrade. Consensus with three voters handles this naturally because any two can commit.` }, { title: "In-flight payments and external side effects", body: `The database can be perfect and you can still double-charge. A payment sent to the card network just before the region died has an unknown outcome. Design: - Persist the intent before the external call, with a unique idempotency reference passed to the network or acquirer where supported. - On failover, the recovering region scans payments in an in-flight state and resolves each by querying the network/acquirer status or reconciling against settlement files, rather than retrying blindly. - Merchant retries use the same idempotency key and get the stored result, not a second charge. - Daily reconciliation against network and bank settlement files is the final backstop that catches anything the system state got wrong.` }, { title: "Failover runbook and decision rights", body: `A 15-minute RTO fails on hesitation more often than on technology. The runbook should be short, rehearsed and tool-driven: 1. Declare incident; incident commander confirms regional impairment from independent signals (synthetic transactions failing from multiple vantage points, provider health, database health). 2. Decide using pre-agreed criteria (for example, authorisation success below threshold for 3 minutes and not recovering) so no executive approval is needed in the moment. 3. Fence region A: block writes and revoke its database lease and external-link credentials. 4. Confirm the ledger in region B is leader/promoted and caught up (for consensus, verify quorum; for sync replication, you cannot query a dead primary, so confirm from replication monitoring that the standby was in synchronous state up to the failure; if it had dropped out, the RPO-0 guarantee no longer holds and the decision changes). 5. Shift traffic and verify external connectivity with test authorisations. 6. Run in-flight reconciliation; communicate to merchants. Each step has a single command, a verification signal and a timer.` }, { title: "Testing DR so it actually works", body: `Untested DR is a hope. Layers: automated per-component failover tests in staging weekly; production **game days** quarterly where a region is really drained under live traffic during a low-volume window; restore drills from the isolated backups monthly, measured by time to a verified, consistent ledger; chaos experiments for partial failures (one AZ, elevated latency to the standby, network link loss). Measure achieved RTO and RPO each time and file postmortems on misses. Auditors want evidence; engineers want the muscle memory.` }, { title: "Corruption, ransomware and account compromise", body: `Cross-region replication copies bad writes and deletes instantly, so it protects against infrastructure loss only. For logical disasters: point-in-time recovery from continuously archived logs, kept in a separate cloud account or project with separate credentials and object lock so an attacker with production admin cannot delete them; delayed replicas (lagging an hour) for fast rollback of bad migrations; and ledger-level invariants (debits equal credits, balances reconcile) checked continuously so corruption is detected in minutes, not at month end.` } ], tradeoffs: [ { decision: "Ledger database strategy", options: "Distributed SQL with three-region consensus vs relational primary with synchronous cross-region standby vs async replication with reconciliation", choice: `**Three-region consensus if the team can operate it, otherwise synchronous standby with an explicit block-on-loss policy.** Consensus gives RPO 0 and automatic leader election without split-brain risk, at the cost of write latency to a quorum and a newer operational model. Async with reconciliation from network files can recover money movements but cannot honestly claim RPO 0.` }, { decision: "Region placement", options: "Nearby regions in one geography vs distant regions on different continents", choice: `**Nearby regions for the synchronous quorum** (single-digit to low tens of milliseconds), plus an asynchronous copy farther away for geographic disasters with an RPO of seconds. Synchronous writes across an ocean blow the latency budget.` }, { decision: "Active-active vs active-hot-standby for the application tier", options: "Both regions serve payments vs one serves and one is hot standby", choice: `**Active-active stateless tier over the consensus database**, or active-hot standby that takes a small share of real traffic. Either way the standby proves its external connectivity daily; a standby that never processes a real authorisation will fail on credentials or allow-listed IPs on the day it matters.` }, { decision: "Automatic vs human-initiated failover", options: "Database auto-failover vs one-command human decision with pre-agreed criteria", choice: `**Consensus re-election is automatic for the database; the regional traffic shift and fencing of external links is a single human-approved command.** The 15-minute RTO leaves room for a human decision and avoids flapping on grey failures.` } ], failureModes: [ { failure: "Complete loss of the active region", mitigation: `Consensus keeps a majority in the other two regions and elects a new leader; runbook shifts traffic and fences region A's external links; in-flight payments reconciled via network status queries; RTO measured against 15 minutes.` }, { failure: "Synchronous standby unreachable (link or region B impaired)", mitigation: `Pre-defined policy: automatically attach a synchronous standby in the third region, or pause writes. Never silently fall back to async. Alert immediately because the system is one failure away from data loss or downtime.` }, { failure: "Logical corruption from a bad migration replicated everywhere", mitigation: `Ledger invariant checks detect it; stop writes on affected tables; point-in-time restore to an isolated environment and replay valid transactions from the outbox and event log; delayed replica as a fast path.` }, { failure: "Ransomware or compromised admin credentials deleting backups", mitigation: `Backups in a separate account with independent credentials, object lock in compliance mode, and break-glass access requiring multiple approvers. Restore drills prove the backups are usable.` }, { failure: "Failover succeeds but card network connections fail from region B", mitigation: `Each region has its own pre-established, continuously exercised connections, certificates and allow-listed IPs with the networks and acquirers; synthetic authorisations run from both regions continuously.` }, { failure: "Split brain: old region recovers and accepts writes", mitigation: `Consensus prevents two leaders by design; for sync replication, fencing via lease and credential revocation before promotion. Merchant-facing endpoints in the fenced region return retriable errors.` }, { failure: "Duplicate charges from merchant retries during the failover", mitigation: `Idempotency keys persisted in the replicated ledger, so a retry in region B finds the original result; responses are deterministic for the same key.` } ], followUps: [ { q: "What happens to the latency of every payment with three-region consensus?", a: `Each commit waits for the leader plus one other voter, so latency is roughly one round trip to the nearest other region plus fsync, around 5\u201320 ms with nearby regions, order of magnitude. Place the leader (or leaseholder) in the region serving the traffic and keep the voters close. Reads can be served locally from the leader or with bounded staleness where acceptable.` }, { q: "The provider has a multi-region outage of a shared control plane. Now what?", a: `Design data planes that run without control-plane calls (static stability). For the worst case, some payments firms keep a cross-provider or on-premises fallback for authorisations only, with reduced features and store-and-forward to the main ledger. It is expensive; justify it with the regulator's requirements and revenue at risk.` }, { q: "How do you convince auditors the DR plan works?", a: `Evidence: scheduled game day reports with measured RTO/RPO, restore drill logs with integrity checks, runbook versions with change history, access logs for break-glass, and postmortems with completed action items. A plan document alone is not evidence.` }, { q: "Where do encryption keys live, and what if KMS in a region fails?", a: `Keys must be usable from every region that may serve traffic: multi-region keys or replicated key material in each region's KMS/HSM, with key policies identical across regions. Test decryption in the standby region continuously; an unusable key is an outage as complete as a lost database.` }, { q: "Could you meet the goal with only async replication?", a: `Not honestly for RPO 0. You could reduce loss to seconds and then rebuild missing ledger entries from the card network and bank records, but that turns a technical failover into a reconciliation project with merchant-visible inconsistencies. It might be acceptable for non-ledger data like notifications and reporting.` } ], rubric: [ { area: "Requirements & scoping", signals: [ "Clarifies that RPO 0 applies to acknowledged ledger writes and lets reporting lag.", "Includes logical corruption and account compromise in the disaster scope, not only region loss." ] }, { area: "Estimation", signals: [ "Quantifies the synchronous commit latency penalty versus the authorisation budget.", "Breaks the 15-minute RTO into detection, decision, execution and verification.", "Estimates revenue at risk to justify cost." ] }, { area: "Architecture", signals: [ "Chooses consensus across three regions or synchronous standby and explains degraded-mode behaviour.", "Uses idempotency keys, intent records and an outbox for exactly-once effects.", "Pre-provisions external connectivity and keys in every region." ] }, { area: "Reliability & failure", signals: [ "Handles in-flight payments with unknown outcomes via status query and reconciliation.", "Prevents split brain with fencing or consensus.", "Separates replication (infrastructure loss) from backups (logical loss) with immutable, isolated backups." ] }, { area: "Operations", signals: [ "Writes a short, tool-driven runbook with pre-agreed decision criteria.", "Tests through game days and restore drills with measured RTO/RPO.", "Produces audit evidence." ] }, { area: "Communication", signals: [ "States trade-offs plainly (for example, block writes rather than silently lose RPO 0).", "Uses order-of-magnitude numbers instead of vague claims." ] } ], references: [ { title: "PostgreSQL documentation: High Availability, Load Balancing, and Replication", url: "https://www.postgresql.org/docs/current/high-availability.html" }, { title: "Raft consensus algorithm", url: "https://raft.github.io/" }, { title: "AWS Builders\u2019 Library: Making retries safe with idempotent APIs", url: "https://aws.amazon.com/builders-library/making-retries-safe-with-idempotent-APIs/" }, { title: "Principles of Chaos Engineering", url: "https://principlesofchaos.org/" } ] } ]; // ../../packages/content/src/infra/design-2.ts var designCases2 = [ // --------------------------------------------------------------------------- // 6. Enterprise landing zone & hybrid network // --------------------------------------------------------------------------- { id: "sd-hybrid-network", title: "Enterprise landing zone and hybrid network", difficulty: "staff", topics: ["net-cloud", "net-fundamentals", "sec-identity", "auto-iac", "rel-resilience"], prompt: `We are a large enterprise moving to the cloud. Today we have two data centers, one in each of two countries, and about 40 cloud accounts \u2014 subscriptions or projects, depending on the provider \u2014 that teams created on their own over the last two years. Some of them overlap in IP space with each other and with on-prem. Security wants every byte that leaves for the internet to go through inspection, and the application teams want to reach on-prem databases and Active Directory from the cloud without hairpinning through a VPN appliance someone set up in 2021. Design the landing zone and the network: how accounts are organized, how traffic flows between spokes, on-prem and the internet, how you manage IP addresses and how DNS works end to end.`, clarifyingQuestions: [ "How many cloud regions are in scope now and in two years, and do they map to the two data-center countries (data residency)?", "What is the current and projected bandwidth between cloud and on-prem \u2014 steady state and peak (backups, batch, replication)?", "Is east-west traffic between spokes required to be inspected, or only north-south (internet) traffic?", "Which existing accounts overlap in CIDR with each other or with on-prem, and can those workloads be re-addressed or must they be NATed?", "Who owns DNS today (AD-integrated DNS, a separate appliance), and which namespaces must resolve in both directions?", "Are there regulatory constraints (PCI, regulated data) that require separate network segments or dedicated inspection?", "What is the tolerance for an outage of the cloud-to-on-prem link \u2014 which workloads hard-depend on on-prem (AD, mainframe, databases)?", "Is the organization single-cloud, or must the design leave room for a second provider?" ], requirements: { functional: [ "Account/subscription hierarchy with guardrails: organization-level policies, separate accounts per workload and environment, centrally owned shared-services and network accounts.", "Hub-and-spoke (or transit) connectivity: spokes reach shared services, on-prem and each other only where policy allows.", "Private, redundant connectivity to both data centers with automatic failover; encrypted VPN as a backup path.", "Centralized internet egress through a stateful firewall / inspection layer with logging; centralized ingress for internet-facing apps through WAF and load balancers.", "IP address management: a non-overlapping allocation plan for cloud and on-prem, automated allocation for new VPCs, a remediation plan for existing overlaps.", "Hybrid DNS: cloud private zones resolvable from on-prem, on-prem zones (including AD) resolvable from the cloud.", "Self-service vending of new accounts with network attached, via IaC, in under a day." ], nonFunctional: [ "Connectivity availability of at least 99.99% for the hybrid path (dual circuits, dual locations).", "No single inspection appliance or AZ failure takes down egress for the whole estate.", "Added latency for inspected paths in the low single-digit milliseconds.", "Every network change through code review and pipeline; no console changes in network or security accounts.", "Cost visibility per spoke for data-processing and egress charges.", "Scales to 200+ accounts and multiple regions without re-architecture." ] }, estimates: `**Accounts and VPCs.** 40 accounts today, plan for 200. Typical shape: one VPC/VNet per account per region; two regions \u2192 80 VPCs today, ~400 at target. **Address space.** Default spoke size /20 (4,096 addresses), large spokes /19. 400 \xD7 /20 \u2248 1.6M addresses \u2248 a /11. Reserve a contiguous /10 for cloud (4.2M addresses), carved into one /12 per region (1M each, room for four regions) so each region can be summarized as one route toward on-prem. **Kubernetes pressure.** A cluster with 300 nodes \xD7 30 pods = 9,000 pod IPs. If pods take VPC-routable IPs, one cluster eats more than two /20s. Put pods in a non-routable secondary range (for example the shared address space 100.64.0.0/10 from RFC 6598, reused per VPC and source-NATed at the node) or use an overlay CNI, so the routable plan only carries nodes and load balancers. Confirm the range is not already used on-prem or by a carrier-grade NAT in the path. **Hybrid bandwidth.** Steady 2 Gbps, peaks 8 Gbps during nightly backup/replication. Two 10 Gbps dedicated circuits per data center at diverse provider locations: normally 8 Gbps spread over four circuits is ~20% each; even with a whole DC's circuits down, the other site's 2 \xD7 10 Gbps carries the 8 Gbps peak at ~40%. Rule of thumb: size so that N-1 (here, a full site) carries peak, and keep surviving circuits under ~70% at peak so failover does not congest. **Egress.** 3 Gbps internet egress peak, ~1 Gbps average: 1 Gb/s \xD7 86,400 s \u2248 86 Tb \u2248 11 TB/day \u2248 320 TB/month. Central NAT and firewall endpoints each charge per GB processed (order of cents per GB), so at ~320 TB/month NAT plus firewall processing alone is tens of thousands of dollars a month \u2014 a material line item, which is why private endpoints for provider services (object storage, queues, registries) are part of the design, not an afterthought. **Latency.** Inspection adds ~1 ms (order of magnitude) per traversal; cross-region hub hops add the region RTT (tens of ms). DC to nearest cloud region over dedicated interconnect: typically 2\u201310 ms depending on metro distance.`, architecture: `**1. Organization and guardrails.** A root organization (AWS Organizations / Azure management groups / Google Cloud folders) with OUs: Security (log archive, security tooling), Infrastructure (network hub, shared services, DNS), Workloads/Prod, Workloads/NonProd, Sandbox. Org-level policies (SCPs / Azure Policy / Org Policy) deny creating internet gateways, public IPs and peering outside the network account, deny disabling logging, and restrict regions. **2. Network account and hubs.** One hub per region in a dedicated network account: a transit router (AWS Transit Gateway / Azure Virtual WAN hub or hub VNet / Google Cloud Network Connectivity Center or Shared VPC host project). Spokes attach to the hub; no spoke-to-spoke peering. Route tables on the hub implement segmentation: prod, nonprod, shared-services and on-prem route domains. Prod and nonprod cannot route to each other; both reach shared services and on-prem. **3. Inspection.** An inspection VPC per region with a horizontally scaled firewall tier behind a gateway-style load balancer (or the provider's managed firewall) spread across three AZs. Hub routing sends 0.0.0.0/0 and inter-domain traffic through it. Flow symmetry is preserved by keeping both directions of a flow in the same AZ (appliance mode or equivalent) so the stateful firewall sees both halves. **4. Egress and ingress.** Egress: spokes have no NAT or internet gateway; default route \u2192 hub \u2192 inspection \u2192 central NAT \u2192 internet. Ingress: internet-facing apps sit behind a regional WAF + L7 load balancer in an ingress VPC (or per-app in their own spoke, with WAF mandatory via policy), forwarding to private targets. **5. Hybrid connectivity.** Each DC has two dedicated circuits to two different provider edge locations (AWS Direct Connect / Azure ExpressRoute / Google Cloud Interconnect), terminated on a gateway attached to every regional hub. BGP with summarized prefixes: on-prem advertises its aggregates; cloud advertises one /12 per region. IPsec VPN over the internet as the third path with higher BGP cost (longer AS path / lower local preference). BFD for sub-second failure detection. **6. IPAM.** A single source of truth (provider IPAM or an IPAM tool) owns 10.0.0.0/8 allocation: on-prem keeps its existing blocks, cloud gets a /10, per-region /12, per-environment pools. The account-vending pipeline requests a CIDR from IPAM; nobody types a CIDR by hand. **7. DNS.** Cloud private zones per domain (for example aws.corp.example or app.cloud.example) associated with spokes centrally. Resolver endpoints in the shared-services VPC: inbound endpoints that on-prem DNS conditionally forwards to; outbound rules that forward corp.example and the AD domains to on-prem DNS servers in both DCs. Provider-service private endpoints get private zones so service names resolve to private IPs. **8. Vending and IaC.** Account vending (Control Tower-style / Azure landing zone accelerators / Google Cloud project factory or equivalent Terraform modules) creates the account, baseline logging and IAM, the VPC from an IPAM allocation, the hub attachment into the right route domain and the DNS associations. \`\`\` on-prem DC-A on-prem DC-B [AD, DNS, DBs] [AD, DNS, DBs] | 2x circuits | 2x circuits (+ IPsec backup) v v +-------- interconnect gateway (BGP, summarized) --------+ | | [Hub region 1] <---- inter-region peering ----> [Hub region 2] | route domains: prod | nonprod | shared | onprem |-- inspection VPC (FW tier x3 AZ) -- NAT -- internet |-- shared services (resolver endpoints, AD connectors, CI) |-- ingress VPC (WAF + L7 LB) |-- spoke: prod-app-1 spoke: prod-app-2 spoke: nonprod-... \`\`\``, deepDives: [ { title: "IP address management and fixing the existing overlaps", body: `The plan matters more than the tool. Reserve contiguous, summarizable blocks: one /10 for cloud, one /12 per region, pools per environment. Summarization keeps the BGP table small (providers and on-prem routers cap accepted prefixes per session) and makes firewall rules readable. For the existing overlapping accounts there are three options, in order of preference: - **Re-address**: rebuild the VPC in a new CIDR via IaC and migrate workloads. Cheapest long term; feasible for stateless apps and anything already deployed by pipeline. - **Isolate**: leave the overlapping VPC unattached to the hub and expose only specific services through private endpoint services (provider-level private link), which do not require routable, non-overlapping CIDRs. - **NAT**: a private NAT in front of the overlapping range. Works, but breaks source-IP visibility and makes troubleshooting painful; use only as a time-boxed bridge. Pods and other high-density address consumers go into non-routable ranges reused per VPC. A senior answer also names the governance hook: an org policy that blocks VPC creation outside the vending pipeline, so overlaps cannot reappear.` }, { title: "Centralized inspection without making it a single point of failure", body: `Centralized egress gives one place for allow-listing, TLS inspection decisions, logging and threat intel, and avoids paying for NAT plus firewall in 400 VPCs. The risks are blast radius, throughput and asymmetry. - **Scale out, not up**: a firewall fleet behind a gateway load balancer with per-AZ instances and autoscaling, or the provider's managed firewall. Health checks must test the data path, not just the management plane. - **AZ affinity and symmetry**: traffic enters and leaves inspection in the same AZ; otherwise a stateful firewall drops return traffic. Cross-AZ also costs money. - **Fail-open vs fail-closed**: for internet egress, fail closed (security requirement) but with enough N+1 capacity that a single-AZ failure does not trigger it. For east-west inspection, decide per route domain; many orgs inspect only prod \u2194 nonprod and on-prem \u2194 cloud, not every spoke-to-spoke flow, to limit cost and latency. - **Bypass for bulk provider traffic**: object storage and registry traffic goes through private endpoints (gateway or interface endpoints / Private Link / Private Service Connect), not through the firewall, which saves both throughput and per-GB processing charges.` }, { title: "Hybrid connectivity: redundancy, BGP and failover behavior", body: `"Two circuits" is not redundancy if both land in the same provider facility, share a conduit or terminate on the same on-prem router. Target: two DCs \xD7 two circuits \xD7 two distinct provider locations, each pair on separate customer routers. That is the shape providers recommend for their highest-resilience tier. BGP policy decides which path wins. Use local preference (outbound from on-prem) and AS-path prepending or MED (inbound) to make each DC primary for its nearest region and secondary for the other. The VPN path is advertised with a worse metric so it is only used when all dedicated paths are down \u2014 and it is sized honestly (a few Gbps of IPsec, not 10), with a documented list of which flows get shed. Failure detection: BGP hold timers default to 90 s or more (vendor-dependent), so a silently failed path can blackhole traffic for minutes; BFD brings detection to sub-second. Test failover quarterly by actually draining a circuit, and watch for the classic problem: the backup path works but a firewall rule or MTU (IPsec overhead reduces effective MTU, so enable MSS clamping) breaks large transfers.` }, { title: "Hybrid DNS end to end", body: `Two directions, one rule: each namespace has exactly one authoritative home. - **Cloud \u2192 on-prem**: outbound resolver endpoints with forwarding rules for corp.example and the AD forest domains, targeting DNS servers in both DCs. Rules are shared to all spokes from the network account. - **On-prem \u2192 cloud**: on-prem DNS conditionally forwards the cloud zones to inbound resolver endpoint IPs (Route 53 Resolver endpoints / Azure DNS Private Resolver / Cloud DNS inbound server policy). Endpoints sit in at least two AZs. - **Private endpoints**: provider service names must resolve to private IPs from both cloud and on-prem, otherwise on-prem clients use the public path. That means private zones for those service names plus forwarding from on-prem. Pitfalls: forwarding loops (on-prem forwards to cloud, which forwards back), split-horizon confusion when the same name has public and private answers, resolver endpoint query-rate limits during a cache-cold event, and TTLs that make failover slow. Monitor resolution latency and SERVFAIL rate as SLIs.` } ], tradeoffs: [ { decision: "Centralized vs distributed egress", options: "Central inspection + NAT in the hub vs per-VPC NAT and firewall", choice: `Centralized for the estate, because it gives one policy and log point and avoids hundreds of NAT/firewall stacks. Accept the per-GB processing charge and an extra hop; mitigate with private endpoints for high-volume provider traffic. Allow a documented exception (local egress) for very high-throughput, low-risk workloads such as public dataset ingestion.` }, { decision: "Transit hub vs mesh peering", options: "Hub router with route tables vs direct VPC-to-VPC peering", choice: `Hub. Peering is non-transitive and grows as N\xB2 relationships; at 400 VPCs it is unmanageable and cannot enforce segmentation centrally. Keep direct peering only for a few latency- or bandwidth-critical pairs where the hub's per-GB charge or added hop is measurable.` }, { decision: "Inspect east-west traffic or not", options: "All spoke-to-spoke through firewall vs segmentation by route domain plus security groups", choice: `Route-domain segmentation plus identity-aware security groups for most east-west; firewall inspection only across trust boundaries (prod \u2194 nonprod is blocked, cloud \u2194 on-prem inspected, regulated zones inspected). Full east-west inspection doubles firewall throughput and cost for little additional risk reduction.` }, { decision: "One hub per region vs one global hub", options: "Regional hubs interconnected vs a single hub that all regions route through", choice: `Regional hubs. A single global hub adds cross-region latency and cost to local traffic and makes one region a dependency for all. Regional hubs keep failure domains regional and are peered for inter-region traffic.` }, { decision: "Re-address overlapping VPCs vs NAT them", options: "Rebuild in new CIDRs vs private NAT / private link exposure", choice: `Re-address wherever deployment is automated; private-link exposure for the few that cannot move; NAT only as a time-boxed bridge with an owner and a deadline.` } ], failureModes: [ { failure: "Single circuit or provider location failure", mitigation: `Dual circuits at diverse locations per DC, BGP with BFD for sub-second failover, N-1 sizing so the survivor carries peak, VPN as a last-resort path with a pre-agreed traffic-shedding list.` }, { failure: "Firewall fleet degraded in one AZ, or a bad rule push", mitigation: `Per-AZ instances with data-path health checks so the load balancer removes bad nodes; rule changes through a pipeline with staged rollout (one AZ or one region first) and automated synthetic probes; a pre-approved rollback of the last policy version.` }, { failure: "Asymmetric routing drops return traffic through the stateful firewall", mitigation: `Enable AZ/flow-symmetric mode on the hub attachment for the inspection VPC; keep routes deterministic; include asymmetric scenarios in network tests after every route change.` }, { failure: "BGP route leak or prefix-limit breach (someone advertises a /24 per subnet)", mitigation: `Only aggregates advertised by policy, prefix filters on both sides, maximum-prefix alarms well below the provider limit, and route-table changes reviewed as code.` }, { failure: "DNS resolution failure for on-prem names (resolver endpoints overloaded, DC DNS down)", mitigation: `Forwarding rules target DNS servers in both DCs; endpoints in multiple AZs with capacity headroom; monitor SERVFAIL and latency; critical apps cache and tolerate short resolver outages.` }, { failure: "Hidden hard dependency on on-prem (AD authentication, licence servers) takes down cloud apps during a hybrid outage", mitigation: `Place AD domain controllers (or a managed directory with trust) in the cloud shared-services account; inventory and test on-prem dependencies with a planned link-down game day.` } ], followUps: [ { q: "An application team says the hub adds latency and cost and wants direct internet egress. How do you respond?", a: `Measure first: the inspection hop is typically about a millisecond and the cost is per GB. If their traffic is mostly to provider services, private endpoints remove it from the firewall path entirely. If they still have a real case (high-volume, low-risk egress), grant a documented exception with local egress through a provider-managed firewall in their VPC, policy-enforced logging, and a review date. Exceptions are a product of the platform, not a fight.` }, { q: "How do you migrate the 40 existing accounts into this landing zone without breaking them?", a: `Inventory CIDRs, internet paths and dependencies. Move accounts into the new OU structure with guardrails in audit-only mode first, fix violations, then enforce. Attach non-overlapping VPCs to the hub and shift their default route to central egress one account at a time, with flow logs compared before and after. Overlapping ones get re-addressed or private-link exposure. Remove legacy VPNs and NAT only after traffic on them is zero for a defined period.` }, { q: "How would you add a second cloud provider?", a: `Keep IPAM global (the second cloud gets its own /10), connect both clouds through on-prem or a colocation interconnect fabric rather than over the internet, keep DNS authority per namespace with conditional forwarding, and express guardrails in a tool-neutral way where possible (Terraform modules, OPA policies). Avoid stretching one application across providers unless there is a concrete reason.` }, { q: 'What do you log and how do you troubleshoot "I cannot reach the database on-prem"?', a: `VPC flow logs, hub/route-table changes, firewall allow/deny logs, resolver query logs, and BGP session state. Troubleshoot in layers: DNS resolves to the right IP? Route exists in spoke, hub and on-prem? Security group and firewall allow it? MTU/MSS on the path (VPN fallback)? A provider reachability analyzer saves time, but the senior move is having synthetic probes from each route domain to key on-prem endpoints, so you know before the ticket.` }, { q: "How do you keep network changes safe when 200 teams depend on the hub?", a: `Everything as code with separate state per hub and per region to limit blast radius; plan output reviewed by the network team; policy-as-code checks (no 0.0.0.0/0 to on-prem, no new peering); changes rolled out region by region with synthetic connectivity tests as a gate; change freeze windows for the hub during major business events.` } ], rubric: [ { area: "Landing zone structure and guardrails", signals: [ "Separates security, network, shared services and workload accounts with an OU hierarchy", "Uses org-level preventive policies (deny IGW/public IP outside network account, region restriction)", "Includes account vending through IaC with network attached automatically" ] }, { area: "Topology and segmentation", signals: [ "Chooses hub-and-spoke/transit and explains why mesh peering fails at scale", "Implements segmentation with route domains, not only firewalls", "Keeps hubs regional and limits blast radius per region" ] }, { area: "IP address management", signals: [ "Produces a summarizable plan with concrete sizes (/10, /12, /20) and growth math", "Handles Kubernetes pod address consumption explicitly", "Offers ordered remediation for overlaps (re-address, private link, NAT as bridge)" ] }, { area: "Hybrid connectivity and DNS", signals: [ "Designs real diversity (locations, routers) and N-1 capacity, with VPN as backup", "Explains BGP path preference and failure detection (BFD)", "Describes bidirectional DNS with resolver endpoints and private-endpoint name resolution" ] }, { area: "Inspection and egress", signals: [ "Scales the firewall tier horizontally across AZs and addresses flow symmetry", "Uses private endpoints to bypass inspection for provider services and reduce cost", "States fail-open/fail-closed decisions per path" ] }, { area: "Operability and cost", signals: [ "Names per-GB processing and cross-AZ charges as design inputs", "Defines synthetic probes, flow logs and staged network rollouts", "Plans failover game days and dependency inventory" ] } ], references: [ { title: "Amazon VPC User Guide", url: "https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html" }, { title: "RFC 1918: Address Allocation for Private Internets", url: "https://www.rfc-editor.org/rfc/rfc1918" }, { title: "RFC 1034: Domain Names - Concepts and Facilities", url: "https://www.rfc-editor.org/rfc/rfc1034" }, { title: "Azure Well-Architected Framework", url: "https://learn.microsoft.com/en-us/azure/well-architected/" } ] }, // --------------------------------------------------------------------------- // 7. Global static & video delivery // --------------------------------------------------------------------------- { id: "sd-cdn-media", title: "Global static and video delivery", difficulty: "senior", topics: ["net-edge", "data-caching", "storage-types", "sec-data", "arch-finops"], prompt: `We run a video platform: on-demand video plus a web and mobile app, users on every continent. Today everything is served from object storage in one region through a single CDN, and two things hurt \u2014 the egress bill and the fact that when a popular video drops, our origin falls over. Premium videos must only be playable by paying users. Design the delivery path for static assets and video: caching at the edge, protecting the origin, invalidating content, securing access, and keeping cost under control.`, clarifyingQuestions: [ "On-demand only, or live streaming too? Live changes manifest TTLs and origin design significantly.", "What are views per day, average watch time and average bitrate, and how peaky is traffic (release events)?", "How large is the catalog and how skewed is popularity \u2014 what fraction of bytes comes from the top 1% of titles?", "What protection is required for premium content: signed URLs only, or studio-grade DRM?", "Are there geographic licensing restrictions (geo-blocking) or data residency rules?", "What are the targets for startup time and rebuffering, and which clients (browsers, smart TVs) must be supported?", "Is there an existing CDN contract with committed spend, and is multi-CDN acceptable?", "How often do static assets and video metadata change, and who triggers invalidations?" ], requirements: { functional: [ "Serve web/app static assets and adaptive-bitrate video (HLS/DASH, ideally CMAF segments) globally.", "Origin shielding so a cache miss storm becomes a small number of origin fetches.", "Cache invalidation for static assets and metadata; immutable, versioned video segments.", "Access control: signed URLs or signed cookies with expiry for premium content; DRM for high-value titles; geo-restriction.", "Upload/transcode pipeline writes renditions to origin storage (in scope only as the source of objects).", "Per-title and per-region delivery analytics: hit ratio, egress, errors, startup time." ], nonFunctional: [ "Video start time p95 under 2 s; rebuffer ratio under 1% of watch time.", "Edge cache hit ratio \u2265 95% by bytes for video, origin offload \u2265 98% with shielding.", "Origin survives a release of a top title (10\xD7 normal request rate on one object set) without degradation.", "Availability of delivery \u2265 99.95%, tolerant of a single CDN PoP or provider-region outage.", "Delivery cost per GB tracked and reduced \u2265 30% from current." ] }, estimates: `**Traffic.** 5M views/day \xD7 10 min average watch \xD7 3 Mbps average bitrate. Per view: 600 s \xD7 3 Mb/s = 1,800 Mb = 225 MB. Daily: 5M \xD7 225 MB \u2248 1.1 PB/day, \u2248 34 PB/month. **Throughput.** 1.1 PB/day \xF7 86,400 s \u2248 13 GB/s \u2248 104 Gbps average; peak-to-average ~3\xD7 \u2192 ~300 Gbps at peak. A release event can add a spike on top. **Requests.** 6 s segments \u2192 100 segment requests per 10-minute view, plus manifests: ~5M \xD7 110 \u2248 550M video requests/day (~6.4k RPS average, ~20k peak). Static assets: say 2B requests/day (~23k RPS average), mostly small and highly cacheable. **Origin load.** At 95% edge byte hit ratio, edges fetch 5% = 1.7 PB/month from the next tier. With a shield tier at 70\u201380% hit ratio on those misses, origin egress is ~0.35\u20130.5 PB/month \u2014 roughly 1\u20131.5% of delivered bytes. **Cost (illustrative).** CDN egress at negotiated volume rates is often around a cent or two per GB (list prices are higher and vary by geography). 34M GB \xD7 $0.01\u20130.02 \u2248 $340k\u2013680k/month. Origin egress from object storage to the CDN is often discounted or free on the same provider but billed when crossing providers. A 1-point improvement in edge byte hit ratio at this scale removes ~340 TB/month of edge-miss fetches to the shield (and a fraction of that from origin). The biggest lever on total bytes, though, is encoding: a more efficient codec or per-title encoding that cuts average bitrate 20% cuts egress 20%. **Storage.** Catalog 200k titles \xD7 ~6 renditions \xD7 ~1.5 GB average per title across renditions \u2248 300 TB; long-tail titles move to an infrequent-access storage class.`, architecture: `**1. Origin.** Object storage bucket(s) holding renditions and static builds, private (only the CDN/shield can read: origin access identity/control, or signed origin requests). A small origin service generates manifests if they are personalized (ad insertion, entitlement-filtered renditions); otherwise manifests are static objects. **2. Shield tier.** One or two shield PoPs/regions close to origin (the CDN's origin shield / tiered cache feature, or your own caching proxy fleet). All edge misses go to the shield, which collapses concurrent misses for the same object into a single origin fetch (request coalescing). **3. Edge.** Global CDN PoPs with anycast or DNS-based routing. Cache key = path + selected query params (rendition, never the auth token). Segments: long TTL (days to a year) because they are immutable and versioned. Manifests: shorter TTL for VOD (minutes) and seconds for live. Static assets: content-hashed filenames with a one-year TTL and immutable caching; HTML entry points with a short TTL. **4. Access control.** Entitlement service issues a signed cookie or signed URL scoped to a path prefix (the title's directory) with a short expiry (for example 1\u20134 hours, longer than the title). Edge validates the signature without calling the origin. DRM (Widevine, FairPlay, PlayReady) for premium titles: segments are encrypted, the license server enforces entitlements. **5. Multi-CDN and steering (at this scale).** Two CDNs behind a steering layer (DNS-based or client-side, using real-user measurements of throughput and errors). Gives resilience and pricing leverage. **6. Observability.** CDN logs streamed to an analytics store; client-side player telemetry (startup time, rebuffering, bitrate) as the real SLIs. \`\`\` player \u2500\u2500> steering (DNS / client) \u2500\u2500> CDN A edge \u2500\u2510 \u2514\u2500\u2500> CDN B edge \u2500\u2524 (miss) v shield tier (coalescing) \u2502 (miss) v entitlement svc \u2500\u2500 signs \u2500\u2500> origin: object storage license server (DRM) + manifest service \`\`\``, deepDives: [ { title: "Origin shielding and the release-day thundering herd", body: `Without a shield, each of hundreds of PoPs misses independently on a new title: 300 PoPs \xD7 6 renditions \xD7 first segments = thousands of near-simultaneous origin requests, repeated for every segment as viewers progress. The shield turns that into one fetch per object per shield location. Make it robust: - **Request coalescing** (collapsed forwarding) at the shield so 500 concurrent misses for one segment produce one origin fetch. - **Pre-warm** the first N minutes of segments of a scheduled release through the shield before publication. - **Stale-while-revalidate / stale-if-error** for manifests and static assets so an origin hiccup serves slightly stale content instead of errors. - **Origin protection**: rate-limit and concurrency-limit requests at the origin layer, and return a fast 503 (which the shield can absorb with stale content) rather than queueing until timeouts cascade. Choose the shield location near the origin to minimise shield\u2192origin latency and cost; with origins in two regions, use one shield per origin.` }, { title: "Cache keys, TTLs and invalidation", body: `The fastest invalidation is never needing one. Segments and static assets are immutable and content-addressed (hash or version in the path), so publishing a new version is a new URL and the old one ages out. Purges are for mistakes and for mutable objects (manifests, HTML, metadata JSON). Practical rules: - **Surrogate keys / cache tags** where the CDN supports them, so you purge "everything for title 123" without enumerating URLs. - **Purge is eventually consistent** across PoPs (seconds to minutes); for legal takedowns, also revoke at the authorisation layer (stop issuing tokens, block the path at the edge) because a purge alone does not stop a holder of a valid token from refetching the object from origin. - **Cache-key hygiene**: strip tracking and auth query params from the cache key; a token in the key yields a 0% hit ratio. Normalize case and parameter order. - **Vary carefully**: varying on full User-Agent fragments the cache; vary on a small set of device classes computed at the edge if you must.` }, { title: "Signed URLs vs signed cookies vs DRM", body: `A video is a manifest plus hundreds of segments, so signing every segment URL forces the manifest to be personalised and uncacheable. **Signed cookies** (or a token in a path prefix) scoped to the title directory let the manifest and segments stay cacheable while the edge validates the signature on every request. Design points: - Short expiry plus prefix scope limits link sharing; binding to IP breaks mobile users switching networks, so use it sparingly. - Keys: asymmetric or HMAC keys with rotation; publish two active keys during rotation so in-flight tokens stay valid. - Signed URLs/cookies are **access control, not content protection**: a paying user can still download segments. Studio content needs DRM (encrypted CMAF with multi-DRM licensing), with the license server as the entitlement check. DRM adds a license round trip to start-up; cache licenses on the device where allowed.` }, { title: "Cost of egress and how to reduce it", body: `Delivery cost \u2248 bytes delivered \xD7 blended CDN rate + origin egress + requests. The levers, by usual impact: - **Fewer bytes**: per-title encoding and more efficient codecs (HEVC/AV1 where devices support it) reduce average bitrate; capping the top rendition on small screens. Often the largest single saving. - **Better rate**: committed-volume contracts, multi-CDN to create price competition, routing traffic in expensive geographies to the cheapest adequate CDN. - **Higher hit ratio**: shield tier, cache-key cleanup, longer TTLs on immutable objects, larger edge cache footprint for the long tail. - **Cheaper origin path**: keep origin and shield on the same provider to avoid inter-cloud egress, and use the provider's discounted CDN-origin pricing. - **Embedded caches / ISP peering** at very large scale (appliances inside ISPs) \u2014 a later-stage optimisation that only pays off at hundreds of Gbps sustained. Track cost per hour watched as the unit metric, by region and by CDN.` } ], tradeoffs: [ { decision: "Single CDN vs multi-CDN", options: "One provider with deep integration vs two or more with a steering layer", choice: `Multi-CDN at ~300 Gbps peak: resilience against a provider outage and pricing leverage outweigh the cost of maintaining two configs, two log formats and token schemes. Keep config in code and use the lowest common denominator of features (or an abstraction) so steering can move traffic freely.` }, { decision: "Segment length", options: "2 s vs 6 s vs 10 s segments", choice: `About 4\u20136 s for VOD: fewer requests and better cache efficiency than 2 s, faster bitrate adaptation and start-up than 10 s. Live low-latency needs shorter segments or partial segments, accepting more requests.` }, { decision: "Purge-based vs versioned invalidation", options: "Stable URLs with purges vs content-addressed URLs", choice: `Versioned URLs for everything immutable (segments, JS/CSS, images); purges only for a small set of mutable entry points (manifests, HTML) with short TTLs. Purges are slow, rate-limited and eventually consistent.` }, { decision: "Signed cookies vs per-segment signed URLs", options: "Prefix-scoped cookie/token vs each URL signed individually", choice: `Prefix-scoped signed cookies or path tokens, keeping manifests cacheable. Per-URL signing only where cookies are not supported by the client, and then the manifest is generated per session by a small, scaled manifest service.` }, { decision: "Managed shield vs self-run caching tier", options: "CDN tiered cache feature vs own proxy fleet near origin", choice: `Managed shield first; it is cheap and operationally simple. A self-run tier makes sense with multi-CDN (one shared shield for both CDNs, so one origin fetch serves both) or when origin is on-prem.` } ], failureModes: [ { failure: "Release-day stampede overloads origin", mitigation: `Shield with request coalescing, pre-warming, origin concurrency limits returning fast 503s, and stale-if-error so the edge keeps serving.` }, { failure: "Cache-key mistake (token or tracking param in key) drops hit ratio to near zero", mitigation: `Cache-key config in code with tests; alert on byte hit ratio per CDN dropping by more than a few points; canary config changes to a fraction of PoPs or traffic first.` }, { failure: "CDN provider outage or regional degradation", mitigation: `Multi-CDN steering driven by real-user metrics and synthetic probes; DNS TTLs short enough (seconds to a minute) to shift traffic; capacity commitments sized so either CDN can carry most of the load.` }, { failure: "Signing key leak or broken key rotation", mitigation: `Keys in a secrets manager/KMS, two-key overlap during rotation, ability to revoke a key at the edge within minutes, short token expiry to bound exposure.` }, { failure: "Bad purge (wildcard) wipes the cache and stampedes the origin", mitigation: `Restrict wildcard purges, require surrogate-key purges, rate-limit purge API usage, and rely on the shield to absorb refills.` }, { failure: "Origin bucket deleted or corrupted renditions published", mitigation: `Versioning and object lock/deletion protection on origin buckets, cross-region replication for the catalog, checksum validation in the publish pipeline, and immutable URLs so a bad version can be replaced by republishing the manifest to the previous version.` } ], followUps: [ { q: "How would this change for live streaming of a sports event with 2M concurrent viewers?", a: `Manifests refresh every segment, so manifest TTL is about one segment duration or less and request coalescing at the shield becomes critical. Use a packager with redundant encoders in two regions, origin per region, short or partial segments for low latency, and pre-provisioned CDN capacity (tell the CDN in advance). Every viewer requests the same newest segment, so hit ratio is high but the miss window is tiny and simultaneous.` }, { q: "How do you measure whether the CDN is performing well?", a: `Client-side metrics are the truth: start-up time, rebuffer ratio, average delivered bitrate and error rate, segmented by CDN, ISP and country. CDN-side: byte and request hit ratio, origin fetch rate, edge 4xx/5xx, time-to-first-byte. Synthetic probes catch regional problems before users report them.` }, { q: "A content owner demands a video be removed worldwide within 10 minutes. How?", a: `Stop issuing tokens for the title in the entitlement service, add an edge rule that blocks the path prefix (propagates faster and more reliably than purge), purge by surrogate key, and remove or hide it at origin. Verify with probes from multiple regions. Short token expiry bounds the remaining exposure.` }, { q: "Would you use HTTP/3 to the client?", a: `Yes where the CDN supports it: QUIC avoids head-of-line blocking at the transport layer and recovers faster on lossy mobile networks, and connection migration helps devices switching networks. Keep HTTP/2 and HTTP/1.1 fallback because some networks block UDP. Measure start-up and rebuffering by protocol before declaring a win.` } ], rubric: [ { area: "Estimation", signals: [ "Derives bytes per view and PB/month from views, watch time and bitrate", "Converts to Gbps average and peak, and request rate from segment length", "Connects hit ratio to origin load and cost numerically" ] }, { area: "Caching design", signals: [ "Uses a shield tier with request coalescing", "Distinguishes TTLs for immutable segments, manifests and HTML", "Prefers versioned URLs over purges and keeps tokens out of the cache key" ] }, { area: "Security", signals: [ "Chooses prefix-scoped signed cookies/tokens to keep manifests cacheable", "Distinguishes access control from DRM content protection", "Covers key rotation and fast revocation" ] }, { area: "Cost", signals: [ "Identifies bitrate/encoding as a top egress lever", "Discusses committed rates, multi-CDN leverage and origin egress between providers", "Proposes a unit metric such as cost per hour watched" ] }, { area: "Resilience and operations", signals: [ "Plans for CDN outage with steering and short DNS TTLs", "Protects origin with concurrency limits and stale-if-error", "Measures QoE from the client, not just CDN dashboards" ] } ], references: [ { title: "High Performance Browser Networking", url: "https://hpbn.co/" }, { title: "RFC 9114: HTTP/3", url: "https://www.rfc-editor.org/rfc/rfc9114" }, { title: "System Design Primer", url: "https://github.com/donnemartin/system-design-primer" }, { title: "FinOps Framework", url: "https://www.finops.org/framework/" } ] }, // --------------------------------------------------------------------------- // 8. API gateway with distributed rate limiting // --------------------------------------------------------------------------- { id: "sd-rate-limiter-gateway", title: "API gateway with distributed rate limiting", difficulty: "senior", topics: ["dist-patterns", "dist-theory", "net-edge", "data-caching", "rel-resilience"], prompt: `We have a public API used by about 10,000 tenants, from hobby developers to large enterprises. Peak traffic is around 100,000 requests per second across three regions. Each tenant has a plan with quotas \u2014 requests per second and requests per day \u2014 and some enterprise tenants have custom limits. Last quarter one tenant's runaway script took down a shared backend. Design the API gateway layer, with emphasis on how rate limiting works across many gateway nodes and multiple regions, and what consistency you can realistically promise.`, clarifyingQuestions: [ "Are limits per tenant only, or also per API key, per endpoint and per source IP (for unauthenticated traffic)?", "How accurate must enforcement be \u2014 is 5\u201310% over-admission briefly acceptable, or are quotas billing-critical?", "Are daily/monthly quotas tied to billing (hard stop or overage charges)?", "How is traffic distributed across regions \u2014 does a tenant usually hit one region or all three?", "What is the latency budget the gateway may add per request (p99)?", "Should the system behave fail-open or fail-closed if the rate-limit store is unavailable?", "Do we need to protect backends from aggregate overload separately from tenant fairness?", "What does the client contract look like \u2014 429 with Retry-After, rate-limit headers, documented burst sizes?" ], requirements: { functional: [ "Authenticate requests (API key / OAuth token) and resolve tenant and plan.", "Enforce per-tenant short-window limits (RPS with burst) and long-window quotas (per day/month), plus per-endpoint and per-IP limits.", "Return 429 with Retry-After and rate-limit headers describing limit, remaining and reset.", "Allow live updates to tenant limits without redeploying gateways.", "Global backend protection: concurrency limits and load shedding independent of tenant quotas.", "Usage metering per tenant for billing and analytics." ], nonFunctional: [ "100k RPS peak across three regions, headroom to 2\xD7.", "Rate-limit decision adds < 1 ms p50 and < 5 ms p99.", "Gateway availability 99.99%; rate-limit store failure must not take the API down.", "Short-window limits accurate within ~10% globally; daily quotas accurate within ~1% for billing.", "Noisy tenant cannot degrade other tenants (isolation)." ] }, estimates: `**Traffic.** 100k RPS peak; roughly 40/35/25k across three regions. With 2\xD7 headroom design for 200k RPS. **Gateway fleet.** A well-tuned proxy (Envoy/NGINX class) handles very roughly several thousand to ~10k+ RPS per vCPU for simple proxying (benchmark your own request mix); with TLS termination, auth and filters assume ~2\u20135k RPS per vCPU. 200k RPS \xF7 3k \u2248 70 vCPUs in total; the busiest region (40% \u2192 80k RPS at 2\xD7) needs ~27 vCPUs \u2248 4 nodes of 8 vCPU. With N+2, three AZs and nodes kept under ~60% CPU, run ~6\u20139 nodes per region. **Rate-limit store.** If every request does one atomic check-and-increment in an in-memory store (Redis-class), that is 100k ops/s, \xD72\u20133 if you check several dimensions (tenant, endpoint, IP). A single in-memory shard handles on the order of 100k simple ops/s; with scripts closer to tens of thousands. The busiest region at 2\xD7 headroom is ~80k RPS \xD7 3 dimensions \u2248 240k script ops/s, so 6\u201310 shards per region with replicas, sharded by tenant ID \u2014 if every request went to the store, which is exactly what the local tier below avoids. **Latency.** Same-AZ round trip ~0.2\u20130.5 ms, cross-AZ ~1 ms (order of magnitude), cross-region 30\u2013150 ms. A synchronous cross-region check per request is not viable inside a 5 ms budget. **State size.** 10k tenants \xD7 a few dimensions \xD7 ~100 bytes \u2248 a few MB. Per-IP limits for anonymous traffic can mean millions of keys, still only hundreds of MB with TTLs. **Hot tenant.** The biggest tenant may send 20k RPS alone; if all its counters live on one shard key, that shard takes 20k+ ops/s \u2014 which motivates local aggregation for large tenants.`, architecture: `**1. Edge.** Anycast/global load balancer and DDoS/WAF layer in front of three regions; per-IP coarse limits applied here for unauthenticated abuse. **2. Gateway fleet per region.** Stateless L7 proxies across three AZs: TLS termination, authentication (key lookup cached locally with short TTL), tenant/plan resolution, routing, request size limits, and the rate-limit filter. **3. Rate limiting in two tiers.** - **Local tier**: each gateway node keeps in-memory token buckets per tenant. It admits requests locally against a share of the tenant's limit and handles bursts with zero network calls. - **Regional tier**: a sharded in-memory store (Redis-class, replicated across AZs) holding authoritative counters. Nodes sync with it asynchronously every ~50\u2013100 ms (batch increments, fetch current usage) or synchronously for small tenants where precision matters and load is low. Algorithm: token bucket or GCRA for RPS with burst; sliding-window counter for per-minute; daily quota via counters per tenant per day. **4. Cross-region.** Each region gets an allocation of each tenant's global limit, rebalanced every few seconds based on observed demand by a quota coordinator. Daily quotas aggregate usage events through a stream to a metering service that is the billing source of truth. **5. Config.** Tenant limits stored in a database, published to gateways through a config distribution channel (push or polled snapshot) with versioning; gateways keep the last known good config. **6. Backend protection.** Separate from fairness: adaptive concurrency limits per backend, priority-based load shedding (enterprise and health checks last to shed), circuit breakers, and timeouts with budgets. **7. Metering and observability.** Every decision emits a counter (allowed/limited by tenant and rule); access logs go to a stream for usage analytics and billing reconciliation. \`\`\` client \u2500> global LB / WAF (per-IP coarse limits) \u251C\u2500 region A \u2500 gateway nodes [auth | local buckets | route] \u2502 \u2502 async sync every ~100 ms \u2502 v \u2502 regional limit store (sharded by tenant) \u2502 ^ \u2502 quota coordinator (rebalances regional shares) \u251C\u2500 region B ... \u2502 \u2514\u2500 region C ... usage stream \u2500> metering (daily quota, billing) backends (adaptive concurrency, shedding) \`\`\``, deepDives: [ { title: "Choosing the algorithm", body: `- **Fixed window**: simplest, but allows 2\xD7 the limit across a window boundary. - **Sliding log**: exact, but stores a timestamp per request \u2014 too much memory at 100k RPS. - **Sliding window counter**: weights the previous window's count by overlap; tiny state, error of a few percent. Good for per-minute and per-hour limits. - **Token bucket**: rate r, capacity b; natural expression of "100 RPS with bursts of 200". State is (tokens, last refill time) \u2014 update lazily on each request. - **GCRA**: equivalent to a token bucket but stores a single timestamp (theoretical arrival time); easy to implement as one atomic compare-and-set. Choice: token bucket/GCRA for per-second limits with burst, sliding-window counter for longer windows, and a durable usage pipeline for daily/monthly billing quotas. Always perform check-and-decrement atomically (server-side script or single command), never read-then-write from the gateway, or concurrent nodes over-admit.` }, { title: "Local vs centralized counting: accuracy vs latency", body: `A purely centralized check per request is accurate but puts a network round trip and a hot dependency on every request; a purely local limit (limit \xF7 node count) is fast but wrong when traffic is unevenly balanced or node count changes. The hybrid: each node admits against locally cached tokens and periodically (every ~100 ms) reports consumed tokens to the regional store and receives the tenant's remaining global budget, from which it derives its local allowance. Over-admission is bounded by roughly sync interval \xD7 admitted rate per node \u2014 for a 1,000 RPS tenant spread over 8 nodes and a 100 ms sync, the worst case is around one sync interval's worth (~100 requests) of overshoot, about 10% for a second. Small tenants (a few RPS) can use synchronous checks because their volume is tiny. Large tenants use the local tier, which also removes the hot-shard problem. This is the honest promise: short-window limits are approximate and protective; billing quotas are exact because they come from the metering pipeline, not from the fast path.` }, { title: "Multi-region consistency", body: `A globally consistent counter would need consensus or a single home region; at 30\u2013150 ms between regions that is incompatible with a 5 ms budget and couples region availability. Options: - **Static split**: each region gets limit/3. Simple; unfair when a tenant's traffic is concentrated in one region. - **Home region**: route each tenant's traffic to a home region. Accurate, but loses latency and failover benefits. - **Dynamic allocation**: a coordinator observes per-region demand and reassigns shares every few seconds (with a floor per region). Close to the global limit; tolerates coordinator failure by freezing the last allocation. - **CRDT-style counters** (per-region grow-only counters merged asynchronously): good for daily quotas where a few seconds of lag is fine. Pick dynamic allocation for RPS and asynchronous merged counters for daily quotas. During a region partition, each region enforces its last allocation. If allocations summed to the global limit (per-region floors can push the sum slightly above), the global limit still roughly holds; the real cost is unfairness \u2014 a region whose demand grows stays throttled at its stale share while another region's share sits unused.` }, { title: "Failure behavior of the limiter itself", body: `The limiter must never be a bigger outage than the abuse it prevents. - **Store unavailable**: fall back to local-only buckets at a conservative share (fail-open with a local cap), not to "allow everything" and not to "reject everything". Emit an alert and a metric for degraded mode. - **Timeouts**: the store call gets a 1\u20132 ms timeout; on timeout, use the local decision. - **Config distribution failure**: keep last known good; new tenants get the default plan. - **Hot keys**: shard by tenant, and use the local tier for large tenants so no single key sees 20k ops/s. - **Retry storms**: 429s with Retry-After and documented backoff with jitter; clients ignoring them are throttled harder at the edge (per-key penalty). Separately, tenant quotas do not protect backends from aggregate overload; adaptive concurrency limits and priority load shedding at the gateway do.` } ], tradeoffs: [ { decision: "Accuracy vs latency in the fast path", options: "Synchronous central check per request vs local buckets with async sync", choice: `Hybrid: synchronous for low-volume tenants, local-with-sync for high-volume ones. Accept bounded short-term over-admission (~10%) in exchange for sub-millisecond decisions and no hard dependency on the store.` }, { decision: "Fail-open vs fail-closed when the limit store is down", options: "Allow all / deny all / degrade to local limits", choice: `Degrade to local limits (a form of fail-open with a cap). Fail-closed turns a cache outage into a full API outage; unconstrained fail-open removes protection exactly when the system is stressed.` }, { decision: "Global vs per-region limits", options: "Static per-region split vs home region vs dynamic allocation", choice: `Dynamic allocation with a per-region floor and last-known-good on coordinator failure. Static split as the initial default for new tenants until demand data exists.` }, { decision: "Build vs buy the gateway", options: "Managed API gateway service vs self-run proxy fleet (Envoy-based)", choice: `At 100k RPS with custom multi-region quota logic, a self-run proxy fleet with a rate-limit service gives control over algorithms, latency and cost; managed gateways price per request, which at 100B+ requests/month (100k RPS sustained would be ~260B) is significant. Use a managed edge (DDoS/WAF) in front either way. Re-evaluate if the team cannot staff on-call for the fleet.` }, { decision: "Billing quota enforcement source", options: "Fast-path counters vs metering pipeline", choice: `Metering pipeline is the billing truth (durable, reconcilable); fast-path counters enforce approximately and are periodically corrected from metering. Never bill from a cache.` } ], failureModes: [ { failure: "Rate-limit store shard fails or becomes slow", mitigation: `Replicas with automatic failover, 1\u20132 ms client timeout, fallback to local buckets, and alerts on degraded-mode decisions. Counters lost on failover are acceptable for short windows.` }, { failure: "Hot tenant overloads a single shard", mitigation: `Local aggregation for large tenants so the shard sees batched updates every ~100 ms per node instead of every request; optionally split a tenant's counter across sub-keys and sum.` }, { failure: "Misconfigured limit (extra zero, or 0) pushed to all gateways", mitigation: `Validation and diff review for limit changes, staged rollout of config by region, bounds checks (no change more than N\xD7 without approval), and instant rollback to the previous config version.` }, { failure: "Retry storm from clients after an incident", mitigation: `Retry-After headers, documented exponential backoff with jitter in SDKs, server-side retry budgets, and edge penalties for clients ignoring 429s.` }, { failure: "Aggregate overload below every tenant limit (many tenants spike together)", mitigation: `Adaptive concurrency limits per backend, priority-based load shedding at the gateway, and capacity planning against the sum of realistic peaks, not the sum of quotas.` }, { failure: "Region partition from the coordinator", mitigation: `Regions keep enforcing the last allocation; metering reconciles daily quotas after recovery; alert if allocations are stale beyond a threshold.` } ], followUps: [ { q: "Why not just divide each tenant limit by the number of gateway nodes?", a: `Load balancing is not perfectly even (long-lived HTTP/2 connections pin a tenant to a few nodes), and node counts change with autoscaling and deploys. A tenant with traffic on 3 of 8 nodes would get under 40% of its limit. Local shares must be derived from observed usage, which is what the sync loop provides.` }, { q: "How do you rate limit by cost rather than by request count?", a: `Assign each endpoint a weight (for example a search costs 10 tokens, a read 1) or charge tokens after the fact based on measured work. The bucket algorithm is unchanged; only the decrement varies. Communicate costs in documentation and headers so clients can plan.` }, { q: "What headers and status codes do you return?", a: `429 Too Many Requests with Retry-After (seconds or a date), plus headers for limit, remaining and reset. The IETF HTTPAPI working group has a long-running draft standardising RateLimit / RateLimit-Policy headers; most APIs today use X-RateLimit-* conventions, so document whichever you emit. Return 503 (not 429) when shedding for backend overload, so clients and dashboards can tell "you exceeded your plan" from "we are overloaded".` }, { q: "How would you test this before launch?", a: `Unit tests of algorithms against reference traces; load tests with skewed tenant distributions and node churn to measure over-admission; fault injection on the store (kill shards, add latency) to verify degraded mode; and shadow mode in production where decisions are logged but not enforced, comparing with expected limits before switching to enforcement.` } ], rubric: [ { area: "Algorithms", signals: [ "Compares fixed window, sliding window, token bucket/GCRA with their errors and state cost", "Insists on atomic check-and-decrement", "Separates per-second limits from billing quotas" ] }, { area: "Distributed design", signals: [ "Proposes local + central hybrid and quantifies over-admission bounds", "Handles hot tenants and sharding by tenant", "Explains why synchronous cross-region checks do not fit the latency budget" ] }, { area: "Failure handling", signals: [ "Defines degraded mode when the store fails (local caps, timeouts)", "Protects against config mistakes with staged rollout and bounds", "Addresses retry storms with Retry-After and backoff with jitter" ] }, { area: "Capacity and latency", signals: [ "Sizes gateway fleet and store shards from RPS", "States latency numbers for intra-AZ, cross-AZ and cross-region", "Plans headroom and AZ spread" ] }, { area: "Product and API contract", signals: [ "Defines 429 vs 503 semantics and headers", "Supports weighted/cost-based limits and live limit changes", "Treats metering as the billing source of truth" ] } ], references: [ { title: "SRE Book: Handling Overload", url: "https://sre.google/sre-book/handling-overload/" }, { title: "Amazon Builders' Library: Timeouts, retries and backoff with jitter", url: "https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/" }, { title: "SRE Book: Addressing Cascading Failures", url: "https://sre.google/sre-book/addressing-cascading-failures/" }, { title: "Jepsen: Consistency Models", url: "https://jepsen.io/consistency" } ] }, // --------------------------------------------------------------------------- // 9. Data-center to cloud migration with near-zero downtime // --------------------------------------------------------------------------- { id: "sd-migration", title: "Monolith and 5 TB database migration to the cloud", difficulty: "staff", topics: ["arch-frameworks", "data-databases", "rel-resilience", "auto-delivery", "net-cloud"], prompt: `Our core product is a ten-year-old monolith \u2014 a Java application on about 30 VMs in our data center \u2014 backed by a 5 TB relational database. Most of it is Oracle, and one newer module uses PostgreSQL. The data-center lease ends in nine months. The business will accept at most a few minutes of downtime for the cutover, and we must be able to roll back if things go wrong. Walk me through how you would migrate it: the strategy for each component, how you move the data, how the cutover works and how you roll back.`, clarifyingQuestions: [ "Is moving off Oracle a goal of this migration, or can we keep Oracle (licence-included or bring-your-own) and convert later?", "What is the write rate and redo/WAL generation per day, and what are peak hours?", "How much PL/SQL, triggers, sequences and Oracle-specific features (packages, CONNECT BY, materialized views) does the app use?", "What else talks to this database directly \u2014 reports, ETL jobs, other apps, DB links?", "What network do we have to the cloud today (internet VPN vs dedicated circuit) and how much bandwidth?", "Are there compliance constraints (data residency, encryption, audit) that affect the target?", "What does the release process look like today, and is there a test suite or staging environment we can trust?", 'What is the definition of "a few minutes" \u2014 total write unavailability, or user-visible errors?' ], requirements: { functional: [ "Move the application tier, the Oracle database and the PostgreSQL database to the cloud before the lease ends.", "Continuous replication (CDC) from source to target so cutover requires only draining the last changes.", "Validation that the target data matches the source (counts, checksums, business invariants).", "A cutover runbook with go/no-go criteria and a tested rollback path, including reverse replication.", "All integrations (batch jobs, reports, file transfers, DB links, external partners) inventoried and moved or re-pointed." ], nonFunctional: [ "Write downtime \u2264 5\u201310 minutes at cutover; read degradation acceptable for a short window.", "Zero data loss (RPO = 0 at cutover).", "Rollback possible within an agreed window (for example 48 hours) without data loss.", "Performance on the target at least equal to current p95 latency for key transactions.", "Security and compliance controls equal to or better than the DC (encryption, audit, network isolation)." ] }, estimates: `**Bulk copy time.** 5 TB = 40 Tb. Over a 10 Gbps dedicated link at ~70% efficiency (7 Gbps): 40,000 Gb \xF7 7 \u2248 5,700 s \u2248 1.6 h for the raw bytes. Over a 1 Gbps VPN at ~70%: ~16 h. Raw transfer is not the bottleneck; logical load (inserts, index builds, constraint validation) usually is \u2014 plan 1\u20133 days for a full load with indexes, which is why CDC is mandatory. **Change rate.** Say 50 GB/day of redo/WAL, peaking at 3\xD7 during business hours: average ~0.6 MB/s, peak ~2 MB/s. CDC throughput needs comfortable headroom over peak (\u2265 5\xD7) so lag recovers quickly after a pause. **Lag budget.** If CDC is paused for 4 h (target maintenance), backlog at peak \u2248 2 MB/s \xD7 14,400 s \u2248 29 GB; at a 10 MB/s apply rate the net drain is ~8 MB/s (new changes keep arriving), so it catches up in ~1 hour. This number determines how long you can tolerate an interruption without reloading. **Physical alternative.** Storage-level backup/restore of 5 TB plus archived log shipping (homogeneous only) avoids slow logical loads: restore in hours, then apply logs continuously. **Offline transfer.** Only relevant below ~1 Gbps or for many TB of archives; shipping appliances take days, so they seed the initial copy at best. **Application tier.** 30 VMs; re-hosted roughly 1:1 at first, then rightsized after observing real utilisation for a few weeks (typical DC VMs run at 10\u201320% CPU).`, architecture: `**1. Discover and decide per component (the 7 Rs).** - Monolith app: **re-host / re-platform** \u2014 move as-is to VMs or containers, externalise config, put it behind a cloud load balancer. Do not combine "move" and "rewrite"; the deadline is the lease. - PostgreSQL module: **re-platform** to managed PostgreSQL (RDS/Aurora PostgreSQL, Azure Database for PostgreSQL, Cloud SQL/AlloyDB). - Oracle: depends on code coupling. If heavy PL/SQL, **re-host or re-platform Oracle first** (Oracle on VMs, or a managed Oracle offering), and convert to PostgreSQL as a later project. If light, convert now with schema-conversion tooling, but only if there is time to test. - Batch jobs, file drops, reports: inventory; re-point or retire. **2. Landing zone and connectivity.** Dedicated circuit (or at least redundant VPN) between DC and cloud, private DNS forwarding, target VPC with app and data subnets, IAM and secrets in place. **3. Data path.** - Initial load: physical backup/restore (homogeneous) or a parallel logical load by table chunk. - Ongoing replication: CDC from the source log. Homogeneous Oracle: Data Guard-style standby or log-based replication; heterogeneous: a CDC tool (AWS DMS, Google Database Migration Service for Oracle \u2192 PostgreSQL, Oracle GoldenGate, Debezium + Kafka, or the provider's equivalent \u2014 confirm the source/target pair is supported with CDC, not just a one-time load). PostgreSQL \u2192 managed PostgreSQL: native logical replication (publications and subscriptions). - Continuous validation: chunked checksums, row counts and business-level reconciliation queries running on both sides. **4. Application in parallel.** Deploy the app in the cloud pointing at the target replica in read-only mode for testing; run performance tests against the replica with production-like load (replayed traffic). **5. Cutover (minutes).** Freeze writes, drain CDC lag to zero, validate, fix sequences, switch app and integrations to the target, start reverse replication, unfreeze. **6. Rollback.** Reverse CDC (target \u2192 source) keeps the DC database current for the rollback window; switching back is the same runbook in reverse. \`\`\` DATA CENTER CLOUD [app VMs x30] \u2500\u2500writes\u2500\u2500> [Oracle] \u2500\u2500CDC\u2500\u2500> [target DB] <\u2500\u2500 [app (warm, read-only tests)] [Postgres]\u2500logical repl\u2500> [managed PG] ^ \u2502 \u2514\u2500\u2500\u2500\u2500 reverse CDC \u2500\u2500\u2500\u2500\u2500\u2500\u2518 (after cutover, rollback window) DNS / config switch moves traffic DC \u2500\u2500> cloud LB at cutover \`\`\``, deepDives: [ { title: "Strategy per component and why not refactor now", body: `The lease deadline is the dominant constraint, so the default is "move first, improve second". Re-hosting the monolith keeps the risk to infrastructure differences (network latency, storage IOPS, time zones, hostnames, file shares, licence servers) rather than code changes. The Oracle decision is the real staff-level call. Converting to PostgreSQL removes licence cost and is often a stated goal, but the conversion risk sits in PL/SQL packages, implicit type behaviour (Oracle DATE has a time component; empty string equals NULL in Oracle but not in PostgreSQL; NUMBER precision), sequences, hierarchical queries and transaction semantics. Schema conversion tools typically auto-convert most DDL but leave the hard procedural code. If an assessment shows weeks of manual PL/SQL work, decouple: move Oracle to the cloud homogeneously now, convert in a second phase with its own CDC and cutover. Two smaller, reversible steps beat one large irreversible one. Strangler-fig extraction of services comes after the move, when the platform is stable.` }, { title: "Replication and CDC mechanics", body: `Sequence: start CDC capture **before** the initial load (record the source log position/SCN/LSN), load the snapshot consistent to that position, then apply captured changes from that position. That ordering avoids a gap. What breaks CDC in practice: - **Tables without primary keys**: updates cannot be applied reliably; add keys or use full-row supplemental logging. - **LOBs**: often handled in a slower mode; test large-object tables separately. - **DDL during migration**: freeze schema changes or ensure the tool replicates DDL. - **Triggers and cascades on the target**: disable on the target during replication or changes are applied twice. - **Sequences**: not replicated by logical CDC; set target sequences above source values at cutover (with a safety gap). - **Log retention**: source must keep logs long enough to cover any CDC outage, otherwise reload. Monitor CDC lag in seconds and in bytes as an SLI with alerts; a cutover is only scheduled when lag at peak has stayed under a few seconds for days.` }, { title: "Cutover runbook", body: `A scripted, rehearsed sequence with timings and a named decision owner: 1. T-7 days: dress rehearsals on a production clone, at least two, measured end to end. 2. T-1 h: go/no-go \u2014 CDC lag < 5 s, validation green, rollback tested, on-call staffed, stakeholders notified. 3. Put the app into maintenance/read-only mode (feature flag), stop batch jobs, block writes at the DB (revoke or restrict sessions). 4. Wait for CDC lag = 0; record final source position. 5. Run fast validation (row counts and checksums on hot tables, business invariants). 6. Reset sequences on the target; enable triggers/constraints if deferred. 7. Start reverse replication target \u2192 source from the current position. 8. Switch the app (already deployed and warm in the cloud) to the target; flip DNS (low TTL set days in advance) or load balancer weights; re-point integrations. 9. Smoke tests on critical journeys, then lift read-only. Total write freeze: target 5\u201310 minutes to fit the agreed budget, dominated by validation and smoke tests, so rehearse those to be fast and pre-agree which checks can run after writes resume.` }, { title: "Rollback design", body: `Rollback is only real if the old system stays current. After cutover, reverse CDC replicates writes from the cloud target back to the DC source, so switching back loses nothing. Define rollback triggers in advance (error rate above X for Y minutes, p95 latency above Z on key transactions, data inconsistency detected) and a rollback window (for example 48 hours or one business cycle such as month-end). After the window, stop reverse replication and decommission deliberately. Pitfalls: reverse replication for heterogeneous migrations must map types back (test it as rigorously as forward); identity columns/sequences must not collide; external partners who were re-pointed must be re-pointed back; and anything that wrote only to the cloud (new features enabled post-cutover) must be disabled during the window. Practise the rollback in rehearsal, not just the forward path.` } ], tradeoffs: [ { decision: "Convert Oracle to PostgreSQL during the move vs after", options: "Heterogeneous migration now vs homogeneous move then conversion", choice: `Assess PL/SQL volume first. Heavy procedural code or a tight deadline \u2192 homogeneous move now, convert later. Light usage and time to test \u2192 convert now and avoid migrating twice. State the licence cost of delay explicitly so the business makes an informed choice.` }, { decision: "Physical vs logical replication", options: "Backup/restore + log shipping vs row-level CDC", choice: `Physical for homogeneous moves to self-managed or compatible targets (faster load, exact copy); logical CDC when heterogeneous or when the managed target does not accept physical replication. Logical gives table-level control and reverse replication at the cost of more edge cases.` }, { decision: "Big-bang cutover vs phased", options: "All components in one window vs move integrations and modules in waves", choice: `Phased where coupling allows (PostgreSQL module, batch jobs, reporting replicas first), with one final short cutover for the core write path. A hybrid period where the cloud app talks to the DC database is acceptable only if latency allows \u2014 chatty ORMs across a 5\u201310 ms link can multiply page latency.` }, { decision: "Lift-and-shift VMs vs containerise now", options: "Re-host 30 VMs vs re-platform to containers/Kubernetes", choice: `Re-host or minimal re-platform (VM images built by pipeline) given the deadline; containerise after cutover. Exception: if the app is already stateless and has a working build, containers are a cheap win.` }, { decision: "Read-only window vs dual writes", options: "Short write freeze vs application dual-writing to both databases", choice: `Short write freeze. Dual writes without distributed transactions create divergence that is hard to detect and reconcile; minutes of read-only mode is a much smaller risk.` } ], failureModes: [ { failure: "CDC lag grows during peak or the CDC task fails silently", mitigation: `Lag SLI with alerts in seconds and bytes, sized apply capacity (\u2265 5\xD7 peak change rate), source log retention covering the longest plausible outage, and a documented reload procedure.` }, { failure: "Data mismatch discovered after cutover (type conversion, missing rows, sequence collisions)", mitigation: `Continuous chunked checksums before cutover, business reconciliation queries, sequences reset with a large gap, and reverse replication enabling rollback without loss.` }, { failure: "Performance regression in the cloud (storage IOPS, missing indexes, network latency between tiers)", mitigation: `Replay production traffic against the cloud stack before cutover, provision storage for measured peak IOPS, co-locate app and DB in the same region and keep DB in one AZ with standby in another, and keep the rollback trigger tied to latency.` }, { failure: "Forgotten integration (nightly file drop, DB link, hard-coded IP) breaks after cutover", mitigation: `Dependency discovery from network flow data and DB session/audit logs over weeks, not only interviews; low DNS TTLs; an integration checklist with owners signed off in rehearsal.` }, { failure: "Cutover overruns the downtime window", mitigation: `Timed rehearsals, pre-agreed abort point (if not done by T+X, roll back), parallelised validation, and warm app instances already deployed.` }, { failure: "Licensing or support surprise (Oracle licensing on cloud vCPUs, vendor support of the target)", mitigation: `Resolve licensing with procurement early; confirm the vendor's position on licence counting in the chosen cloud and instance type before sizing.` } ], followUps: [ { q: "How do you validate 5 TB of data without stopping the source?", a: `Chunk tables by primary-key range and compute hashes per chunk on both sides at the same replicated position (or repeatedly until stable), compare row counts per chunk, and run business invariants (sum of balances, open orders count). Re-check only chunks that changed since the last pass. Final validation at cutover focuses on hot tables because cold chunks were already verified.` }, { q: "The lease deadline slips to six months. What changes?", a: `Cut scope, not safety: homogeneous Oracle move, re-host app, defer any conversion and containerisation, move low-risk components first to burn down the inventory, and get the network circuit ordered immediately because provisioning lead times can be weeks to months. Keep rehearsals \u2014 they are the cheapest risk reduction.` }, { q: "How would you handle the 30 app VMs talking to the database during a hybrid phase?", a: `Measure query counts per request. With a 5\u201310 ms round trip, a page that makes 100 sequential queries gains up to a second. Either keep app and DB on the same side (move them together at cutover) or only move components that are coarse-grained in their DB access.` }, { q: "What would you do differently for a 50 TB database?", a: `Raw transfer becomes significant (50 TB at 7 Gbps \u2248 16 h), and logical full loads may take a week, so physical seeding (backup restore or storage-level copy) plus log apply becomes essential. CDC headroom and log retention planning become stricter; consider partitioning historical data and moving cold partitions early as a separate, offline step.` } ], rubric: [ { area: "Strategy and scoping", signals: [ "Applies the migration strategies (re-host, re-platform, refactor, retire) per component", 'Separates "move" from "modernise" under a hard deadline', "Makes an explicit, assessed decision about Oracle conversion" ] }, { area: "Data movement", signals: [ "Computes bulk transfer time and change-rate headroom", "Orders CDC start before snapshot to avoid gaps", "Names CDC pitfalls: primary keys, LOBs, sequences, triggers, DDL" ] }, { area: "Cutover", signals: [ "Writes a step-by-step runbook with go/no-go criteria and timings", "Rehearses on production-like data at least twice", "Pre-lowers DNS TTLs and keeps the app warm in the cloud" ] }, { area: "Rollback and risk", signals: [ "Uses reverse replication to make rollback lossless", "Defines rollback triggers and a window in advance", "Discovers integrations from data (flow/audit logs), not just interviews" ] }, { area: "Operations and performance", signals: [ "Tests performance with replayed traffic before cutover", "Monitors CDC lag as an SLI", "Plans post-migration rightsizing and decommissioning" ] } ], references: [ { title: "AWS Prescriptive Guidance: Migration strategies", url: "https://docs.aws.amazon.com/prescriptive-guidance/latest/large-migration-guide/migration-strategies.html" }, { title: "PostgreSQL: High Availability, Load Balancing, and Replication", url: "https://www.postgresql.org/docs/current/high-availability.html" }, { title: "Google Cloud Architecture Center", url: "https://cloud.google.com/architecture" }, { title: "Apache Kafka Documentation", url: "https://kafka.apache.org/documentation/" } ] }, // --------------------------------------------------------------------------- // 10. Cut a $2M/month cloud bill by 30% // --------------------------------------------------------------------------- { id: "sd-cost-reduction", title: "Cut a $2M/month cloud bill by 30%", difficulty: "staff", topics: ["arch-finops", "compute-scaling", "compute-models", "storage-types", "rel-slo"], prompt: `Our cloud bill is about two million dollars a month and growing faster than revenue. The CFO has asked engineering to cut it by 30% within two quarters, and the CTO has said we cannot hurt reliability while we do it. You have been asked to lead this. How do you approach it \u2014 what do you look at first, what do you do quickly, what structural changes do you make, and how do you make sure the bill does not grow back?`, clarifyingQuestions: [ "What is the breakdown by service category (compute, managed databases, storage, data transfer, observability, support) and by team or product?", "How much of the spend is covered by commitments (reservations, savings plans, committed-use discounts) today, and when do they expire?", "Is resource tagging/labelling in place, and what fraction of spend is attributable to an owner?", "What are the reliability SLOs per service, so we know which savings are safe?", "Is there an enterprise discount agreement up for renewal?", "How much of the fleet is Kubernetes vs VMs vs serverless, and how are requests/limits set?", "Is the 30% measured on absolute spend, or on spend normalised for growth (unit cost)?", "Who has authority to change architecture in teams \u2014 central platform or each product team?" ], requirements: { functional: [ "Full cost visibility: allocation of \u2265 95% of spend to teams/services via tags, accounts and shared-cost rules.", "A prioritised savings backlog with estimated value, effort and risk per item.", "Execution of quick wins within the first 4\u20136 weeks and structural changes over two quarters.", "Unit-economics metrics (cost per request, per customer, per transaction) per product.", "Ongoing governance: budgets, anomaly alerts, showback/chargeback, design reviews for cost." ], nonFunctional: [ "No SLO breaches attributable to cost work; every change rolled out with the same safety as a feature change.", "$600k/month run-rate reduction (30%) at the end of two quarters, measured against a growth-adjusted baseline agreed with finance.", "Commitments sized so that under-utilisation stays under ~5%.", "Savings sustained: unit cost trend tracked monthly; regressions caught within days." ] }, estimates: `**Illustrative breakdown of $2M/month** (validate against the real bill): - Compute (VMs, Kubernetes nodes): $1.0M (50%) - Managed databases: $300k (15%) - Storage (block, object, snapshots): $250k (12.5%) - Data transfer (egress, cross-AZ, NAT processing): $200k (10%) - Observability (logs, metrics, APM): $150k (7.5%) - Other (support, misc services): $100k (5%) **Target**: $600k/month. Plausible contributions (each estimated after the previous, so no double counting): - **Non-prod scheduling**: if 25% of compute ($250k) is non-prod and runs 24\xD77, turning it off nights and weekends (~12 h \xD7 5 days on of 168 h \u2248 36% uptime) saves ~60% of it \u2248 $150k. - **Rightsizing and Kubernetes bin packing**: fleets running at 10\u201320% average CPU; reducing remaining compute ($750k) by 15\u201320% \u2248 $110\u2013150k. - **Commitments** on the new, smaller steady baseline: cover ~70\u201380% of it with 1-year commitments at roughly 25\u201340% discount (varies by provider, term and type). On ~$500k committable compute and database spend not already covered: 75% \xD7 $500k \xD7 ~30% \u2248 $110k, up to ~$150k with deeper discounts on stable databases \u2248 $100\u2013150k. - **Spot/preemptible** for stateless and batch: often 60\u201390% off on-demand (approximate, varies); moving $100k of batch \u2248 $60k. - **Storage**: delete unattached volumes and orphaned snapshots, lifecycle object storage to colder tiers, move to cheaper block volume types: 20\u201330% of $250k \u2248 $50\u201375k. - **Data transfer**: private endpoints instead of NAT for provider services, keep chatty services in one AZ or use topology-aware routing, compress: 20\u201330% of $200k \u2248 $40\u201360k. - **Observability**: drop debug logs in prod, sampling, retention tiers, cardinality limits: 25\u201340% of $150k \u2248 $40\u201360k. Sum \u2248 $550\u2013700k/month, so 30% is achievable but needs the structural items, not just commitments.`, architecture: `This is an organisational system as much as a technical one. Reference approach, following the FinOps lifecycle (Inform \u2192 Optimise \u2192 Operate): **1. Weeks 0\u20133: Inform.** - Ingest detailed billing exports (AWS CUR / Azure cost exports / Google Cloud billing export to a warehouse) into a cost data warehouse. - Allocation: account/subscription/project structure + mandatory tags (team, service, env); rules for shared costs (Kubernetes clusters split by namespace requests, shared networking split by traffic). - Top-down: rank spend by service, team, and SKU; identify the 20 line items that make up ~80% of spend. - Bottom-up: utilisation data (CPU, memory, IOPS, storage access patterns) for those items. - Agree the baseline and target definition with finance (absolute vs growth-adjusted). **2. Weeks 2\u20138: Quick wins (low risk, central team can execute).** - Idle and orphaned resources: unattached volumes, idle load balancers, old snapshots, unused IPs, forgotten test environments. - Non-prod schedules and auto-shutdown for sandboxes. - Storage lifecycle policies and cheaper volume types. - Log retention and debug-level cleanup. - Commitments for the clearly stable floor only (for example the minimum hourly usage over the last 3 months), so you do not lock in waste you are about to remove. **3. Months 2\u20136: Structural (owned by product teams, supported centrally).** - Rightsizing with real utilisation; Kubernetes request/limit tuning and node autoscaler/bin-packing improvements. - Spot/preemptible for stateless services and batch, with interruption handling. - Arm-based instances where the stack supports it (often meaningfully better price-performance; benchmark per workload). - Architecture fixes for egress: private endpoints, AZ-aware routing, caching, compression. - Database rightsizing, read replica review, storage engine/tier changes, archiving cold data. - Second wave of commitments once the baseline has shrunk. **4. Operate: governance so it stays down.** - Showback dashboards per team with unit cost; monthly reviews with engineering leads. - Budgets and anomaly detection alerts to owning teams. - Cost as a non-functional requirement in design reviews; policy-as-code guardrails (allowed instance families, mandatory tags, no unbounded log retention). - A central FinOps function that owns commitments portfolio management. \`\`\` billing export \u2500> cost warehouse \u2500> allocation (tags, accounts, shared rules) \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u253C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510 dashboards / unit cost savings backlog anomaly + budget alerts (per team, monthly) (value x effort x risk) (to owning team) \u2502 quick wins (central) \u2500\u2500 structural (teams) \u2500\u2500 commitments (FinOps) \`\`\``, deepDives: [ { title: "Analysis approach: find the money before you touch anything", body: `Start with allocation, because unowned spend does not get optimised. Untagged spend is often a large fraction (commonly quoted as 20\u201340%) in organisations that have never enforced tagging; fix allocation first with account structure (cheap and complete) and then tags (precise but leaky). Then rank: - **By SKU and service**: which 20 lines make 80% of spend. - **By growth**: what grew fastest in the last 6 months, because that is where waste is being created now. - **By utilisation**: average and p95 CPU/memory per instance group, IOPS vs provisioned, object storage access frequency. - **By unit cost**: cost per request or per customer per product; a product whose unit cost is rising faster than its traffic has architectural waste. Every backlog item gets estimated monthly value, effort, risk to SLOs and owner. A senior answer resists "turn on commitments and declare victory": commitments come after removing waste, or you pay a discount on resources you should have deleted.` }, { title: "Commitments without overcommitting", body: `Commitments (reservations, savings plans, committed-use discounts) are one of the largest levers with no engineering risk, and also the easiest way to waste money if sized badly. - Size to the **floor** of usage, not the average: use the minimum hourly spend over the last 60\u201390 days, then subtract planned reductions (rightsizing, spot migrations). - Prefer **flexible** forms (spend-based or convertible, across instance families/regions) while the fleet is changing; specific reservations only for very stable workloads such as databases. - **Ladder** commitments: buy in tranches every month or quarter rather than once, so expirations are staggered and you can adapt. - Track **coverage** (share of eligible usage covered) and **utilisation** (share of commitments used); targets around 70\u201380% coverage and > 95% utilisation are common. - 3-year terms give deeper discounts but lock in architecture; use them only for workloads you are confident will exist (core databases).` }, { title: "Savings that do not hurt reliability", body: `Cost changes are production changes. Rules: - Rightsizing happens through the normal pipeline with canaries, and the SLO dashboard is the guardrail. Reduce in steps (for example one size down), watch p99 latency and saturation for a week. - Keep **headroom for failure**: an N+1 multi-AZ setup must still carry peak if one AZ is lost. Rightsizing that removes AZ-failure headroom is a reliability regression disguised as savings. - Spot only where interruption is handled: stateless replicas spread over several instance types and AZs, graceful termination on the interruption notice, a floor of on-demand capacity for baseline. - Non-prod scheduling with an easy override, so teams do not bypass it. - Observability cuts target noise (debug logs, unused metrics, high-cardinality labels), not the signals behind SLO alerts. Report savings alongside SLO attainment every month so the trade-off is visible.` }, { title: "Data transfer: the hidden line items", body: `Data transfer is often poorly understood because it is spread across many line items: internet egress, inter-region, cross-AZ, NAT processing, load balancer processing, and transit hub processing. Common fixes: - **Private endpoints** for provider storage, queues and registries so traffic does not traverse NAT (which charges per GB processed). - **AZ-aware routing**: keep chatty service-to-service and service-to-cache calls in the same AZ (topology-aware routing in Kubernetes, zonal endpoints), while keeping multi-AZ for failover. - **Compression** and protocol efficiency for service-to-service payloads and replication streams. - **CDN** in front of public downloads; cached bytes are usually cheaper than origin egress. - **Log shipping**: ship logs within a region and aggregate there; cross-region log replication of everything is a classic surprise. Make transfer visible per service with flow logs joined to the allocation model; teams cannot fix what they cannot see.` } ], tradeoffs: [ { decision: "Central team executes vs teams own their savings", options: "FinOps team makes changes centrally vs product teams change their own services", choice: `Central team executes commitments, idle cleanup and platform-wide policies (fast, low coordination). Product teams own rightsizing and architecture changes, because they own the SLOs; the central team provides data, recommendations and tooling. Executive sponsorship sets per-team targets.` }, { decision: "Commit early vs commit after optimising", options: "Buy commitments in week 1 vs after rightsizing", choice: `Commit only the clear floor early (captures savings immediately with low risk), then a second tranche after structural reductions. Waiting entirely forfeits months of discount; committing everything early locks in waste.` }, { decision: "Showback vs chargeback", options: "Report costs to teams vs bill teams against their budgets", choice: `Showback first, with unit costs and trends, because chargeback without trusted allocation creates disputes. Move to chargeback (or budget accountability) once allocation is above ~95% and shared-cost rules are agreed.` }, { decision: "Spot/preemptible adoption", options: "Aggressive spot for most stateless services vs only batch", choice: `Batch and CI first (easy, large savings), then stateless services with a mixed on-demand floor and instance diversification. Not for stateful single-instance workloads or anything where interruption handling is not tested.` }, { decision: "Absolute target vs unit-cost target", options: "30% off the bill vs 30% lower cost per unit of business", choice: `Agree both with finance: an absolute run-rate target for this programme, and unit cost as the long-term metric, so growth does not mask efficiency gains or erase them.` } ], failureModes: [ { failure: "Rightsizing causes latency regressions or outages under peak or during an AZ failure", mitigation: `Step-wise changes through the deployment pipeline, SLO guardrails with automatic rollback, and capacity checks that include N+1 AZ failure headroom.` }, { failure: "Overcommitting: commitments go unused after migrations or rightsizing", mitigation: `Size to the usage floor minus planned reductions, prefer flexible commitments, ladder purchases, monitor utilisation monthly.` }, { failure: "Savings decay: costs creep back within two quarters", mitigation: `Anomaly detection and budgets routed to owning teams, unit-cost dashboards reviewed monthly, guardrails in policy-as-code (tags, instance families, retention), and cost review in design approvals.` }, { failure: 'Deleting "orphaned" resources that were actually needed (backups, DR snapshots)', mitigation: `Tag-and-notify before deleting, a quarantine period (stop or snapshot before deletion), and an explicit allow-list for backup and DR assets with owners.` }, { failure: "Spot interruptions cascade into capacity shortfalls", mitigation: `Diversify across instance types and AZs, keep an on-demand floor, handle termination notices gracefully, and test with injected interruptions.` }, { failure: "Cutting observability removes signals needed during incidents", mitigation: `Classify telemetry: SLO and alerting signals are protected; cut debug logs, unused dashboards' metrics and high-cardinality labels; keep short-retention full-fidelity data with sampling for the long tail.` } ], followUps: [ { q: "After a month you have only found 15%. What next?", a: `Go to architecture: look at unit cost per product and find the services whose cost per request is out of line; typical culprits are over-provisioned databases, chatty cross-AZ traffic, logging everything, and duplicated environments. Revisit the enterprise agreement and support tier. Present the gap honestly with options and their risk, rather than quietly cutting headroom.` }, { q: "How do you get product teams to prioritise cost work over features?", a: `Make it visible and owned: per-team showback with unit cost, targets set by leadership, savings items sized like features with value per engineering week. Make the easy path cheap (platform defaults: schedules, rightsized templates, spot-ready node pools) so most savings require little team effort. Celebrate and report savings next to reliability metrics.` }, { q: "How does Kubernetes complicate cost allocation and what do you do?", a: `Nodes are shared, so the bill shows nodes, not services. Allocate by namespace based on requested CPU/memory (or max of requested and used), plus a share of idle capacity and cluster overhead. Tune requests to actual usage (vertical recommendations), enable node autoscaling with consolidation, and use separate node pools for spot and for special hardware.` }, { q: "Would you move to a cheaper cloud or back on-prem to save money?", a: `Only with a full TCO model: hardware, facilities, staff, migration cost and time, lost elasticity and managed services. Repatriation can make sense for large, stable, predictable workloads (storage-heavy, steady compute) but takes far longer than two quarters, so it does not meet this goal. Mention it as a long-term option, not a lever for this programme.` } ], rubric: [ { area: "Analysis and visibility", signals: [ "Starts with allocation and ownership before optimisation", "Breaks the bill down by category, team and growth with concrete numbers", "Defines unit-economics metrics and an agreed baseline with finance" ] }, { area: "Prioritised plan", signals: [ "Separates quick wins from structural changes with timelines", "Estimates savings per lever without double counting", "Shows the sum reaches the target and identifies the risky items" ] }, { area: "Commitments and pricing", signals: [ "Sizes commitments to the usage floor after planned reductions", "Prefers flexible, laddered commitments and tracks coverage and utilisation", "Uses spot/preemptible where interruption is handled" ] }, { area: "Reliability protection", signals: [ "Treats cost changes as production changes with SLO guardrails", "Preserves N+1/AZ-failure headroom", "Protects SLO-critical observability signals" ] }, { area: "Governance and culture", signals: [ "Introduces showback, budgets and anomaly alerts routed to owners", "Adds policy-as-code guardrails and cost in design reviews", "Describes how to influence product teams and leadership" ] } ], references: [ { title: "FinOps Framework", url: "https://www.finops.org/framework/" }, { title: "AWS Well-Architected Framework", url: "https://aws.amazon.com/architecture/well-architected/" }, { title: "Google Cloud Architecture Framework", url: "https://cloud.google.com/architecture/framework" }, { title: "SRE Book: Service Level Objectives", url: "https://sre.google/sre-book/service-level-objectives/" } ] } ]; // ../../packages/content/src/infra/behavioral.ts var behavioralPrompts = [ { id: "bh-major-incident", theme: "incident", question: "Tell me about a major production incident you led. What happened, what did you do, and what changed afterwards?", signals: [ "Took a clear role (incident commander, ops lead) and coordinated people rather than only typing commands", "Prioritised mitigation and customer impact over finding the root cause in the moment", "Communicated status on a cadence to stakeholders and customers", "Ran a blameless postmortem whose action items were actually completed", "Quantifies impact: duration, users or requests affected, SLO budget consumed" ], guidance: "Use STAR plus **Learnings**. Situation in two sentences: the system, its scale and the user-visible symptom. Task: your role and why it was yours. Action is the bulk: how you declared the incident, split roles (command, ops, comms), the hypotheses you ruled out, and the mitigation you chose (rollback, failover, shed load) and **why that one first**. Result in numbers: time to detect, time to mitigate, error budget burned, customers affected.\n\nFinish with Learnings that changed the **system**, not just people: a new alert on a symptom, a safer deploy gate, a runbook, a removed single point of failure. A senior answer names the one or two systemic causes and shows the follow-up was tracked to done.", pitfalls: [ "Telling a heroic solo-debugging story with no coordination or communication", "Blaming an individual or another team for the outage", "No numbers for impact or time to mitigate", 'Action items that ended at "we will be more careful"' ], exampleOutline: "- **S:** [service] serving [N req/s] began returning [symptom] at [time]; [customer-facing impact]\n- **T:** I was [on-call / IC]; owned coordination and the decision to mitigate\n- **A:** declared [SEV level]; assigned [ops / comms] roles; status updates every [N] min\n- **A:** ruled out [hypothesis 1, 2] using [dashboard / trace]; correlated with [recent change]\n- **A:** chose [rollback / failover / feature flag off] because [fastest safe reversal]\n- **R:** mitigated in [N] min; [X%] of requests affected; [Y%] of monthly error budget burned\n- **L:** postmortem found [systemic cause]; shipped [guardrail]; tracked [N] actions to completion; repeat incidents since: [0]" }, { id: "bh-owned-migration", theme: "ownership", question: "Describe a migration or large infrastructure project you owned end to end.", signals: [ "Defined the goal and success metrics before starting", "Planned for risk: phased rollout, rollback path, dual-running or shadow traffic", "Managed stakeholders and dependencies across teams", "Finished the long tail (decommissioning the old system) rather than declaring victory at 80%", "Reports measurable outcomes: cost, latency, reliability, toil" ], guidance: "Scope matters most here, so open with the size: number of services, teams, data volume, traffic and the timeline. Explain **why** the migration was worth it (the business or reliability driver) and which strategy you chose (rehost, replatform, refactor) and why not the alternatives.\n\nIn Action, show the plan: inventory, wave grouping, a pilot, success criteria per wave, the rollback mechanism, and how you handled the hardest dependency. Show how you kept teams moving (tooling, docs, office hours). Result: before/after metrics and the date the old system was turned off. Learnings: what you would sequence differently.", pitfalls: [ "Describing a team effort with no clarity about your personal contribution", 'No rollback or risk plan \u2014 "we just cut over"', "Stopping the story before the old system was decommissioned", "Only technical detail, no stakeholder or timeline management" ], exampleOutline: "- **S:** [N services / TB of data] on [old platform]; driver: [cost / EOL / reliability]\n- **T:** I owned [design, plan and delivery]; deadline [date]; success = [metrics]\n- **A:** inventoried [N] workloads; grouped into [N] waves by [risk / dependency]\n- **A:** piloted with [low-risk service]; built [tooling / checklist] to make waves repeatable\n- **A:** used [dual-write / shadow traffic / blue-green] with rollback at each step\n- **A:** unblocked [hard dependency] by [negotiation / adapter]\n- **R:** migrated [N%] by [date]; [cost / latency / incident] change of [X]; old system off on [date]\n- **L:** next time I would [start decommissioning earlier / automate X sooner]" }, { id: "bh-influence-standard", theme: "influence", question: "Tell me about a time you got a team you didn't manage to adopt a standard or practice.", signals: [ "Started by understanding the other team's incentives and constraints", "Used data and a working example rather than authority", "Lowered the cost of adoption (tooling, templates, migration help)", "Accepted and incorporated feedback; adjusted the standard where they had a point", "Measures adoption, not just agreement" ], guidance: "Make the lack of authority explicit early: who owned the decision and why they had reasons to say no. Action should show a sequence: listen first, find a pain they already feel, prototype with one willing team, publish results, then make the right thing the easy thing (golden path, default module, CI check that warns before it blocks).\n\nResult: adoption rate over time and the outcome the standard was meant to produce (fewer incidents, faster deploys). Learnings: what you would do to build the coalition sooner.", pitfalls: [ "Escalating to a manager as the main lever", "Presenting the other team as obstructive or wrong", "Mandating via a blocking gate with no migration support", 'Counting "they agreed in a meeting" as success' ], exampleOutline: "- **S:** [N] teams each did [practice, e.g. deploys / IaC modules] differently; caused [incidents / drift]\n- **T:** I had no authority over [team]; goal: [standard] adopted by [date]\n- **A:** interviewed [team leads]; their concern was [velocity / ownership]\n- **A:** built [template / module] solving [their pain]; piloted with [early adopter]\n- **A:** shared [metric] from pilot; added [non-blocking check] before enforcing\n- **A:** changed [part of standard] based on their feedback\n- **R:** adoption went from [X%] to [Y%]; [incident / lead time] improved by [Z]\n- **L:** I learned to [find a champion first / publish data earlier]" }, { id: "bh-ambiguity", theme: "ambiguity", question: "Tell me about a significant decision you made with incomplete data.", signals: [ "Separated what was known, unknown and unknowable within the time available", "Identified whether the decision was reversible and sized the effort accordingly", "Bought information cheaply (spike, load test, small experiment) where it paid off", "Made the call, stated assumptions and set checkpoints to revisit", "Owns the outcome, including what turned out wrong" ], guidance: "Frame the decision: options, deadline, and the cost of being wrong. Seniors distinguish **one-way** from **two-way doors** \u2014 say which this was and how it shaped your approach. In Action, list the assumptions you wrote down, the cheapest experiments you ran, and the explicit trigger that would make you change course.\n\nResult: what happened, and whether the assumptions held. Learnings: how you now handle similar decisions (e.g. timebox research, write a decision record).", pitfalls: [ "Waiting for perfect data and missing the window", "Presenting a guess as certainty, with no stated assumptions", "A story where the data was actually complete", 'Hindsight-only reasoning \u2014 "it worked so it was right"' ], exampleOutline: "- **S:** needed to choose [option A vs B] for [system] by [deadline]; [key unknown]\n- **T:** I was the [decision owner / tech lead]\n- **A:** classified as [reversible / irreversible] because [reason]\n- **A:** ran [spike / load test / cost model] in [N days] to narrow [unknown]\n- **A:** wrote decision record with assumptions [1, 2] and revisit trigger [metric > threshold]\n- **R:** chose [option]; outcome [metric]; assumption [X] proved [right / wrong] and we [adjusted]\n- **L:** I now [timebox / write ADRs / design for reversibility]" }, { id: "bh-disagree-senior", theme: "conflict", question: "Describe a time you disagreed with a senior stakeholder or architect on a technical direction.", signals: [ "Disagreed on substance, respectfully, with data and a concrete alternative", "Genuinely understood the other position and its constraints", 'Escalated or committed appropriately \u2014 "disagree and commit" when the decision went the other way', "Kept the relationship healthy", "Focus on the outcome for users and the business, not on being right" ], guidance: "State both positions fairly; if the listener cannot tell why the senior person thought what they did, the story is weak. Action: how you gathered evidence (benchmarks, incident history, cost model), how you framed the trade-off in their terms, and the forum you used (design review, 1:1, written proposal).\n\nResult can go either way: you persuaded them, a compromise emerged, or you committed to their direction and helped it succeed. Learnings: what you now do earlier (e.g. write the doc before the meeting).", pitfalls: [ "Portraying the stakeholder as incompetent", "Winning the argument but damaging the relationship", "Going around them without telling them", "No evidence \u2014 just opinion against opinion" ], exampleOutline: "- **S:** [architect / director] proposed [approach] for [system]\n- **T:** I believed [risk: cost / reliability / lock-in]; I was [role]\n- **A:** asked about their constraints: [timeline / strategy]\n- **A:** built [benchmark / failure analysis / cost model] comparing [options]\n- **A:** presented in [design review / written doc] with a [hybrid / phased] alternative\n- **R:** [we adopted X / compromise Y / I committed to their plan and helped by Z]; outcome [metric]\n- **L:** I learned to [frame in their goals / raise concerns in writing earlier]" }, { id: "bh-failure", theme: "failure", question: "Tell me about a time you failed. What did you change as a result?", signals: [ "Chooses a real failure with real consequences, owned personally", "Explains their own contributing decisions without deflection", "Shows how they contained the damage", "Describes a durable change in their behaviour or in the system", "Evidence the change worked later" ], guidance: "Pick a failure that matters but that you recovered from \u2014 e.g. a change you shipped that caused an outage, an estimate that blew up, a project that was cancelled. Spend little time on Situation; most on what **you** got wrong and why it made sense at the time. Then the recovery, then the change: a personal habit (pre-mortems, smaller batches) and, ideally, a systemic guardrail so nobody repeats it.\n\nClose with a later moment where the change paid off.", pitfalls: [ 'A humble-brag ("I worked too hard")', "Blaming circumstances or other people", "A failure with no consequence, so no learning", "No evidence the lesson stuck" ], exampleOutline: "- **S:** I [shipped / planned / decided] [X] for [system]\n- **T:** my responsibility was [scope]\n- **A (mistake):** I [skipped staging / underestimated / assumed]; reasoning at the time: [why]\n- **R (impact):** caused [outage N min / delay N weeks / cost $X]\n- **A (recovery):** I [rolled back / reset expectations / informed stakeholders]\n- **L:** personally I now [practice]; systemically we added [guardrail]\n- **Later:** on [project], that [practice / guardrail] caught [issue]" }, { id: "bh-toil", theme: "ownership", question: "Tell me about a time you significantly reduced toil or on-call pain.", signals: [ "Measured toil first (pages per week, hours, repetitive tickets)", "Prioritised by frequency and cost rather than by interest", "Fixed root causes or automated safely, not just silenced alerts", "Improved the alerting design (symptom-based, actionable)", "Quantified the before/after and the effect on the team" ], guidance: "Open with the measurement: pages per shift, after-hours pages, percent of time on interrupts, ticket volume. Show the analysis: which alert or task made up most of the load (often a few sources dominate). Action: delete work that is not needed, fix the root cause, and only then automate what remains \u2014 in that order of preference \u2014 and how you made sure automation was safe (dry runs, rate limits, auditability).\n\nResult: concrete reductions and the reclaimed engineering time, plus any reliability gain. Learnings: how you keep toil from creeping back (budgets, regular review).", pitfalls: [ "Reducing pages by deleting alerts without checking for missed real incidents", "No baseline measurement", "Automation that introduced a new failure mode", "Doing it alone without changing team process, so toil returned" ], exampleOutline: "- **S:** on-call averaged [N] pages/week, [M] after hours; team spent [X%] on interrupts\n- **T:** I took ownership of [on-call health]\n- **A:** categorised [N weeks] of pages; top [3] sources were [Y%] of volume\n- **A:** fixed [root cause]; automated [runbook] with [safety: dry run / limits]; converted [cause alerts] to [SLO burn alerts]\n- **A:** set up [weekly review / toil budget]\n- **R:** pages down to [N]/week; after-hours down [X%]; reclaimed [hours/week]\n- **L:** measuring first stopped us chasing [the interesting but rare problem]" }, { id: "bh-cost-reliability", theme: "tradeoff", question: "Describe a time you had to trade off cost against reliability. How did you decide?", signals: [ "Framed the trade-off in business terms (cost of downtime vs cost of redundancy)", "Used SLOs and real data rather than gut feel", "Considered intermediate options, not just two extremes", "Made blast radius and risk explicit to decision makers", "Revisited the decision with production data" ], guidance: "Make the numbers the backbone: what the reliability option cost (e.g. a second region, extra capacity headroom) and what the risk cost (expected downtime x cost per hour, or SLO violation). Show the options spectrum \u2014 e.g. single-region multi-AZ with tested backups vs warm standby vs active-active \u2014 and why you landed where you did.\n\nResult: money saved or spent and the reliability outcome. Learnings: how you now present such trade-offs (a one-page cost/risk table to the decision owner).", pitfalls: [ "Treating reliability as always worth any cost", "Cutting cost silently and leaving risk undocumented", "No numbers on either side", "Making a business-risk decision alone instead of with the owner" ], exampleOutline: "- **S:** [system] cost [$X/month]; proposal to [cut / add] [redundancy / capacity]\n- **T:** I was asked to [recommend / decide]\n- **A:** quantified: SLO [target], historical incidents [N], estimated downtime cost [$Y/hour]\n- **A:** compared [option 1, 2, 3] by cost, RTO/RPO and blast radius\n- **A:** presented to [owner]; agreed on [option] with [explicit accepted risk]\n- **R:** saved / spent [$Z/year]; reliability since: [metric]\n- **L:** I now [present expected-loss math / revisit quarterly]" }, { id: "bh-mentoring", theme: "mentoring", question: "Tell me about a time you raised the bar for your team or mentored someone to grow.", signals: [ "Tailored the approach to the person or team rather than lecturing", "Delegated real ownership with support, not just tasks", "Created leverage: practices, reviews, docs that outlive the mentoring", "Concrete evidence of growth (promotion, owning on-call, leading a project)", "Humility \u2014 learned something themselves" ], guidance: "Choose one person or one team practice. Situation: where they started and the gap. Action: how you diagnosed what they needed, how you gave stretch work with a safety net (pairing, review, a clear escalation path), and how you gave feedback. For raising the bar, show a mechanism: design review template, production readiness checklist, incident-review rotation.\n\nResult: observable change in the person or team metrics. Learnings: what mentoring taught you.", pitfalls: [ "Taking credit for the mentee's achievements", 'Mentoring as "I told them the answer"', 'Vague results ("they got better")', "Raising the bar by gatekeeping instead of teaching" ], exampleOutline: "- **S:** [engineer] was [new to on-call / unsure in design reviews]; or team lacked [practice]\n- **T:** I [volunteered / was asked] to help\n- **A:** agreed goals: [own X by date]; paired on [first incidents / design]\n- **A:** handed over [ownership of Y] with [weekly check-in / review]\n- **A:** introduced [checklist / review template / rotation] so it scales beyond me\n- **R:** they [led incident / shipped project / promoted]; team [metric] improved\n- **L:** I learned to [ask more, tell less / let people make recoverable mistakes]" }, { id: "bh-push-back-scope", theme: "conflict", question: "Tell me about a time you said no or pushed back on scope or a deadline.", signals: [ "Pushed back with data on risk, effort and trade-offs, not emotion", "Offered options (reduce scope, phase, add resources, move date)", "Protected reliability or the team without being obstructive", "Reached agreement and then delivered on what was committed" ], guidance: "Set up the request and why it was unsafe or unrealistic (e.g. launch without load testing, migration in a freeze window). Action: how you quantified it, the alternatives you proposed, and how you made it easy for the requester to say yes to one. Seniors negotiate the **shape** of the work, not just the date.\n\nResult: what was agreed and delivered, and what risk was avoided. Learnings: how you now surface constraints earlier.", pitfalls: [ "Saying no without an alternative", "Caving and then complaining later", "Framing the requester as unreasonable", "Not following through on the reduced commitment" ], exampleOutline: "- **S:** [stakeholder] asked for [scope] by [date] for [launch / customer]\n- **T:** I owned [delivery / platform readiness]\n- **A:** estimated [effort]; identified risks: [no load test / no rollback / on-call gap]\n- **A:** proposed [MVP scope by date + phase 2] or [date + full scope]\n- **A:** wrote [one-page trade-off] for [decision owner]\n- **R:** agreed [option]; shipped [what] on [date]; [risk avoided / incident-free launch]\n- **L:** I now [raise readiness criteria at kickoff]" }, { id: "bh-security-issue", theme: "incident", question: "Describe a security issue you discovered or handled. How did you approach it?", signals: [ "Contained first (revoke, rotate, isolate) and preserved evidence", "Followed or established a disclosure and escalation process with security and legal", "Assessed blast radius with logs and data, not assumptions", "Fixed the class of problem, not just the instance (guardrail, policy as code)", "Appropriate discretion about sensitive details in the answer itself" ], guidance: "Keep details generic enough to be appropriate to share. Situation: what was found and how (scanner, audit, alert, report). Action: immediate containment (e.g. rotate a leaked credential, remove public access), who you involved and when, how you determined exposure (access logs, audit trail), and the permanent fix \u2014 e.g. short-lived credentials via workload identity, a policy that blocks public buckets, secret scanning in CI.\n\nResult: exposure window and confirmed impact. Learnings: the preventive control and how you verified it works.", pitfalls: [ "Sharing confidential specifics or customer data in the interview", "Fixing quietly without involving the security team", "Rotating a secret without checking whether it was used", "Only fixing the one instance" ], exampleOutline: "- **S:** [secret scanner / audit / alert] flagged [class of issue, e.g. exposed credential / public storage]\n- **T:** I was [owner of the system / on-call / security champion]\n- **A:** contained within [N min]: [revoke / rotate / block]\n- **A:** engaged [security / incident process]; preserved [logs]\n- **A:** reviewed [audit logs for window]; confirmed [no / limited] use\n- **A:** prevented recurrence: [policy guardrail / short-lived creds / CI check]\n- **R:** exposure window [N]; impact [none confirmed / scoped]; [N] similar cases found and fixed\n- **L:** we now [detect at commit time / deny by default]" }, { id: "bh-delivery-speed", theme: "delivery", question: "Tell me about a time you improved delivery speed without compromising safety.", signals: [ "Measured delivery with recognised metrics (lead time, deploy frequency, change failure rate, time to restore)", "Found the actual bottleneck before optimising", "Added safety mechanisms (canaries, automated rollback, feature flags) alongside speed", "Brought teams along; adoption, not just tooling", "Shows both speed and stability improved or held" ], guidance: "Baseline first: e.g. lead time of days, weekly deploys, manual approvals, frequent rollback pain. Show the bottleneck analysis (flaky tests, manual gates, large batch sizes). Action: smaller changes, pipeline parallelism, progressive delivery with automated canary analysis, removing manual steps that did not reduce risk.\n\nResult: before/after on speed **and** stability metrics. The senior point: safety mechanisms are what let you go faster.", pitfalls: [ "Speed gains at the expense of more incidents", "Optimising a stage that was not the bottleneck", "Only tooling \u2014 no change to how teams worked", "No metrics" ], exampleOutline: "- **S:** lead time [N days]; deploys [weekly]; change failure rate [X%]\n- **T:** I owned [CI/CD platform / release process]\n- **A:** measured pipeline stages; bottleneck was [flaky tests / manual approval / batch size]\n- **A:** introduced [canary with auto-rollback / feature flags / parallel tests]\n- **A:** replaced [manual gate] with [automated check]; coached teams on [small batches]\n- **R:** lead time [N \u2192 M]; deploys [weekly \u2192 daily]; change failure rate [X% \u2192 Y%]\n- **L:** safety automation was what made the speed acceptable to [stakeholders]" }, { id: "bh-cross-org", theme: "influence", question: "Tell me about a project that required working across organisational boundaries.", signals: [ "Mapped stakeholders and their goals early", "Created shared artefacts (design doc, roadmap, RACI) to align", "Handled competing priorities and dependency risk proactively", "Communicated in each audience's terms", "Delivered an outcome neither org could have achieved alone" ], guidance: "Scope: how many orgs/teams, and why their priorities differed. Action: how you built alignment (shared goal, written plan, clear owners), the mechanisms for keeping it (regular syncs, a shared tracker, escalation path agreed up front), and the hardest conflict and how you resolved it.\n\nResult: delivered outcome plus the relationship that remained. Learnings: how you would structure the collaboration next time.", pitfalls: [ "Story is only about your team; other orgs appear only as blockers", 'No mechanism \u2014 just "lots of meetings"', "Escalation as the first tool", "Unclear what you personally drove" ], exampleOutline: "- **S:** [initiative] needed [platform, security, product, finance] orgs; each had [different priority]\n- **T:** I was [technical lead / driver] with no authority over [orgs]\n- **A:** wrote [design doc / one-pager] with shared goal [metric]\n- **A:** agreed owners per workstream and an escalation path up front\n- **A:** resolved [conflict, e.g. timeline vs security review] by [compromise]\n- **R:** delivered [outcome] on [date]; [metric]; [teams now collaborate on X]\n- **L:** next time I would [align on success metric before design]" }, { id: "bh-tech-debt", theme: "tradeoff", question: "How have you prioritised technical debt against feature or roadmap work?", signals: [ "Quantified the cost of the debt (incidents, toil, lead time, risk)", "Translated debt into business impact that product leadership understood", "Used a sustainable mechanism (capacity allocation, error budget policy) rather than heroics", "Prioritised ruthlessly \u2014 not all debt is worth paying", "Showed outcome after paying it down" ], guidance: "Start with a concrete debt item or portfolio and its **interest**: e.g. a legacy deploy path causing a share of incidents, an unsupported runtime version, manual cluster upgrades. Action: how you inventoried and scored debt (impact x likelihood x cost to fix), how you made the case (incident data, error budget exhaustion, security exposure), and the mechanism you won (a fixed share of capacity, or error budget policy that pauses features).\n\nResult: what was paid down and its measured effect. Learnings: which debt you deliberately chose **not** to pay and why.", pitfalls: [ "Treating all debt as equally urgent or as a matter of taste", "Making the case on engineering aesthetics instead of impact", "A big-bang rewrite with no incremental value", "No follow-up measurement" ], exampleOutline: "- **S:** [system] had [debt items]; caused [N incidents / X hours toil / slow lead time]\n- **T:** I was [tech lead] responsible for [roadmap input]\n- **A:** inventoried [N] items; scored by [impact, risk, effort]\n- **A:** presented [top items] with [incident / cost data] to [product lead]\n- **A:** agreed [X% capacity / error-budget policy]; tackled incrementally via [strangler / phased]\n- **R:** paid down [items]; [incidents / toil / lead time] improved by [Y]\n- **L:** deliberately left [item] because [low interest]; we review the list [quarterly]" } ]; // ../../packages/content/src/infra/flashcards.ts var infraFlashcards = [ // ---------------- Networking & Edge ---------------- { id: "ifc-001", lessonId: "infra-net-fundamentals", objective: "net-fundamentals", front: "Latency orders of magnitude: memory reference, SSD random read, intra-AZ round trip, cross-continent round trip.", back: "Approximate orders of magnitude:\n- main memory reference: ~100 ns\n- SSD random read: ~tens to ~100 \xB5s\n- round trip within a data centre / AZ: ~0.1\u20130.5 ms\n- round trip across a continent or ocean: ~50\u2013150 ms\n\nThe gaps are uneven (memory \u2192 SSD ~1000x, SSD \u2192 intra-AZ RTT only a few x, intra-AZ \u2192 cross-ocean ~100x+), but the lesson holds: wide-area network round trips dominate most request budgets." }, { id: "ifc-002", lessonId: "infra-net-fundamentals", objective: "net-fundamentals", front: "How many round trips of connection setup before the client can send its first HTTPS request: TCP + TLS 1.2 vs TCP + TLS 1.3 vs QUIC?", back: "- TCP handshake: 1 RTT\n- TLS 1.2 full handshake: +2 RTT \u2192 ~3 RTT before the request\n- TLS 1.3 full handshake: +1 RTT \u2192 ~2 RTT\n- QUIC (HTTP/3): transport and TLS 1.3 combined \u2192 ~1 RTT; 0-RTT on resumption\n\nAt 100 ms RTT, that is the difference between ~300 ms and ~100 ms of setup." }, { id: "ifc-003", lessonId: "infra-net-fundamentals", objective: "net-fundamentals", front: "What is the risk of TLS 1.3 / QUIC **0-RTT** early data?", back: "Early data can be **replayed** by an attacker, so it must only carry idempotent requests (e.g. GETs without side effects). Servers often restrict or disable 0-RTT for non-idempotent operations." }, { id: "ifc-004", lessonId: "infra-net-fundamentals", objective: "net-fundamentals", front: "HTTP/2 multiplexes streams over one TCP connection. What problem remains, and how does HTTP/3 fix it?", back: "**Transport-level head-of-line blocking**: one lost TCP segment stalls every stream on the connection. HTTP/3 runs over QUIC (UDP), where loss on one stream does not block the others, and connections can migrate across IP changes." }, { id: "ifc-005", lessonId: "infra-net-fundamentals", objective: "net-fundamentals", front: "Why does lowering a DNS TTL right before a migration not always work?", back: "Resolvers keep the **old** record until the **old** TTL expires, and some clients and resolvers cache longer than the TTL. Lower the TTL at least one old-TTL period ahead of the cutover, and expect a long tail of stale clients." }, { id: "ifc-006", lessonId: "infra-net-fundamentals", objective: "net-fundamentals", front: "Rule of thumb: how much round-trip time does distance add over fibre?", back: "Light in fibre travels at roughly 200,000 km/s, so ~**1 ms of RTT per ~100 km** of path (approximate, before routing detours and queuing). No protocol tuning beats physics; move data or compute closer instead." }, { id: "ifc-007", lessonId: "infra-net-cloud", objective: "net-cloud", front: "CIDR sizes to know: /16, /20, /24, /28.", back: "- /16 = 65,536 addresses\n- /20 = 4,096\n- /24 = 256\n- /28 = 16\n\nEach bit shorter doubles the size. A few addresses per subnet are reserved by providers (e.g. 5 on AWS), so a /28 gives far fewer usable IPs than 16." }, { id: "ifc-008", lessonId: "infra-net-cloud", objective: "net-cloud", front: "What are the RFC 1918 private address ranges?", back: "- `10.0.0.0/8`\n- `172.16.0.0/12`\n- `192.168.0.0/16`\n\nPlan non-overlapping allocations across all VPCs/VNets and on-prem from day one; overlapping ranges block peering and hybrid routing later." }, { id: "ifc-009", lessonId: "infra-net-cloud", objective: "net-cloud", front: "Security groups vs network ACLs (AWS terms) \u2014 the key difference.", back: "Security groups are **stateful** and attach to instances/interfaces (return traffic is allowed automatically, allow rules only). NACLs are **stateless** and apply at the subnet (you must allow return traffic, and they support explicit deny). Azure NSGs and GCP firewall rules are stateful." }, { id: "ifc-010", lessonId: "infra-net-cloud", objective: "net-cloud", front: "Peering mesh vs transit hub: when does a hub win?", back: "Full-mesh peering needs n(n-1)/2 connections \u2014 20 networks means 190 peerings \u2014 and peering is typically non-transitive. A hub (transit gateway / virtual WAN hub / network connectivity centre style) centralises routing, inspection and hybrid links at the cost of an extra hop, per-GB processing charges and a shared blast radius." }, { id: "ifc-011", lessonId: "infra-net-cloud", objective: "net-cloud", front: "Why put a managed NAT gateway per AZ rather than one per VPC?", back: "A single NAT gateway is a **cross-AZ dependency**: if its AZ fails, private subnets in healthy AZs lose egress, and you also pay cross-AZ transfer. Per-AZ NAT keeps failure domains aligned \u2014 more cost, smaller blast radius." }, { id: "ifc-012", lessonId: "infra-net-edge", objective: "net-edge", front: "L4 vs L7 load balancing in one line each.", back: "**L4** forwards TCP/UDP connections by address and port \u2014 fast, protocol-agnostic, no request awareness. **L7** terminates HTTP(S) and routes per request (path, header, host), enabling retries, canaries and WAF \u2014 more CPU and more features to misconfigure." }, { id: "ifc-013", lessonId: "infra-net-edge", objective: "net-edge", front: "Why should a load balancer health check not depend on downstream dependencies?", back: "If the check fails when a shared dependency (e.g. the database) is slow, **every** instance fails at once and the LB removes the whole fleet, turning a partial outage into a total one. Health checks should reflect the instance's own ability to serve; handle dependency failure with degradation." }, { id: "ifc-014", lessonId: "infra-net-edge", objective: "net-edge", front: "Anycast vs DNS-based global load balancing.", back: "**Anycast** advertises one IP from many locations; BGP routes users to the nearest, and failover is as fast as routing converges. **DNS-based** steering returns different IPs per region/health, but failover is bounded by TTLs and resolver caching. Many global edges combine both." }, { id: "ifc-015", lessonId: "infra-net-edge", objective: "net-edge", front: "CDN cache hit ratio from 90% to 99%: what happens to origin load?", back: "Misses drop from 10% to 1% \u2014 a **10x** reduction in origin traffic. Small hit-ratio gains at the top end matter enormously; that is why cache keys, TTLs and origin shielding are worth tuning." }, // ---------------- Compute & Platforms ---------------- { id: "ifc-016", lessonId: "infra-compute-models", objective: "compute-models", front: "VMs vs containers vs serverless functions: the core trade-off.", back: "Moving right you give up **control** (kernel, runtime, long-running processes, tuning) for **less operational work** and finer-grained scaling. Serverless adds cold starts, execution time limits and per-invocation pricing that can exceed always-on compute at steady high load." }, { id: "ifc-017", lessonId: "infra-compute-models", objective: "compute-models", front: "Spot / preemptible capacity: what discount, what catch, which workloads?", back: "Often a large discount (frequently quoted at up to ~60\u201390% off on-demand, approximate and variable) in exchange for reclamation at short notice (e.g. a two-minute warning on AWS). Good for stateless, fault-tolerant, checkpointed or batch work; diversify instance types and AZs." }, { id: "ifc-018", lessonId: "infra-compute-models", objective: "compute-models", front: "What is immutable infrastructure, and what does it buy you?", back: "Never patch servers in place; build a new image and replace instances. You get reproducibility, no configuration drift, trivial rollback (redeploy the previous image) and easier forensics. Cost: a fast, reliable image pipeline." }, { id: "ifc-019", lessonId: "infra-compute-models", objective: "compute-models", front: "What is a serverless cold start and how do you mitigate it?", back: "Latency added when the platform must create a new execution environment (download code, start runtime, run init). Mitigate with smaller packages, lighter runtimes, init outside the handler, and provisioned / minimum instances where the tail latency matters." }, { id: "ifc-020", lessonId: "infra-compute-scaling", objective: "compute-scaling", front: "Why does reactive autoscaling fail on sharp spikes?", back: "Total lag = metric collection + evaluation window + instance boot + app warm-up, often minutes. A spike can saturate the fleet before capacity arrives. Keep headroom, use scheduled or predictive scaling for known peaks, warm pools / pre-baked images, and load shedding as the backstop." }, { id: "ifc-021", lessonId: "infra-compute-scaling", objective: "compute-scaling", front: "Which autoscaling signal is usually better than CPU for a request-serving tier?", back: "A load signal closer to demand \u2014 requests per instance, in-flight requests or queue depth \u2014 because CPU may not be the bottleneck (I/O-bound, thread-pool-bound) and lags behind demand. For queue consumers, scale on backlog per worker or age of oldest message." }, { id: "ifc-022", lessonId: "infra-compute-scaling", objective: "compute-scaling", front: "N+1 vs N+2 vs AZ-level headroom: how much spare capacity for surviving an AZ loss with 3 AZs?", back: "To lose one of three AZs and still serve peak, the remaining two must carry 100%, so each AZ needs ~50% of peak \u2014 i.e. run at **\u2264 ~67% utilisation** at peak overall. Static stability means this capacity is already running, not launched during the failure." }, { id: "ifc-023", lessonId: "infra-compute-scaling", objective: "compute-scaling", front: "Back-of-envelope: 1 million requests per day is about how many per second?", back: "~**12 req/s** average (86,400 seconds per day). Peaks are often several times the average, so design for peak \u2014 e.g. 3\u201310x \u2014 not for the mean." }, { id: "ifc-024", lessonId: "infra-compute-platform", objective: "compute-platform", front: "Soft vs hard multi-tenancy in Kubernetes.", back: "**Soft**: trusted tenants (internal teams) separated by namespaces, RBAC, quotas and network policies on a shared cluster. **Hard**: untrusted tenants need stronger isolation \u2014 separate clusters, dedicated nodes, sandboxed runtimes \u2014 because the kernel and control plane are shared." }, { id: "ifc-025", lessonId: "infra-compute-platform", objective: "compute-platform", front: "How many etcd members, and why not 4?", back: "Use **3 or 5**. A cluster of n tolerates \u230A(n-1)/2\u230B failures: 3 \u2192 1, 5 \u2192 2. Four members still tolerate only 1 failure but need a larger quorum (3), adding write latency and failure surface without benefit." }, { id: "ifc-026", lessonId: "infra-compute-platform", objective: "compute-platform", front: "What is a golden path in platform engineering?", back: "An opinionated, supported, self-service way to build, deploy and run a service (templates, pipelines, defaults for observability and security). It makes the right thing the easy thing without forbidding alternatives; success is measured by voluntary adoption and developer lead time." }, { id: "ifc-027", lessonId: "infra-compute-platform", objective: "compute-platform", front: "Why must Kubernetes cluster upgrades be a routine, not a project?", back: "Upstream maintains patch releases for only the most recent three minor versions, so clusters fall out of support quickly. Upgrade on a cadence, test in lower environments, upgrade control plane before nodes, and watch for removed APIs." }, // ---------------- Storage & Data ---------------- { id: "ifc-028", lessonId: "infra-storage-types", objective: "storage-types", front: "Durability vs availability.", back: "**Durability** = probability data is not lost. **Availability** = probability you can access it right now. Object stores are typically designed for far higher durability (e.g. 99.999999999% for S3) than availability (often 99.9\u201399.99%). A region outage can make data unavailable while it remains durable." }, { id: "ifc-029", lessonId: "infra-storage-types", objective: "storage-types", front: "Block vs file vs object storage: access model and typical use.", back: "- **Block**: raw volume attached to one host (usually), low latency \u2014 databases, boot disks\n- **File**: shared POSIX filesystem over the network \u2014 shared content, legacy apps\n- **Object**: HTTP API, flat keys, effectively unlimited scale, higher latency \u2014 backups, data lakes, static assets" }, { id: "ifc-030", lessonId: "infra-storage-types", objective: "storage-types", front: "Are replication and snapshots a backup?", back: "Replication is **not** a backup: it faithfully copies deletes and corruption. Snapshots help but often share the account, region or keys. A backup must be point-in-time, isolated (separate account/region, ideally immutable) and **restore-tested**." }, { id: "ifc-031", lessonId: "infra-storage-types", objective: "storage-types", front: "Storage class / lifecycle trap with cold tiers.", back: "Cold and archive tiers are cheap to store but can charge for retrieval, have minimum storage durations and retrieval delays. Moving frequently-read or short-lived data there can cost **more**. Base lifecycle rules on measured access patterns." }, { id: "ifc-032", lessonId: "infra-data-databases", objective: "data-databases", front: "Synchronous vs asynchronous replication: what does each cost?", back: "**Sync**: a commit waits for a replica, so RPO \u2248 0 but every write pays replica latency and availability depends on the replica. **Async**: fast writes, but failover can lose the last seconds of writes (RPO > 0). Semi-sync and quorum commits sit in between." }, { id: "ifc-033", lessonId: "infra-data-databases", objective: "data-databases", front: "Read replicas: the classic correctness bug.", back: "**Read-your-writes** violations: a user writes to the primary, then reads a lagging replica and sees old data. Fix with primary reads for recent writers, session stickiness, or waiting until the replica has caught up to the write's position." }, { id: "ifc-034", lessonId: "infra-data-databases", objective: "data-databases", front: "How do you choose a shard key?", back: "High cardinality, even distribution and alignment with the dominant access pattern so most queries hit one shard. Avoid monotonic keys (timestamps, sequential IDs) that create hot shards. Resharding is expensive \u2014 consistent hashing or many logical shards per node eases it." }, { id: "ifc-035", lessonId: "infra-data-databases", objective: "data-databases", front: "Expand/contract schema migration.", back: "Make schema changes backward compatible across a rolling deploy: **expand** (add nullable column / new table), deploy code that writes both, backfill, switch reads, then **contract** (drop old). Each step is independently deployable and reversible." }, { id: "ifc-036", lessonId: "infra-data-caching", objective: "data-caching", front: "Cache-aside vs write-through vs write-back.", back: "- **Cache-aside**: app reads cache, on miss loads DB and fills cache \u2014 simple, may serve stale data\n- **Write-through**: writes go to cache and DB together \u2014 fresher, slower writes\n- **Write-back**: write to cache, flush later \u2014 fastest writes, risk of data loss" }, { id: "ifc-037", lessonId: "infra-data-caching", objective: "data-caching", front: "What is a cache stampede and three mitigations?", back: "Many requests miss the same key at once (expiry or cold cache) and all hit the database. Mitigate with **request coalescing** (single flight / lock per key), **jittered TTLs** or early probabilistic refresh, and serving stale while revalidating." }, { id: "ifc-038", lessonId: "infra-data-caching", objective: "data-caching", front: "The cold-cache trap after a cache cluster restart.", back: "If the database is sized only for the miss traffic at a 95% hit ratio, a cold cache sends ~20x the usual load to it and it falls over. The cache is a **load-bearing dependency**: warm it gradually, shed load, or size the database for degraded operation." }, { id: "ifc-039", lessonId: "infra-data-caching", objective: "data-caching", front: "Hot key in a distributed cache: symptoms and fixes.", back: "One shard saturates (CPU or network) while others idle; latency spikes for everything on that shard. Fix with a small in-process cache in front, key replication with random suffixes across shards, or request coalescing." }, // ---------------- Distributed Systems ---------------- { id: "ifc-040", lessonId: "infra-dist-theory", objective: "dist-theory", front: "CAP vs PACELC in one line.", back: "**CAP**: during a network Partition, choose Consistency or Availability. **PACELC** adds: **E**lse (no partition) you still trade **L**atency against **C**onsistency \u2014 which is the trade-off you live with every day." }, { id: "ifc-041", lessonId: "infra-dist-theory", objective: "dist-theory", front: "Quorum sizes: how many failures does a cluster of 3, 5 or 7 tolerate?", back: "Majority quorum = \u230An/2\u230B + 1; tolerates \u230A(n-1)/2\u230B failures:\n- 3 \u2192 quorum 2, tolerates 1\n- 5 \u2192 quorum 3, tolerates 2\n- 7 \u2192 quorum 4, tolerates 3\n\nUse odd sizes; spread members across failure domains (e.g. one per AZ)." }, { id: "ifc-042", lessonId: "infra-dist-theory", objective: "dist-theory", front: "Leaderless replication: what does R + W > N guarantee?", back: "With N replicas, writes acknowledged by W and reads from R, R + W > N means every read set overlaps the latest write set, so a read can see the latest acknowledged write (e.g. N=3, W=2, R=2). It does not by itself give linearizability under concurrency and sloppy quorums." }, { id: "ifc-043", lessonId: "infra-dist-theory", objective: "dist-theory", front: "Linearizability vs serializability.", back: "**Linearizability**: single-object recency \u2014 once a write completes, every later read sees it (as if one copy). **Serializability**: multi-object transactions behave as if executed in some serial order. Strict serializability gives both." }, { id: "ifc-044", lessonId: "infra-dist-theory", objective: "dist-theory", front: "Why not order events across machines by wall-clock timestamps?", back: 'Clocks drift and jump (NTP corrections), so "last write wins" by timestamp can silently drop newer writes. Use logical clocks (Lamport, vector), a single sequencer/leader, or bounded-uncertainty clocks if your platform provides them.' }, { id: "ifc-045", lessonId: "infra-dist-patterns", objective: "dist-patterns", front: "Retry amplification: 3 retries at each of 5 layers.", back: "Each layer makes up to 4 attempts, so worst case is 4^5 = **1,024x** load on the bottom dependency. Retry at one layer (usually nearest the caller), cap with a retry budget, and use exponential backoff with jitter." }, { id: "ifc-046", lessonId: "infra-dist-patterns", objective: "dist-patterns", front: "Why add **jitter** to exponential backoff?", back: "Without jitter, clients that failed together retry together, producing synchronised waves that keep the dependency overloaded. Randomising the delay spreads retries out so the system can recover." }, { id: "ifc-047", lessonId: "infra-dist-patterns", objective: "dist-patterns", front: "What makes a retry safe?", back: "The operation must be **idempotent**. For non-idempotent operations (payments, orders) the client sends an idempotency key; the server stores the result per key and returns it on duplicates instead of executing twice." }, { id: "ifc-048", lessonId: "infra-dist-patterns", objective: "dist-patterns", front: "Circuit breaker states.", back: "**Closed** (calls flow, failures counted) \u2192 **Open** after a threshold (fail fast, no calls) \u2192 **Half-open** after a cool-down (let trial calls through; success closes, failure reopens). It protects both the caller's resources and the struggling dependency." }, { id: "ifc-049", lessonId: "infra-dist-patterns", objective: "dist-patterns", front: "How should timeouts be set across a call chain?", back: "Based on the dependency's measured latency (e.g. somewhat above its p99.9), and **decreasing down the chain** so the caller's deadline exceeds the total of its downstream attempts. Better: propagate a deadline so downstream work stops when the caller has given up." }, { id: "ifc-050", lessonId: "infra-dist-messaging", objective: "dist-messaging", front: "Queue vs log/stream.", back: "A **queue** delivers each message to one consumer and deletes it on ack \u2014 work distribution. A **log/stream** retains ordered records for a period; many consumer groups read independently at their own offsets and can replay \u2014 event distribution and reprocessing." }, { id: "ifc-051", lessonId: "infra-dist-messaging", objective: "dist-messaging", front: 'Is "exactly-once delivery" achievable end to end?', back: "Not across arbitrary side effects. Practical systems give **at-least-once** delivery plus **idempotent processing** (dedupe by message ID or idempotency key), giving effectively-once results. Some brokers offer exactly-once within their own transactional boundary." }, { id: "ifc-052", lessonId: "infra-dist-messaging", objective: "dist-messaging", front: "Ordering and parallelism in partitioned logs (e.g. Kafka).", back: "Order is guaranteed only **within a partition**. Key messages by entity so one entity's events stay ordered. Consumer parallelism within a group is capped by partition count; a hot key concentrates load on one partition." }, { id: "ifc-053", lessonId: "infra-dist-messaging", objective: "dist-messaging", front: "What problem does the transactional outbox solve?", back: "The **dual-write** problem: updating a database and publishing an event cannot be atomic. Write the event to an outbox table in the same DB transaction, then a relay publishes it \u2014 at-least-once, so consumers must be idempotent." }, // ---------------- Reliability & SRE ---------------- { id: "ifc-054", lessonId: "infra-rel-slo", objective: "rel-slo", front: "Downtime per year and per month for 99.9%, 99.95%, 99.99%, 99.999%.", back: "Approximate (30-day month):\n- 99.9% \u2192 ~8.76 h/year, ~43 min/month\n- 99.95% \u2192 ~4.38 h/year, ~22 min/month\n- 99.99% \u2192 ~52.6 min/year, ~4.3 min/month\n- 99.999% \u2192 ~5.3 min/year, ~26 s/month\n\nEach extra nine is 10x less downtime and usually much more than 10x the cost." }, { id: "ifc-055", lessonId: "infra-rel-slo", objective: "rel-slo", front: "Serial vs parallel availability arithmetic.", back: "**Serial** (all required): multiply \u2014 two 99.9% dependencies \u2192 ~99.8%. **Parallel** (any one suffices, independent failures): 1 \u2212 (1 \u2212 a)^n \u2014 two 99% replicas \u2192 99.99%. Independence is the big assumption; shared failure domains break it." }, { id: "ifc-056", lessonId: "infra-rel-slo", objective: "rel-slo", front: "What is a burn rate, and what does burn rate 1 mean?", back: "Burn rate = how fast you consume error budget relative to the SLO window. **1** means the budget runs out exactly at the end of the window; **10** means it runs out in a tenth of the window (a 30-day budget gone in 3 days)." }, { id: "ifc-057", lessonId: "infra-rel-slo", objective: "rel-slo", front: "Classic fast-burn page threshold for a 30-day SLO.", back: "Burn rate **14.4 over 1 hour** = 2% of the 30-day budget consumed in an hour (14.4 x 1 h / 720 h). Pair a long window with a short one (e.g. 1 h and 5 min) so the alert fires fast and resets fast; add a slower page (6x over 6 h = 5% of budget) and a ticket for slow burns (e.g. 1x over 3 days = 10%)." }, { id: "ifc-058", lessonId: "infra-rel-slo", objective: "rel-slo", front: "SLI vs SLO vs SLA.", back: "**SLI**: a measured ratio of good events to valid events (e.g. requests < 300 ms). **SLO**: the internal target for it over a window (99.9% over 30 days). **SLA**: a contractual promise with penalties, set looser than the SLO so you breach the SLO first." }, { id: "ifc-059", lessonId: "infra-rel-slo", objective: "rel-slo", front: "What does an error budget policy do?", back: "It turns the SLO into decisions: while budget remains, ship freely; when it is exhausted, prioritise reliability work (freeze risky launches, fix top causes). It aligns product and SRE on one number instead of arguing about risk case by case." }, { id: "ifc-060", lessonId: "infra-rel-incidents", objective: "rel-incidents", front: "Incident command roles.", back: "**Incident commander** (coordinates, decides, does not debug), **operations lead** (hands on keyboard), **communications lead** (stakeholder and customer updates), optionally a scribe/planner. Separating roles stops everyone debugging while nobody communicates." }, { id: "ifc-061", lessonId: "infra-rel-incidents", objective: "rel-incidents", front: "Mitigate before root cause \u2014 why?", back: "Customer impact accrues every minute. Roll back, fail over, disable the flag or shed load first; root cause analysis happens after service is restored (preserve evidence while mitigating). The most recent change is the most likely suspect." }, { id: "ifc-062", lessonId: "infra-rel-incidents", objective: "rel-incidents", front: "What makes a postmortem blameless and useful?", back: "It focuses on how the system and process allowed the failure, assuming people acted reasonably with the information they had. Useful = clear timeline, impact in numbers, contributing factors, and owned, prioritised action items that are tracked to completion." }, { id: "ifc-063", lessonId: "infra-rel-incidents", objective: "rel-incidents", front: "Define toil and the Google SRE guideline for it.", back: "Toil is manual, repetitive, automatable, tactical work with no enduring value that scales linearly with service growth. Google SRE aims to keep it **under 50%** of an SRE's time so the rest goes to engineering that reduces future toil." }, { id: "ifc-064", lessonId: "infra-rel-resilience", objective: "rel-resilience", front: "RPO vs RTO.", back: "**RPO** (recovery point objective): how much data loss is acceptable, measured in time. **RTO** (recovery time objective): how long until service is restored. Backups drive RPO; automation, warm capacity and practice drive RTO." }, { id: "ifc-065", lessonId: "infra-rel-resilience", objective: "rel-resilience", front: "DR strategies from cheapest to fastest recovery.", back: "**Backup and restore** (hours, cheapest) \u2192 **pilot light** (core data replicated, minimal compute) \u2192 **warm standby** (scaled-down full stack) \u2192 **multi-site active-active** (near-zero RTO, highest cost and complexity, data consistency challenges)." }, { id: "ifc-066", lessonId: "infra-rel-resilience", objective: "rel-resilience", front: "What is static stability?", back: "The system keeps working during a failure **without needing to make changes** \u2014 e.g. capacity in each AZ is already provisioned to absorb an AZ loss, rather than relying on launching instances via a control plane that may itself be impaired." }, { id: "ifc-067", lessonId: "infra-rel-resilience", objective: "rel-resilience", front: "What is cell-based architecture, and what does it limit?", back: "Split the system into independent, identical cells each serving a subset of customers, with a thin routing layer. A bad deploy, poison request or overload affects only one cell, limiting **blast radius** to roughly 1/number-of-cells." }, // ---------------- Security & Identity ---------------- { id: "ifc-068", lessonId: "infra-sec-identity", objective: "sec-identity", front: "Zero trust core principle.", back: "No implicit trust from network location: every request is authenticated and authorised based on identity, device/workload posture and context, with least privilege and continuous verification (NIST SP 800-207)." }, { id: "ifc-069", lessonId: "infra-sec-identity", objective: "sec-identity", front: "Why prefer workload identity over long-lived access keys?", back: "Workload identity (instance roles, Kubernetes service account federation, managed identities) issues **short-lived, automatically rotated** credentials bound to the workload. Static keys leak into repos, logs and laptops and stay valid until someone notices." }, { id: "ifc-070", lessonId: "infra-sec-identity", objective: "sec-identity", front: "How do you get to least privilege in practice?", back: "Start from deny, grant narrowly scoped roles per workload, use access analysis on actual usage to remove unused permissions, add guardrails at the organisation level (deny policies), and use just-in-time elevation for humans instead of standing admin." }, { id: "ifc-071", lessonId: "infra-sec-identity", objective: "sec-identity", front: "Authentication vs authorisation, and where federation fits.", back: "**AuthN** proves who you are; **AuthZ** decides what you may do. **Federation / SSO** (SAML, OIDC) delegates authentication to a central identity provider so access can be granted and revoked in one place." }, { id: "ifc-072", lessonId: "infra-sec-data", objective: "sec-data", front: "Envelope encryption.", back: "Data is encrypted with a **data encryption key (DEK)**; the DEK is encrypted by a **key encryption key (KEK)** held in KMS/HSM. Bulk data never goes to KMS, rotation of the KEK does not require re-encrypting all data, and access to the KEK is centrally audited and controlled." }, { id: "ifc-073", lessonId: "infra-sec-data", objective: "sec-data", front: "What does mTLS add over TLS?", back: "Both sides present certificates, so the **server also authenticates the client**. In service meshes it gives encrypted, identity-based service-to-service traffic; the hard part is certificate issuance and rotation, which must be automated." }, { id: "ifc-074", lessonId: "infra-sec-data", objective: "sec-data", front: "Encryption at rest: what threat does it actually address?", back: "Mainly physical media loss and some storage-layer access. It does **not** protect against a compromised application or identity that is authorised to decrypt. Pair it with tight key policies, access controls and audit." }, { id: "ifc-075", lessonId: "infra-sec-data", objective: "sec-data", front: "Secrets management must-haves.", back: "Central store with access control and audit, injection at runtime (not baked into images or repos), short-lived or dynamic credentials where possible, rotation without redeploys, and secret scanning in CI to catch leaks." }, { id: "ifc-076", lessonId: "infra-sec-supply-chain", objective: "sec-supply-chain", front: "Shared responsibility model in one line.", back: "The provider secures the cloud (facilities, hardware, hypervisor, managed service internals); the customer secures what they put **in** it (identity, data, configuration, network rules, OS for IaaS). The line moves up as services become more managed." }, { id: "ifc-077", lessonId: "infra-sec-supply-chain", objective: "sec-supply-chain", front: "SBOM vs provenance vs signing.", back: "**SBOM**: what is inside an artifact (components, versions). **Provenance**: how and where it was built (source, builder, steps), as SLSA describes. **Signing**: cryptographic proof of who produced it and that it is unchanged (e.g. Sigstore). Admission policies verify these at deploy." }, { id: "ifc-078", lessonId: "infra-sec-supply-chain", objective: "sec-supply-chain", front: 'Vulnerability management: why not "fix every CVE"?', back: "Scanners produce far more findings than teams can fix. Prioritise by exploitability, reachability and exposure (internet-facing, privileged), keep base images minimal and rebuilt frequently, and track time-to-remediate per severity." }, { id: "ifc-079", lessonId: "infra-sec-supply-chain", objective: "sec-supply-chain", front: "Preventive vs detective guardrails.", back: "**Preventive** controls block bad config before it exists (policy as code in CI, admission controllers, organisation deny policies). **Detective** controls find it afterwards (config scanning, audit logs). Use both: prevent the critical, detect the rest." }, // ---------------- Automation & Delivery ---------------- { id: "ifc-080", lessonId: "infra-auto-iac", objective: "auto-iac", front: "What is Terraform state, and why does it need locking?", back: "State maps configuration to real resource IDs and tracks attributes. Two concurrent applies against the same state can corrupt it or create duplicates, so a remote backend with **locking** is required for teams. State can contain secrets \u2014 encrypt and restrict it." }, { id: "ifc-081", lessonId: "infra-auto-iac", objective: "auto-iac", front: "How do you limit IaC blast radius?", back: "Split state by environment, region and lifecycle (network vs app), keep plans small, require reviewed plans before apply, use prevent-destroy style protections for critical resources, and promote the same modules through environments." }, { id: "ifc-082", lessonId: "infra-auto-iac", objective: "auto-iac", front: "What is drift and how do you handle it?", back: "Real infrastructure diverging from code, usually via console changes or out-of-band automation. Detect with scheduled plans, decide to revert or codify, and reduce it by removing write access outside the pipeline." }, { id: "ifc-083", lessonId: "infra-auto-iac", objective: "auto-iac", front: "Declarative vs imperative infrastructure.", back: "**Declarative**: describe desired end state; the tool computes the diff and order (Terraform, Kubernetes manifests). **Imperative**: script the steps. Declarative gives idempotency, plans and drift detection; imperative is still useful for one-off orchestration." }, { id: "ifc-084", lessonId: "infra-auto-delivery", objective: "auto-delivery", front: "Blue/green vs canary.", back: "**Blue/green**: full parallel environment, switch all traffic, instant rollback, double capacity during switch. **Canary**: shift a small percentage, compare metrics, ramp gradually \u2014 catches issues with small blast radius but needs good automated analysis." }, { id: "ifc-085", lessonId: "infra-auto-delivery", objective: "auto-delivery", front: "The four DORA delivery metrics.", back: "**Deployment frequency** and **lead time for changes** (throughput); **change failure rate** and **time to restore service** (stability; recent DORA reports call the latter failed deployment recovery time and add rework rate). High performers do well on both \u2014 speed and stability are not a trade-off when delivery is automated." }, { id: "ifc-086", lessonId: "infra-auto-delivery", objective: "auto-delivery", front: "Build once, promote the artifact \u2014 why?", back: "Rebuilding per environment means what you tested is not what you ship. Build an immutable, versioned (ideally signed) artifact once, then promote the same digest through environments with only configuration changing." }, { id: "ifc-087", lessonId: "infra-auto-delivery", objective: "auto-delivery", front: "Feature flags: benefit and hidden cost.", back: "They decouple deploy from release and give a fast kill switch. Hidden costs: combinatorial test paths, stale flags as debt and the flag service as a critical dependency \u2014 define owners and expiry, and fail to a safe default." }, { id: "ifc-088", lessonId: "infra-auto-delivery", objective: "auto-delivery", front: "GitOps in one sentence.", back: "Git holds the declared desired state; an in-cluster agent continuously pulls and reconciles the live system to it, so changes are reviewed, audited and reverted via Git, and drift is corrected automatically." }, // ---------------- Observability & Performance ---------------- { id: "ifc-089", lessonId: "infra-obs-signals", objective: "obs-signals", front: "Four golden signals vs RED vs USE.", back: "- **Golden signals**: latency, traffic, errors, saturation (user-facing services)\n- **RED**: rate, errors, duration (request-driven services)\n- **USE**: utilisation, saturation, errors (resources: CPU, disk, network)" }, { id: "ifc-090", lessonId: "infra-obs-signals", objective: "obs-signals", front: "Symptom-based vs cause-based alerting.", back: "Page on **symptoms** users feel (SLO burn, error rate, latency), because every page should be urgent and actionable. Causes (high CPU, a node down) belong on dashboards or tickets \u2014 many causes never hurt users and paging on them burns out on-call." }, { id: "ifc-091", lessonId: "infra-obs-signals", objective: "obs-signals", front: "Why is high-cardinality metric labelling dangerous?", back: "Each unique label combination is a separate time series; adding a user ID or request ID label can create millions of series, exploding cost and query latency. Put high-cardinality detail in logs or traces, not metric labels." }, { id: "ifc-092", lessonId: "infra-obs-signals", objective: "obs-signals", front: "Why can't you average percentiles across hosts?", back: "The mean of per-host p99s is not the fleet p99 and can badly understate tail latency. Aggregate histograms (buckets) and compute percentiles from the merged distribution." }, { id: "ifc-093", lessonId: "infra-obs-performance", objective: "obs-performance", front: "Little's law.", back: "**L = \u03BB x W**: items in the system = arrival rate x time in system. Example: 1,000 req/s at 200 ms average latency \u2192 ~200 requests in flight, so you need at least ~200 concurrent workers/connections. If latency doubles, required concurrency doubles." }, { id: "ifc-094", lessonId: "infra-obs-performance", objective: "obs-performance", front: "Queueing intuition: why does latency explode near 100% utilisation?", back: "For a simple single-server queue (M/M/1), time in system \u221D 1 / (1 \u2212 utilisation): at 50% it is 2x service time, at 80% ~5x, at 90% ~10x, at 95% ~20x. Leave headroom on latency-sensitive resources." }, { id: "ifc-095", lessonId: "infra-obs-performance", objective: "obs-performance", front: "Tail latency fan-out: a request calls 100 backends in parallel, each with 1% chance of being slow.", back: "Probability the request is slow = 1 \u2212 0.99^100 \u2248 **63%**. Fan-out turns a backend's p99 into the user's median. Mitigate with hedged requests, smaller fan-out, and tighter backend tail latency." }, { id: "ifc-096", lessonId: "infra-obs-performance", objective: "obs-performance", front: "The USE method in practice.", back: "For every resource (CPU, memory, disks, network, locks, thread pools) check **utilisation**, **saturation** (queued work) and **errors**. It quickly finds the bottleneck instead of guessing. Saturation often matters more than utilisation." }, { id: "ifc-097", lessonId: "infra-obs-performance", objective: "obs-performance", front: "First 60 seconds on a slow Linux host: what do you look at?", back: "Load and CPU (`uptime`, `top`, `mpstat`), memory and swapping (`free`, `vmstat`), disk I/O (`iostat`), network (`sar -n DEV`, `ss`) and recent errors (`dmesg`). The aim is to find which resource is saturated before diving into application code." }, // ---------------- Architecture & Cost ---------------- { id: "ifc-098", lessonId: "infra-arch-frameworks", objective: "arch-frameworks", front: "Well-Architected pillars: AWS vs Azure.", back: "**AWS (6)**: operational excellence, security, reliability, performance efficiency, cost optimisation, sustainability. **Azure (5)**: reliability, security, cost optimisation, operational excellence, performance efficiency. The senior skill is articulating the trade-offs between pillars." }, { id: "ifc-099", lessonId: "infra-arch-frameworks", objective: "arch-frameworks", front: 'Migration strategies ("7 Rs").', back: "**Retire, retain, rehost** (lift and shift), **relocate**, **repurchase** (move to SaaS), **replatform** (lift, tinker and shift), **refactor** (re-architect). Choose per workload by value, risk and timeline; most estates mix several." }, { id: "ifc-100", lessonId: "infra-arch-finops", objective: "arch-finops", front: "FinOps lifecycle phases.", back: "**Inform** (visibility, allocation, showback), **Optimise** (rightsizing, commitments, waste removal), **Operate** (governance, continuous improvement). It is iterative; engineering, finance and product share ownership of cost." }, { id: "ifc-101", lessonId: "infra-arch-finops", objective: "arch-finops", front: "Why track unit economics rather than total cloud spend?", back: "Total spend rises with growth, which may be healthy. **Cost per unit** (per request, per customer, per transaction) shows efficiency: if the bill doubles while traffic triples, things are improving." }, // ---------------- Interview Craft ---------------- { id: "ifc-102", lessonId: "infra-craft-system-design", objective: "craft-system-design", front: "The system design interview flow in 45 minutes.", back: "Clarify requirements and scale (~5 min) \u2192 back-of-envelope estimates (~5) \u2192 high-level design (~10\u201315) \u2192 deep dives on the hardest parts (~15) \u2192 trade-offs, failure modes and evolution (~5). Drive it yourself and state assumptions out loud." }, { id: "ifc-103", lessonId: "infra-arch-frameworks", objective: "arch-frameworks", front: "Multi-cloud for resilience: the senior take.", back: "It usually costs more than it returns: lowest-common-denominator services, duplicated tooling and skills, and cross-cloud egress. Multi-region within one provider covers most resilience needs; multi-cloud is justified by regulation, acquisitions, negotiating leverage or a specific best-of-breed service." }, { id: "ifc-104", lessonId: "infra-arch-finops", objective: "arch-finops", front: "Commitments (reserved / savings plans / committed use) vs spot vs on-demand.", back: "Cover the steady **baseline** with commitments (discount for 1\u20133 year terms), run interruptible, fault-tolerant work on **spot**, and leave spiky or uncertain load on **on-demand**. Over-committing turns a discount into waste; ladder commitments over time." }, { id: "ifc-105", lessonId: "infra-arch-finops", objective: "arch-finops", front: "The cost drivers people forget in architecture reviews.", back: "**Data transfer** (internet egress, cross-region and cross-AZ traffic, NAT and load balancer processing), log and metric ingestion/retention, idle non-production environments and unattached volumes/snapshots. Chatty cross-AZ microservices can cost more in transfer than in compute." }, { id: "ifc-106", lessonId: "infra-craft-system-design", objective: "craft-system-design", front: "Back-of-envelope numbers to keep in your head.", back: "- ~86,400 seconds/day; ~2.6 million seconds/month\n- 1M requests/day \u2248 12 req/s average\n- 1 KB x 1M/day \u2248 1 GB/day \u2248 365 GB/year\n- 99.9% \u2192 ~43 min/month downtime\n\nRound aggressively; the goal is orders of magnitude that drive design choices." }, { id: "ifc-107", lessonId: "infra-craft-system-design", objective: "craft-system-design", front: "What separates a senior system design answer from a mid-level one?", back: "Explicit **trade-offs** with reasons, quantified estimates, **failure modes and blast radius**, operability (deploys, observability, on-call), cost, and an evolution path \u2014 not just a diagram of boxes. Senior candidates also say what they would **not** build yet." }, { id: "ifc-108", lessonId: "infra-craft-behavioral", objective: "craft-behavioral", front: "STAR + L: what goes in each part, and how long?", back: "**Situation** and **Task** briefly (scope, stakes, your role; ~20%), **Action** in depth (what *you* did and why; ~50\u201360%), **Result** in numbers (~10\u201320%), then **Learnings** \u2014 what you changed afterwards. Aim for ~2\u20133 minutes before follow-ups." }, { id: "ifc-109", lessonId: "infra-craft-behavioral", objective: "craft-behavioral", front: "How do you show seniority in a behavioural answer?", back: 'Scope (teams, systems, users, money affected), **influence without authority**, judgement under ambiguity, durable mechanisms rather than heroics, and measured outcomes. Say "I" for your actions and "we" for the team result.' }, { id: "ifc-110", lessonId: "infra-craft-behavioral", objective: "craft-behavioral", front: "How many stories should you prepare, and how?", back: "Around 8\u201310 real stories, each mapped to several themes (incident, ownership, conflict, failure, influence, mentoring, trade-off). Write a bullet outline with metrics for each, rehearse out loud, and be ready for two levels of follow-up on any detail." } ]; // ../../packages/content/src/infra/index.ts var infraLessons = [...infraLessons1, ...infraLessons2, ...infraLessons3].sort( (a, b) => a.stage - b.stage || a.order - b.order ); var infraQuestions = [...infraQuestions1, ...infraQuestions2, ...infraQuestions3]; var designCases = [...designCases1, ...designCases2]; var infraLessonIndex = new Map(infraLessons.map((l) => [l.id, l])); var infraQuestionIndex = new Map(infraQuestions.map((q2) => [q2.id, q2])); var infraLessonById = (id) => infraLessonIndex.get(id); var infraQuestionById = (id) => infraQuestionIndex.get(id); var designCaseById = (id) => designCases.find((c) => c.id === id); // ../../packages/content/src/lessons/a.ts var lessonsA = [ // ───────────────────────────── Stage 0 · Foundations ───────────────────────────── { id: "linux-essentials", title: "Linux essentials for containers", stage: 0, order: 1, objectives: ["kf-containerization"], scope: "foundation", estMinutes: 20, summary: "A container is an ordinary Linux process wrapped in kernel namespaces (what it can see), cgroups (what it can use) and its own root filesystem. Signals decide how it stops.", what: `Containers are not a kernel feature of their own. They are a **combination of Linux kernel features** applied to a normal process: - **Processes** \u2013 every running program has a PID, a parent, a user ID and open files. A container's main process is just a process on the host. - **Namespaces** \u2013 give a process its own private *view* of a system resource: process IDs, network stack, mount points, hostname, IPC and users. - **cgroups (control groups)** \u2013 limit and account for what a group of processes may *consume*: CPU time, memory, PIDs, I/O. - **Root filesystem** \u2013 the process sees a directory tree (unpacked from an image) as its \`/\`, instead of the host's. - **Signals** \u2013 asynchronous notifications like \`SIGTERM\` (please stop) and \`SIGKILL\` (stop now, cannot be caught) that the runtime and Kubernetes use to shut containers down.`, why: `Kubernetes settings map almost one-to-one onto these primitives. A memory **limit** becomes a cgroup memory limit; exceeding it gets the process killed by the kernel (\`OOMKilled\`). Pods sharing \`localhost\` works because the containers in a Pod share one **network namespace**. A graceful shutdown works only if your process handles \`SIGTERM\`. When you debug a container you are debugging a Linux process. Knowing that removes most of the "magic".`, problem: `Before containers, running two applications on one server meant they shared everything: the same PID space, the same ports, the same \`/etc\`, the same library versions. One runaway process could eat all memory and take the neighbours down. The options were to buy another machine or run a full virtual machine per app. Namespaces and cgroups solve this cheaply: each app gets an isolated view and a resource budget, while all apps still share one kernel.`, how: `What a runtime such as runc does when it starts a container, step by step: - **Prepare the filesystem.** Image layers are stacked (usually with an overlay filesystem) into one directory that will become the container's root. - **Create namespaces.** The runtime asks the kernel (via \`clone\`/\`unshare\`) for new PID, mount, network, UTS (hostname), IPC and optionally user namespaces. Inside the new PID namespace the first process sees itself as **PID 1**. - **Place the process in a cgroup.** The runtime writes limits such as \`memory.max\` and \`cpu.max\` (cgroup v2) for that cgroup. The kernel enforces them: CPU over the limit is **throttled**; memory over the limit triggers the **OOM killer**. - **Switch the root.** The process's root is changed to the prepared directory (\`pivot_root\`), so the host filesystem is invisible. - **Drop privileges.** Linux capabilities are reduced, and seccomp/AppArmor/SELinux profiles may restrict system calls. - **Exec the entrypoint.** The image's command replaces the runtime's setup code. From here on it is just your program. - **Stop.** To stop it, the runtime sends \`SIGTERM\` to PID 1, waits, then sends \`SIGKILL\`. In Kubernetes the wait is the Pod's \`terminationGracePeriodSeconds\` (default 30).`, components: [ { name: "Namespaces", description: "Isolate what a process can **see**: `pid`, `net`, `mnt`, `uts`, `ipc`, `user`, `cgroup` (and `time` on newer kernels)." }, { name: "cgroups", description: "Limit and meter what a process can **use**: CPU, memory, PIDs, block I/O. Modern distributions use the unified cgroup v2 hierarchy." }, { name: "Root filesystem / overlayfs", description: "Read-only image layers plus a thin writable layer, merged into one view that becomes the container's `/`." }, { name: "PID 1", description: "The first process in a PID namespace. It receives signals from the runtime and must reap zombie children; the kernel does not apply default signal actions to it, so an unhandled `SIGTERM` is simply ignored." }, { name: "Signals", description: "`SIGTERM` (15) asks for graceful shutdown and can be handled; `SIGKILL` (9) is enforced by the kernel and cannot be caught." }, { name: "Capabilities & seccomp", description: "Split root privileges into small units (e.g. `NET_BIND_SERVICE`) and filter which syscalls are allowed." } ], misconceptions: [ { myth: "A container has its own kernel.", reality: "All containers on a host share the **host kernel**. Only the view (namespaces) and budget (cgroups) differ. That is why a Linux container cannot run natively on a Windows kernel and why a kernel exploit affects every container on the node." }, { myth: "A CPU limit kills the container when exceeded, just like memory.", reality: "CPU is **compressible**: exceeding the limit causes **throttling** (the process waits). Memory is **incompressible**: exceeding the limit causes the kernel OOM killer to terminate a process, which Kubernetes reports as `OOMKilled`." }, { myth: 'root inside a container is harmless because it is "inside".', reality: "Without user namespaces, UID 0 in the container is UID 0 on the host, only constrained by capabilities, seccomp and the other layers. Escaping the namespace gives host root. That is why running as non-root is a security baseline." } ], example: { title: "See that a container is just a process", description: `On a Linux host with Docker (or any runtime), start a container and look at it from both sides. The same process has two PIDs: one inside its PID namespace and one on the host.`, language: "bash", code: `# start a long-running container docker run -d --name demo --memory 64m busybox sleep 3600 # inside: the process believes it is PID 1 docker exec demo ps # PID USER TIME COMMAND # 1 root 0:00 sleep 3600 # outside: the same sleep is an ordinary host process ps -ef | grep "sleep 3600" # compare namespaces of the host shell and the container process HOSTPID=$(docker inspect -f '{{.State.Pid}}' demo) sudo ls -l /proc/$HOSTPID/ns/ # net, pid, mnt ... differ from /proc/self/ns/ # graceful stop: SIGTERM, then SIGKILL after the timeout docker stop -t 10 demo` }, exercise: { prompt: `A Pod's container is configured with \`limits.memory: 128Mi\` and \`limits.cpu: 500m\`. Under load it uses 300m CPU and grows to 140Mi of memory. Describe what the kernel does for each resource, and what Kubernetes will report.`, solution: `CPU at 300m is under the 500m limit, so nothing happens. (Above 500m it would be throttled, never killed.) Memory at 140Mi exceeds the 128Mi cgroup limit. The kernel's OOM killer terminates the process in that cgroup. The kubelet reports the container's last state as **Terminated** with reason \`OOMKilled\` (exit code 137 = 128 + signal 9), and the container is restarted according to the Pod's \`restartPolicy\`. Repeated failures produce \`CrashLoopBackOff\`.` }, faq: [ { q: "Why does my container take exactly 30 seconds to stop?", a: "Your process probably ignores `SIGTERM` (common when a shell script is PID 1 and does not forward signals). Kubernetes waits `terminationGracePeriodSeconds` (default 30) and then sends `SIGKILL`. Handle `SIGTERM` in the app, or use `exec` in the entrypoint script so the app itself becomes PID 1." }, { q: "Do I need to memorize every namespace type for the KCNA?", a: "No. Know the concept: namespaces isolate what a process sees, cgroups limit what it uses, and containers share the host kernel. Recognizing `net` and `pid` namespaces helps explain why containers in a Pod share `localhost`." }, { q: "Are Linux namespaces the same as Kubernetes namespaces?", a: "No. A Kubernetes Namespace is an API-level grouping of objects (names, RBAC, quotas). It has nothing to do with kernel namespaces, which isolate processes on one host." } ], keyTerms: ["process", "PID 1", "Linux namespace", "cgroup", "OOM killer", "SIGTERM", "SIGKILL", "capabilities"], deeper: `Exit code 137 means "killed by signal 9" (128 + 9); 143 means \`SIGTERM\` (128 + 15). Tiny init processes such as \`tini\` exist solely to forward signals and reap zombies when your app is not written to be PID 1. Kubernetes can also share a single PID namespace across a Pod's containers with \`shareProcessNamespace: true\`. User namespaces for Pods (\`hostUsers: false\`) map container root to an unprivileged host UID; check its feature state for your cluster version before relying on it.`, references: [ { title: "namespaces(7) \u2013 Linux manual page", url: "https://man7.org/linux/man-pages/man7/namespaces.7.html" }, { title: "cgroups(7) \u2013 Linux manual page", url: "https://man7.org/linux/man-pages/man7/cgroups.7.html" }, { title: "Pod lifecycle \u2013 termination of Pods", url: "https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/" } ] }, { id: "networking-fundamentals", title: "Networking fundamentals", stage: 0, order: 2, objectives: ["co-networking"], scope: "foundation", estMinutes: 25, summary: "IP addresses identify hosts, ports identify processes, TCP and UDP carry data, DNS turns names into addresses, NAT rewrites addresses at boundaries, and load balancers spread traffic across backends.", what: `Kubernetes networking is built from a handful of classic ideas: - **IP address and CIDR** \u2013 \`10.244.1.17\` identifies an interface; \`10.244.0.0/16\` describes a range (the first 16 bits are the network part). - **Port** \u2013 a 16-bit number (0\u201365535) that identifies which process on a host gets a connection. An endpoint is \`IP:port\`. - **TCP vs UDP** \u2013 TCP is connection-oriented, ordered and retransmits lost data. UDP sends independent datagrams with no delivery guarantee but less overhead (DNS queries usually use UDP). - **DNS** \u2013 a distributed directory mapping names to records: \`A\` (IPv4), \`AAAA\` (IPv6), \`CNAME\` (alias), \`SRV\` (service + port). - **HTTP** \u2013 an application-layer (L7) request/response protocol with methods (\`GET\`, \`POST\`), paths, headers and status codes. - **NAT** \u2013 rewriting source (SNAT) or destination (DNAT) addresses as packets cross a boundary. - **Load balancing** \u2013 distributing connections or requests over several backends, at L4 (IP/port) or L7 (HTTP paths, headers).`, why: `Every Kubernetes networking object is one of these ideas wearing a new name. A **Service** is a stable virtual IP plus DNAT and L4 load balancing. **CoreDNS** is DNS. An **Ingress** or **Gateway** is an L7 HTTP load balancer. A **NodePort** is "open this port on every node". **NetworkPolicy** is a firewall on IPs and ports. If you can trace a plain \`curl\` across a network, you can trace a request into a cluster.`, problem: `Applications need to find and talk to each other while the machines underneath change. Hard-coding \`192.168.1.20:8080\` breaks the moment that server is replaced. DNS gives stable names, load balancers give one entry point for many replicas, and NAT lets many private addresses share fewer public ones. Kubernetes leans on exactly these tools because its backends (Pods) are replaced constantly.`, how: `Trace what happens when you run \`curl http://shop.example.com/cart\`: - **Resolve the name.** The client asks its configured resolver (see \`/etc/resolv.conf\`) for the \`A\` record of \`shop.example.com\`. The answer, say \`203.0.113.10\`, is cached for the record's TTL. - **Pick a source port.** The OS picks an ephemeral source port, e.g. \`54012\`. The connection is identified by the 5-tuple: protocol, source IP, source port, destination IP, destination port (80). - **Route the packet.** The host checks its routing table; the destination is not local, so the packet goes to the default gateway. - **NAT at the edge.** A home or cloud router rewrites the private source IP to a public one (**SNAT**) and remembers the mapping so replies come back. - **TCP handshake.** \`SYN\` \u2192 \`SYN-ACK\` \u2192 \`ACK\` establishes the connection. - **Load balancer.** \`203.0.113.10\` is a load balancer. An L4 balancer picks a backend by IP/port and forwards the connection (often using **DNAT**). An L7 balancer terminates the connection, reads the HTTP request, and can route \`/cart\` to a different backend pool than \`/search\`. - **HTTP exchange.** The backend receives \`GET /cart\`, returns \`200 OK\` (or \`404\`, \`503\`...), and the reply follows the NAT mappings back to the client.`, components: [ { name: "IP & CIDR", description: "Addresses and ranges. Private ranges such as `10.0.0.0/8`, `172.16.0.0/12` and `192.168.0.0/16` are not routable on the internet." }, { name: "Ports & sockets", description: "Ports below 1024 are privileged on Linux. Only one process can listen on a given IP:port at a time." }, { name: "DNS resolver", description: "Turns names into records. Search domains in `/etc/resolv.conf` let short names like `db` expand to longer ones; Kubernetes uses this heavily." }, { name: "NAT (SNAT/DNAT)", description: "Rewrites source or destination addresses. kube-proxy uses DNAT to send Service traffic to a Pod IP." }, { name: "L4 vs L7 load balancer", description: "L4 sees only IPs, ports and protocol; L7 understands HTTP and can route by host, path or header." } ], misconceptions: [ { myth: "DNS is only for websites on the internet.", reality: "Internal service discovery is DNS too. Inside Kubernetes, `my-svc.my-namespace.svc.cluster.local` is answered by the cluster DNS server (CoreDNS)." }, { myth: 'UDP is "unreliable" so nothing important uses it.', reality: "UDP simply leaves reliability to the application. DNS, many VPNs, video streaming and HTTP/3 (QUIC) all run on UDP." }, { myth: "A load balancer always understands HTTP.", reality: "Only L7 balancers do. An L4 balancer (like a Kubernetes Service of type `LoadBalancer` in most clouds) forwards TCP/UDP connections without looking at paths or headers." } ], example: { title: "Inspecting each layer from a shell", description: "These standard tools show the layers in order: name resolution, routing, and the HTTP exchange.", language: "bash", code: `# DNS: which IP does the name resolve to? dig +short example.com A nslookup example.com # Routing: which interface and gateway would be used? ip route get 1.1.1.1 # Listening sockets on this host (which process owns which port) ss -tlnp # HTTP: verbose output shows the TCP connect, request headers and status code curl -v http://example.com/` }, exercise: { prompt: `Three Pods run the same web app at \`10.244.1.5:8080\`, \`10.244.2.9:8080\` and \`10.244.3.4:8080\`. Clients should use one stable address and should not care when Pods are replaced. Using only the vocabulary of this lesson, describe the pieces you would need.`, solution: `- A **stable virtual IP** (and port) that clients connect to. - A **DNS name** that resolves to that virtual IP, so clients use a name rather than an address. - **DNAT + L4 load balancing** that rewrites each new connection's destination from the virtual IP to one of the healthy backend \`IP:8080\` endpoints. - A way to **update the backend list** whenever Pods come and go. That is exactly what a Kubernetes Service (ClusterIP), CoreDNS, kube-proxy and EndpointSlices provide together.` }, faq: [ { q: "What is the difference between a port and a protocol?", a: "The protocol (TCP or UDP) decides how data is carried; the port decides which process receives it. `53/UDP` and `53/TCP` are different sockets, which is why Kubernetes Service ports declare a `protocol` field (default TCP)." }, { q: "Why does /etc/resolv.conf matter in Kubernetes?", a: "The kubelet writes a `resolv.conf` into each Pod pointing at the cluster DNS Service and adding search domains like `.svc.cluster.local`. That is how a Pod can reach another Service by its short name." }, { q: "Is NAT the same as a firewall?", a: "No. NAT rewrites addresses; a firewall allows or drops traffic. They often run on the same box (and both use Linux netfilter), but they are separate functions." } ], keyTerms: ["CIDR", "port", "TCP", "UDP", "DNS A record", "SNAT/DNAT", "L4 load balancer", "L7 load balancer"], deeper: `Linux implements NAT and packet filtering in the kernel's netfilter framework, programmed by \`iptables\` or the newer \`nftables\`. kube-proxy writes such rules to implement Services. Some CNI plugins (e.g. Cilium) replace this path with eBPF programs attached in the kernel, which avoids long rule chains in very large clusters.`, references: [ { title: "Kubernetes \u2013 Services, Load Balancing, and Networking", url: "https://kubernetes.io/docs/concepts/services-networking/" }, { title: "MDN \u2013 An overview of HTTP", url: "https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview" } ] }, { id: "virtualization-and-containers", title: "Virtual machines vs containers", stage: 0, order: 3, objectives: ["kf-containerization"], scope: "kcna", estMinutes: 15, summary: "A VM virtualizes hardware and runs its own kernel; a container virtualizes the operating system view and shares the host kernel. That one difference explains their size, speed and isolation trade-offs.", what: `Think of a building. A **virtual machine** is a detached house: its own foundation, plumbing and walls. A **hypervisor** carves physical hardware into virtual hardware, and every VM boots a full **guest operating system with its own kernel**. A **container** is an apartment in a block: private rooms and a front door, but shared foundation and plumbing. Containers share the **host kernel** and get isolation from kernel features (namespaces, cgroups), not from virtual hardware. - **Type 1 hypervisor** \u2013 runs directly on hardware (e.g. KVM, Xen, ESXi, Hyper-V). Used by cloud providers. - **Type 2 hypervisor** \u2013 runs as an application on a host OS (e.g. VirtualBox). Common on laptops. - **Container runtime** \u2013 sets up namespaces, cgroups and the root filesystem and starts a process (e.g. containerd + runc).`, why: `The KCNA expects you to explain why the industry moved application packaging to containers and where VMs still fit. In practice they are combined: almost every managed Kubernetes cluster runs its **nodes as VMs**, and containers inside them. VMs give strong tenant isolation between customers; containers give fast, dense, portable packaging of apps.`, problem: `VMs solved "one app per physical server" waste, but each VM still carries a whole OS: gigabytes of disk, a boot sequence measured in tens of seconds, its own patching. Teams that wanted to deploy many small services dozens of times a day found that too heavy. They also suffered "works on my machine" bugs because the app's dependencies were not packaged with it. Containers package the app with its userland dependencies, start in well under a second (no kernel to boot), and pack many workloads onto one host.`, how: `Compare how each one starts an nginx web server: - **VM:** the hypervisor allocates virtual CPUs, RAM and disks \u2192 virtual firmware runs \u2192 the guest kernel boots \u2192 init system starts services \u2192 nginx starts. Isolation boundary: **virtual hardware**. A guest kernel bug stays inside the VM. - **Container:** the runtime unpacks the image layers \u2192 creates namespaces and a cgroup \u2192 switches the root filesystem \u2192 execs \`nginx\` as a process on the host kernel. Isolation boundary: **kernel features**. A host kernel bug can affect every container. Middle ground exists for untrusted workloads: - **Sandboxed runtimes** such as **gVisor** (a user-space kernel that intercepts syscalls) and **Kata Containers** (each Pod in a lightweight VM) keep the container workflow but add a stronger boundary. Kubernetes selects them per Pod with a **RuntimeClass**.`, components: [ { name: "Hypervisor", description: "Software that presents virtual hardware to guest OSes. Type 1 runs on bare metal; type 2 runs on top of a host OS." }, { name: "Guest OS / kernel", description: "Each VM boots its own kernel, so VMs can run different OS families (Linux and Windows) side by side." }, { name: "Container runtime", description: "Creates isolated processes on the shared host kernel; e.g. containerd or CRI-O with runc underneath." }, { name: "Sandboxed runtime", description: "gVisor or Kata Containers: container interface, VM-like isolation, some performance cost." } ], misconceptions: [ { myth: "Containers are just lightweight VMs.", reality: 'They are a different mechanism. A VM emulates hardware and boots a kernel; a container is an isolated **process** on an already-running kernel. That is why there is no "boot" when a container starts.' }, { myth: "Kubernetes replaces virtual machines.", reality: "Kubernetes schedules containers onto **nodes**, and nodes are very often VMs. The layers are complementary." }, { myth: "A Linux container image runs on any OS.", reality: "Because the kernel is shared, a Linux image needs a Linux kernel. Docker Desktop on macOS or Windows quietly runs a small Linux VM to provide one. Windows containers likewise need a Windows host." } ], example: { title: "Side-by-side comparison", description: "Typical, order-of-magnitude characteristics. Exact numbers vary by workload and platform.", language: "text", code: ` Virtual machine Container Isolation boundary virtual hardware kernel namespaces + cgroups Kernel own guest kernel shared host kernel Typical size gigabytes (full OS) megabytes (app + userland libs) Start time seconds to minutes milliseconds to seconds Density per host tens hundreds Mixed OS families yes (Linux + Windows) no (must match host kernel) Typical use tenant isolation, nodes packaging and running apps` }, exercise: { prompt: `A SaaS company runs code uploaded by untrusted customers. They want container-style packaging and Kubernetes scheduling, but are worried that one customer could exploit a kernel bug to reach another customer's workload. What options does this lesson give them?`, solution: `- Run those Pods with a **sandboxed runtime** (gVisor or Kata Containers) selected through a **RuntimeClass**, adding a boundary beyond the shared kernel. - Or give each customer **separate nodes (VMs)** or even separate clusters, so the hypervisor is the boundary between tenants. Plain containers alone share the host kernel, so they are a weaker boundary for hostile multi-tenancy.` }, faq: [ { q: "If containers share the kernel, how can an Alpine container run on an Ubuntu host?", a: "Distributions differ in **userland** (libraries, package manager, shell), not in the kernel interface. The Alpine image brings its own userland files; it only borrows the Ubuntu host's Linux kernel." }, { q: "Are containers secure enough for production?", a: "Yes for most workloads, when combined with good practices: non-root users, dropped capabilities, seccomp, read-only root filesystems and Pod Security Admission. For hostile multi-tenant code, add sandboxed runtimes or VM boundaries." }, { q: "What is RuntimeClass on the exam?", a: "Know it exists: a Kubernetes object that lets a Pod choose which runtime configuration (for example a gVisor or Kata handler) the node should use, via `spec.runtimeClassName`." } ], keyTerms: ["hypervisor", "virtual machine", "guest kernel", "container", "shared kernel", "gVisor", "Kata Containers", "RuntimeClass"], deeper: `Hardware virtualization extensions (Intel VT-x, AMD-V) make type 1 hypervisors fast. MicroVM projects such as Firecracker shrink the VM to the essentials so it boots in a fraction of a second; serverless platforms use them to get VM isolation with near-container speed.`, references: [ { title: "Kubernetes \u2013 Containers", url: "https://kubernetes.io/docs/concepts/containers/" }, { title: "Kubernetes \u2013 Runtime Class", url: "https://kubernetes.io/docs/concepts/containers/runtime-class/" } ] }, { id: "container-images-and-oci", title: "Container images, OCI and registries", stage: 0, order: 4, objectives: ["kf-containerization"], scope: "kcna", estMinutes: 25, summary: "An image is a stack of read-only filesystem layers plus a config, described by a manifest and addressed by content digests. The OCI specifications standardize image format, runtime behaviour and registry distribution so any compliant tool can build, push, pull and run it.", what: `A **container image** is a portable, read-only template for a container. Concretely it is: - a set of **layers** \u2013 compressed tarballs, each holding the filesystem changes of one build step; - an **image config** \u2013 JSON with the default command, environment, working directory, user and the ordered list of layer digests; - a **manifest** \u2013 JSON that points to the config and the layers by **digest** (\`sha256:...\`). An **image index** can point to several manifests, one per platform (e.g. \`linux/amd64\`, \`linux/arm64\`). **Docker** popularized this format and the \`Dockerfile\` build recipe. The **Open Container Initiative (OCI)**, a Linux Foundation project, now standardizes it in three specs: - **Image spec** \u2013 the manifest, config and layer formats. - **Runtime spec** \u2013 how to run an unpacked "bundle" (filesystem + \`config.json\`); \`runc\` is the reference implementation. - **Distribution spec** \u2013 the HTTP API registries use for push and pull.`, why: `Kubernetes never builds images; it only **pulls** them by reference and asks a runtime to run them. Because of OCI, an image built with Docker, Buildah, kaniko or BuildKit runs on containerd or CRI-O and can live in any compliant registry (Docker Hub, GHCR, Harbor, cloud registries). That is also why removing dockershim in Kubernetes 1.24 did **not** break Docker-built images. Tags vs digests is a frequent exam and production topic: it decides whether a rollout is reproducible.`, problem: `"It works on my machine" usually means the machine had a library, a config file or a runtime version the server did not. Images freeze the userland into an artifact you can version and ship. Layering then fixes the next problem: shipping a 500 MB file for every one-line change would be wasteful, so only changed layers are rebuilt, pushed and pulled.`, how: `Trace a build and a pull: - **Build.** \`FROM\` starts from the base image's layers; each filesystem-changing instruction (\`COPY\`, \`RUN\`, \`ADD\`) adds a new layer. Metadata instructions (\`CMD\`, \`ENV\`, \`EXPOSE\`, \`USER\`) only change the config. - **Cache.** If an instruction and its inputs are unchanged, the builder reuses the cached layer. A change invalidates that layer **and every layer after it** \u2013 so put rarely-changing steps (installing dependencies) before frequently-changing ones (copying source). - **Hash.** Every layer and the config get a SHA-256 **digest** of their content. The manifest lists these digests; the manifest's own digest identifies the whole image. - **Push.** The client uploads blobs the registry does not already have, then uploads the manifest under a **tag** such as \`v1.4.2\`. - **Pull.** The node resolves the tag to a manifest digest, downloads only missing layers, and verifies every blob against its digest. - **Run.** The runtime stacks the read-only layers with overlayfs and adds a thin **writable container layer** on top. Files written there disappear with the container.`, components: [ { name: "Layer", description: "Read-only, content-addressed tarball of filesystem changes. Shared between images that use the same base." }, { name: "Manifest / image index", description: `Manifest lists config + layers for one platform; an index (multi-arch "manifest list") picks the right manifest for the node's OS/CPU.` }, { name: "Tag", description: "Human-friendly, **mutable** pointer like `nginx:1.27` or `latest`. Can be moved to a different image at any time." }, { name: "Digest", description: "**Immutable** content hash like `nginx@sha256:...`. The same digest always means exactly the same bytes." }, { name: "Registry", description: "Server implementing the OCI distribution API, organized into repositories. Public or private (credentials via `imagePullSecrets`)." }, { name: "OCI runtime (runc)", description: "Low-level runtime that takes an unpacked bundle and creates the container process with namespaces and cgroups." } ], misconceptions: [ { myth: "Kubernetes needs Docker installed on every node.", reality: "Since 1.24 the kubelet talks only to CRI runtimes such as **containerd** or **CRI-O**. Docker-built images are OCI images, so they still run unchanged." }, { myth: "The tag `latest` means the newest version.", reality: "`latest` is just the default tag name when none is given. It points wherever someone last pushed it. In Kubernetes, `:latest` (or no tag) also makes the default `imagePullPolicy` `Always`." }, { myth: "Deleting a file in a later Dockerfile step makes the image smaller.", reality: 'Earlier layers are immutable; the deletion is only a "whiteout" marker in a new layer. The bytes still ship. Clean up in the **same** `RUN` step, or use a multi-stage build.' } ], example: { title: "A cache-friendly, multi-stage Dockerfile", description: `Dependencies are copied and installed before the source code, so a code-only change reuses the dependency layer. The final stage copies only the built binary into a small base, leaving compilers behind.`, language: "text", code: `# ---- build stage ---- FROM golang:1.23 AS build WORKDIR /src COPY go.mod go.sum ./ RUN go mod download # cached until go.mod/go.sum change COPY . . RUN CGO_ENABLED=0 go build -o /out/app ./cmd/app # ---- runtime stage ---- FROM gcr.io/distroless/static:nonroot COPY --from=build /out/app /app USER nonroot ENTRYPOINT ["/app"] # Build, tag and push; then deploy by digest for reproducibility: # docker build -t registry.example.com/shop/app:1.4.2 . # docker push registry.example.com/shop/app:1.4.2 # image: registry.example.com/shop/app@sha256:` }, exercise: { prompt: `Your Deployment uses \`image: shop/api:prod\`. Someone re-pushes the \`prod\` tag with a broken build. Two nodes already have the old image cached; a third node pulls fresh. Explain what happens and how to prevent it.`, solution: `With an explicit non-\`latest\` tag, the default \`imagePullPolicy\` is \`IfNotPresent\`. The two nodes reuse their cached (old) image; the new node pulls the moved tag and gets the broken build. The same Deployment now runs **two different images**. Prevent it by deploying **immutable references**: a unique tag per build (e.g. a version or commit SHA) that is never re-pushed, or better, pin the **digest** (\`shop/api@sha256:...\`). Many registries can also enforce tag immutability.` }, faq: [ { q: "Is a Dockerfile part of the OCI standard?", a: "No. OCI standardizes the **resulting** image, the runtime bundle and the registry API. The Dockerfile is just one popular build recipe; Buildpacks or other tools can produce OCI images without one." }, { q: "What is the difference between containerd and runc?", a: "**containerd** is a high-level runtime: it pulls images, manages storage and snapshots, and exposes the CRI to the kubelet. **runc** is the low-level OCI runtime that containerd invokes to actually create each container process." }, { q: "How does a node pull from a private registry?", a: "Create a Secret of type `kubernetes.io/dockerconfigjson` and reference it in the Pod's `imagePullSecrets` (directly or through the ServiceAccount). Some clouds also provide node-level credential plugins." } ], keyTerms: ["image layer", "manifest", "digest", "tag", "registry", "OCI image spec", "OCI runtime spec", "OCI distribution spec"], deeper: `Because OCI registries store arbitrary content-addressed blobs, they now hold more than images: Helm charts, signatures and SBOMs (OCI "artifacts" and the \`subject\`/referrers mechanism). Supply-chain tools such as Sigstore cosign attach signatures to an image digest this way, so a signature can never silently follow a moved tag.`, references: [ { title: "Open Container Initiative", url: "https://opencontainers.org/" }, { title: "Kubernetes \u2013 Images", url: "https://kubernetes.io/docs/concepts/containers/images/" }, { title: "Kubernetes \u2013 Container Runtime Interface", url: "https://kubernetes.io/docs/concepts/architecture/cri/" } ], diagram: "container-layers" }, { id: "yaml-for-kubernetes", title: "YAML for Kubernetes manifests", stage: 0, order: 5, objectives: ["kf-core"], scope: "foundation", estMinutes: 20, summary: "YAML expresses maps, lists and scalars through indentation. Every Kubernetes manifest uses the same top-level shape: apiVersion, kind, metadata, spec \u2013 and the cluster writes back status.", what: `**YAML** is a human-friendly data format (a superset of JSON). Kubernetes reads it, converts it to JSON, and sends it to the API server. You only need three building blocks: - **Mapping** (key: value) \u2013 \`name: web\` - **Sequence** (list) \u2013 items start with \`- \` - **Scalar** \u2013 strings, numbers, booleans, null Indentation with **spaces** (never tabs) shows nesting. \`#\` starts a comment. \`---\` separates multiple documents in one file. Every Kubernetes object has the same skeleton: - \`apiVersion\` \u2013 API group and version, e.g. \`v1\` (core group) or \`apps/v1\` - \`kind\` \u2013 the type, e.g. \`Pod\`, \`Deployment\` - \`metadata\` \u2013 \`name\`, \`namespace\`, \`labels\`, \`annotations\` - \`spec\` \u2013 the **desired state** you write - \`status\` \u2013 the **observed state** the cluster writes; you do not author it`, why: `Declarative Kubernetes is "write YAML, apply it". Most beginner errors are YAML errors, not Kubernetes errors: wrong indentation turns a field into a sibling of the field it belonged to, a missing \`-\` turns a list into a map, and an unquoted value becomes the wrong type. Reading YAML fluently is a prerequisite for every later lesson and for the exam's manifest-reading questions.`, problem: `Raw JSON is noisy to read and cannot hold comments; ad-hoc command flags cannot be reviewed or versioned. YAML gives a readable, diffable text form for API objects that can live in Git. The cost is that whitespace and typing rules are strict and sometimes surprising.`, how: `Read any manifest in this order: - **Find the type.** \`apiVersion\` + \`kind\` tell you which schema applies. \`kubectl explain .\` shows that schema. - **Find the identity.** \`metadata.name\` (+ \`namespace\`) identifies the object; labels are for selection, annotations for extra notes. - **Walk the spec by indentation.** Children are indented further than their parent. Items at the same indentation are siblings. - **Spot lists.** A \`- \` begins a new list item; every key indented under it belongs to that item. \`containers:\` is always a list, even with one container. - **Check scalar types.** \`8080\` is a number, \`"8080"\` a string, \`true\` a boolean. Fields typed as strings (like env \`value\`) need quotes around numbers or booleans. - **Submit.** \`kubectl apply -f file.yaml\` parses the YAML, validates it against the schema on the server, and stores it.`, components: [ { name: "apiVersion", description: "`/` such as `apps/v1`, or just `v1` for the core group (Pods, Services, ConfigMaps)." }, { name: "kind", description: "Object type, CamelCase: `Pod`, `Deployment`, `Service`." }, { name: "metadata", description: "Identity and tags: `name`, `namespace`, `labels`, `annotations`. The server adds `uid`, `resourceVersion`, `creationTimestamp`." }, { name: "spec", description: "Desired state; structure depends on `kind`." }, { name: "status", description: "Observed state written by controllers and the kubelet. Ignored if you include it in `apply`." } ], misconceptions: [ { myth: "Tabs and spaces are interchangeable in YAML.", reality: "Tabs are **not allowed** for indentation. Use spaces (2 per level is the Kubernetes convention)." }, { myth: "Every value is a string, so quoting does not matter.", reality: 'YAML infers types. `value: 8080` in an env var is a number and the API rejects it because the field must be a string; write `value: "8080"`. Words like `yes`, `no`, `on`, `true` can also be read as booleans.' }, { myth: "You should copy the `status` section when saving a manifest.", reality: "`status` is owned by the cluster. Strip it (and server fields like `uid`, `resourceVersion`) from manifests you keep in Git." } ], example: { title: "Spot the three bugs", description: `This Pod manifest is broken in three ways: the \`env\` value is an unquoted number, \`image\` is indented as a sibling of \`containers\` instead of inside the list item, and \`ports\` is a map where a list is required. The corrected version follows.`, language: "yaml", code: `# BROKEN apiVersion: v1 kind: Pod metadata: name: web spec: containers: - name: web image: nginx:1.27 # wrong level: belongs to the container item ports: containerPort: 80 # must be a list item env: - name: PORT value: 8080 # must be a string --- # FIXED apiVersion: v1 kind: Pod metadata: name: web labels: app: web spec: containers: - name: web image: nginx:1.27 ports: - containerPort: 80 env: - name: PORT value: "8080"` }, exercise: { prompt: `Without running anything, answer: in the FIXED manifest above, (1) how many containers are defined, (2) what is the full field path to the container port, and (3) which API group does \`v1\` refer to?`, solution: `(1) One container \u2013 \`containers\` is a list with a single \`- name: web\` item. (2) \`spec.containers[0].ports[0].containerPort\`. (3) The **core** (legacy) API group, which has no group name \u2013 hence just \`v1\` rather than \`/v1\`.` }, faq: [ { q: "How do I find which fields a kind supports?", a: "Use `kubectl explain`, e.g. `kubectl explain pod.spec.containers` or add `--recursive` for the whole tree. It reads the schema from your cluster, so it matches your version." }, { q: "Can I write manifests in JSON instead?", a: "Yes. kubectl accepts JSON, and `kubectl get -o json` prints objects that way. YAML is the convention because it is easier to read and comment." }, { q: "Where do apiVersion values like apps/v1 come from?", a: "From the API groups your cluster serves. `kubectl api-resources` lists each resource with its group/version and whether it is namespaced." } ], keyTerms: ["mapping", "sequence", "scalar", "apiVersion", "kind", "metadata", "spec", "status"], deeper: `Kubernetes converts YAML to JSON before validation, so anything YAML can express beyond JSON (anchors \`&\`/\`*\`, merge keys) is resolved client-side and never reaches the API server. Block scalars \`|\` (keep newlines) and \`>\` (fold lines) are handy for embedding scripts or config files in ConfigMaps.`, references: [ { title: "Kubernetes \u2013 Objects in Kubernetes", url: "https://kubernetes.io/docs/concepts/overview/working-with-objects/" }, { title: "YAML 1.2.2 specification", url: "https://yaml.org/spec/1.2.2/" }, { title: "kubectl reference", url: "https://kubernetes.io/docs/reference/kubectl/" } ] }, { id: "distributed-systems-basics", title: "Distributed systems basics", stage: 0, order: 6, objectives: ["cna-ecosystem"], scope: "foundation", estMinutes: 20, summary: "In a distributed system, networks drop messages and machines die. Kubernetes copes with consensus (Raft in etcd), idempotent operations, retries, and eventual consistency driven by control loops.", what: `A **distributed system** is several computers cooperating over a network so that they appear as one service. Four ideas carry most of the weight: - **Partial failure** \u2013 some parts fail while others keep running; a slow node and a dead node can look identical. - **Consensus** \u2013 getting a group of machines to agree on one value (or one ordered log) despite failures. **Raft** does this with an elected leader and a **majority quorum**. - **Idempotency** \u2013 an operation that has the same effect whether it is applied once or many times ("set replicas to 3" vs "add 1 replica"). Idempotent operations make retries safe. - **Eventual consistency** \u2013 the system may be temporarily out of sync but converges to the correct state if no new changes arrive.`, why: `A Kubernetes cluster *is* a distributed system. etcd uses Raft, so you must run an odd number of members and keep a majority alive. Controllers converge **eventually** \u2013 a new Deployment is not "done" when \`kubectl apply\` returns. Rolling updates, retries and self-healing only work because operations are expressed as idempotent desired state. These ideas explain dozens of exam answers that otherwise look arbitrary.`, problem: `Three short failure stories: - **The double charge.** A payment request times out; the client retries; both requests actually succeeded. The fix: an **idempotency key** so the second request is recognized and ignored. - **The split brain.** A network splits two database servers; each thinks the other is dead and both accept writes. The fix: require a **majority quorum** \u2013 at most one side can have a majority, so only it may write. - **The stale read.** A cache still shows a deleted item for a few seconds. Often acceptable \u2013 that is **eventual consistency** \u2013 as long as the system converges.`, how: `How Raft (used by etcd) keeps one consistent log: - **Roles.** Each member is a **follower**, **candidate** or **leader**. Normally there is exactly one leader. - **Election.** If a follower hears no heartbeat within a randomized timeout, it becomes a candidate, increments the **term**, and asks for votes. A candidate with votes from a **majority** becomes leader. - **Replication.** All writes go to the leader, which appends them to its log and sends them to followers. - **Commit.** Once a **majority** has stored the entry, it is committed and applied; the client gets success. - **Fault tolerance.** With *n* members, quorum is \u230An/2\u230B+1. Three members tolerate one failure; five tolerate two. Four members still tolerate only one, which is why odd sizes are recommended. - **Losing quorum.** If a majority is unreachable, the cluster refuses writes rather than risk divergence \u2013 it chooses **consistency over availability** during the partition (the CAP trade-off).`, components: [ { name: "Raft leader", description: "Single member that orders all writes; re-elected automatically if it fails." }, { name: "Quorum", description: "A majority of members, \u230An/2\u230B+1. Needed both to elect a leader and to commit a write." }, { name: "Idempotent operation", description: 'Safe to repeat. Declarative "make it look like this" requests are naturally idempotent.' }, { name: "Optimistic concurrency", description: "Writers include the version they read; the write fails if someone changed it meanwhile. Kubernetes uses `metadata.resourceVersion` for this." }, { name: "Eventual consistency", description: "Components converge to the desired state over time instead of all at once." } ], misconceptions: [ { myth: "More etcd members always means more resilience.", reality: "Fault tolerance only increases at odd sizes (3 \u2192 1 failure, 5 \u2192 2). Every extra member also adds replication latency to every write. 3 or 5 is typical." }, { myth: "If an API call succeeded, the change is already in effect everywhere.", reality: "A successful `kubectl apply` means the desired state was **stored in etcd**. Scheduling, image pulls and container starts happen afterwards, asynchronously." }, { myth: "Retries are always safe.", reality: 'Only for **idempotent** operations. Retrying a non-idempotent "increment" or "charge" can apply it twice.' } ], example: { title: "Optimistic concurrency in Kubernetes", description: `Every object carries a \`resourceVersion\`. If two clients read version 4812 and both try to update, the first update wins and the second gets an HTTP **409 Conflict**; it must re-read and retry. Nothing is locked, and no update is silently lost.`, language: "bash", code: `kubectl get deployment web -o jsonpath='{.metadata.resourceVersion}' # 4812 # client A and client B both edit based on 4812 # A's update is accepted -> resourceVersion becomes 4830 # B's update still claims 4812 -> rejected: # Error from server (Conflict): Operation cannot be fulfilled on # deployments.apps "web": the object has been modified; # please apply your changes to the latest version and try again` }, exercise: { prompt: `An etcd cluster has 5 members spread across 3 zones as 2 + 2 + 1. Zone A (2 members) goes offline. Can the cluster still accept writes? What if zone B also fails?`, solution: `Quorum for 5 members is 3. After zone A fails, 3 members remain (zone B: 2, zone C: 1) \u2013 still a majority, so the cluster elects a leader if needed and keeps accepting writes. If zone B also fails, only 1 member remains. It cannot form a majority, so the cluster **stops accepting writes** (reads of possibly-stale data aside) until quorum is restored. Running Pods keep running \u2013 the kubelets just cannot get new instructions.` }, faq: [ { q: "What is the difference between level-triggered and edge-triggered?", a: 'Edge-triggered logic reacts to **events** ("a Pod was deleted"); if an event is missed, the system is wrong forever. Level-triggered logic looks at the **current state** each time ("are there 3 Pods?"). Kubernetes controllers are level-triggered, which makes them robust to missed events and restarts.' }, { q: "Does the KCNA test the Raft algorithm in detail?", a: "No. Know that etcd uses Raft-based consensus, needs a majority quorum, and is usually run with an odd number of members (3 or 5)." }, { q: 'Is Kubernetes "eventually consistent" in its storage?', a: "etcd itself is strongly consistent (linearizable writes via Raft). The **cluster as a whole** \u2013 Pods, endpoints, DNS \u2013 is eventually consistent, because many independent controllers converge the actual state towards the stored desired state." } ], keyTerms: ["partial failure", "consensus", "Raft", "quorum", "idempotency", "eventual consistency", "CAP theorem", "resourceVersion"], deeper: `The CAP theorem says that during a network partition a system must choose between consistency and availability. etcd chooses consistency (a minority partition rejects writes). Many caches and DNS systems choose availability and accept stale answers. The "fallacies of distributed computing" (the network is reliable, latency is zero, ...) are a useful checklist when designing cloud-native services.`, references: [ { title: "The Raft consensus algorithm", url: "https://raft.github.io/" }, { title: "etcd documentation", url: "https://etcd.io/docs/" }, { title: "Kubernetes \u2013 Controllers", url: "https://kubernetes.io/docs/concepts/architecture/controller/" } ] }, // ───────────────────────────── Stage 1 · Architecture ───────────────────────────── { id: "cluster-architecture", title: "Cluster architecture: control plane and nodes", stage: 1, order: 1, objectives: ["kf-core"], scope: "kcna", estMinutes: 20, summary: "A Kubernetes cluster is a control plane that stores and decides, plus worker nodes that run containers. Every component talks through the API server; only the API server talks to etcd.", what: `A **cluster** has two halves. The **control plane** is the brain. It stores the desired state and makes decisions: - **kube-apiserver** \u2013 the front door; every read and write goes through it. - **etcd** \u2013 consistent key-value store holding all cluster data. - **kube-scheduler** \u2013 picks a node for each new Pod. - **kube-controller-manager** \u2013 runs the built-in control loops (Deployments, ReplicaSets, Nodes, Jobs...). - **cloud-controller-manager** \u2013 optional; integrates with a cloud provider (load balancers, node lifecycle, routes). **Worker nodes** are the muscle. Each one runs: - **kubelet** \u2013 the node agent that makes the containers for its Pods actually run. - **container runtime** \u2013 containerd or CRI-O, behind the CRI. - **kube-proxy** \u2013 programs node networking for Services (optional with some CNI plugins). Cluster **add-ons** such as CoreDNS and a CNI network plugin run on top, usually as Pods themselves.`, why: `The KCNA's largest domain starts here: you will be asked which component does what, which component stores state, and what happens when one fails. The picture also explains the design principle that runs through all of Kubernetes: components are **decoupled** and communicate only through the API, so each can be replaced, scaled or restarted independently.`, problem: `Running containers by hand on many servers raises questions no single machine can answer: which server has room? What happens when a server dies at 3 a.m.? Who notices that only 2 of 3 copies are running? Kubernetes centralizes the **record of what should exist** and distributes the **work of making it so** to small, specialized components and node agents.`, how: `Think of it as a company: - **etcd** is the filing cabinet: the only place the truth is written down. - **kube-apiserver** is the front desk. Nobody opens the cabinet directly; everyone files and reads through the desk, which checks identity and permissions. - **Controllers** are department managers who keep reading the files and issuing work orders: "the Deployment wants 3 Pods, I see 2, file one more Pod". - **kube-scheduler** is the dispatcher who assigns each new Pod to a node by writing the node's name onto it. - **kubelets** are site supervisors on each node. Each watches the front desk for Pods assigned to its node, gets them running through the container runtime, and reports status back. - **kube-proxy** on each node maintains the routing so traffic for a Service reaches one of its Pods. Important consequences: - **Hub and spoke.** Components coordinate by **watching** and writing through the API server rather than calling each other. Only the API server talks to etcd. - **Running Pods survive control-plane outages.** If the control plane is down, existing containers keep running; you just cannot change anything, and failed Pods are not replaced. - **High availability** means running several API servers behind a load balancer, an odd number of etcd members, and leader election for the scheduler and controller manager (one active instance each).`, components: [ { name: "kube-apiserver", description: "REST front end and the only component that reads/writes etcd. Horizontally scalable." }, { name: "etcd", description: "Raft-replicated key-value store; the cluster's single source of truth. Back it up." }, { name: "kube-scheduler", description: "Assigns unscheduled Pods to nodes; does not start containers itself." }, { name: "kube-controller-manager", description: "One binary running many controllers (Deployment, ReplicaSet, Node, Job, EndpointSlice, ServiceAccount...)." }, { name: "kubelet", description: "Node agent: registers the node, runs Pods assigned to it via the CRI, executes probes, reports status." }, { name: "kube-proxy", description: "Implements Service virtual IPs on each node using iptables, IPVS or nftables rules." } ], misconceptions: [ { myth: "The scheduler starts containers on the chosen node.", reality: "The scheduler only **records the decision** (it binds the Pod, setting `spec.nodeName`). The kubelet on that node notices and starts the containers." }, { myth: "If the control plane goes down, all applications stop.", reality: "Running containers keep running and kube-proxy rules stay in place. What stops is change: no new scheduling, no self-healing, no `kubectl` operations." }, { myth: "The kubelet runs only on worker nodes.", reality: "In kubeadm-style clusters the control-plane machines also run a kubelet, which starts the control-plane components as **static Pods** from manifest files on disk." } ], example: { title: "Look at the architecture of a running cluster", description: "In a kubeadm or kind cluster the control-plane components are visible as Pods in `kube-system`. In managed services (EKS, GKE, AKS) the control plane is hidden and you see only nodes and add-ons.", language: "bash", code: `kubectl get nodes -o wide # NAME STATUS ROLES VERSION # kind-control-plane Ready control-plane v1.31.0 # kind-worker Ready v1.31.0 kubectl get pods -n kube-system # etcd-kind-control-plane 1/1 Running # kube-apiserver-kind-control-plane 1/1 Running # kube-controller-manager-kind-control-plane 1/1 Running # kube-scheduler-kind-control-plane 1/1 Running # kube-proxy-7xk2p 1/1 Running # coredns-6f6b679f8f-9q2lw 1/1 Running kubectl cluster-info` }, exercise: { prompt: `For each event, name the component that reacts first: (a) a user runs \`kubectl apply\`; (b) a new Pod object exists with no node assigned; (c) a Pod has been assigned to \`node-3\`; (d) a ReplicaSet wants 3 Pods but only 2 exist; (e) the cluster needs a cloud load balancer for a Service.`, solution: `(a) **kube-apiserver** \u2013 authenticates, authorizes, admits and stores the object in etcd. (b) **kube-scheduler** \u2013 selects a node and binds the Pod. (c) The **kubelet on node-3** \u2013 asks the container runtime (via CRI) to start the containers. (d) The **ReplicaSet controller** in kube-controller-manager \u2013 creates one more Pod object. (e) The service controller in the **cloud-controller-manager** \u2013 provisions the load balancer through the cloud API.` }, faq: [ { q: "How many control-plane nodes should production have?", a: "Commonly **3** (with stacked etcd, matching an odd etcd member count) so one can fail. Managed Kubernetes services run and scale the control plane for you." }, { q: "Is CoreDNS part of the control plane?", a: "It is a **cluster add-on**, not one of the core control-plane components, but nearly every cluster runs it because Service discovery depends on DNS." }, { q: "Can I run my own Pods on control-plane nodes?", a: "Control-plane nodes are normally **tainted** (`node-role.kubernetes.io/control-plane:NoSchedule`) so ordinary Pods avoid them. Single-node test clusters often remove that taint." } ], keyTerms: ["control plane", "worker node", "kube-apiserver", "etcd", "kube-scheduler", "kube-controller-manager", "kubelet", "kube-proxy"], deeper: `Nodes send heartbeats by renewing **Lease** objects in the \`kube-node-lease\` namespace; the node controller marks a node \`NotReady\`/\`Unknown\` when leases stop and, after a grace period, Pods on it are evicted via taints. etcd can be **stacked** (on the control-plane nodes) or **external** (its own machines), trading simplicity against failure isolation.`, references: [ { title: "Kubernetes Components", url: "https://kubernetes.io/docs/concepts/overview/components/" }, { title: "Cluster Architecture", url: "https://kubernetes.io/docs/concepts/architecture/" } ], diagram: "cluster-architecture" }, { id: "api-server-and-etcd", title: "The API server and etcd", stage: 1, order: 2, objectives: ["kf-core"], scope: "kcna", estMinutes: 25, summary: "Every request to Kubernetes passes through the API server: authentication, authorization, mutating admission, validation, validating admission, then persistence in etcd. Clients then learn about changes through watches.", what: `**kube-apiserver** exposes the Kubernetes API as RESTful HTTP resources such as \`/api/v1/namespaces/default/pods\` and \`/apis/apps/v1/namespaces/default/deployments\`. kubectl, controllers, the scheduler, kubelets and your own tools are all just clients of it. **etcd** is a distributed, strongly consistent key-value store. The API server serializes every object and stores it under keys (by default with the prefix \`/registry/\`). etcd is the **single source of truth**: if it is not in etcd, the cluster does not know about it. The API server is the **only** component that talks to etcd. Everything else goes through the API server, which enforces security and validation consistently.`, why: `Exam questions love the request chain ("which step rejects a request with an invalid token?", "where would a policy that injects a sidecar run?"). Operationally, etcd is the one stateful thing whose loss destroys the cluster's memory \u2013 which is why backing it up is a core admin task.`, problem: `If every component wrote directly to the database, each would need to re-implement authentication, permission checks, schema validation and defaults, and one buggy component could corrupt everything. Centralizing access in one API server gives one place for security policy, one place for validation, and one consistent change feed that every client can watch.`, how: `Follow \`kubectl apply -f deploy.yaml\` through the API server: - **Transport.** kubectl reads kubeconfig and sends an HTTPS request with credentials (client certificate, bearer token, or OIDC token). - **Authentication (who are you?).** Authenticator modules identify the user or ServiceAccount. Failure \u2192 \`401 Unauthorized\`. - **Authorization (may you do this?).** Usually **RBAC** (with the Node authorizer for kubelets) checks verb + resource + namespace. Denied \u2192 \`403 Forbidden\`. - **Mutating admission.** Admission controllers and mutating webhooks may **change** the object \u2013 e.g. set defaults, inject a sidecar, add a default StorageClass. - **Schema validation.** The object is checked against the API schema (field types, required fields). - **Validating admission.** Controllers, webhooks and ValidatingAdmissionPolicies may **reject** the object \u2013 e.g. Pod Security Admission, ResourceQuota. They cannot modify it. - **Persist.** The object is written to etcd; \`resourceVersion\` is updated. The client gets \`200\`/\`201\`. - **Notify.** Every client **watching** that resource type receives an event (ADDED/MODIFIED/DELETED) \u2013 this is how the Deployment controller learns it has work to do.`, components: [ { name: "Authentication", description: "Identifies the caller: X.509 client certs, bearer/ServiceAccount tokens, OIDC. Kubernetes has no User objects; users are external identities." }, { name: "Authorization", description: "Decides allow/deny, typically via RBAC and the Node authorizer. Default is deny." }, { name: "Admission control", description: "Mutating phase (may modify) then validating phase (may only reject). Built-in plugins plus webhooks and CEL-based ValidatingAdmissionPolicy." }, { name: "Watch", description: "Long-lived request that streams changes after a given `resourceVersion`; the basis of every controller." }, { name: "etcd", description: "Raft-replicated key-value store holding all API objects. Run 3 or 5 members; take regular snapshots." } ], misconceptions: [ { myth: "The scheduler and controllers read etcd directly for speed.", reality: "Only the API server reads and writes etcd. Other components use the API (with local caches fed by watches) \u2013 which keeps security and validation in one place." }, { myth: "Admission controllers run before authorization.", reality: "Order is **authentication \u2192 authorization \u2192 mutating admission \u2192 schema validation \u2192 validating admission \u2192 etcd**. Admission only sees requests that are already authenticated and authorized." }, { myth: "Secrets in etcd are encrypted by default.", reality: "By default Secrets are stored **base64-encoded, not encrypted**. Encryption at rest must be configured on the API server (an EncryptionConfiguration, optionally with a KMS provider)." } ], example: { title: "Watching the API, and backing up etcd", description: `\`--watch\` uses the same streaming mechanism controllers use. The etcd snapshot command is what an administrator runs on a control-plane node (certificate paths vary per installation).`, language: "bash", code: `# Stream changes to Pods in the current namespace (a client-side watch) kubectl get pods --watch # See raw API paths and the request chain at high verbosity kubectl get deployments -v=6 # ... GET https://127.0.0.1:6443/apis/apps/v1/namespaces/default/deployments 200 OK # Ask the API server what you are allowed to do (authorization check) kubectl auth can-i create deployments --namespace default # On a control-plane node: snapshot etcd ETCDCTL_API=3 etcdctl snapshot save /backup/etcd.db \\ --endpoints=https://127.0.0.1:2379 \\ --cacert=/etc/kubernetes/pki/etcd/ca.crt \\ --cert=/etc/kubernetes/pki/etcd/server.crt \\ --key=/etc/kubernetes/pki/etcd/server.key` }, exercise: { prompt: `For each outcome, name the stage of the request chain responsible: (a) \`error: You must be logged in to the server (Unauthorized)\`; (b) a Pod created without a ServiceAccount ends up with \`serviceAccountName: default\`; (c) a privileged Pod is rejected in a namespace labelled \`pod-security.kubernetes.io/enforce: restricted\`; (d) \`User "dev" cannot delete resource "pods"\`.`, solution: `(a) **Authentication** \u2013 the credentials were missing or invalid (401). (b) **Mutating admission** \u2013 the ServiceAccount admission plugin defaults the field. (c) **Validating admission** \u2013 Pod Security Admission enforces the Pod Security Standards. (d) **Authorization** \u2013 RBAC found no rule granting \`delete\` on \`pods\` (403).` }, faq: [ { q: "What happens to the cluster if etcd loses all its data?", a: "The cluster forgets every object: Deployments, Services, Secrets, RBAC. Containers already running keep going for a while, but nothing can be managed or recovered without restoring an etcd **snapshot**." }, { q: "Why do some API paths start with /api and others with /apis?", a: "`/api/v1` is the **core** (legacy) group: Pods, Services, ConfigMaps, Secrets, Namespaces. Named groups live under `/apis//`, e.g. `/apis/apps/v1` for Deployments." }, { q: "Can I extend the API?", a: "Yes. **CustomResourceDefinitions** add new resource types that the API server stores in etcd like built-ins; aggregated API servers are the less common alternative. Operators build on CRDs." } ], keyTerms: ["kube-apiserver", "etcd", "authentication", "authorization", "admission controller", "mutating webhook", "watch", "API group"], deeper: `To avoid hammering the API server, clients use **informers**: one list + watch per resource type, a local in-memory cache, and event handlers that enqueue work. The API server also has its own watch cache in front of etcd. **API Priority and Fairness** queues requests by priority so a noisy client cannot starve system components.`, references: [ { title: "Controlling Access to the Kubernetes API", url: "https://kubernetes.io/docs/concepts/security/controlling-access/" }, { title: "Admission Control in Kubernetes", url: "https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/" }, { title: "etcd documentation", url: "https://etcd.io/docs/" } ], diagram: "request-flow" }, { id: "control-plane-controllers", title: "Scheduler and controller managers", stage: 1, order: 3, objectives: ["kf-core", "kf-scheduling"], scope: "kcna", estMinutes: 20, summary: "kube-scheduler decides where each Pod runs by filtering and scoring nodes. kube-controller-manager runs the built-in control loops. cloud-controller-manager holds the loops that need a cloud provider API.", what: `Three control-plane programs make decisions; none of them runs containers. - **kube-scheduler** watches for Pods with no \`spec.nodeName\` and picks the best node for each. - **kube-controller-manager** is one process bundling many independent **controllers**, each a loop that watches some resources and nudges the cluster towards their spec: ReplicaSet, Deployment, StatefulSet, DaemonSet, Job, CronJob, Node, Namespace, EndpointSlice, ServiceAccount, garbage collector, and more. - **cloud-controller-manager** (CCM) contains the controllers that must call a cloud provider: the **node** controller (match nodes to cloud instances, remove deleted ones), **route** controller (configure cloud routes for Pod networks) and **service** controller (create cloud load balancers for \`type: LoadBalancer\`).`, why: `KCNA asks you to distinguish these clearly: "which component chooses the node?", "which component creates replacement Pods?", "what provisions a cloud load balancer?". Scheduling concepts (resources, taints, affinity) are their own objective, and they all plug into the filter-and-score process described here.`, problem: `Separating decisions into small loops makes each one simple and replaceable. One giant "cluster manager" would be hard to extend and a single bug would stall everything. Splitting cloud logic into the CCM let Kubernetes remove provider-specific code from the core and lets each provider release its integration independently.`, how: `Follow a single Pod from creation to placement: - **A controller creates the Pod.** The ReplicaSet controller sees 2 Pods but wants 3, so it creates a Pod object from its template. The Pod has no node yet; it is \`Pending\`. - **The scheduler queues it.** The scheduler's watch delivers the unscheduled Pod; it enters a priority-ordered **scheduling queue**. - **Filtering.** The scheduler removes nodes that cannot run the Pod: not enough unreserved CPU/memory for the Pod's **requests**, a **taint** the Pod does not tolerate, a mismatched **nodeSelector** or required **node affinity**, port conflicts, volume topology constraints. - **Scoring.** Remaining nodes are ranked by plugins \u2013 e.g. spreading Pods across nodes/zones, preferring nodes that already have the image, balancing resource use, preferred affinities. - **Binding.** The highest-scoring node wins (ties broken randomly). The scheduler writes a **Binding**, which sets \`spec.nodeName\`. - **Unschedulable?** If no node passes filtering, the Pod stays \`Pending\` with a \`FailedScheduling\` event explaining why (e.g. \`0/3 nodes are available: 3 Insufficient cpu\`). Higher-priority Pods may trigger **preemption** of lower-priority ones. - **Hand-off.** The kubelet on the chosen node takes over.`, components: [ { name: "kube-scheduler", description: "Filter \u2192 score \u2192 bind. Considers requests (not actual usage), taints/tolerations, affinity, topology spread." }, { name: "kube-controller-manager", description: "Runs built-in controllers in one binary; one active instance via leader election." }, { name: "cloud-controller-manager", description: "Node, route and service controllers that talk to the cloud provider API. Absent on bare metal unless a provider integration is installed." }, { name: "Leader election", description: "Multiple replicas of scheduler/controller managers run for HA, but only the lease holder acts." } ], misconceptions: [ { myth: "The scheduler places Pods based on current CPU usage.", reality: `Filtering uses resource **requests** compared to node allocatable minus other Pods' requests. A node can look idle in metrics and still be "full" for scheduling.` }, { myth: "The scheduler moves Pods to better nodes later.", reality: 'Scheduling happens **once** per Pod. A bound Pod is never moved; to "move" it, it must be deleted and a new Pod scheduled. (The separate Descheduler project can evict Pods to trigger this.)' }, { myth: "kube-controller-manager is a single controller.", reality: "It is a **process** containing dozens of independent controllers, each with its own loop." } ], example: { title: "Reading a scheduling failure", description: `The scheduler explains filter failures in events. Here, no node had enough CPU for the Pod's requests, and one node was excluded by a taint.`, language: "bash", code: `kubectl describe pod api-7c9d5b7f6-xq2lp # ... # Status: Pending # Events: # Type Reason From Message # Warning FailedScheduling default-scheduler 0/3 nodes are available: # 1 node(s) had untolerated taint {node-role.kubernetes.io/control-plane: }, # 2 Insufficient cpu. preemption: 0/3 nodes are available: # 1 Preemption is not helpful for scheduling, # 2 No preemption victims found for incoming pod.` }, exercise: { prompt: `A Pod requests \`cpu: 2\`. Node A has 4 allocatable CPUs with Pods requesting 3; node B has 8 allocatable CPUs with Pods requesting 5 but carries the taint \`gpu=true:NoSchedule\`; node C has 4 allocatable CPUs with Pods requesting 1. The Pod has no tolerations. Which nodes pass filtering, and where does it go?`, solution: `- Node A: 4 \u2212 3 = 1 CPU free < 2 \u2192 **filtered out**. - Node B: 3 CPUs free, but the Pod does not tolerate \`gpu=true:NoSchedule\` \u2192 **filtered out**. - Node C: 4 \u2212 1 = 3 CPUs free \u2265 2 \u2192 **passes**. Only node C is feasible, so the Pod is bound to node C (scoring is trivial with one candidate).` }, faq: [ { q: "Can I run more than one scheduler?", a: "Yes. A Pod can choose one with `spec.schedulerName`; Pods without it use `default-scheduler`." }, { q: "Who sets a Node to NotReady?", a: "The **node lifecycle controller** in kube-controller-manager, when the kubelet stops renewing its heartbeat. After a timeout, taints cause Pods on that node to be evicted so their controllers replace them elsewhere." }, { q: "What if I bypass the scheduler by setting nodeName myself?", a: "Setting `spec.nodeName` in the manifest skips scheduling entirely; the named node's kubelet just tries to run it. Filtering (resources, taints) is not checked, so the Pod may be rejected by that kubelet." } ], keyTerms: ["kube-scheduler", "filtering", "scoring", "binding", "kube-controller-manager", "cloud-controller-manager", "leader election", "FailedScheduling"], deeper: `The scheduler is built on the **scheduling framework**: extension points (PreFilter, Filter, Score, Reserve, Permit, Bind...) where plugins hook in, configured through scheduler profiles. Custom schedulers for batch/AI workloads (e.g. gang scheduling) plug in this way or run alongside the default scheduler.`, references: [ { title: "Kubernetes Scheduler", url: "https://kubernetes.io/docs/concepts/scheduling-eviction/kube-scheduler/" }, { title: "Controllers", url: "https://kubernetes.io/docs/concepts/architecture/controller/" }, { title: "Cloud Controller Manager", url: "https://kubernetes.io/docs/concepts/architecture/cloud-controller/" } ] }, { id: "node-components", title: "Node components: kubelet, runtime, kube-proxy", stage: 1, order: 4, objectives: ["kf-core", "kf-containerization"], scope: "kcna", estMinutes: 20, summary: "On each node the kubelet turns Pod specs into running containers by calling a container runtime through the CRI (containerd or CRI-O, which call runc). kube-proxy programs Service routing.", what: `Look at the cluster from a single node's point of view: - **kubelet** \u2013 the node's agent. It registers the node with the API server, watches for Pods bound to it, makes their containers run, mounts volumes, runs probes, and reports Pod and node status. - **Container Runtime Interface (CRI)** \u2013 a gRPC API between the kubelet and the runtime. Any runtime implementing it works. - **High-level runtime** \u2013 **containerd** or **CRI-O**: pulls images, manages storage, creates the Pod sandbox and containers. - **Low-level OCI runtime** \u2013 usually **runc** (alternatives: crun, gVisor's runsc, Kata). Creates the actual namespaced, cgrouped process. - **kube-proxy** \u2013 watches Services and EndpointSlices and programs rules (iptables, IPVS, or nftables in newer versions) so a Service IP reaches a backend Pod. Some CNI plugins replace it entirely. - **CNI plugin** \u2013 called by the runtime to give each Pod sandbox a network interface and IP.`, why: `The 1.24 **dockershim removal** made "Kubernetes runtime" a common exam topic: the kubelet only speaks CRI, and Docker Engine does not implement CRI natively. Knowing the chain kubelet \u2192 CRI \u2192 containerd/CRI-O \u2192 runc also tells you where to look when a Pod is stuck in \`ContainerCreating\` or \`ImagePullBackOff\`.`, problem: `Early Kubernetes hard-coded Docker support into the kubelet (dockershim). Every new runtime needed kubelet changes, and the extra Docker daemon layer added complexity. The CRI defined a stable plug-in boundary, so the kubelet stays the same while runtimes evolve independently \u2013 the same "define an interface" pattern as CNI for networking and CSI for storage.`, how: `What the kubelet does when a Pod is bound to its node: - **Observe.** Its watch on the API server delivers a Pod with \`spec.nodeName\` equal to this node. - **Admit.** It checks node-level conditions (enough resources, no node pressure that blocks admission). - **Prepare volumes.** ConfigMaps, Secrets, emptyDirs and persistent volumes are attached and mounted; the kubelet waits for this before starting the Pod. - **Create the sandbox.** CRI \`RunPodSandbox\`: the runtime creates the Pod's shared namespaces (notably the network namespace, held by a tiny "pause" container in containerd/CRI-O). The **CNI plugin** attaches a network interface and assigns the Pod IP. - **Pull images.** CRI \`PullImage\` according to \`imagePullPolicy\`. - **Start containers.** Init containers run first, one by one, to completion; then the app containers start via CRI \`CreateContainer\`/\`StartContainer\`. The runtime hands an OCI bundle to runc, which creates the process. - **Supervise.** The kubelet runs liveness/readiness/startup probes, restarts failed containers per \`restartPolicy\` (with exponential back-off), and reports status (\`Running\`, \`Ready\`, restart counts) to the API server. - **Heartbeat.** It updates the node's Lease and status so the control plane knows the node is alive.`, components: [ { name: "kubelet", description: "Node agent; the only component that actually causes containers to start on a node. Also runs **static Pods** from local manifest files." }, { name: "CRI", description: "gRPC interface (RuntimeService + ImageService) between kubelet and runtime." }, { name: "containerd", description: "CNCF graduated high-level runtime with a built-in CRI plugin; default in many distributions and managed services." }, { name: "CRI-O", description: "Lightweight runtime built specifically for the Kubernetes CRI; a CNCF project used e.g. by OpenShift." }, { name: "runc", description: "Reference OCI runtime that creates container processes from bundles." }, { name: "kube-proxy", description: "Per-node Service implementation; typically a DaemonSet. Does not proxy traffic in user space in modern modes \u2013 it programs the kernel." } ], misconceptions: [ { myth: "After dockershim removal, images built with Docker no longer work.", reality: "Docker builds standard OCI images; containerd and CRI-O run them unchanged. Only using **Docker Engine as the node runtime** was affected (it now needs the external cri-dockerd adapter)." }, { myth: "kube-proxy carries all Service traffic through itself.", reality: "In iptables/IPVS/nftables modes kube-proxy only **writes kernel rules**; packets are redirected by the kernel. kube-proxy can be down briefly without breaking existing rules." }, { myth: "The kubelet manages any container on the node.", reality: "The kubelet manages containers for **Pods** (from the API server or static manifests). Containers started directly with a runtime CLI are invisible to Kubernetes." } ], example: { title: "Inspecting the node layer", description: `\`crictl\` is the CRI debugging CLI; it talks to the same socket the kubelet uses, so it shows exactly what the kubelet sees. Run it on a node (e.g. \`docker exec -it kind-worker bash\` in kind).`, language: "bash", code: `# Which runtime does each node use? kubectl get nodes -o wide # NAME ... CONTAINER-RUNTIME # kind-worker ... containerd://1.7.18 # On the node: list Pod sandboxes and containers through the CRI crictl pods crictl ps crictl images # kubelet logs on a systemd-based node journalctl -u kubelet --since "10 min ago"` }, exercise: { prompt: `A Pod is stuck in \`ContainerCreating\` for several minutes. List which node-level component could be responsible at each step of the kubelet's start-up sequence, and one concrete thing that could go wrong for each.`, solution: `- **Sandbox / CNI:** the CNI plugin is missing or failing \u2192 events like \`failed to setup network for sandbox\`. - **Volumes (kubelet):** a referenced ConfigMap/Secret does not exist, or a persistent volume cannot attach/mount \u2192 \`FailedMount\` events. - **Image pull (runtime):** pull is slow or failing \u2192 usually shown as \`ErrImagePull\`/\`ImagePullBackOff\` rather than \`ContainerCreating\`. - **Runtime itself:** containerd/CRI-O is unhealthy \u2192 kubelet logs show CRI errors and the node may go \`NotReady\`. \`kubectl describe pod\` (events) is the first place to look; kubelet logs on the node are the next.` }, faq: [ { q: "Is Docker still useful with Kubernetes?", a: "Yes \u2013 for **building** images and local development. It is just not the recommended node runtime. Tools like kind even run whole Kubernetes nodes inside Docker containers." }, { q: "What is the pause container?", a: "A tiny container that holds the Pod's shared namespaces (especially the network namespace) so app containers can restart without losing the Pod IP. It is an implementation detail of runtimes like containerd and CRI-O." }, { q: "Do I always need kube-proxy?", a: "Most clusters run it. Some CNI plugins (Cilium in kube-proxy replacement mode, for example) implement Services with eBPF instead, so kube-proxy is not deployed." } ], keyTerms: ["kubelet", "CRI", "containerd", "CRI-O", "runc", "kube-proxy", "dockershim", "static Pod"], deeper: `Static Pods are how kubeadm runs the control plane: the kubelet reads manifests from a directory (commonly \`/etc/kubernetes/manifests\`) and creates the Pods without any API server involvement, then publishes read-only "mirror Pods" to the API. The kubelet also enforces node-pressure **eviction** when memory or disk runs low, evicting Pods by QoS class and usage.`, references: [ { title: "Kubernetes Components", url: "https://kubernetes.io/docs/concepts/overview/components/" }, { title: "Container Runtime Interface (CRI)", url: "https://kubernetes.io/docs/concepts/architecture/cri/" }, { title: "Container Runtimes", url: "https://kubernetes.io/docs/setup/production-environment/container-runtimes/" } ] }, { id: "declarative-reconciliation", title: "Desired state and reconciliation", stage: 1, order: 5, objectives: ["kf-core"], scope: "kcna", estMinutes: 20, summary: "You declare what should exist; controllers repeatedly observe actual state, compare it with desired state, and act to close the gap. kubectl apply is the declarative way to submit desired state.", what: `**Desired state** is what you write in an object's \`spec\` ("3 replicas of image v2"). **Actual state** is what is really running, reported in \`status\`. A **controller** is a loop that never stops trying to make actual match desired. This pattern is called **reconciliation**. Two ways to talk to Kubernetes: - **Imperative** \u2013 tell it *what to do*: \`kubectl create deployment\`, \`kubectl scale --replicas=5\`, \`kubectl delete pod\`. Fast for experiments; nothing records why. - **Declarative** \u2013 tell it *what you want*: keep manifests in files (ideally Git) and run \`kubectl apply -f\`. Kubernetes works out the changes.`, why: `Reconciliation is the single most important idea in Kubernetes: it explains self-healing, rolling updates, scaling, GitOps and operators. Exam questions often describe a symptom ("I deleted a Pod and it came back") whose answer is "a controller reconciled it".`, problem: `Scripts that execute steps ("start 3 containers") work only if the world is exactly as the script expected and nothing changes afterwards. Servers crash, someone deletes something by hand, a step fails half-way. A declarative system does not care how you got here \u2013 it compares where you are with where you should be and corrects the difference, every time.`, how: `A thermostat is the classic analogy: you set 21 \xB0C (desired), it measures 19 \xB0C (actual), it turns on the heat (act), and it keeps checking. A Kubernetes controller does the same: - **Observe.** Watch the relevant objects through the API server (e.g. a ReplicaSet and the Pods it owns). - **Compare.** Desired: \`spec.replicas: 3\`. Actual: 2 Pods match the selector. - **Act.** Make the smallest change that moves towards desired: create 1 Pod. Never "start from scratch". - **Report.** Update \`status\` (e.g. \`readyReplicas\`) so others can observe progress. - **Repeat.** Triggered by watch events **and** periodic resyncs. Because the logic is based on current state (level-triggered), a missed event or a controller restart does no harm. How \`kubectl apply\` fits in: - On the first apply, the object is created. kubectl records what you applied (client-side: in the \`kubectl.kubernetes.io/last-applied-configuration\` annotation; server-side apply: as **managed fields** per field manager). - On later applies, kubectl computes a **three-way merge** of your file, the last-applied state and the live object, and sends a patch. Fields you removed from the file are removed; fields set by others (e.g. an autoscaler) are left alone. - \`kubectl diff -f\` shows what an apply would change before you run it.`, components: [ { name: "spec", description: "Desired state, written by users or higher-level controllers." }, { name: "status", description: "Observed state, written by controllers and kubelets." }, { name: "Controller / control loop", description: "Observe \u2192 compare \u2192 act \u2192 repeat. Each controller owns one concern." }, { name: "kubectl apply", description: "Declarative create-or-update from files using a merge of file, last-applied and live state." }, { name: "Operator", description: "A custom controller (usually with CRDs) that encodes operational knowledge for an application, e.g. a database." } ], misconceptions: [ { myth: "Declarative means kubectl never changes anything until I re-apply.", reality: "Controllers act continuously. If a Pod dies, a replacement appears without any new apply \u2013 the desired state is still stored." }, { myth: "`kubectl apply` and `kubectl create` are interchangeable.", reality: "`create` fails if the object exists (`AlreadyExists`). `apply` creates **or** updates and tracks what you manage. Mixing them on the same object is a common source of surprises." }, { myth: "Fixing a running Pod by hand is a permanent fix.", reality: "If the Pod is owned by a controller, the next replacement Pod comes from the **template**. Manual changes to live objects (`kubectl edit`) also drift from what is in Git and may be overwritten by the next apply or a GitOps sync." } ], example: { title: "Watch a control loop heal", description: "Delete a Pod owned by a Deployment and the ReplicaSet controller restores the count. Then change the desired state declaratively and preview it first.", language: "bash", code: `kubectl apply -f web-deployment.yaml # replicas: 3 kubectl get pods -l app=web # web-5d8f7c6b9-2kq4x Running # web-5d8f7c6b9-8hz7m Running # web-5d8f7c6b9-tw9pd Running kubectl delete pod web-5d8f7c6b9-2kq4x kubectl get pods -l app=web # web-5d8f7c6b9-8hz7m Running # web-5d8f7c6b9-tw9pd Running # web-5d8f7c6b9-x7n2c ContainerCreating <- replacement # change replicas: 3 -> 5 in the file, then: kubectl diff -f web-deployment.yaml # preview the change kubectl apply -f web-deployment.yaml` }, exercise: { prompt: `A teammate runs \`kubectl scale deployment web --replicas=10\` during an incident. The manifest in Git says \`replicas: 3\`, and a GitOps tool applies Git every few minutes. What happens next, and what should they have done instead?`, solution: `The imperative scale changes the live desired state to 10, and the controller creates 7 Pods. On the next sync the GitOps tool re-applies Git, setting \`replicas\` back to **3**, and the extra Pods are removed \u2013 possibly mid-incident. Better: change \`replicas\` in Git (so the declared state is the real intent), or let a HorizontalPodAutoscaler own the replica count and remove \`replicas\` from the manifest so the two do not fight.` }, faq: [ { q: "If everything is declarative, why does kubectl have imperative commands?", a: "They are convenient for learning, debugging and generating starter YAML (`kubectl create deployment web --image=nginx --dry-run=client -o yaml`). For anything long-lived, store manifests and apply them." }, { q: "What is server-side apply?", a: "`kubectl apply --server-side` performs the merge on the API server and records which **field manager** owns each field, reporting conflicts when two managers set the same field. It is the alternative to the last-applied annotation used by client-side apply, which remains the kubectl default." }, { q: "How fast does reconciliation happen?", a: "Usually within seconds, because controllers react to watch events. But it is asynchronous: `apply` returning success means the desired state was stored, not that it is achieved. Use `kubectl rollout status` or `kubectl get -w` to watch convergence." } ], keyTerms: ["desired state", "actual state", "reconciliation", "control loop", "declarative", "imperative", "kubectl apply", "operator"], deeper: `Controllers are written as a work queue fed by informers: events only enqueue an object key, and a worker re-reads the latest state before acting. This is why controllers are idempotent and tolerate duplicate or out-of-order events. The same pattern scales out to GitOps: Argo CD and Flux are reconcilers whose "desired state" lives in Git instead of etcd.`, references: [ { title: "Controllers", url: "https://kubernetes.io/docs/concepts/architecture/controller/" }, { title: "Declarative Management of Kubernetes Objects Using Configuration Files", url: "https://kubernetes.io/docs/tasks/manage-kubernetes-objects/declarative-config/" }, { title: "Kubernetes Object Management", url: "https://kubernetes.io/docs/concepts/overview/working-with-objects/object-management/" } ], diagram: "reconciliation-loop" }, // ───────────────────────────── Stage 2 · Workloads ───────────────────────────── { id: "pods", title: "Pods", stage: 2, order: 1, objectives: ["kf-core"], scope: "kcna", estMinutes: 25, summary: "A Pod is the smallest deployable unit: one or more containers that share a network namespace and volumes and are always scheduled together. Pods are disposable; controllers recreate them.", what: `A **Pod** wraps one or more containers that must live together: - They are **scheduled onto the same node** as a unit. - They share one **network namespace**: one Pod IP, one port space; containers talk over \`localhost\`. - They can share **volumes** declared at Pod level. - They share a lifecycle: the Pod is created, runs, and is deleted as one object. Container roles inside a Pod: - **App containers** \u2013 the main workload; started together, run in parallel. - **Init containers** \u2013 run **one at a time, to completion**, before app containers start (wait for a dependency, run a migration, fetch config). - **Sidecar containers** \u2013 helpers that run alongside the app for the Pod's whole life (log shipping, proxies). Native sidecars are declared as init containers with \`restartPolicy: Always\` (stable since Kubernetes 1.33): they start before the app containers, keep running, and are stopped after them.`, why: `Everything that runs in Kubernetes runs in a Pod \u2013 Deployments, Jobs, StatefulSets all create Pods. Pod phases, restart policies and container states are exactly what you see in \`kubectl get pods\` when something is wrong, and they come up repeatedly on the exam.`, problem: `Some processes are tightly coupled: a web server and the agent that ships its logs, or an app and its local proxy. Putting them in one container breaks "one process per container" and couples their images and releases. Putting them in separate, independently scheduled units loses \`localhost\` and shared files. The Pod is the middle ground: separate images, shared context.`, how: `Follow the Pod lifecycle as a state machine. **Pod phase** (\`status.phase\`) \u2013 a coarse summary: - \`Pending\` \u2013 accepted, but not all containers are running yet: waiting to be scheduled, pulling images, or running init containers. - \`Running\` \u2013 bound to a node, all containers created, at least one running (or starting/restarting). - \`Succeeded\` \u2013 all containers exited 0 and will not restart. - \`Failed\` \u2013 all containers terminated and at least one failed (non-zero exit or killed) and will not restart. - \`Unknown\` \u2013 the node cannot be reached, so status cannot be obtained. **Container state** (per container) \u2013 \`Waiting\` (with a reason such as \`ContainerCreating\`, \`ImagePullBackOff\`, \`CrashLoopBackOff\`), \`Running\`, or \`Terminated\` (with exit code and reason such as \`Completed\`, \`Error\`, \`OOMKilled\`). **restartPolicy** (Pod-level, applies to app containers): \`Always\` (default; required for Deployments), \`OnFailure\` (restart only on non-zero exit; common for Jobs), \`Never\`. Restarts happen **in place on the same node** with exponential back-off (10s, 20s, 40s ... capped at 5 minutes) \u2013 that back-off is what \`CrashLoopBackOff\` means. **Termination:** on delete, the Pod is marked terminating, removed from Service endpoints, any \`preStop\` hook runs, containers get \`SIGTERM\`, and after \`terminationGracePeriodSeconds\` (default 30) the remaining ones get \`SIGKILL\`.`, components: [ { name: "Pod IP / network namespace", description: "One IP per Pod, shared by all its containers. Two containers in a Pod cannot both listen on the same port." }, { name: "Init containers", description: "Sequential, run-to-completion setup steps. If one fails, the kubelet retries it (per restartPolicy) and app containers do not start." }, { name: "Sidecar containers", description: "Init containers with `restartPolicy: Always`; run for the Pod's lifetime and do not block Job completion." }, { name: "restartPolicy", description: "`Always` | `OnFailure` | `Never`, set once for the whole Pod." }, { name: "Phase vs conditions", description: "Phase is a summary; conditions (`PodScheduled`, `Initialized`, `ContainersReady`, `Ready`) give detail. `Ready` controls Service traffic." } ], misconceptions: [ { myth: "`CrashLoopBackOff` is a Pod phase.", reality: "It is a **container waiting reason**: the container keeps crashing and the kubelet is backing off before the next restart. The Pod phase is usually still `Running`." }, { myth: "A Pod that crashes gets rescheduled to another node.", reality: "Containers are restarted **in place** by the kubelet. A Pod is never moved; only a controller can create a **new** Pod (with a new name and IP) elsewhere \u2013 for example after the Pod is deleted or its node fails." }, { myth: "Each container in a Pod gets its own IP.", reality: "The **Pod** gets one IP. Containers inside share it and distinguish themselves by port." } ], example: { title: "Init container, native sidecar and app in one Pod", description: `The init container waits for the \`db\` Service to resolve. The sidecar (an init container with \`restartPolicy: Always\`) tails the app's log file from a shared \`emptyDir\` volume and keeps running alongside the app.`, language: "yaml", code: `apiVersion: v1 kind: Pod metadata: name: shop labels: app: shop spec: restartPolicy: Always volumes: - name: logs emptyDir: {} initContainers: - name: wait-for-db image: busybox:1.36 command: ["sh", "-c", "until nslookup db; do echo waiting; sleep 2; done"] - name: log-shipper # native sidecar image: busybox:1.36 restartPolicy: Always command: ["sh", "-c", "tail -F /var/log/app/app.log"] volumeMounts: - name: logs mountPath: /var/log/app containers: - name: app image: registry.example.com/shop/app:1.4.2 ports: - containerPort: 8080 volumeMounts: - name: logs mountPath: /var/log/app` }, exercise: { prompt: `Predict \`kubectl get pod\` output for each case: (a) the \`db\` Service in the example does not exist yet; (b) the app container exits with code 1 every few seconds; (c) the app container finishes with exit code 0 (restartPolicy \`Always\`).`, solution: `(a) The first init container never completes. STATUS shows \`Init:0/2\`, phase \`Pending\`; the app container never starts. (b) The kubelet restarts it with growing back-off. STATUS alternates between \`Error\` and \`CrashLoopBackOff\`, the RESTARTS count climbs, phase stays \`Running\`. (c) With \`Always\`, even a clean exit triggers a restart, so you again see RESTARTS increasing (and eventually \`CrashLoopBackOff\`). A run-to-completion task belongs in a **Job** with \`OnFailure\` or \`Never\`.` }, faq: [ { q: "When should I put two containers in one Pod?", a: "Only when they must share lifecycle, network or files \u2013 a sidecar proxy, log shipper or config reloader. If they could scale independently (a web app and its database), use separate Pods." }, { q: "Should I create Pods directly?", a: "Rarely. A bare Pod is not recreated if it is deleted or its node fails. Use a controller \u2013 Deployment, StatefulSet, DaemonSet or Job \u2013 that manages Pods from a template. Note that `kubectl run` creates only a single bare Pod." }, { q: "Can I change a running Pod's spec?", a: "Mostly no \u2013 most Pod spec fields are immutable (image is a notable exception). In practice you change the controller's template and let it replace Pods." }, { q: "What is the difference between Running and Ready?", a: "`Running` means the containers are started. `Ready` means readiness probes pass and the Pod should receive Service traffic. A Pod can be Running but not Ready." } ], keyTerms: ["Pod", "init container", "sidecar container", "Pod phase", "container state", "restartPolicy", "CrashLoopBackOff", "terminationGracePeriodSeconds"], deeper: `**Ephemeral containers** can be added to a running Pod for debugging (\`kubectl debug\`); they cannot be restarted and have no ports or probes. **Static Pods** are created by a kubelet from local files rather than the API. The **Pod overhead** and **Pod-level resources** features let the scheduler account for sandbox costs or set budgets for the whole Pod \u2013 check feature states for your version.`, references: [ { title: "Pods", url: "https://kubernetes.io/docs/concepts/workloads/pods/" }, { title: "Pod Lifecycle", url: "https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/" }, { title: "Sidecar Containers", url: "https://kubernetes.io/docs/concepts/workloads/pods/sidecar-containers/" } ] }, { id: "replicasets-and-deployments", title: "ReplicaSets and Deployments", stage: 2, order: 2, objectives: ["kf-core"], scope: "kcna", estMinutes: 25, summary: "A ReplicaSet keeps N identical Pods running. A Deployment manages ReplicaSets to add rolling updates and rollbacks. Ownership links the three levels, and garbage collection cleans up children.", what: `Two controllers stacked on top of each other: - **ReplicaSet** \u2013 ensures that a specified number of Pods matching its **selector** exist. It creates Pods from its **Pod template** when there are too few and deletes some when there are too many. It does not know about versions. - **Deployment** \u2013 the object you normally write for stateless apps. It owns ReplicaSets: one per version of the Pod template. Changing the template creates a new ReplicaSet and gradually shifts Pods to it (**rolling update**); old ReplicaSets are kept (scaled to 0) to allow **rollback**. The chain is **Deployment \u2192 ReplicaSet \u2192 Pods**, linked by \`metadata.ownerReferences\` on each child.`, why: `Deployments are the default way to run stateless workloads, and most exam workload questions touch them: scaling, self-healing, update strategy, rollback, and "who created this Pod?". Understanding the ReplicaSet layer explains the odd Pod names (\`web-5d8f7c6b9-x7n2c\`) and what happens during a rollout.`, problem: `Running one Pod is fragile. Running N Pods by hand means noticing failures and replacing them yourself. And updating N Pods by deleting them all and creating new ones causes downtime and gives no way back if the new version is broken. ReplicaSets solve "keep N", Deployments solve "change versions safely".`, how: `Run an experiment in your head (or on a cluster): - **Create.** You apply a Deployment \`web\` with \`replicas: 3\` and image \`nginx:1.26\`. The Deployment controller creates ReplicaSet \`web-\` (the hash comes from the Pod template and is also added as a \`pod-template-hash\` label). The ReplicaSet controller creates 3 Pods. - **Break something.** Delete a Pod. The **ReplicaSet** controller (not the Deployment controller) sees 2 < 3 and creates one more. - **Scale.** \`kubectl scale deployment web --replicas=5\` \u2013 the Deployment updates its current ReplicaSet's replica count; no new ReplicaSet is created because the template did not change. - **Update.** Change the image to \`nginx:1.27\`. The template hash changes, so a **new ReplicaSet** is created. With the default **RollingUpdate** strategy (\`maxSurge: 25%\`, \`maxUnavailable: 25%\`), the controller scales the new one up and the old one down step by step, waiting for new Pods to become Ready. - **Roll back.** \`kubectl rollout undo deployment/web\` points the Deployment back at the previous template; the old ReplicaSet is scaled up again. How many old ReplicaSets are kept is set by \`revisionHistoryLimit\` (default 10). - **Delete.** Deleting the Deployment triggers **cascading deletion**: the garbage collector follows ownerReferences and removes the ReplicaSets and Pods. The **Recreate** strategy is the alternative: scale old Pods to zero first, then create new ones (downtime, but never two versions at once).`, components: [ { name: "Pod template", description: "`spec.template` \u2013 the blueprint for every Pod. Any change to it triggers a rollout." }, { name: "Selector", description: "`spec.selector` must match the template's labels; immutable for `apps/v1` Deployments after creation." }, { name: "ReplicaSet", description: "Keeps the replica count for one template version. Rarely created directly." }, { name: "Rolling update parameters", description: "`maxSurge` (extra Pods allowed above desired) and `maxUnavailable` (Pods allowed below desired); both default to 25%." }, { name: "ownerReferences & garbage collection", description: "Children point to their owner; deleting the owner removes dependents (cascading deletion) unless orphaning is requested." } ], misconceptions: [ { myth: "Scaling a Deployment creates a new revision.", reality: "Only changes to `spec.template` create a new ReplicaSet/revision. Changing `replicas` adjusts the existing ReplicaSet." }, { myth: "You should edit the ReplicaSet to change the image.", reality: "The Deployment owns the ReplicaSet and will revert or ignore such changes. Always change the **Deployment**; for a bare ReplicaSet, an edited template only affects Pods created later." }, { myth: "Rollback restores the previous number of replicas too.", reality: "`rollout undo` restores the previous **Pod template**. The replica count is not part of the revision." } ], example: { title: "A Deployment with an explicit rolling update strategy", description: `With 4 replicas, \`maxSurge: 1\` and \`maxUnavailable: 0\`, the rollout never drops below 4 ready Pods and runs at most 5 Pods at a time \u2013 zero-downtime at the cost of one extra Pod of capacity.`, language: "yaml", code: `apiVersion: apps/v1 kind: Deployment metadata: name: web labels: app: web spec: replicas: 4 revisionHistoryLimit: 5 selector: matchLabels: app: web strategy: type: RollingUpdate rollingUpdate: maxSurge: 1 maxUnavailable: 0 template: metadata: labels: app: web # must match spec.selector spec: containers: - name: web image: nginx:1.27 ports: - containerPort: 80 # kubectl set image deployment/web web=nginx:1.28 # kubectl rollout status deployment/web # kubectl rollout history deployment/web # kubectl rollout undo deployment/web --to-revision=2` }, exercise: { prompt: `You have Deployment \`api\` with 10 replicas and default rolling update settings. You change the image. (a) What is the maximum number of Pods that may exist during the rollout? (b) The minimum number that must be available? (c) Afterwards, how many ReplicaSets does \`kubectl get rs\` show for \`api\`, and with what replica counts?`, solution: `(a) \`maxSurge\` 25% of 10 = 2.5, rounded **up** \u2192 3, so up to **13** Pods. (b) \`maxUnavailable\` 25% of 10 = 2.5, rounded **down** \u2192 2, so at least **8** available. (c) **Two** ReplicaSets: the new one with 10 replicas and the old one scaled to **0** (kept for rollback, within \`revisionHistoryLimit\`).` }, faq: [ { q: "Why are Pod names like web-5d8f7c6b9-x7n2c?", a: "`web` is the Deployment, `5d8f7c6b9` is the ReplicaSet's Pod template hash, and `x7n2c` is a random suffix for the individual Pod. It lets you see at a glance which version a Pod belongs to." }, { q: "How do I find out who owns a Pod?", a: "Look at `metadata.ownerReferences` (`kubectl get pod -o yaml`) or the `Controlled By:` line in `kubectl describe pod`." }, { q: "When would I use a ReplicaSet directly?", a: "Almost never. Deployments give you everything a ReplicaSet does plus updates and rollbacks. Use StatefulSets for stable identity and DaemonSets for one-Pod-per-node instead." } ], keyTerms: ["ReplicaSet", "Deployment", "Pod template", "RollingUpdate", "Recreate", "maxSurge", "maxUnavailable", "ownerReferences"], deeper: `\`kubectl rollout pause\` lets you batch several template changes into one rollout. \`progressDeadlineSeconds\` (default 600) marks a rollout as failed (\`ProgressDeadlineExceeded\`) if it stops making progress \u2013 it reports, but does not roll back automatically. Garbage collection supports **foreground**, **background** (default) and **orphan** propagation policies, e.g. \`kubectl delete deployment web --cascade=orphan\` keeps the ReplicaSets and Pods.`, references: [ { title: "Deployments", url: "https://kubernetes.io/docs/concepts/workloads/controllers/deployment/" }, { title: "ReplicaSet", url: "https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/" }, { title: "Garbage Collection", url: "https://kubernetes.io/docs/concepts/architecture/garbage-collection/" } ], diagram: "deployment-hierarchy" }, { id: "namespaces-labels-selectors", title: "Namespaces, labels, selectors and annotations", stage: 2, order: 3, objectives: ["kf-core", "kf-admin"], scope: "kcna", estMinutes: 20, summary: "Namespaces partition names, permissions and quotas. Labels are queryable key/value tags; selectors are the queries that wire Services, Deployments and policies to Pods. Annotations hold non-identifying metadata.", what: `Think of the cluster as a database and these as its organizing tools. - **Namespace** \u2013 a scope for names. Two Deployments called \`web\` can coexist in \`team-a\` and \`team-b\`. Namespaces are also the unit for RBAC Roles, ResourceQuotas, LimitRanges, and (by label) Pod Security Admission. Default ones: \`default\`, \`kube-system\`, \`kube-public\`, \`kube-node-lease\`. - **Labels** \u2013 key/value pairs in \`metadata.labels\` that **identify** objects: \`app: web\`, \`tier: frontend\`, \`env: prod\`. Keys may have a DNS prefix (\`app.kubernetes.io/name\`); the name part is at most 63 characters. - **Selectors** \u2013 queries over labels. **Equality-based**: \`app=web\`, \`env!=prod\`. **Set-based**: \`env in (staging,prod)\`, \`tier notin (cache)\`, \`release\` (key exists), \`!release\` (key absent). - **Annotations** \u2013 key/value pairs in \`metadata.annotations\` for **non-identifying** data: build info, contact, tool configuration. Values can be large; they cannot be selected on.`, why: `Labels and selectors are the glue of Kubernetes. Objects are not linked by name but by **label queries**: a Service finds its Pods by selector, a Deployment's ReplicaSet counts Pods by selector, NetworkPolicies and affinity rules select Pods by label. When a Service has no endpoints, a label mismatch is the first suspect. Namespaces are the first tool for multi-team clusters.`, problem: `In a cluster with thousands of objects you need to answer "show me all production frontend Pods" and "let team A manage only its own things". Folder-like hierarchies cannot express overlapping views (a Pod is both "frontend" and "prod" and "v2"). Free-form labels with a query language can, and namespaces add hard naming and permission boundaries where you need them.`, how: `How a selector connects objects, step by step, using a Service: - **Label the Pods.** The Deployment template sets \`labels: {app: web, tier: frontend}\` on every Pod it creates. - **Write the query.** The Service declares \`selector: {app: web}\`. Services support only equality-based selectors (all listed pairs must match). - **Controller evaluates it.** The EndpointSlice controller lists Pods **in the Service's namespace** that carry \`app=web\` and writes their IPs into EndpointSlices, marking each endpoint ready or not; only ready endpoints receive traffic. - **Labels change \u2192 membership changes.** Remove the \`app=web\` label from one Pod and it drops out of the Service (and out of the ReplicaSet's count, so the ReplicaSet creates a replacement \u2013 a handy trick for debugging a Pod in isolation). - **Namespace boundary.** Selectors in Services, ReplicaSets and Deployments only match objects in the same namespace. Cross-namespace access uses DNS names like \`web.team-a.svc.cluster.local\`. Note that not everything is namespaced: **Nodes, PersistentVolumes, StorageClasses, Namespaces, ClusterRoles** and CRDs are cluster-scoped. \`kubectl api-resources --namespaced=false\` lists them.`, components: [ { name: "Namespace", description: "Scope for names and for RBAC, quotas and policies. Not a network or security boundary by itself." }, { name: "Label", description: "Identifying key/value pair; indexed and selectable. Recommended keys: `app.kubernetes.io/name`, `/instance`, `/version`, `/component`, `/part-of`, `/managed-by`." }, { name: "Equality-based selector", description: "`=`, `==`, `!=`. Used by Services and `matchLabels`." }, { name: "Set-based selector", description: "`in`, `notin`, exists, does-not-exist. Used by `matchExpressions` (Deployments, Jobs, affinity) and kubectl `-l`." }, { name: "Annotation", description: "Non-identifying metadata for tools and humans; not selectable." } ], misconceptions: [ { myth: "Namespaces isolate network traffic between teams.", reality: "By default every Pod can reach every other Pod across namespaces. Isolation needs **NetworkPolicies** (and a CNI that enforces them); permission isolation needs **RBAC**." }, { myth: "Annotations and labels are interchangeable.", reality: "Only labels can be used in selectors. Annotations are for data you want to attach but never query, e.g. a git commit or a tool setting." }, { myth: "A Service can select Pods in any namespace by label.", reality: "A Service selector only matches Pods in **its own namespace**." } ], example: { title: "Querying with labels and working across namespaces", description: "Common label and namespace operations with kubectl.", language: "bash", code: `kubectl create namespace team-a kubectl config set-context --current --namespace=team-a # change default namespace kubectl get pods --show-labels kubectl get pods -l app=web # equality-based kubectl get pods -l 'env in (staging,prod),tier!=cache' # set-based + equality kubectl get pods -l '!canary' # label key absent kubectl get pods -A -l app=web # all namespaces kubectl label pod web-5d8f7c6b9-x7n2c env=prod # add a label kubectl label pod web-5d8f7c6b9-x7n2c env=staging --overwrite kubectl label pod web-5d8f7c6b9-x7n2c env- # remove a label kubectl annotate deployment web owner="team-a@example.com" kubectl api-resources --namespaced=false # cluster-scoped kinds` }, exercise: { prompt: `A Service in namespace \`shop\` has \`selector: {app: cart, tier: backend}\`. Pods: (1) \`app=cart, tier=backend\` in \`shop\`; (2) \`app=cart\` in \`shop\`; (3) \`app=cart, tier=backend, version=v2\` in \`shop\`; (4) \`app=cart, tier=backend\` in \`default\`. Which Pods become endpoints (assume all are Ready)?`, solution: `**Pods 1 and 3.** A selector requires **all** its pairs to match; extra labels on the Pod (\`version=v2\`) do not matter. Pod 2 lacks \`tier=backend\`. Pod 4 matches the labels but is in another namespace, and Service selectors only match within the Service's own namespace.` }, faq: [ { q: "Does deleting a namespace delete everything inside it?", a: "Yes \u2013 all namespaced objects in it are deleted. The namespace sits in `Terminating` until that finishes. Cluster-scoped objects (e.g. PersistentVolumes) are not inside namespaces and follow their own rules." }, { q: "Should I use namespaces for environments like dev and prod?", a: "It works for small setups, but many organizations put production in a **separate cluster** for stronger isolation. Namespaces are the usual unit for teams or applications within a cluster." }, { q: "Can I change a Deployment's selector later?", a: "No \u2013 in `apps/v1` the selector is immutable. Create a new Deployment instead. You *can* add labels to the template, as long as the selector still matches." } ], keyTerms: ["namespace", "label", "label selector", "matchLabels", "matchExpressions", "annotation", "cluster-scoped", "namespaced"], deeper: `Field selectors (\`--field-selector status.phase=Running\`) filter on a small set of built-in fields, not on arbitrary spec values. Hierarchical namespaces and virtual clusters (e.g. vcluster) are ecosystem projects for stronger multi-tenancy than plain namespaces provide.`, references: [ { title: "Labels and Selectors", url: "https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/" }, { title: "Namespaces", url: "https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/" }, { title: "Annotations", url: "https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations/" } ] } ]; // ../../packages/content/src/lessons/b.ts var lessonsB = [ // ───────────────────────────── Stage 2 · Workloads ───────────────────────────── { id: "jobs-and-cronjobs", title: "Jobs and CronJobs", stage: 2, order: 4, objectives: ["kf-core"], scope: "kcna", estMinutes: 18, summary: "Jobs run Pods until a task finishes successfully; CronJobs create Jobs on a schedule. They are the workload controllers for work that is supposed to end.", what: `A **Job** is a controller that creates one or more Pods and keeps creating replacements until a specified number of them **complete successfully** (exit code 0). Then it stops. The Job object stays around as a record of the run. A **CronJob** is a controller one level higher: on a cron schedule (for example \`0 2 * * *\` = every day at 02:00) it creates a new Job from a \`jobTemplate\`. The chain is CronJob \u2192 Job \u2192 Pod, the same "controller owns controller" pattern you saw with Deployment \u2192 ReplicaSet \u2192 Pod.`, why: `A Deployment assumes its Pods should run forever: if a Pod exits, the ReplicaSet replaces it. That is exactly wrong for a database migration, a report generator or a batch image resize. Those tasks should run, finish, and **stay finished**. Jobs give batch work the same self-healing as long-running services: if the node dies halfway through, the Job controller notices the missing Pod and starts another, but once the work succeeds nothing gets restarted.`, problem: `Imagine running a nightly backup with a plain Pod. If the node reboots at 02:05, the Pod is gone and nothing retries it. If you wrap it in a Deployment instead, the backup "succeeds", exits, and is immediately started again in an endless loop. Before Kubernetes, the usual answer was a crontab on one specific server: a single point of failure that nobody remembered to migrate. CronJob moves the schedule into the cluster, where it survives the loss of any single machine.`, how: `Follow one run of a CronJob from schedule to cleanup: - The **CronJob controller** (part of kube-controller-manager) checks schedules. When a schedule time arrives, it creates a **Job** object from \`spec.jobTemplate\`. - If the previous Job is still running, \`concurrencyPolicy\` decides: \`Allow\` (default, run both), \`Forbid\` (skip this run) or \`Replace\` (cancel the old one, start the new one). - The **Job controller** sees the new Job and creates Pods from its Pod template. \`parallelism\` caps how many run at once; \`completions\` says how many must succeed (both default to 1). - Each Pod's \`restartPolicy\` must be \`Never\` or \`OnFailure\` \u2014 \`Always\` is rejected for Jobs. With \`OnFailure\` the kubelet restarts the failed container in place; with \`Never\` the Job controller creates a fresh Pod. - Failures are counted against \`backoffLimit\` (default 6), with exponential back-off between retries. When the limit is exceeded the Job is marked **Failed**. \`activeDeadlineSeconds\` puts a hard wall-clock limit on the whole Job. - When enough Pods succeed, the Job gets a **Complete** condition. Its Pods are left in \`Completed\` status so you can still read their logs. - Cleanup: the CronJob keeps the last \`successfulJobsHistoryLimit\` (default 3) and \`failedJobsHistoryLimit\` (default 1) Jobs. A plain Job can clean itself up with \`ttlSecondsAfterFinished\`.`, components: [ { name: "Job", description: "Runs Pods until `completions` successes are recorded, retrying failures up to `backoffLimit`." }, { name: "CronJob", description: "Creates a Job from `jobTemplate` each time `schedule` (standard 5-field cron syntax) fires." }, { name: "completions / parallelism", description: "How many successful Pods are needed in total, and how many may run at the same time." }, { name: "backoffLimit", description: "Number of retries before the Job is marked Failed (default 6)." }, { name: "concurrencyPolicy", description: "CronJob behaviour when the previous run is still active: `Allow`, `Forbid` or `Replace`." }, { name: "ttlSecondsAfterFinished", description: "Lets the TTL controller delete a finished Job (and its Pods) after N seconds." } ], misconceptions: [ { myth: "A Job can use restartPolicy: Always like any other Pod.", reality: `No. The API server rejects a Job whose Pod template uses \`Always\`. Only \`Never\` and \`OnFailure\` make sense for work that is meant to finish.` }, { myth: "The Completed Pods of a finished Job are still running and using resources.", reality: `A \`Completed\` Pod has exited and uses no CPU or memory. It is kept only so you can read logs and status. Remove it with \`ttlSecondsAfterFinished\` or history limits when you no longer need it.` }, { myth: "A CronJob guarantees exactly one run per schedule tick.", reality: `CronJobs are approximately once. A run can be skipped (controller down, \`Forbid\` policy, missed \`startingDeadlineSeconds\`) or, rarely, happen twice. Batch tasks should be **idempotent** \u2014 safe to run again.` } ], example: { title: "A nightly report CronJob", description: `Runs at 02:30 every day, never overlaps with itself, retries twice, and keeps only a short history. Trigger it manually for testing with \`kubectl create job report-manual --from=cronjob/nightly-report\`.`, language: "yaml", code: `apiVersion: batch/v1 kind: CronJob metadata: name: nightly-report spec: schedule: "30 2 * * *" concurrencyPolicy: Forbid successfulJobsHistoryLimit: 3 failedJobsHistoryLimit: 1 jobTemplate: spec: backoffLimit: 2 activeDeadlineSeconds: 600 template: spec: restartPolicy: Never containers: - name: report image: busybox:1.36 command: ["sh", "-c", "echo generating report; sleep 5"]` }, exercise: { prompt: `You need to process 12 files. Each Pod handles one file, and you want at most 3 Pods running at the same time. Which two Job fields do you set, and to what values? What happens if one Pod crashes?`, solution: `Set \`completions: 12\` and \`parallelism: 3\`. The Job controller keeps up to 3 Pods running until 12 have succeeded. If a Pod crashes, the failure counts against \`backoffLimit\`. With \`restartPolicy: Never\` the controller creates a replacement Pod after a back-off delay; with \`OnFailure\` the container is restarted in the same Pod. Once failures exceed \`backoffLimit\`, the whole Job is marked Failed.` }, faq: [ { q: "Which API group are Jobs and CronJobs in?", a: `Both are in \`batch/v1\`. CronJob graduated to \`batch/v1\` (GA) in Kubernetes 1.21.` }, { q: "What time zone does a CronJob schedule use?", a: `By default, the time zone of the kube-controller-manager. You can set \`spec.timeZone\` (for example \`"Europe/Berlin"\`) to make it explicit.` }, { q: "How do I see why a Job failed?", a: `\`kubectl describe job \` shows conditions and events; then \`kubectl logs\` on one of its Pods (they carry the label \`job-name=\`) shows the application output.` } ], keyTerms: ["Job", "CronJob", "completions", "parallelism", "backoffLimit", "concurrencyPolicy", "ttlSecondsAfterFinished", "idempotency"], deeper: `**Indexed Jobs** (\`completionMode: Indexed\`) give each Pod a stable index (exposed as the \`JOB_COMPLETION_INDEX\` environment variable), so Pod 0 processes shard 0, and so on \u2014 the basis for static work partitioning. A **podFailurePolicy** lets a Job fail fast on non-retryable exit codes or ignore Pod disruptions (such as preemption) instead of burning \`backoffLimit\`. Jobs can also be suspended with \`spec.suspend: true\`, which queueing systems such as Kueue use to admit batch work only when capacity is available.`, references: [ { title: "Kubernetes docs: Jobs", url: "https://kubernetes.io/docs/concepts/workloads/controllers/job/" }, { title: "Kubernetes docs: CronJob", url: "https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/" } ] }, { id: "daemonsets-and-statefulsets", title: "DaemonSets and StatefulSets", stage: 2, order: 5, objectives: ["kf-core"], scope: "kcna", estMinutes: 20, summary: "DaemonSets run one Pod per eligible node for node-level agents; StatefulSets give Pods stable names, ordered rollout and their own persistent volumes for stateful apps.", what: `Both are workload controllers that exist because a Deployment's assumption \u2014 "all replicas are identical and interchangeable" \u2014 does not always hold. A **DaemonSet** ensures that **every eligible node runs exactly one copy** of a Pod. You do not set a replica count; the number of nodes is the replica count. Add a node and a Pod appears on it; remove the node and the Pod is garbage-collected. A **StatefulSet** manages Pods that each have a **persistent identity**: a stable ordinal name (\`db-0\`, \`db-1\`, \`db-2\`), a stable DNS name via a headless Service, and **its own PersistentVolumeClaim** that follows that name across rescheduling.`, why: `Think of a Deployment as a taxi rank: any car will do. A DaemonSet is a security guard posted at **every** building entrance. A StatefulSet is a numbered seat in a parliament: seat 2 is always seat 2, keeps its own desk drawer (volume), and members are sworn in in order. Log shippers (Fluent Bit), node metrics exporters, CNI agents and kube-proxy itself need to be on every node \u2014 that is the DaemonSet case. Databases, message brokers and consensus systems (PostgreSQL replicas, Kafka, etcd, ZooKeeper) need peers to find each other by name and keep their data \u2014 that is the StatefulSet case.`, problem: `Try running a three-node database with a Deployment. Pods get random names like \`db-7c9d4-xk2lp\`; when one is replaced, its name and IP change, so the other members no longer recognise it. Worse, all replicas mount the same PVC \u2014 or none \u2014 so members cannot each keep their own data, and a replacement may start with an empty disk. Try running a log agent with a Deployment of 5 replicas on 5 nodes. The scheduler may place two on one node and none on another, and when you scale the cluster to 8 nodes, three nodes are silently uncovered.`, how: `**DaemonSet, step by step:** - The DaemonSet controller lists nodes and checks which ones match the Pod template's \`nodeSelector\`/affinity and tolerate the node's taints. - For each eligible node without a Pod, it creates one with node affinity pinning it to that node; the default scheduler then binds it there. - It automatically adds tolerations for conditions such as \`not-ready\` and \`unreachable\`, so node agents keep running on unhealthy nodes. To run on control-plane nodes you must add a toleration for the control-plane taint yourself. - Updates use \`RollingUpdate\` (default) or \`OnDelete\`. **StatefulSet, step by step (default \`OrderedReady\` policy):** - \`spec.serviceName\` points at a **headless Service** (\`clusterIP: None\`) that gives each Pod a DNS name: \`db-0.db..svc.cluster.local\`. - The controller creates \`db-0\`, waits until it is Running and Ready, then creates \`db-1\`, and so on. - For each Pod it creates a PVC from \`volumeClaimTemplates\`, named \`