forgecommandline 0.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. forgecli/__init__.py +2 -0
  2. forgecli/ads.py +322 -0
  3. forgecli/agent.py +1093 -0
  4. forgecli/art.py +574 -0
  5. forgecli/attach.py +246 -0
  6. forgecli/brief.py +215 -0
  7. forgecli/browsercheck.py +99 -0
  8. forgecli/checkpoints.py +81 -0
  9. forgecli/city.py +833 -0
  10. forgecli/cli.py +1668 -0
  11. forgecli/config.py +194 -0
  12. forgecli/courier.py +177 -0
  13. forgecli/courier_data.py +164 -0
  14. forgecli/courier_hd.py +431 -0
  15. forgecli/courier_hd_data.bin +0 -0
  16. forgecli/courier_hd_data.py +19 -0
  17. forgecli/ghlogin.py +76 -0
  18. forgecli/github.py +54 -0
  19. forgecli/guards.py +403 -0
  20. forgecli/hooks.py +50 -0
  21. forgecli/httpapi.py +434 -0
  22. forgecli/images.py +110 -0
  23. forgecli/keys.py +152 -0
  24. forgecli/keyvault.py +320 -0
  25. forgecli/mcp.py +674 -0
  26. forgecli/memory.py +42 -0
  27. forgecli/openapi.py +331 -0
  28. forgecli/parallel.py +308 -0
  29. forgecli/prices.py +72 -0
  30. forgecli/procs.py +144 -0
  31. forgecli/providers.py +758 -0
  32. forgecli/quality.py +192 -0
  33. forgecli/repomap.py +78 -0
  34. forgecli/roster.py +227 -0
  35. forgecli/safety.py +93 -0
  36. forgecli/sandbox.py +83 -0
  37. forgecli/sessions.py +97 -0
  38. forgecli/skills.py +446 -0
  39. forgecli/tools.py +1184 -0
  40. forgecli/ui.py +860 -0
  41. forgecli/worktrees.py +79 -0
  42. forgecommandline-0.8.0.data/data/skills/commit/SKILL.md +14 -0
  43. forgecommandline-0.8.0.data/data/skills/debug/SKILL.md +17 -0
  44. forgecommandline-0.8.0.data/data/skills/explain/SKILL.md +14 -0
  45. forgecommandline-0.8.0.data/data/skills/init/SKILL.md +19 -0
  46. forgecommandline-0.8.0.data/data/skills/library/LICENSES/agent-skills-MIT.txt +21 -0
  47. forgecommandline-0.8.0.data/data/skills/library/LICENSES/wondelai-MIT.txt +23 -0
  48. forgecommandline-0.8.0.data/data/skills/library/README.md +9 -0
  49. forgecommandline-0.8.0.data/data/skills/library/_references/accessibility-checklist.md +160 -0
  50. forgecommandline-0.8.0.data/data/skills/library/_references/definition-of-done.md +67 -0
  51. forgecommandline-0.8.0.data/data/skills/library/_references/observability-checklist.md +92 -0
  52. forgecommandline-0.8.0.data/data/skills/library/_references/orchestration-patterns.md +370 -0
  53. forgecommandline-0.8.0.data/data/skills/library/_references/performance-checklist.md +238 -0
  54. forgecommandline-0.8.0.data/data/skills/library/_references/security-checklist.md +248 -0
  55. forgecommandline-0.8.0.data/data/skills/library/_references/testing-patterns.md +235 -0
  56. forgecommandline-0.8.0.data/data/skills/library/api-and-interface-design/SKILL.md +367 -0
  57. forgecommandline-0.8.0.data/data/skills/library/architecture-optimization/SKILL.md +279 -0
  58. forgecommandline-0.8.0.data/data/skills/library/architecture-optimization/references/artifact-templates.md +157 -0
  59. forgecommandline-0.8.0.data/data/skills/library/architecture-optimization/references/methods.md +87 -0
  60. forgecommandline-0.8.0.data/data/skills/library/awwwards-tier-web-application/SKILL.md +877 -0
  61. forgecommandline-0.8.0.data/data/skills/library/browser-testing-with-devtools/SKILL.md +317 -0
  62. forgecommandline-0.8.0.data/data/skills/library/ci-cd-and-automation/SKILL.md +390 -0
  63. forgecommandline-0.8.0.data/data/skills/library/code-review-and-quality/SKILL.md +398 -0
  64. forgecommandline-0.8.0.data/data/skills/library/code-simplification/SKILL.md +331 -0
  65. forgecommandline-0.8.0.data/data/skills/library/constraint-driven-development/SKILL.md +311 -0
  66. forgecommandline-0.8.0.data/data/skills/library/constraint-driven-development/references/floor-guard.md +182 -0
  67. forgecommandline-0.8.0.data/data/skills/library/context-engineering/SKILL.md +353 -0
  68. forgecommandline-0.8.0.data/data/skills/library/debugging-and-error-recovery/SKILL.md +300 -0
  69. forgecommandline-0.8.0.data/data/skills/library/deprecation-and-migration/SKILL.md +247 -0
  70. forgecommandline-0.8.0.data/data/skills/library/documentation-and-adrs/SKILL.md +297 -0
  71. forgecommandline-0.8.0.data/data/skills/library/doubt-driven-development/SKILL.md +243 -0
  72. forgecommandline-0.8.0.data/data/skills/library/frontend-ui-engineering/SKILL.md +340 -0
  73. forgecommandline-0.8.0.data/data/skills/library/git-workflow-and-versioning/SKILL.md +355 -0
  74. forgecommandline-0.8.0.data/data/skills/library/idea-refine/SKILL.md +193 -0
  75. forgecommandline-0.8.0.data/data/skills/library/idea-refine/examples.md +238 -0
  76. forgecommandline-0.8.0.data/data/skills/library/idea-refine/frameworks.md +99 -0
  77. forgecommandline-0.8.0.data/data/skills/library/idea-refine/refinement-criteria.md +113 -0
  78. forgecommandline-0.8.0.data/data/skills/library/idea-refine/scripts/idea-refine.sh +15 -0
  79. forgecommandline-0.8.0.data/data/skills/library/improve-code-quality/SKILL.md +275 -0
  80. forgecommandline-0.8.0.data/data/skills/library/improve-code-quality/references/artifact-templates.md +101 -0
  81. forgecommandline-0.8.0.data/data/skills/library/incremental-implementation/SKILL.md +249 -0
  82. forgecommandline-0.8.0.data/data/skills/library/interview-me/SKILL.md +235 -0
  83. forgecommandline-0.8.0.data/data/skills/library/observability-and-instrumentation/SKILL.md +238 -0
  84. forgecommandline-0.8.0.data/data/skills/library/performance-optimization/SKILL.md +267 -0
  85. forgecommandline-0.8.0.data/data/skills/library/performance-optimization/references/optimization-patterns.md +250 -0
  86. forgecommandline-0.8.0.data/data/skills/library/planning-and-task-breakdown/SKILL.md +257 -0
  87. forgecommandline-0.8.0.data/data/skills/library/remove-technical-debt/SKILL.md +203 -0
  88. forgecommandline-0.8.0.data/data/skills/library/remove-technical-debt/references/artifact-templates.md +79 -0
  89. forgecommandline-0.8.0.data/data/skills/library/security-and-hardening/SKILL.md +216 -0
  90. forgecommandline-0.8.0.data/data/skills/library/security-and-hardening/references/hardening-patterns.md +324 -0
  91. forgecommandline-0.8.0.data/data/skills/library/shipping-and-launch/SKILL.md +336 -0
  92. forgecommandline-0.8.0.data/data/skills/library/source-driven-development/SKILL.md +216 -0
  93. forgecommandline-0.8.0.data/data/skills/library/spec-driven-development/SKILL.md +259 -0
  94. forgecommandline-0.8.0.data/data/skills/library/system-design/SKILL.md +207 -0
  95. forgecommandline-0.8.0.data/data/skills/library/system-design/references/building-blocks.md +272 -0
  96. forgecommandline-0.8.0.data/data/skills/library/system-design/references/common-designs.md +257 -0
  97. forgecommandline-0.8.0.data/data/skills/library/system-design/references/database-scaling.md +295 -0
  98. forgecommandline-0.8.0.data/data/skills/library/system-design/references/estimation-numbers.md +250 -0
  99. forgecommandline-0.8.0.data/data/skills/library/system-design/references/four-step-process.md +286 -0
  100. forgecommandline-0.8.0.data/data/skills/library/system-design/references/reliability-operations.md +373 -0
  101. forgecommandline-0.8.0.data/data/skills/library/test-driven-development/SKILL.md +398 -0
  102. forgecommandline-0.8.0.data/data/skills/library/using-agent-skills/SKILL.md +192 -0
  103. forgecommandline-0.8.0.data/data/skills/review/SKILL.md +16 -0
  104. forgecommandline-0.8.0.data/data/skills/run/SKILL.md +17 -0
  105. forgecommandline-0.8.0.data/data/skills/security-review/SKILL.md +20 -0
  106. forgecommandline-0.8.0.data/data/skills/simplify/SKILL.md +18 -0
  107. forgecommandline-0.8.0.data/data/skills/test/SKILL.md +16 -0
  108. forgecommandline-0.8.0.data/data/skills/web-build/SKILL.md +25 -0
  109. forgecommandline-0.8.0.dist-info/METADATA +357 -0
  110. forgecommandline-0.8.0.dist-info/RECORD +113 -0
  111. forgecommandline-0.8.0.dist-info/WHEEL +5 -0
  112. forgecommandline-0.8.0.dist-info/entry_points.txt +2 -0
  113. forgecommandline-0.8.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,157 @@
