A Practical Codex Guide: Seven Common Use Cases and Prompt Templates
Adapted from “How OpenAI Uses Codex,” this guide covers seven engineering tasks Codex handles especially well—understanding unfamiliar code, refactoring and migration, performance optimization, test coverage, feature development, small tasks, and solution exploration—with reusable prompt templates.
Codex is more than a code generator. It is best suited to well-defined, verifiable engineering tasks such as understanding code, large-scale refactoring, performance optimization, adding tests, and developing features.
This article is adapted from “How OpenAI Uses Codex” and focuses on practical use cases, prompt examples, and a reusable template.
Use Case 1: Quickly Understand Unfamiliar Code
Useful when joining a new project, investigating incidents, reviewing code, or locating business logic.
Codex can help you:
- Locate the core implementation of a feature
- Map call relationships between modules
- Trace how requests or data move through the system
- Analyze how errors propagate
- Identify missing architectural documentation
Prompt Examples
Where is authentication implemented in this repository? List the entry files, core modules, main functions, and related tests.
Trace the complete path of a request from the route entry point to the response, explaining how the data changes at each stage.
Which modules call
UserService, and how does each one handle failures?Analyze the overall architecture of this feature and use a flowchart to show the relationships between its components.
Search the codebase for other implementations that use the same pattern as the current vulnerability. Report their locations first; do not modify code.
Use Case 2: Refactoring and Technical Migration
Useful for cross-file changes, dependency upgrades, legacy migrations, and splitting large modules.
Codex is especially helpful when simple search-and-replace cannot understand code structure or dependencies.
Prompt Examples
Split the current file into independent modules based on business responsibilities. Preserve the public interface and add tests for the resulting modules.
Migrate callback-based database access in this directory to
async/await. Do not change business behavior, and run the relevant tests afterward.Migrate every legacy
getUserById()call to the new user service. Find all call sites first, then update and verify them together.Refactor this Vue component using the project's existing Composition API style while preserving its behavior and interactions.
Find modules that still use the legacy SDK, create a migration plan, and then migrate them one by one.
Use Case 3: Performance Optimization
Useful for diagnosing slow requests, repeated computation, expensive queries, and memory usage.
Codex can inspect:
- Inefficient loops
- Repeated database queries
- Unnecessary data transformations
- Cacheable computations
- Risky or deprecated implementation patterns
Prompt Examples
Optimize this loop's memory usage and explain why the new implementation is more efficient. Keep its output exactly the same.
Find repeated expensive operations in this request handler and propose a caching strategy.
Check whether this function has an N+1 query problem and replace it with batch queries.
Analyze this code's time and space complexity, and identify the main bottlenecks as the data grows.
First locate performance hot spots and provide evidence without modifying the code. Then propose three options: low risk, moderate change, and a full redesign.
Use Case 4: Expand Test Coverage
Useful for legacy code, vulnerability fixes, refactoring validation, and new-feature testing.
Codex is good at finding easily overlooked cases such as:
- Empty input
- Maximum and minimum values
- Invalid states
- Dependency failures
- Uncommon but valid inputs
- Concurrency and timeout scenarios
Prompt Examples
Write unit tests for this function that cover the happy path, boundary cases, and failure paths.
Generate property-based tests for this sorting utility to verify sort stability and result completeness.
Extend the existing test file with cases for empty input, duplicate data, and invalid states.
Add a regression test for the vulnerability that was just fixed. It should fail on the old version and pass on the new one.
Review the current test coverage, list missing scenarios, and add only high-value tests without duplicating coverage of the same logic.
Use Case 5: Accelerate Feature Development
Useful for generating project scaffolding, API routes, configuration files, telemetry code, and first-pass implementations of requirements.
Codex can handle structured but time-consuming groundwork, leaving developers more time for business decisions.
Prompt Examples
Create a new
POST /eventsAPI route with basic parameter validation, error handling, logging, and tests.Create an initial implementation from the following product requirements:
[paste requirements]. First find a similar feature in the project and follow its structure.Using the user-management module as a reference, generate the directory structure, APIs, state management, and basic pages for order management.
Use the telemetry code below as a template and add success, failure, and abandonment events to the new-user onboarding flow:
[paste template]Create a runnable feature scaffold. Use mock data for now, but retain the interfaces needed to connect a real API later.
Use Case 6: Handle Small Tasks and Stay Focused
Useful during meeting-heavy days, frequent interruptions, or when several small tasks need to move forward at once.
You can hand temporary ideas, pending issues, and small fixes to Codex, then review the results together later.
Prompt Examples
Fix the copy error on the Settings page. Change only the relevant text and tests; do not adjust the page structure.
Turn the following work notes into a to-do list, prioritizing tasks that can be completed independently:
[paste notes]Inspect the current incomplete implementation and explain what is finished, what remains, and the recommended next step.
Turn this idea into the smallest runnable prototype without over-engineering it. When finished, tell me which parts are still temporary.
This is a low-priority task: remove unused code and stale comments from this module, and ensure its tests and build still pass.
Use Case 7: Explore Solutions and Ideas
Useful for architecture design, technology selection, comparing alternatives, and validating a design.
When the direction is not yet settled, ask Codex to explore different approaches before changing code.
Prompt Examples
How would the overall architecture change if the system moved from request-response to an event-driven model? Explain the benefits, costs, and migration risks.
Propose three ways to implement this feature, comparing development cost, performance, maintenance difficulty, and extensibility.
Find every module that manually concatenates SQL strings instead of using the project's query builder. Produce a report first; do not modify code.
Rewrite this code in a more idiomatic functional style, minimizing mutation and side effects.
Stress-test the current design: list problems that might arise under high concurrency, network failure, and inconsistent data.
What alternatives are available if no new third-party dependencies may be introduced?
General Codex Prompt Template
Replace the bracketed text when using this template.
Background
[Explain the current feature, the problem, and why a change is needed]
Goal
[Describe the functionality or outcome to deliver]
Scope
- May change:
[files, directories, or modules] - Do not change:
[interfaces, shared components, or unrelated modules]
Reference Implementation
Follow the code structure, naming, and error-handling patterns in [file path, module, or existing feature].
If there is no suitable reference, explain the proposed approach first.
Implementation Requirements
[Specific requirement 1][Specific requirement 2][Compatibility, performance, or security requirement]- Preserve the existing code style and avoid unrelated refactoring
- Do not introduce new dependencies unless they are genuinely necessary
Execution
- Read the relevant code and explain the current implementation.
- List the files to change, implementation steps, and potential risks.
- Make the code changes.
- Add or update relevant tests.
- Run tests, type checks, and build commands.
- If a check fails, determine whether the change caused it and fix related problems.
Acceptance Criteria
[Functional acceptance criterion][Boundary cases and failure paths][Performance or compatibility requirement]- Existing behavior and public interfaces remain unaffected
- Relevant tests, type checks, and builds pass
Final Response
When finished, summarize:
- Which files changed
- Which functionality was implemented
- Which checks were run and their results
- Any remaining risks or items requiring manual confirmation
Note: Do not claim that a check passed unless you actually ran it. If the environment or permissions prevent a step, explain why.
Compact Template
For a simple task, natural language is enough; you do not need to fill in every section:
In
[scope], complete[task goal], follow[existing implementation], and observe[constraints]. Then run[tests or checks]and summarize the changes and verification results. Do not modify unrelated code.
Example:
Fix the duplicate API request on the user-list page. Change only that page and its related request logic, follow the project's existing data-loading approach, and do not add dependencies. Then run the relevant tests and type checks, and explain the cause, changes, and verification results.
You can append this sentence:
Do not claim that a check passed unless you actually ran it. If a check cannot be run because of environment or permission constraints, explain why.
The template's fixed structure can be summarized as:
Background → Goal → Scope → Reference → Requirements → Execution → Acceptance → Summary.
Discussion
Support the author