# Performance Engineering

## Overview

Implementation-level rules for achieving performance targets across all AI-DLC
phases. Each rule is a blocking constraint: a phase or stage cannot complete
until all applicable checks pass or are marked N/A.

### Relationship to EGS

EGS defines performance policy (§9: latency targets, resource selection, caching
strategy, auto-scaling, load testing, query optimization) and capacity planning
(§8.6). This extension covers implementation patterns that achieve those targets:
N+1 prevention, connection management, async patterns, payload optimization, and
cold start mitigation. It does not redefine thresholds or target values.

### Blocking Behavior

When a check fails:
1. List the finding in the phase/stage completion message under "Performance
   Findings" with the rule ID and failed check.
2. Do NOT present "Continue to Next Stage" until resolved.
3. Present only "Request Changes" with what needs to change.
4. Log the finding in `aidlc-docs/audit/audit-log.md` as `EXTENSION_FINDING`.

If a rule does not apply (e.g., no database in this bolt), mark it **N/A**.

---

## Applicability Question

Asked during pre-flight when this extension is loaded:

```
Should performance engineering rules be enforced for this project?

A) Yes — enforce as blocking constraints (recommended for production with latency SLAs)
B) No — skip all performance rules (suitable for internal tools or PoCs)
```

Record the answer in `aidlc-docs/aidlc-state.md` under Extension Configuration.

---

## Design-Time Rules

Enforced during Mob Elaboration and the design stages of Mob Construction.

### PERF-01: Data Access Pattern Design

Architecture prevents inefficient data access from the start.

- [ ] Access patterns documented before selecting a database engine
- [ ] Read-heavy vs write-heavy classification per entity
- [ ] Hot partition risk assessed for key-value and wide-column stores
- [ ] No unbounded queries in any design; all list operations paginated
- [ ] *Defers to EGS §9.6 for query optimization policy and §9.2 for database engine selection*

### PERF-02: Async-First for Non-Critical Paths

Operations that don't need synchronous responses are designed as async.

- [ ] Notification delivery, report generation, and batch processing are async
- [ ] Synchronous call chains limited to 3 hops maximum
- [ ] Long-running operations return 202 Accepted with a status polling endpoint
- [ ] Event-driven decoupling preferred over synchronous orchestration for cross-service flows

### PERF-03: Caching Strategy

Cacheable data is identified during design, not retrofitted.

- [ ] Read-heavy, infrequently-changing data identified as cache candidates
- [ ] Cache invalidation strategy chosen per data type (TTL, event-driven, or hybrid)
- [ ] Cache-aside vs read-through pattern selected and documented
- [ ] *Defers to EGS §9.3 for caching policy and hit ratio monitoring thresholds*

---

## Build-Time Rules

Enforced during Mob Construction implementation stages and Code Elevation.

### PERF-04: N+1 Query Prevention

Code never issues per-item queries inside loops.

- [ ] No database calls inside iteration loops (for/forEach/map)
- [ ] Batch reads used for loading related entities (batch-get APIs, IN clauses, DataLoader patterns)
- [ ] ORM eager/lazy loading strategy explicitly configured, not defaulted
- [ ] *Defers to EGS §9.6 for indexing and query review requirements*

### PERF-05: Connection and Resource Management

External connections are pooled and bounded.

- [ ] Database connections use connection pooling (pool size documented)
- [ ] HTTP clients reuse connections (keep-alive enabled, client instantiated once)
- [ ] Connection pool size aligned with concurrency limits (serverless functions: 1 connection per invocation in single-concurrency runtimes)
- [ ] Resources (connections, streams, file handles) closed in finally/dispose blocks

### PERF-06: Payload Optimization

Data transferred between services and to clients is minimized.

- [ ] API responses include only requested fields (sparse fieldsets or projection)
- [ ] Large payloads compressed (gzip/brotli) at gateway or application level
- [ ] Binary data (images, files) served via signed URLs, not inline in API responses
- [ ] No full-entity responses when only a status or ID is needed (e.g., 204 for updates)

### PERF-07: Cold Start Mitigation

Serverless and container workloads minimize initialization latency.

- [ ] Serverless function initialization code outside the handler (module-level)
- [ ] Dependencies minimized: no unused libraries in deployment package
- [ ] Pre-warming or provisioned concurrency strategy documented for latency-sensitive paths
- [ ] Container images use minimal base images; multi-stage builds for compiled languages
- [ ] *Defers to EGS §9.1 for latency target thresholds*

### PERF-08: Efficient Serialization

High-volume internal communication uses efficient formats.

- [ ] Internal service-to-service payloads prefer binary formats (Protobuf, Avro, CBOR) over JSON when volume exceeds 1000 msg/sec
- [ ] JSON used for external/public APIs (human readability)
- [ ] Date/time serialized as ISO 8601 strings or epoch milliseconds (consistent per service)
- [ ] No redundant serialization/deserialization in middleware chains

---

## Operational Readiness Rules

Flagged during Mob Elaboration, verified in implementation.

### PERF-09: Performance Observability

Performance is measurable in production from day one.

- [ ] Latency metrics emitted per endpoint (p50, p95, p99)
- [ ] Database query duration tracked and alerted on threshold breach
- [ ] Cache hit/miss ratio tracked per cache layer
- [ ] *Defers to EGS §9.1 for target values and §5.1 for observability stack*

### PERF-10: Load Testing Readiness

The system can be load tested before production.

- [ ] Load test scenarios defined for critical paths (aligned with peak traffic estimates)
- [ ] Test data generation strategy documented
- [ ] Performance baseline recorded and compared across releases
- [ ] *Defers to EGS §9.5 for load testing cadence and requirements*

---

## Enforcement by Ritual

| Ritual | Primary Rules | Secondary Rules |
|--------|--------------|-----------------|
| Mob Elaboration | PERF-01 through PERF-03 | PERF-09, PERF-10 (flag as requirements) |
| Mob Construction: Design stages | PERF-01 through PERF-03 | PERF-04 through PERF-08 (verify design supports them) |
| Mob Construction: Implementation | PERF-04 through PERF-08 | PERF-01 through PERF-03 (verify code matches design) |
| Code Elevation | All rules | Assess existing code against full checklist |

At each phase/stage completion, include a "Performance Compliance" section:
- List each applicable rule as ✅ compliant, ❌ non-compliant, or N/A
- Any ❌ is a blocking finding