1
+ # architecture-optimization artifact templates
2
+
3
+ Skeletons for every docs/ file this journey writes. Read the file before writing: if it is missing, create it from the full skeleton below (all section headings), then fill only the sections your phase names; if it exists, extend it — add or update your sections and preserve everyone else's. A journey that starts in a project with no `docs/` folder creates several of these from scratch, which is the normal case for this skill.
4
+
5
+ ## Tracker: docs/ARCHITECTURE-OPTIMIZATION-PLAN.md
6
+
7
+ Created on the first run (Intake). Never shared with another journey.
8
+
9
+ ```markdown
10
+ # Architecture Optimization Plan
11
+
12
+ ## Context
13
+ Intake answers, date started, hot paths in scope.
14
+ Mode: skills-installed | fallback (Briefs + references/methods.md) — set at the first phase, so a
15
+ resumed session knows whether earlier artifacts are skill-grade or Brief-grade.
16
+
17
+ ## Phase Status
18
+ | Phase | Skill | Status | Artifact | Date |
19
+ |---|---|---|---|---|
20
+ | 1 | working-with-legacy-code | pending | TESTING.md, TECH-DEBT.md, PERFORMANCE.md | |
21
+ | 2 | clean-architecture | pending | ARCHITECTURE.md | |
22
+ | 3 | software-design-philosophy | pending | TECH-DEBT.md | |
23
+ | 4 | refactoring-patterns | pending | TECH-DEBT.md, TESTING.md | |
24
+ | 5 | system-design | pending | PERFORMANCE.md, ARCHITECTURE.md | |
25
+ | 6 | ddia-systems | pending | ARCHITECTURE.md, PERFORMANCE.md | |
26
+ | 7 | release-it | pending | RELIABILITY.md | |
27
+ | 8 | pragmatic-programmer | pending | PERFORMANCE.md, TECH-DEBT.md, TESTING.md | |
28
+ Statuses: pending · in-progress · awaiting-evidence · done · deferred: <reason> · skipped: <reason>
29
+ A phase parked at `awaiting-evidence` carries a Next Actions row naming the evidence owed, its owner,
30
+ and the date — otherwise the next session cannot tell what it is waiting for.
31
+
32
+ ## Key Decisions
33
+ | Date | Phase | Decision | Rationale |
34
+ |---|---|---|---|
35
+
36
+ ## Next Actions
37
+ - [ ] action (owner, due)
38
+ ```
39
+
40
+ ## docs/PERFORMANCE.md
41
+
42
+ Measured performance state — baselines, budgets, findings, and the before/after ledger. Creates: architecture-optimization.
43
+
44
+ ```markdown
45
+ # Performance
46
+
47
+ ## Baselines & Budgets
48
+ | Metric (p50/p95, throughput, cost) | Baseline (date) | Budget | Gate |
49
+ |---|---|---|---|
50
+
51
+ ## Load Reality
52
+ Measured QPS average/peak, data volumes, growth rate. This is the single source for load numbers —
53
+ ARCHITECTURE.md `## System Context` cites it rather than repeating them.
54
+
55
+ ## Profile Findings
56
+ | Hotspot | Evidence (profiler/APM) | Suspected cause | Fix | Status |
57
+ |---|---|---|---|---|
58
+
59
+ ## Optimization Ledger
60
+ | Change | Before | After | Verdict (keep/revert) | Date |
61
+ |---|---|---|---|---|
62
+ ```
63
+
64
+ ## docs/TESTING.md
65
+
66
+ The safety net — what behavior is pinned, where the gaps are.
67
+
68
+ ```markdown
69
+ # Testing
70
+
71
+ ## Test Strategy
72
+ Pyramid, tooling, what "green" gates.
73
+
74
+ ## Safety Net Map
75
+ | Module | Pinned behaviors | Test files | Gaps |
76
+ |---|---|---|---|
77
+
78
+ ## Characterization Backlog
79
+ - [ ] module (risk, priority)
80
+
81
+ ## CI Gates
82
+ ```
83
+
84
+ ## docs/TECH-DEBT.md
85
+
86
+ The debt ledger — single queue for all code journeys.
87
+
88
+ ```markdown
89
+ # Technical Debt
90
+
91
+ ## Debt Ledger
92
+ | Item | Location | Type | Risk | Effort | Priority | Status |
93
+ |---|---|---|---|---|---|---|
94
+
95
+ ## Smell Inventory
96
+ | Smell | Location | Refactoring | Status |
97
+ |---|---|---|---|
98
+
99
+ ## Sprout / Wrap Register
100
+ Code added beside legacy (to fold back in later).
101
+
102
+ ## Debt Budget & Broken-Windows Policy
103
+ Time per iteration; what gets fixed now vs boarded up with a ticket.
104
+
105
+ ## Adopted Conventions
106
+ ```
107
+
108
+ ## docs/ARCHITECTURE.md
109
+
110
+ System structure and decisions — includes domain model and data decisions (no separate DATA.md or DOMAIN.md).
111
+
112
+ ```markdown
113
+ # Architecture
114
+
115
+ ## System Context
116
+ What the system does, key integrations, load reality (cite PERFORMANCE.md `## Load Reality`).
117
+
118
+ ## Layer Map & Dependency Rule
119
+ Layers, what depends on what, current violations.
120
+ | Violation | Location | Fix | Status |
121
+ |---|---|---|---|
122
+
123
+ ## Bounded Contexts & Context Map
124
+ Contexts, relationships, anti-corruption layers.
125
+
126
+ ## Domain Glossary (Ubiquitous Language)
127
+ | Term | Meaning | Code name |
128
+ |---|---|---|
129
+
130
+ ## Data & Storage Decisions
131
+ Data models, storage engines, isolation levels, replication, system-of-record vs derived data.
132
+
133
+ ## Decision Log
134
+ | Date | Decision | Why | Alternatives rejected |
135
+ |---|---|---|---|
136
+ ```
137
+
138
+ ## docs/RELIABILITY.md
139
+
140
+ Production hardening status.
141
+
142
+ ```markdown
143
+ # Reliability
144
+
145
+ ## Integration-Point Audit
146
+ | Dependency | Timeout | Circuit breaker | Bulkhead | Retry policy | Status |
147
+ |---|---|---|---|---|---|
148
+
149
+ ## Query & Resource Findings
150
+ Unbounded result sets, missing LIMITs/pagination, blocked threads.
151
+
152
+ ## Health Checks & Metrics
153
+ Deep health checks · RED metrics · symptom-based alerts.
154
+
155
+ ## Deploy vs Release
156
+ Feature flags, expand-contract migrations, rollback plan.
157
+ ```
@@ -0,0 +1,87 @@
1
+ # architecture-optimization phase methods
2
+
3
+ The full fallback method for each phase — read the relevant section before running a phase from its Brief (constituent skill not installed). Each section distills the constituent skill plus the named external sources into a runnable procedure. When the constituent skill *is* installed, use it; this file then serves only as the cross-phase glue (formulas, orderings, heuristics).
4
+
5
+ ## §1 Pin it and measure it (Working Effectively with Legacy Code — Feathers; Systems Performance — Gregg)
6
+
7
+ **Behavior net:**
8
+
9
+ 1. **Identify change points.** For each hot flow, list the methods that will change in Phases 2-6. Sketch effects outward from each: what state and outputs does it influence?
10
+ 2. **Break dependencies at seams.** Least-invasive first: Parameterize Constructor (inject the dependency, keep a production-default constructor), Extract Interface for the collaborator, Extract and Override for one buried call. The goal is getting the class into a test harness with minimal edits.
11
+ 3. **Write characterization tests.** Photograph actual behavior: call with representative inputs, assert something deliberately wrong, read the failure, pin the real value. Cover the money behaviors first (billing, auth, the core action). A bug discovered here gets pinned as-is and ledgered — callers may depend on the quirk.
12
+ 4. **When full coverage isn't feasible in time,** Sprout (new code in new tested methods/classes called from the legacy host) or Wrap (new behavior around the old call), and track the untested host in the Debt Ledger.
13
+
14
+ **Performance net:**
15
+
16
+ 5. **Profile before touching anything.** CPU profiler or APM trace on the real workload — the bottleneck is rarely where intuition points, and the profile is the only arbiter. Capture: p50/p95/p99 latency per hot endpoint, throughput, error rate; query time share; external-call time share; allocation/GC pressure where relevant.
17
+ 6. **Measure under realistic data.** Dev databases with 100 rows lie about queries that scan millions. Use a production-like snapshot or synthetic volume; record the volume with the baseline.
18
+ 7. **Run the USE method (Gregg) per resource** — for CPU, memory, disk I/O, network, and every bounded pool (DB connections, thread pools, worker queues): Utilization (how busy), Saturation (queue depth, wait time), Errors. Saturated pools produce latency cliffs that look like application slowness.
19
+ 8. **Set budgets.** Per hot flow: the number it must meet (e.g. p95 < 500ms). State the budget at the load you can actually observe — an APM only sees current traffic, so a "at 2× peak" budget requires a load-test tool; without one, budget at current peak and note the headroom question as unanswered. Budgets make "done" objective, gate Phase 8's CI gates, and stop optimization past the point of payoff.
20
+ 9. **Fix the tool of record.** Same profiler/APM/load-test configuration for every before/after in the ledger — mixed tools make deltas meaningless.
21
+
22
+ ## §2 Re-draw the boundaries (Clean Architecture — Martin)
23
+
24
+ 1. **Map the real dependency graph.** Imports, not intentions: which modules name the framework, the ORM, vendor SDKs? Tooling helps (dependency-cruiser, import-linter, jdeps, go list), but a grep for framework imports inside business logic finds most of it.
25
+ 2. **List violations against the Dependency Rule.** Inward only: Frameworks → Interface Adapters → Use Cases → Entities. A violation = an inner circle naming an outer one (a use case importing the ORM entity, a domain rule reading the HTTP request).
26
+ 3. **Extract by Dependency Inversion, hot paths first.** The use case owns a repository/gateway interface; the Postgres/Stripe/S3 implementation moves to an outer adapter. Do it seam by seam under the Phase 1 tests — never a big-bang re-layering.
27
+ 4. **Boundary only at volatility.** Full interfaces at the DB, external services, and delivery mechanism; collapse ceremony layers elsewhere. A boundary is justified when you can name the second implementation you'd plausibly swap in (test double counts).
28
+ 5. **Why this phase precedes optimization:** a boundary is an insertion point. Cache-aside goes inside the repository adapter; a queue goes behind the gateway interface; neither requires touching business rules — but only if the interface exists.
29
+ 6. **Record every boundary decision** in the Decision Log with alternatives rejected — boundary placement is the expensive-to-reverse class of decision.
30
+
31
+ ## §3 Deepen the modules (A Philosophy of Software Design — Ousterhout)
32
+
33
+ 1. **Score depth.** For each module on the hot paths: functionality ÷ interface complexity. Deep = small interface hiding real machinery. Shallow = interface as large as the implementation (a class whose methods each wrap one call; a "manager" that forwards).
34
+ 2. **Find the three red flags:** shallow classes/pass-throughs (same abstraction on both sides of a call); information leakage (one design decision — a format, a protocol, a naming rule — reflected in multiple modules, so one change touches many files); temporal decomposition (module structure mirrors execution order — `Step1Reader`, `Step2Validator` — instead of knowledge).
35
+ 3. **Consolidate.** Merge shallow classes that always travel together and share state; pull the leaked decision into one owner module; convert pass-through layers into direct calls. Guard: don't merge genuinely unrelated concerns just to cut file count — depth, not size, is the goal.
36
+ 4. **Somewhat-general-purpose interfaces:** design module interfaces for the class of use, not today's single caller — that is what keeps them small while functionality grows.
37
+ 5. **Strategic over tactical:** budget 10-20% of the pass for design investment. The payoff inside this journey is immediate — Phases 4-6 touch fewer files.
38
+
39
+ ## §4 Refactor the hot paths (Refactoring — Fowler; Clean Code — Martin)
40
+
41
+ 1. **Name the smell, cite the transformation.** Long Method → Extract Method (if a block needs a comment, extract it and name it after the comment). Nested conditionals → Replace Nested Conditional with Guard Clauses. Type switches → Replace Conditional with Polymorphism. Data clumps → Introduce Parameter Object. Magic numbers → Symbolic Constant. Repeated computation of an expression → Replace Temp with Query.
42
+ 2. **The mechanical loop:** tests green → one named transformation in small steps → tests green → commit. A red test mid-refactoring means revert and retry smaller, never debug forward. Structure-only commits carry no behavior change.
43
+ 3. **Clean-code fold-in while passing:** names reveal intent (`elapsedDays`, not `d`); functions do one thing at one level of abstraction, 0-2 arguments (a boolean flag argument is two functions); Command-Query Separation; no null returns (empty collection, Optional, Null Object); every thrown error carries operation + state context; catch specific exception types.
44
+ 4. **Preparatory Refactoring:** for each planned Phase 5-6 optimization, first reshape the insertion point so the optimization becomes a small diff ("make the change easy, then make the easy change") — the reshape commit and the optimization commit stay separate.
45
+ 5. **Rule of Three:** tolerate duplication twice; abstract on the third occurrence — premature abstraction on hot paths is how frameworks-within-frameworks start.
46
+
47
+ ## §5 Attack the bottleneck (System Design — Xu; Amdahl; Little's law)
48
+
49
+ 1. **Amdahl's law picks the target.** Speedup_total = 1 / ((1 − p) + p/s), where p is the fraction of time in the optimized part and s its local speedup. Optimizing 5% of the request 10× yields 1.047× overall. Only profile-dominant parts are worth effort — rank Phase 1 hotspots by p.
50
+ 2. **Confirm the gap with numbers.** Measured load always supersedes the estimate — if intake or APM gave you real QPS, use it and keep the formula only for growth projection. Estimating from scratch: QPS = DAU × actions/day ÷ 86,400; peak 2-5× average; storage = records/day × size × retention. Compare measured load and budget: sometimes the honest finding is "no gap — stop here."
51
+ 3. **The cheapest-first order:**
52
+ 1. **Algorithm & I/O shape:** O(n²) loops on growing data, per-item external calls in a loop (batch them), serial awaits that could be parallel, oversized payloads. Free — no new infrastructure.
53
+ 2. **Concurrency and pool sizing:** Little's law (L = λW) gives the in-flight work the fleet must hold — 60 QPS × 4.2s = 252 concurrent requests, which a 32-thread server cannot hold, so requests queue and p95 inflates far beyond service time. Size worker threads, DB connections, and queue depth to L, or cut W; a saturated pool is often the single largest p95 contributor and it is free to diagnose. Beware: once a pool saturates, trace percentages include queue wait, so re-profile after fixing it before trusting the Amdahl split (§1.7).
54
+ 3. **Vertical headroom:** one instance-size bump often buys a year; note the ceiling and cost.
55
+ 4. **Cache-aside** on read-heavy paths: check cache → miss → load → populate, TTL plus explicit invalidation on the write path (name what event invalidates which key — an unnameable invalidation means don't cache it). Measure hit rate; below ~80% on a hot path, re-examine the key design. A cold or thrashing cache is pure overhead. Guard the stampede: on a hot key, expiry lets every concurrent request recompute at once (at 60 QPS and a 4s recompute, ~250 duplicate computations) — use single-flight/request coalescing or a short lock, stagger TTLs with jitter, and cache negative results so misses don't hammer the origin.
56
+ 5. **Queue slow work off the request path:** email, exports, webhooks, image processing. Little's law (L = λW): in-flight requests = arrival rate × latency — halving in-request latency also halves the concurrency the fleet must hold, so queueing is a capacity fix as much as a latency fix. Design for at-least-once delivery + idempotent consumers.
57
+ 6. **Read replicas** when reads dominate and the primary saturates; brings replication lag → §6's read-your-writes decisions.
58
+ 7. **Shard last,** only with evidence (write-side saturation that vertical + replicas can't absorb), by a key that spreads load and matches the dominant query.
59
+ 4. **Re-measure after every move** with the tool of record; ledger before/after; keep only what beats its baseline. Also write down what you're deliberately NOT building (multi-region, CDN, shards) with the number that would trigger revisiting.
60
+
61
+ ## §6 Fix the data layer (Designing Data-Intensive Applications — Kleppmann)
62
+
63
+ 1. **Get a query-level source, then read plans.** If none exists, enable one first: `pg_stat_statements` (ranks by total time — the right ranking), `auto_explain`, or `log_min_duration_statement`. Then `EXPLAIN (ANALYZE, BUFFERS)` the top offenders — plain `EXPLAIN` returns planner estimates, not real timings, so it cannot produce the measured before/after the ledger requires. The plan, not the ORM code, tells the truth. Look for: sequential scans on large tables where an index on predicate + sort columns fits; N+1 patterns (one query per row of a parent result — batch with IN, JOIN, or the ORM's eager loading); SELECT * pulling wide rows into memory; deep OFFSET pagination (switch to keyset: WHERE id > last_seen ORDER BY id LIMIT n); unbounded result sets (every list endpoint gets LIMIT + pagination).
64
+ 2. **Weigh every index:** it speeds the read paths that match it and taxes every write; drop unused indexes found in the stats views. Composite column order decides whether an index is used at all: equality predicates first, then the range or sort column — an index on `(status, created_at)` serves `WHERE status = ? ORDER BY created_at`, while `(created_at, status)` does not.
65
+ 3. **Know your engine:** LSM-trees (Cassandra, RocksDB, LevelDB) favor write throughput; B-trees (Postgres, MySQL/InnoDB) favor read latency and transactional semantics. Match the model to the access pattern — relational for many-to-many and ad-hoc queries, document for self-contained aggregates read whole, graph for recursive traversals — before buying hardware.
66
+ 4. **Audit isolation honestly.** Find the actual default (Postgres: read committed; MySQL/InnoDB: repeatable read snapshot; most cloud SQL: not serializable). Then list read-then-write paths — check availability then decrement, read balance then update — and fix write skew explicitly: `SELECT ... FOR UPDATE`, a unique/check constraint, or a serializable transaction. Write skew passes every single-user test; only concurrency exposes it.
67
+ 5. **Replication-lag consequences (with §5 replicas):** read-your-writes (a user must see their own write — route their reads to the primary briefly), monotonic reads (pin a session to one replica). Decide per flow, deliberately.
68
+ 6. **Derived data over dual writes.** A second read pattern (search index, analytics store, feed) is fed by CDC or an event log from the system of record — never by the application writing to two stores, which drifts on the first failure. Derived stores must be rebuildable from the source.
69
+
70
+ ## §7 Keep it fast under failure (Release It! — Nygard)
71
+
72
+ 1. **Audit every integration point** — DB, HTTP APIs, queues, caches, DNS, SMTP. For each: connect timeout, read timeout, breaker, bulkhead, retry policy, degradation path. An outbound call with no read timeout can hang a thread forever; enough of them hang the fleet — with nothing in the error logs.
73
+ 2. **Derive timeouts from the flow budget:** if checkout owes 500ms and the payment call is one of two sequential dependencies, its read timeout is ~200-250ms, not the library default of 30s. A timeout is a latency budget enforced.
74
+ 3. **Circuit breaker on critical dependencies:** closed → open after a failure threshold (count or rate) → fail fast while open → half-open probe → close on success. Failing fast returns in microseconds what a dying dependency would hold for seconds.
75
+ 4. **Bulkheads:** dedicated connection/thread pools per critical dependency, so a slow vendor drains its own pool, not the shared one.
76
+ 5. **Retry with exponential backoff + jitter,** capped attempts, only on idempotent operations — synchronized naive retries are a self-inflicted DDoS timed exactly to the dependency's worst moment.
77
+ 6. **Steady state:** anything that accumulates (logs, temp files, sessions, cache entries, audit rows) gets a purge policy sized to survive between deploys.
78
+ 7. **Make budgets operational:** RED metrics (Rate, Errors, Duration) per endpoint; deep health checks that touch real dependencies; alerts on symptoms the user feels (p95 over budget, error rate) rather than causes (CPU%). This is what turns Phase 1's snapshot into a permanent guardrail.
79
+
80
+ ## §8 Lock in budgets and habits (The Pragmatic Programmer — Hunt & Thomas)
81
+
82
+ 1. **CI perf gates.** Per hot path, the cheapest reliable check: a query-count assertion (fails when an N+1 regresses — cheap and deterministic), a micro-benchmark with a threshold, or a small load test in a nightly job with the p95 budget as the pass line. A budget without a gate decays into a wish.
83
+ 2. **DRY for knowledge, not text.** The same business rule in two places (client and server validation, two services computing the same price) will drift; the same query issued from two layers doubles load and forks the fix. De-duplicate knowledge; leave coincidental look-alikes alone.
84
+ 3. **Orthogonality check:** a dramatic change to one requirement (swap payment provider, change cache) should touch one module. Where it wouldn't, the Phase 2 interface is leaking — ledger it.
85
+ 4. **Broken windows:** the first tolerated hack invites the second. Policy: fix now, or board it up with a tracked ticket — an untracked `// TODO: temporary` is a defect. Agree the debt budget per iteration (a fixed share of capacity) so paydown is routine, not an event.
86
+ 5. **Reversibility:** every vendor and infrastructure choice behind an owned interface (the forking-road test: could you swap the DB, cache, or LLM provider in a week?). This is what keeps the *next* optimization cycle cheap.
87
+ 6. **Write the conventions down** in TECH-DEBT.md Adopted Conventions — naming, where behavior lives, query rules (no queries outside repositories), the gate list — so the standard survives the people who set it.