Performance Optimization Prompt
Use Codex to identify measured bottlenecks, design or implement bounded optimizations, and verify performance gains without changing required behavior.
Performance target and supplied context - Optimization objective and scope: [Optimization objective and scope] - System and workload context: [System and workload context] - Existing measurements, profiles, traces, logs, or benchmark results: [Performance evidence] - Relevant code, configuration, benchmark harnesses, and test commands: [Code, configuration, and test commands] - Operational constraints, permitted actions, approval boundaries, and risk limits: [Constraints, authority, and risk limits] - Required performance and behavior outcomes: [Acceptance criteria] Codex operating boundaries - Use Codex to inspect only the repository, workspace, files, and execution results that are actually available in the current session. State what was and was not accessible. - Run tests, profilers, benchmarks, or diagnostic commands only when execution access exists and the supplied authority explicitly permits them. Otherwise, provide exact proposed commands and label them not run. - Do not deploy, modify production, run load against production, access undisclosed data, trigger paid external services, perform migrations, weaken security controls, or make irreversible changes without explicit human authorization. - Protect secrets and personal or production data. Prefer sanitized fixtures or representative synthetic data. Do not reproduce sensitive values in the deliverable. - Stop execution if a command may mutate data unexpectedly, exceed an approved resource limit, destabilize a shared environment, expose sensitive information, or produce results that cannot be safely rolled back. Report the stop condition and request authorization. - Never claim that an optimization was implemented, tested, measured, verified, approved, or deployed unless that action occurred and corresponding evidence is available. Input and uncertainty rules 1. Determine whether the objective identifies a performance metric, representative workload, affected component, behavior that must remain unchanged, and acceptance threshold. Reliable measurement also requires a runnable system or credible existing evidence, a controlled environment, and a reproducible workload. 2. Ask focused questions when a missing item blocks safe execution or makes the target uninterpretable. If measurement is unavailable but analysis is still useful, continue with bounded static inspection and a measurement plan; do not estimate gains as facts. 3. Maintain an evidence ledger that distinguishes supplied facts, direct code observations, executed measurements, assumptions, hypotheses, conflicts, and unknowns. Cite file paths, symbols, commands, run identifiers, or supplied artifacts where available. 4. Treat correlations in traces or profiles as hypotheses until the suspected path is isolated or supported by additional evidence. Preserve conflicting results rather than selecting the preferred result without explanation. Optimization workflow 1. Define the performance contract. Restate the metric and unit, workload shape, concurrency, dataset size, cold or warm state, environment, resource budget, behavior invariants, and acceptance threshold. Record unresolved scope questions. 2. Establish or assess the baseline. Specify the commit or version, runtime and dependency versions, hardware or container limits, configuration, data fixture, warm-up policy, sample count, benchmark duration, and noise controls. Prefer repeated measurements and report distributions such as median and p95 rather than relying on one run. 3. Inspect the relevant execution path. Trace entry points and call paths, then examine algorithmic complexity, repeated work, database query counts and N+1 patterns, serialization, allocations and garbage collection, I/O waits, network calls, cache behavior, lock contention, concurrency limits, batching, pagination, and logging overhead as applicable. 4. Use available evidence to localize hotspots. Correlate profiles, flame graphs, traces, query plans, counters, logs, or benchmark breakdowns with code. For each suspected bottleneck, state its evidence, estimated contribution, confidence, and the observation that would disprove it. Apply Amdahl's law or an equivalent bound when estimating the maximum useful impact of optimizing one component. 5. Rank optimization candidates by expected impact, confidence, implementation cost, behavior risk, memory or CPU trade-offs, complexity, maintainability, cache invalidation risk, concurrency effects, and rollback difficulty. Reject micro-optimizations that are outside the measured hot path unless separately justified. 6. If edits are authorized, make the smallest reviewable change that addresses the strongest supported bottleneck. Preserve public interfaces and required semantics unless a change is explicitly approved. Add comments only where the performance trade-off would otherwise be unclear. Keep unrelated refactoring separate. 7. If execution is authorized, validate the candidate with the same benchmark harness, workload, environment, warm-up policy, and sampling method used for the baseline. Record exact commands, exit status, raw-result locations, baseline and candidate values, absolute and percentage deltas, run-to-run variability, and any confounders. Do not infer success from a single faster run. 8. Check behavior preservation with relevant unit, integration, end-to-end, concurrency, and output-equivalence tests. Consider ordering, precision, error handling, timeouts, cancellation, memory growth, stale caches, race conditions, load sensitivity, cold-start performance, and degraded dependencies where relevant. 9. Reconcile the result with every acceptance criterion. Mark each criterion accepted, rejected, blocked, or unverified. A gain is verified only when the target metric passes under the defined workload, required behavior checks pass, resource use remains within limits, and evidence is reproducible enough for the stated confidence. 10. Prepare a safe handoff. Identify the recommended patch or experiment, required reviewer, rollout guardrails, observability signals, regression thresholds, rollback method, and the smallest authorized next action. Keep deployment and approval as human decisions. Required deliverable 1. Performance contract and current status: scope, target metrics, workload, behavior invariants, environment, accessible materials, execution authority, and blocking unknowns. 2. Measurement protocol table: baseline and candidate versions, environment, dataset, workload, concurrency, warm-up, samples, commands, noise controls, and result locations. 3. Evidence ledger: evidence ID, classification, source, observation, relevance, confidence, conflicts, and limitations. 4. Hotspot ranking: code path or resource, metric contribution, supporting evidence, suspected mechanism, falsification check, confidence, and priority. 5. Optimization decision record: candidate, expected impact, trade-offs, behavior and operational risks, rejected alternatives, approval requirement, and rollback strategy. 6. Change set: proposed or executed file-level changes, concise rationale, patch or diff when available, and a clear status label for each change. 7. Verification matrix: criterion, baseline, candidate, delta, expected threshold, actual observation, behavior check, evidence reference, and accepted, rejected, blocked, or unverified status. 8. Safety and release handoff: stop conditions encountered, remaining risks, monitoring signals, regression thresholds, reviewer decisions needed, and rollback steps. 9. Completion statement: separate work actually inspected, executed, and evidenced from work merely proposed or unavailable. End with the smallest safe next action.
Variables to Replace
- Optimization objective and scope
- System and workload context
- Performance evidence
- Code, configuration, and test commands
- Constraints, authority, and risk limits
- Acceptance criteria
How to Use This Prompt
In Codex, replace every bracketed variable with project-specific information. Provide the relevant repository files, configurations, benchmark harness, profiles, traces, logs, baseline results, environment details, test commands, acceptance thresholds, and explicit execution authority. Then run the prompt. If Codex cannot access or execute an item, require it to preserve that limitation and return proposed commands rather than claiming results.
Example Use Case
A team sees an API endpoint's p95 latency rise from 220 ms to 640 ms after a release. They provide Codex with the affected service files, representative request fixture, trace samples, database query logs, benchmark command, container limits, functional tests, and a p95 target below 300 ms. The prompt directs Codex to establish a comparable baseline, rank supported hotspots such as an N+1 query or serialization overhead, prepare a bounded patch if authorized, rerun the same workload, verify response equivalence and resource limits, and report the result with evidence and rollback guidance.