@cassiomc1/forgeloop 0.1.0
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.
- package/.cursor/rules/project-loop.mdc +18 -0
- package/.forgeloop/.gitignore +2 -0
- package/.github/copilot-instructions.md +16 -0
- package/AGENTS.md +16 -0
- package/AGENT_COMPATIBILITY.md +147 -0
- package/CLAUDE.md +14 -0
- package/CONTRACT_COVERAGE.md +27 -0
- package/DELEGATION_PROTOCOL.md +91 -0
- package/ENG/accessibility-eng.md +155 -0
- package/ENG/clean-code-eng.md +223 -0
- package/ENG/design-code-eng.md +511 -0
- package/ENG/games-code-design-web-eng.md +751 -0
- package/ENG/perf-code-eng.md +441 -0
- package/ENG/premium-sites-studio-eng.md +320 -0
- package/ENG/sec-code-eng.md +706 -0
- package/ENG/test-code-eng.md +257 -0
- package/EXECUTION_STATE.md +107 -0
- package/GUIDE_ROUTER.md +274 -0
- package/LICENSE +21 -0
- package/LICENSE-DOCS.md +13 -0
- package/LOOP_ENGINEERING.md +551 -0
- package/LOOP_SYSTEM_DESIGN.md +394 -0
- package/ORCHESTRATOR_INTEGRATION.md +106 -0
- package/PROJECT_PROFILE.md +124 -0
- package/QUALITY_SCORECARD.md +54 -0
- package/README.md +492 -0
- package/TERMINOLOGY.md +21 -0
- package/THIRD_PARTY_NOTICES.md +129 -0
- package/THREAT_MODEL.md +35 -0
- package/package.json +51 -0
- package/schemas/delegated-result.schema.json +33 -0
- package/schemas/evidence.schema.json +15 -0
- package/schemas/execution-receipt.schema.json +46 -0
- package/schemas/routing-input.schema.json +17 -0
- package/schemas/routing-result.schema.json +17 -0
- package/schemas/task-brief.schema.json +24 -0
- package/schemas/work-state.schema.json +46 -0
- package/src/cli.js +341 -0
- package/src/commands/clear-state.js +11 -0
- package/src/commands/doctor.js +165 -0
- package/src/commands/init.js +42 -0
- package/src/commands/inspect.js +17 -0
- package/src/commands/route.js +32 -0
- package/src/commands/status.js +29 -0
- package/src/commands/update.js +109 -0
- package/src/commands/validate-protocol.js +133 -0
- package/src/commands/validate-receipt.js +19 -0
- package/src/commands/validate-state.js +30 -0
- package/src/core/agent-support.js +89 -0
- package/src/core/conformance.js +133 -0
- package/src/core/delegation.js +283 -0
- package/src/core/evidence.js +56 -0
- package/src/core/filesystem.js +122 -0
- package/src/core/inspect.js +115 -0
- package/src/core/json-safety.js +54 -0
- package/src/core/manifest.js +75 -0
- package/src/core/protocol.js +81 -0
- package/src/core/receipt.js +129 -0
- package/src/core/repository.js +19 -0
- package/src/core/router.js +296 -0
- package/src/core/schema-validation.js +179 -0
- package/src/core/templates.js +56 -0
- package/src/core/work-state.js +471 -0
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: perf-code-eng
|
|
3
|
+
language: en
|
|
4
|
+
description: "Performance measurement, diagnosis, and improvement for web, mobile, desktop, APIs, and data."
|
|
5
|
+
version: "2026.09"
|
|
6
|
+
last-reviewed: "2026-08-10"
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# Performance Guide for Web, Mobile, Desktop, and Database Development
|
|
10
|
+
|
|
11
|
+
> Practical instructions for designing, measuring, diagnosing, and improving performance in web, mobile (iOS/Android), desktop (Windows/macOS), APIs, infrastructure, and databases. Use this document to guide AI agents and developers. Performance must be measured in real scenarios before and after the change — do not optimize based on assumptions.
|
|
12
|
+
> **Related documents**: for code structure and readability, see [`clean-code-eng.md`](./clean-code-eng.md). For functional, integration, and E2E testing, see [`test-code-eng.md`](./test-code-eng.md). For security and cache, secrets, and infrastructure trade-offs, see [`sec-code-eng.md`](./sec-code-eng.md). For perceived performance, UX, motion, and responsive design, see [`design-code-eng.md`](./design-code-eng.md). For HTML video preview and rendering performance, see [HyperFrames](https://hyperframes.heygen.com). This file is the canonical performance reference.
|
|
13
|
+
> **Tooling policy**: identify the stack, the stage, and the applicable checks; prefer an already available equivalent that produces compatible evidence. Ask for authorization before installing a tool or changing the environment. If no safe equivalent exists, record the required check as blocked and never claim that it passed. Do not install merely optional resources.
|
|
14
|
+
|
|
15
|
+
## General principles
|
|
16
|
+
|
|
17
|
+
- **Measure before optimizing**: reproduce the problem, record a baseline, find the bottleneck with profiling/telemetry, and only then change the code.
|
|
18
|
+
- **Define a performance budget** per product: startup time, API latency, bundle size, memory consumption, FPS, CPU, battery, and infrastructure cost.
|
|
19
|
+
- **Optimize the critical path**: prioritize what blocks the first render, the first interaction, the most-used operation, or the flow that has the greatest impact on the user.
|
|
20
|
+
- **Distribution metrics**: track median (p50), p75, p95, and p99. A healthy average can hide a minority of users with a very poor experience.
|
|
21
|
+
- **Perceived performance matters**: immediate feedback, skeleton/loading state, streaming, and progressive updates can improve the experience without masking a slow operation.
|
|
22
|
+
- **Do not block the main thread**: CPU work, I/O, parsing, serialization, and heavy processing should be asynchronous, parallelized, or moved to a worker/background when possible.
|
|
23
|
+
- **Less work is better than faster work**: eliminate unnecessary calls, renders, queries, allocations, payloads, and initializations before micro-optimizing an algorithm.
|
|
24
|
+
- **Avoid speculative optimization**: do not add cache, pooling, memoization, or complexity without evidence of a bottleneck and without measuring invalidation, memory, and maintenance cost.
|
|
25
|
+
- **Control concurrency and resources**: use timeouts, queue limits, backpressure, quotas, circuit breakers, and cancellation to prevent slowness from becoming resource exhaustion.
|
|
26
|
+
- **Performance must not break security**: do not disable TLS, authentication, validation, isolation, or security controls to gain speed. Consult [`sec-code-eng.md`](./sec-code-eng.md) before optimizing sensitive flows.
|
|
27
|
+
- **Record the reason for the optimization**: document the affected metric, the reproduced scenario, and the accepted trade-off; remove temporary instrumentation after the investigation.
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Mandatory diagnostic process
|
|
32
|
+
|
|
33
|
+
1. **Define the scenario**: platform, version, hardware, network, data volume, user scale, and affected flow.
|
|
34
|
+
2. **Reproduce in a production/release build**: development builds, hot reload, and excessive logs distort results.
|
|
35
|
+
3. **Collect a baseline**: record p50/p95/p99, CPU, memory, I/O, network, errors, throughput, and battery consumption when applicable.
|
|
36
|
+
4. **Locate the bottleneck**: use a profiler, traces, structured logs, metrics, and flame graphs. Do not conclude that the problem is CPU without measuring CPU.
|
|
37
|
+
5. **Make a small change**: change one main variable at a time to attribute causality to the result.
|
|
38
|
+
6. **Test load and regression**: validate the optimized path with the same data and compare it with the baseline; run the tests from [`test-code-eng.md`](./test-code-eng.md).
|
|
39
|
+
7. **Validate under real conditions**: modest devices, slow network, cold/warm cache, realistic volume, and realistic concurrency.
|
|
40
|
+
8. **Monitor after publishing**: compare production RUM/telemetry, define alerts, and revert if the result degrades other indicators.
|
|
41
|
+
|
|
42
|
+
### General tools
|
|
43
|
+
|
|
44
|
+
- **Profiling**: Chrome DevTools/Lighthouse, Node.js `--prof`/clinic.js, Python `cProfile`/py-spy, .NET dotnet-trace/dotnet-counters, Java JFR/async-profiler, Go pprof, Instruments (Apple), Windows Performance Analyzer.
|
|
45
|
+
- **Observability**: OpenTelemetry for traces/metrics/logs, Prometheus + Grafana, Application Insights, CloudWatch, Datadog, or equivalent.
|
|
46
|
+
- **Load**: k6, Locust, Gatling, JMeter, or an equivalent tool. Use gradual load and scenarios close to production.
|
|
47
|
+
- **Benchmarks**: compare versions with fixed data and environment; do not use an isolated synthetic benchmark as the only evidence.
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## Web — metrics and budget
|
|
52
|
+
|
|
53
|
+
### Core Web Vitals
|
|
54
|
+
|
|
55
|
+
Monitor lab data and real user data (RUM). To decide whether the experience meets Core Web Vitals, use first-party RUM or CrUX at the 75th percentile (p75) of page loads, segmented by mobile and desktop and by the relevant URL or URL group. As an initial reference, target the "good" thresholds recommended by web.dev:
|
|
56
|
+
|
|
57
|
+
- **LCP (Largest Contentful Paint)**: up to `2.5 s` — loading of the largest visible content.
|
|
58
|
+
- **INP (Interaction to Next Paint)**: up to `200ms` — interaction responsiveness.
|
|
59
|
+
- **CLS (Cumulative Layout Shift)**: up to `0.1` — visual stability.
|
|
60
|
+
- Also track **TTFB**, FCP, page weight, hydration time, and JavaScript errors.
|
|
61
|
+
|
|
62
|
+
Lighthouse is a lab diagnostic tool: reproduce and investigate issues in it, but do not treat it as proof of the real-user experience. RUM/CrUX at p75, with the segmentation above, is the evidence for deciding whether users' experience improved.
|
|
63
|
+
|
|
64
|
+
### Document delivery and network
|
|
65
|
+
|
|
66
|
+
- Use **HTTP/2 or HTTP/3**, modern TLS, and Brotli compression (or gzip as a fallback).
|
|
67
|
+
- Configure HTTP caching correctly (`Cache-Control`, `ETag`, `Last-Modified`) and use a CDN for static assets and cacheable content.
|
|
68
|
+
- Use asset name hashing (`app.[hash].js`) for long caching without serving old versions.
|
|
69
|
+
- Preload only critical resources from the initial path (critical font, LCP image); excessive preload competes for the same bandwidth.
|
|
70
|
+
- Use `preconnect` only for truly critical origins and `prefetch` for likely navigation, without wasting mobile data.
|
|
71
|
+
- Reduce TTFB with page/data cache, reused database connections, asynchronous processing, and an appropriate region choice.
|
|
72
|
+
- Stream HTML/data when the framework supports it and when it reduces time to useful content.
|
|
73
|
+
- Avoid network dependency chains: a critical resource should not depend on several sequential requests to appear.
|
|
74
|
+
|
|
75
|
+
### HTML, CSS, and images
|
|
76
|
+
|
|
77
|
+
- Deliver images in the required format and size: **AVIF/WebP**, appropriate compression, `srcset`, `sizes`, explicit dimensions, and `aspect-ratio`; do not assume these formats are compatible without a fallback.
|
|
78
|
+
- Prefer `<picture>` with `AVIF`/`WebP` in `<source>` and JPEG/PNG in the `<img>` fallback. Replace that markup with CDN format negotiation only after a support matrix proves that it honors `Accept`, returns the fallback, and varies caches correctly.
|
|
79
|
+
|
|
80
|
+
```html
|
|
81
|
+
<picture>
|
|
82
|
+
<source srcset="/image.avif" type="image/avif">
|
|
83
|
+
<source srcset="/image.webp" type="image/webp">
|
|
84
|
+
<img src="/image.jpg" alt="Image description" width="1200" height="800">
|
|
85
|
+
</picture>
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
- Do not use `loading="lazy"` on the LCP image; use priority loading for above-the-fold content and lazy loading for the rest.
|
|
89
|
+
- Avoid layout shift: reserve space for images, ads, embeds, and fonts before they load.
|
|
90
|
+
- Minify CSS, remove unused CSS, and avoid excessively complex selectors or selectors that force broad recalculation.
|
|
91
|
+
- Prefer `transform` and `opacity` animations; avoid animating `top`, `left`, `width`, `height`, or properties that cause layout on every frame.
|
|
92
|
+
- Load fonts with `font-display: swap`, limit variants/weights, and use a fallback with compatible metrics to reduce layout shift.
|
|
93
|
+
- Replace large GIFs with optimized video when there is continuous animation.
|
|
94
|
+
|
|
95
|
+
### JavaScript / TypeScript in the browser
|
|
96
|
+
|
|
97
|
+
- Split the bundle by route/component (`code splitting`) and load non-critical resources on demand.
|
|
98
|
+
- Remove unused dependencies and code; analyze the bundle with `source-map-explorer`, `webpack-bundle-analyzer`, or an equivalent.
|
|
99
|
+
- Use `defer`/`async` correctly; do not block the parser with non-critical scripts in the `<head>`.
|
|
100
|
+
- Break long tasks into smaller parts and yield to the main thread; avoid large synchronous loops during interaction.
|
|
101
|
+
- Use Web Workers for parsing, compression, calculations, and processing that do not need to access the DOM.
|
|
102
|
+
- Debounce/throttle high-frequency events (scroll, resize, input), using passive listeners when appropriate.
|
|
103
|
+
- Avoid unnecessary renders: keep state close to where it is used, virtualize long lists, use memoization only after measuring, and stabilize props/callbacks when the framework requires it.
|
|
104
|
+
- Do not create a request waterfall: load in parallel when there is independence, use data cache, and prefer streaming/pagination to huge payloads.
|
|
105
|
+
- In SSR/hydration, reduce the JavaScript sent to the client; consider islands, partial components, or Server Components when appropriate.
|
|
106
|
+
|
|
107
|
+
### React / Next.js
|
|
108
|
+
|
|
109
|
+
- Prefer Server Components/SSR for content that does not need client-side interactivity; mark only what is necessary as client.
|
|
110
|
+
- Use `next/image`, `next/font`, route prefetching judiciously, and appropriate data caching/revalidation.
|
|
111
|
+
- Avoid turning the entire layout into a Client Component for convenience.
|
|
112
|
+
- Virtualize long tables/lists and avoid putting global state that causes the entire application to rerender.
|
|
113
|
+
- Measure hydration cost and use React DevTools Profiler before applying `memo`, `useMemo`, or `useCallback` broadly.
|
|
114
|
+
|
|
115
|
+
### Vue / Nuxt / Angular
|
|
116
|
+
|
|
117
|
+
- Vue/Nuxt: use `defineAsyncComponent`, lazy routes, `v-once`/memoization when proven, and avoid broad watchers.
|
|
118
|
+
- Angular: use `OnPush`, `trackBy`/`track`, lazy routes, deferrable views, and avoid heavy work in templates/change detection.
|
|
119
|
+
- In both: keep bundles per route and measure hydration/rendering cost with DevTools and framework profiling.
|
|
120
|
+
|
|
121
|
+
### WebAssembly, PWA, and Web Workers
|
|
122
|
+
|
|
123
|
+
- Use WebAssembly only for work that is genuinely CPU-bound; the cost of downloading, compiling, and copying data can outweigh the gain.
|
|
124
|
+
- PWA: define a service worker caching strategy, avoid caching sensitive data or incompatible versions, and limit precache size.
|
|
125
|
+
- Service workers must fail safely and allow predictable updates; never leave users stuck on an old shell.
|
|
126
|
+
|
|
127
|
+
---
|
|
128
|
+
|
|
129
|
+
## Backend and web APIs
|
|
130
|
+
|
|
131
|
+
### Common rules
|
|
132
|
+
|
|
133
|
+
- Perform network and disk I/O asynchronously; configure connection, read, and full-operation timeouts.
|
|
134
|
+
- Reuse connections with pools sized based on measurement; a pool that is too large causes contention and brings down the database.
|
|
135
|
+
- Pagination is mandatory for collections; prefer cursor/keyset pagination for large volumes over deep `OFFSET`.
|
|
136
|
+
- Limit payloads, uploads, response size, and query complexity; use compression when the payload justifies it.
|
|
137
|
+
- Avoid N+1 queries with eager loading, batching, or DataLoader, but do not load entire relationships unnecessarily.
|
|
138
|
+
- Use cache with TTL, explicit invalidation, and hit/miss metrics; never rely on cache as the single source of truth.
|
|
139
|
+
- Use queues/background jobs for slow tasks (email, reports, video processing), with idempotency and retries with backoff.
|
|
140
|
+
- Apply graceful degradation: if recommendations, analytics, or a secondary service fails, the main path continues working.
|
|
141
|
+
- Instrument latency by endpoint, status code, payload size, external dependency, and query; averages alone are not sufficient.
|
|
142
|
+
|
|
143
|
+
### Node.js / JavaScript / TypeScript
|
|
144
|
+
|
|
145
|
+
- Do not block the event loop with heavy CPU work, `JSON.parse` of huge payloads, catastrophic regex, or synchronous compression; move work to Worker Threads/queues.
|
|
146
|
+
- Use streams for large files and payloads instead of loading everything into memory.
|
|
147
|
+
- Configure database connection pools and reusable HTTP clients; do not create a client per request.
|
|
148
|
+
- Use `autocannon`, `clinic.js`, `0x`, or Node Profiler to find event-loop lag and hot paths.
|
|
149
|
+
- Avoid expensive global middleware on routes that do not need it; limit serialization of objects and returned fields.
|
|
150
|
+
|
|
151
|
+
### Python
|
|
152
|
+
|
|
153
|
+
- Use `asyncio`/ASGI for concurrent I/O when the application and libraries are genuinely asynchronous; do not mix blocking calls into the event loop.
|
|
154
|
+
- Use workers/processes for CPU-bound work and appropriate pools for I/O; measure before choosing threads or processes.
|
|
155
|
+
- Prefer pagination, generators, and streaming to huge in-memory lists.
|
|
156
|
+
- Profile with `cProfile`, `py-spy`, or `scalene`; use `pytest-benchmark` to prevent regressions in critical functions.
|
|
157
|
+
- Django: use `select_related`/`prefetch_related`, template/data cache judiciously, and avoid queries inside loops.
|
|
158
|
+
- FastAPI: use lean response models, async endpoints only when the I/O is async, and limit size/concurrency.
|
|
159
|
+
|
|
160
|
+
### .NET / ASP.NET Core
|
|
161
|
+
|
|
162
|
+
- Use `async`/`await` end to end for I/O; do not use `.Result`/`.Wait()` in request code.
|
|
163
|
+
- Use `IHttpClientFactory`, connection pooling, `ArrayPool<T>`/`MemoryPool<T>` only after measuring allocations and GC pressure.
|
|
164
|
+
- Configure output/response caching, compression, and pagination; avoid serializing entire entities when smaller DTOs are sufficient.
|
|
165
|
+
- Use `dotnet-counters`, `dotnet-trace`, PerfView, or Application Insights for CPU, GC, allocations, and latency.
|
|
166
|
+
- Avoid allocating closures/objects in hot paths unnecessarily; do not trade clarity for premature micro-optimization.
|
|
167
|
+
|
|
168
|
+
### Java / Spring
|
|
169
|
+
|
|
170
|
+
- Use JFR, async-profiler, and Micrometer/Actuator metrics to locate CPU, GC, locks, and latency.
|
|
171
|
+
- Configure pools (HikariCP, threads, HTTP clients) based on measured load; do not increase threads as an automatic response to slowness.
|
|
172
|
+
- Use pagination and DTO/JPA projections to avoid loading unnecessary entities and relationships.
|
|
173
|
+
- Control the cost of the Spring context: lazy initialization can improve startup, but must be evaluated against first-request latency.
|
|
174
|
+
- Adjust GC/heap only after observing allocation, pauses, and memory pressure in a representative environment.
|
|
175
|
+
|
|
176
|
+
### Go
|
|
177
|
+
|
|
178
|
+
- Use `pprof`, stdlib benchmarks, tracing, and metrics for CPU, heap, goroutines, and blocking.
|
|
179
|
+
- Reuse buffers/connections carefully; `sync.Pool` is for high-frequency temporary objects, not for hiding leaks.
|
|
180
|
+
- Propagate `context.Context` with deadline/cancellation and do not create goroutines without a shutdown strategy.
|
|
181
|
+
- Use streaming and backpressure; limit goroutines and queue size to prevent an explosion under load.
|
|
182
|
+
|
|
183
|
+
---
|
|
184
|
+
|
|
185
|
+
## Database
|
|
186
|
+
|
|
187
|
+
### Relational principles (PostgreSQL, MySQL, SQL Server)
|
|
188
|
+
|
|
189
|
+
- Analyze real queries with `EXPLAIN`/`EXPLAIN ANALYZE` (or equivalent) and use representative data; never create an index by intuition alone.
|
|
190
|
+
- Keep statistics up to date (`ANALYZE`, auto-analyze/equivalent update) so the optimizer chooses realistic plans.
|
|
191
|
+
- Create indexes aligned with real queries (`WHERE`, `JOIN`, `ORDER BY`), considering selectivity and column order in composite indexes.
|
|
192
|
+
- Do not index everything: indexes speed up reads, but increase the cost of `INSERT`/`UPDATE`/`DELETE`, space, and maintenance.
|
|
193
|
+
- Avoid `SELECT *`; select only necessary columns and consider covering/index-only scans when proven.
|
|
194
|
+
- Avoid functions/casts on the filtered column when they prevent index usage; prefer sargable queries.
|
|
195
|
+
- Use short transactions, maintain a consistent lock acquisition order, and investigate lock contention/deadlocks.
|
|
196
|
+
- Batch independent operations; avoid thousands of individual round trips (N+1 in the database).
|
|
197
|
+
- Use a connection pool sized according to database capacity and workload; more connections do not mean more throughput.
|
|
198
|
+
- Use cursor/keyset pagination for large tables; high `OFFSET` forces the database to scan and discard many rows.
|
|
199
|
+
- Partition tables only when volume, retention, or query pattern justifies it; partitioning adds operational complexity.
|
|
200
|
+
- Perform vacuum/maintenance, statistics updates, backups, and restore tests according to the database; monitor growth, bloat, and space.
|
|
201
|
+
- For large schema changes, use migrations compatible with reads/writes during deployment (expand/contract) and avoid prolonged locks.
|
|
202
|
+
|
|
203
|
+
### PostgreSQL
|
|
204
|
+
|
|
205
|
+
- Use `EXPLAIN (ANALYZE, BUFFERS)` in a safe environment to compare the estimated plan with actual execution; remember that `ANALYZE` executes the operation.
|
|
206
|
+
- Monitor `pg_stat_statements`, cache hit ratio, locks, I/O, vacuum, and slow queries.
|
|
207
|
+
- Prefer partial/composite indexes when they match the real workload; confirm usage before keeping them.
|
|
208
|
+
- Use JSONB, full-text search, materialized views, and partitioning only when the access pattern justifies them, not as a substitute for proper modeling.
|
|
209
|
+
|
|
210
|
+
### MySQL / MariaDB
|
|
211
|
+
|
|
212
|
+
- Use `EXPLAIN`/`EXPLAIN ANALYZE`, Performance Schema, and the slow query log.
|
|
213
|
+
- Check the engine, composite indexes, cardinality, `JOIN`, and implicit type conversions.
|
|
214
|
+
- Configure pooling and transactions with attention to InnoDB isolation and locks; avoid keeping a transaction open during external calls.
|
|
215
|
+
|
|
216
|
+
### SQL Server
|
|
217
|
+
|
|
218
|
+
- Use Actual Execution Plan, Query Store, DMVs, and Extended Events to identify regressions, waits, and expensive queries.
|
|
219
|
+
- Evaluate missing/overlapping indexes, parameter sniffing, statistics, and regressive plans before changing the schema.
|
|
220
|
+
- Use pagination and projections; do not solve a slow query by increasing `MAXDOP` or memory without measuring the complete workload.
|
|
221
|
+
|
|
222
|
+
### NoSQL, cache, and search
|
|
223
|
+
|
|
224
|
+
- **Redis**: define TTL, limit value size, avoid O(N) commands in critical requests, monitor memory/eviction, and use pipelining when several operations are independent.
|
|
225
|
+
- **MongoDB**: model according to the access pattern, create indexes based on `explain()`, limit documents, and avoid unbounded arrays; use projection and pagination.
|
|
226
|
+
- **Elasticsearch/OpenSearch**: limit returned fields, use structured filters instead of text queries when possible, use search-after pagination for large sets, and monitor shards/heap.
|
|
227
|
+
- Cache is acceleration, not a primary database: define behavior when it is cold, unavailable, or inconsistent.
|
|
228
|
+
|
|
229
|
+
---
|
|
230
|
+
|
|
231
|
+
## Mobile — iOS and Android
|
|
232
|
+
|
|
233
|
+
### Common rules
|
|
234
|
+
|
|
235
|
+
- Measure on real modest and recent devices, in a Release build, with slow/unstable network and less-than-ideal battery.
|
|
236
|
+
- Define goals for cold/warm start, time to first interactive screen, scroll/transition smoothness, memory, energy consumption, and app size.
|
|
237
|
+
- Do not perform heavy work at startup: initialize only what is necessary to show the first screen and defer the rest until after the first frame/interaction.
|
|
238
|
+
- Avoid blocking the UI thread/main thread; move I/O, parsing, database work, and calculations to the background and update the UI safely.
|
|
239
|
+
- Load lists and images on demand, use pagination, limited cache, controlled prefetch, and placeholders with stable dimensions.
|
|
240
|
+
- Reduce network work: compact payloads, compression, HTTP cache, grouped requests, and request cancellation when the screen no longer exists.
|
|
241
|
+
- Monitor crash-free rate, ANR/hangs, jank, startup, memory/battery consumption, and API latency in production.
|
|
242
|
+
- Never use permanent verbose profiling/logs in Release; instrumentation must preserve privacy and follow [`sec-code-eng.md`](./sec-code-eng.md).
|
|
243
|
+
|
|
244
|
+
### iOS (Swift / SwiftUI / UIKit)
|
|
245
|
+
|
|
246
|
+
- Use **Instruments** (Time Profiler, Allocations, Leaks, Energy Log, Network) and Xcode/MetricKit production metrics.
|
|
247
|
+
- Use `async/await`, URLSession, and background operations; never block the main thread with I/O or processing.
|
|
248
|
+
- SwiftUI: keep `body` cheap, control view identity, avoid global state that causes broad recomputation, and use `LazyVStack`/`LazyHStack` for large lists.
|
|
249
|
+
- UIKit: reuse cells (`UICollectionView`/`UITableView`), pre-calculate layout when necessary, and avoid heavy work in `cellForItem`/main thread.
|
|
250
|
+
- Reduce image cost: use appropriate dimensions, downsample before displaying, use memory-limited caching, and efficient formats.
|
|
251
|
+
- Use BackgroundTasks for deferrable work and respect the system's execution/energy limits.
|
|
252
|
+
- Control Auto Layout: avoid unnecessarily deep hierarchies and layout loops; measure with Instruments before restructuring.
|
|
253
|
+
- Use `os_signpost`/signposts to measure critical phases without leaving permanent prints in the app.
|
|
254
|
+
|
|
255
|
+
### Android (Kotlin / Jetpack Compose / Views)
|
|
256
|
+
|
|
257
|
+
- Use Android Studio Profiler, **Macrobenchmark**, **Microbenchmark**, JankStats, Perfetto, and Baseline Profiles.
|
|
258
|
+
- Use Baseline Profiles and Startup Profiles when applicable; validate gains on representative devices.
|
|
259
|
+
- Defer initialization of nonessential SDKs; use App Startup/on-demand initialization instead of initializing everything in the first frame.
|
|
260
|
+
- Kotlin: use appropriate coroutines/Dispatchers, lifecycle-bound cancellation, and no blocking I/O on the Main dispatcher.
|
|
261
|
+
- Jetpack Compose: minimize recompositions, keep state at the correct level, use `remember` judiciously, use `LazyColumn` for lists, and avoid heavy work inside composables.
|
|
262
|
+
- Views: reuse `RecyclerView`/ViewHolder, avoid deep hierarchies, and use `ConstraintLayout`/simple layouts with real measurement.
|
|
263
|
+
- Use WorkManager for guaranteed/deferrable work; respect Doze, background limits, and battery consumption.
|
|
264
|
+
- Reduce APK/AAB with R8/resource shrinking, use WebP/vector when appropriate, and load images with Coil/Glide at the appropriate dimensions.
|
|
265
|
+
- Track startup, jank, ANR, memory, battery, and crashes through Android Vitals/Play Console.
|
|
266
|
+
|
|
267
|
+
### React Native and Flutter
|
|
268
|
+
|
|
269
|
+
- **React Native**: reduce bridge traffic, avoid rendering entire lists, use `FlatList`/`FlashList` with virtualization, and move animations to the UI thread (Reanimated). Use React Native DevTools to profile renders and commits; use Android Studio and Xcode for native layers. Keep Flipper only for manual/legacy integration in older versions, not as the current default tool.
|
|
270
|
+
- **Flutter**: use DevTools (CPU/Memory/Performance), keep frames within the budget, prefer `const` widgets, `ListView.builder`, and appropriately sized images, and avoid broad rebuilds; use isolates for CPU-bound work.
|
|
271
|
+
- In both, measure the cost of the cross-platform layer and use native code only for proven hot paths.
|
|
272
|
+
|
|
273
|
+
---
|
|
274
|
+
|
|
275
|
+
## Desktop — Windows and macOS
|
|
276
|
+
|
|
277
|
+
### Common rules
|
|
278
|
+
|
|
279
|
+
- Measure cold start, warm start, time to first interactive window, latency of main actions, CPU, memory, I/O, network, and background consumption.
|
|
280
|
+
- Test on modest hardware, high DPI/Retina, multiple monitors, a resized window, a slow disk, and offline/intermittent connection.
|
|
281
|
+
- Do not block the UI thread: use async/await, workers, and queues for long operations; keep the window responsive during I/O.
|
|
282
|
+
- Load modules, screens, and data on demand; defer non-critical initializers until the first window is interactive.
|
|
283
|
+
- Release resources when minimizing/going to the background when possible: timers, streams, polling, images, and unnecessary connections.
|
|
284
|
+
- Control memory: watch for leaks, event references, unbounded caches, large documents, and multiple windows.
|
|
285
|
+
- Test the installer, update, first run, run after update, and uninstallation; startup performance includes the user's real path.
|
|
286
|
+
|
|
287
|
+
### Windows (WinUI 3, WPF, .NET, Win32)
|
|
288
|
+
|
|
289
|
+
- Use Windows Performance Analyzer/Recorder, Visual Studio Profiler, `dotnet-counters`, `dotnet-trace`, and ETW according to the stack.
|
|
290
|
+
- Measure Release on representative hardware, for both cold and warm startup, through the first truly interactive frame.
|
|
291
|
+
- Defer loading non-critical assemblies, services, data, and pages; perform long work asynchronously.
|
|
292
|
+
- WinUI/WPF: avoid deep visual trees, unnecessary renders, and lists without virtualization; use virtualization in `ListView`/`ItemsControl` when possible.
|
|
293
|
+
- Reduce allocations and GC pressure in hot paths; use pooling/structs/low-level optimizations only after profiling.
|
|
294
|
+
- Test DPI scaling (100%, 125%, 150%, 200%), multiple monitors, and resizing to detect expensive or broken layout.
|
|
295
|
+
- Use lean MSIX/packaging, remove unused assets/files, and do not initialize update/telemetry services before the first interaction.
|
|
296
|
+
|
|
297
|
+
### macOS (AppKit, SwiftUI, Catalyst)
|
|
298
|
+
|
|
299
|
+
- Use Instruments (Time Profiler, Allocations, Leaks, Energy Log, Network) and `os_signpost` to measure operations and startup.
|
|
300
|
+
- Respect the main thread; use Swift concurrency/DispatchQueue for I/O and long operations without blocking AppKit/SwiftUI.
|
|
301
|
+
- SwiftUI: reduce recomputations and complex hierarchies, use lazy containers for lists, and avoid state that invalidates entire windows.
|
|
302
|
+
- AppKit: reuse views/cells, virtualize tables/collections, limit redraws, and avoid layouts that recalculate the entire window.
|
|
303
|
+
- Use NSCache/URLCache or a custom cache with memory limits and an eviction policy; never keep unlimited documents/images in memory.
|
|
304
|
+
- Properly support Apple Silicon and Intel when necessary; validate the cost of translation/architecture and distribute appropriate binaries.
|
|
305
|
+
- Use BackgroundTasks/appropriate services and reduce work when the app is in the background to preserve energy.
|
|
306
|
+
|
|
307
|
+
### Electron / Tauri
|
|
308
|
+
|
|
309
|
+
- **Electron**: keep the renderer lightweight, disable unnecessary hidden windows, avoid `nodeIntegration` for security, use preload/context isolation, and do not perform CPU-bound work in the renderer; consider Worker Threads/processes.
|
|
310
|
+
- **Tauri**: keep the WebView lean, avoid serializing large payloads between the frontend and Rust, move processing to Rust commands when a measured gain exists, and limit repeated calls between layers.
|
|
311
|
+
- In both, measure main process + renderer/WebView startup, installer size, memory per window, and the cost of multiple windows.
|
|
312
|
+
|
|
313
|
+
---
|
|
314
|
+
|
|
315
|
+
## APIs, network, and distributed architecture
|
|
316
|
+
|
|
317
|
+
- Define latency, availability, and throughput SLOs per endpoint; monitor p50/p95/p99 separately.
|
|
318
|
+
- Reduce round trips: group independent requests, use HTTP/2 multiplexing, use GraphQL/BFF carefully, and provide endpoints that return exactly what is needed.
|
|
319
|
+
- Use layered caching (browser/CDN/API/data) with TTL and invalidation; document eventual consistency and cold-cache behavior.
|
|
320
|
+
- Use compression for large payloads, but measure CPU versus bandwidth; do not compress small responses.
|
|
321
|
+
- Use connection pooling and keep-alive; configure DNS, TLS handshake, timeout, and retry with backoff and jitter.
|
|
322
|
+
- Never retry blindly: retries multiply load. Use a retry budget, idempotency keys, and a circuit breaker.
|
|
323
|
+
- Use queues to decouple long tasks, with backpressure, a concurrency limit, and a dead-letter queue.
|
|
324
|
+
- Prefer streaming/pagination to huge responses; limit header, body, and response size.
|
|
325
|
+
- Use CDN/edge for suitable assets and content; do not put personalized/sensitive data in shared cache without control.
|
|
326
|
+
|
|
327
|
+
---
|
|
328
|
+
|
|
329
|
+
## Infrastructure, containers, and cloud
|
|
330
|
+
|
|
331
|
+
- Use autoscaling based on the right metrics (latency, queue, CPU, memory, requests), not CPU alone.
|
|
332
|
+
- Define CPU and memory requests/limits in containers; observe throttling, OOM kills, and eviction.
|
|
333
|
+
- Use small images and multi-stage builds; remove unused runtime tools and dependencies.
|
|
334
|
+
- Configure health checks that test essential dependencies without generating a traffic cascade; distinguish liveness from readiness.
|
|
335
|
+
- Prefer resources near users and databases in the same region/network when latency is relevant.
|
|
336
|
+
- Use CDN, object storage, and cache for static content; do not serve heavy assets from application instances.
|
|
337
|
+
- Monitor cost and performance together: a larger instance is not always the best solution; compare cost per request/completed action.
|
|
338
|
+
- Run load tests in representative staging and canary/gradual rollouts in production.
|
|
339
|
+
- Do not increase timeout, memory, or thread limits to hide a leak, slow query, or undersized queue; investigate the cause.
|
|
340
|
+
|
|
341
|
+
---
|
|
342
|
+
|
|
343
|
+
## Performance and security
|
|
344
|
+
|
|
345
|
+
- Caching authenticated data requires isolation by user/tenant; never allow shared cache to deliver another user's response.
|
|
346
|
+
- Do not remove validation, authorization, encryption, rate limiting, or auditing just to reduce latency.
|
|
347
|
+
- Limit payloads and request complexity to prevent uncontrolled CPU/memory consumption (application DoS).
|
|
348
|
+
- Do not log complete payloads, tokens, or PII when creating performance instrumentation; consult [`sec-code-eng.md`](./sec-code-eng.md).
|
|
349
|
+
- Profile with anonymized or synthetic data when real data contains sensitive information.
|
|
350
|
+
|
|
351
|
+
---
|
|
352
|
+
|
|
353
|
+
## Instruction template to include in CLAUDE.md / AGENTS.md
|
|
354
|
+
|
|
355
|
+
```
|
|
356
|
+
## Performance
|
|
357
|
+
|
|
358
|
+
- Measure before optimizing: reproduce the problem, record a baseline, perform
|
|
359
|
+
profiling, identify the bottleneck, and only then change the code.
|
|
360
|
+
- Record p50/p95/p99, not just averages. Validate in a Release build and on
|
|
361
|
+
representative hardware/network.
|
|
362
|
+
- Do not block the main thread/event loop/UI with heavy CPU, I/O, parsing, or
|
|
363
|
+
serialization. Use appropriate async, workers, or background jobs.
|
|
364
|
+
- Avoid N+1 queries, huge payloads, `SELECT *`, unnecessary sequential
|
|
365
|
+
requests, and lists without pagination/virtualization.
|
|
366
|
+
- Use cache only with TTL, invalidation, memory limits, and hit/miss metrics.
|
|
367
|
+
Never treat cache as the single source of truth.
|
|
368
|
+
- Configure timeouts, cancellation, concurrency limits, backpressure, and
|
|
369
|
+
retries with backoff/jitter. Do not retry indefinitely.
|
|
370
|
+
- Web: use LCP ≤ 2.5 s, INP ≤ 200 ms, and CLS ≤ 0.1 at the p75 of
|
|
371
|
+
RUM/CrUX as initial targets—not binding release gates unless the product
|
|
372
|
+
documents them—segmented by mobile/desktop and URL/group; use Lighthouse
|
|
373
|
+
for diagnosis, responsive images with a fallback, code splitting, and a
|
|
374
|
+
proven CDN.
|
|
375
|
+
- Mobile: measure startup, jank, ANR/hangs, memory, and battery on real devices;
|
|
376
|
+
defer initialization and keep the UI thread free.
|
|
377
|
+
- Desktop: measure cold/warm startup, first interactive window, CPU/memory, and
|
|
378
|
+
responsiveness on modest hardware, DPI/Retina, and multiple monitors.
|
|
379
|
+
- Database: use EXPLAIN/EXPLAIN ANALYZE, up-to-date statistics, indexes based
|
|
380
|
+
on real queries, and a connection pool sized through measurement.
|
|
381
|
+
- Performance does not justify removing security controls. Do not disable
|
|
382
|
+
TLS, authorization, validation, or rate limiting to gain speed.
|
|
383
|
+
- After optimizing, run the [`test-code-eng.md`](./test-code-eng.md) tests, compare with the baseline,
|
|
384
|
+
check for regressions, and remove temporary instrumentation.
|
|
385
|
+
```
|
|
386
|
+
|
|
387
|
+
---
|
|
388
|
+
|
|
389
|
+
## Performance review checklist
|
|
390
|
+
|
|
391
|
+
### Measurement and diagnosis
|
|
392
|
+
|
|
393
|
+
- [ ] A reproducible baseline exists before the change.
|
|
394
|
+
- [ ] The bottleneck was confirmed by profiler/telemetry, not by assumption.
|
|
395
|
+
- [ ] p50/p75/p95/p99, CPU, memory, I/O, and network were evaluated when applicable.
|
|
396
|
+
- [ ] The change was isolated and compared with the same previous scenario.
|
|
397
|
+
|
|
398
|
+
### Web and APIs
|
|
399
|
+
|
|
400
|
+
- [ ] LCP, INP, and CLS were evaluated at the p75 of RUM/CrUX by mobile/desktop and URL/group; Lighthouse was used only for diagnosis.
|
|
401
|
+
- [ ] TTFB is within the defined budget.
|
|
402
|
+
- [ ] Assets have appropriate compression, dimensions, caching, and loading; AVIF/WebP has a JPEG/PNG fallback or proven CDN negotiation.
|
|
403
|
+
- [ ] The bundle was analyzed; unused code and dependencies were removed.
|
|
404
|
+
- [ ] Endpoints have pagination, timeout, payload limits, and observability.
|
|
405
|
+
- [ ] There are no N+1 queries, avoidable waterfalls, or excessively large responses.
|
|
406
|
+
|
|
407
|
+
### Mobile and desktop
|
|
408
|
+
|
|
409
|
+
- [ ] Startup and first interaction were measured in a Release build.
|
|
410
|
+
- [ ] The UI/main thread/event loop remains responsive during I/O and calculations.
|
|
411
|
+
- [ ] Memory, battery/energy, jank, and background resources were evaluated.
|
|
412
|
+
- [ ] Tests cover modest devices/hardware, different screens, and poor network.
|
|
413
|
+
|
|
414
|
+
### Database and infrastructure
|
|
415
|
+
|
|
416
|
+
- [ ] Critical queries were analyzed with an execution plan and representative data.
|
|
417
|
+
- [ ] Indexes, pools, cache, and limits were sized through measurement.
|
|
418
|
+
- [ ] A load test, canary, or gradual rollout was planned for high-risk changes.
|
|
419
|
+
- [ ] There is no OOM, throttling, lock contention, unbounded queue, or infinite retry.
|
|
420
|
+
|
|
421
|
+
### Security and quality
|
|
422
|
+
|
|
423
|
+
- [ ] The optimization did not remove security or privacy controls.
|
|
424
|
+
- [ ] Logs and traces do not expose secrets, tokens, or PII.
|
|
425
|
+
- [ ] Functional and performance tests run in CI according to [`test-code-eng.md`](./test-code-eng.md).
|
|
426
|
+
- [ ] The result and trade-offs are documented.
|
|
427
|
+
|
|
428
|
+
---
|
|
429
|
+
|
|
430
|
+
## Sources and references
|
|
431
|
+
|
|
432
|
+
- web.dev — Core Web Vitals, p75, and device segmentation: https://web.dev/articles/vitals
|
|
433
|
+
- web.dev — Field measurement, RUM, and CrUX: https://web.dev/articles/vitals-field-measurement-best-practices
|
|
434
|
+
- web.dev — Image performance and `<picture>` fallback: https://web.dev/learn/performance/image-performance
|
|
435
|
+
- React Native — React Native DevTools and native tooling: https://reactnative.dev/docs/react-native-devtools
|
|
436
|
+
- Android Developers — App performance guide: https://developer.android.com/topic/performance/overview
|
|
437
|
+
- Apple Developer — Performance and Instruments: https://developer.apple.com/documentation/xcode/improving-your-app-s-performance/
|
|
438
|
+
- Microsoft Learn — Windows app performance: https://learn.microsoft.com/windows/apps/develop/performance/
|
|
439
|
+
- PostgreSQL — Performance tips and EXPLAIN: https://www.postgresql.org/docs/current/performance-tips.html
|
|
440
|
+
- OpenTelemetry: https://opentelemetry.io/docs/
|
|
441
|
+
- k6: https://grafana.com/docs/k6/latest/
|