AI Code Review for Large Codebases: Subagent Workflows and Token Optimization
Large language models are increasingly used for code review, but reviewing large projects can quickly drive up token usage—one real review consumed nearly 1.6 million tokens. This article explains why AI code reviews become token-heavy, how subagent roles and staged workflows can define scope and reduce redundant work, how to design structured review output, and how to optimize input, execution, and output. It also outlines criteria for evaluating whether an AI code review is successful.
As large language models enter software development workflows, code review has become a common use case. Developers can ask AI coding tools to scan project files, identify readability issues, potential performance bottlenecks, exception-handling defects, and implementations that do not follow engineering standards, and then make manual corrections based on the results.
However, code review is not a simple task of handing an entire project to a model and waiting for a conclusion. Especially when a project is large, contains many files, and has complex dependencies between modules, the model must not only read source code but also understand directory structure, call relationships, configuration files, test code, and contextual constraints. As input content and intermediate reasoning increase, token consumption can rise quickly.
In one real project review, the model ultimately consumed nearly 1.6 million tokens. This result shows that although AI coding tools can significantly reduce some repetitive work, cost, response time, and output quality may all suffer if task boundaries are not clearly defined. Therefore, making the model “review more accurately, read less, and produce more useful output” is more important than simply pursuing one-time completion of all work.
1. Why Code Reviews Can Consume So Many Tokens
On the surface, code review seems to require only a few steps: read the code, find problems, and give recommendations. In practice, however, the model often performs a large amount of implicit work.
The first issue is project scanning. The model needs to determine which directories contain business code and which contain tests, build artifacts, dependency caches, or generated files. Without a clear exclusion scope, the tool may read a large amount of content unrelated to the review.
The second issue is contextual association. A problem in a function implementation may be related to its callers, data structures, configuration items, or exception-handling logic. To avoid misjudgment, the model continues reading related files, creating recursive context expansion.
The third issue is result organization. Users usually want more than a list of problems; they also want issue locations, causes, risk levels, modification recommendations, and before-and-after code examples. The more detailed the output, the more tokens are required.
In addition, the model may repeatedly confirm the same issue during review. For example, it may first analyze a module and then reread related files to verify a conclusion, or after finding a potential risk, continue tracing multiple call chains. These behaviors can improve accuracy, but they also add overhead.
High token consumption therefore does not necessarily mean the model is more capable, nor does it necessarily mean the task is being executed more efficiently. A more reasonable judgment is whether the model read the necessary information, reduced irrelevant analysis, and produced output that directly helps developers improve the code.
2. What Subagent Mechanisms Are Good For
One common optimization is to split a complex task into multiple subtasks with clear responsibilities and assign them to different subagents.
A subagent can be understood as an intelligent execution unit with an independent role, independent prompt, and independent task boundary. The main agent is responsible for decomposing goals, scheduling tasks, and aggregating results, while subagents focus on a specific type of work.
For example, the following roles can be designed:
- Codebase exploration agent: identifies directory structure, main modules, entry files, and dependencies.
- Readability review agent: focuses on naming, function length, duplicated logic, comment quality, and code organization.
- Performance analysis agent: focuses on loop complexity, repeated computation, resource access, database calls, and unnecessary data copying.
- Security and reliability agent: checks input validation, exception handling, permission boundaries, and sensitive data exposure risks.
- Improvement recommendation agent: organizes modification priorities and example solutions based on earlier review results.
- Report writing agent: merges multiple review results into a unified format for team review and tracking.
The value of this design is not “adding more agents” but establishing clear responsibility boundaries. Each agent focuses only on the problems it is good at, and prompts can be more specific. For example, a readability agent does not need to analyze full runtime performance, and a performance agent does not need to evaluate every comment line by line.
However, subagents do not inherently reduce token consumption. Each subagent may have its own context, tool calls, and output process. If the task split is unreasonable, multiple agents may repeatedly read the same files, which increases cost instead. The core of the subagent mechanism is therefore not the number of agents but scope control and information reuse.
3. A Recommended Staged Code Review Workflow
Compared with reviewing an entire project in one pass, a staged workflow is more reliable.
Stage 1: Build a project index
First, ask the exploration agent to complete only a project overview, without directly evaluating code quality. It can output:
- The main languages and technical structure used by the project;
- Core business directories;
- Test directories and configuration directories;
- Directories that may contain generated files, dependency caches, or build artifacts;
- Key entry files and the approximate relationships between modules.
The goal of this stage is to build a “map,” not to give conclusions immediately. By obtaining a project index first, subsequent reviews can focus only on valuable files.
Stage 2: Define the review scope
Before formal analysis, the following constraints should be defined:
- Check only specified directories;
- Exclude dependency directories, build directories, and automatically generated files;
- Prioritize recently modified files;
- Focus only on specific languages or specific modules;
- Output only high-risk and medium-risk issues;
- Do not allow direct modification of source code;
- Each issue must include a file location and a reason for improvement.
For example, the scope can be defined as:
Review scope:- src/order/- src/payment/Exclusions:- vendor/- build/- generated/Focus areas:- Repeated database access- Exception handling- Function complexity- Input parameter validation
The clearer the scope, the less likely the model is to perform unbounded exploration.
Stage 3: Review files or modules in batches
Do not put all files into the same context at once. Group them by module, directory, or business function, and review one batch of related files at a time.
Batch processing has three advantages:
First, a shorter context per run makes it easier for the model to maintain attention.
Second, issue localization is more accurate, reducing interference between different modules.
Third, when an exception occurs, it is easier to retry without rerunning the entire project.
For large projects, lightweight rules can first be used to filter candidate files—for example, prioritizing files with more lines of code, frequent recent changes, insufficient test coverage, or complex nesting—before handing them to the model for deeper analysis.
Stage 4: Review by category instead of mixing categories
Readability, performance, security, and architecture issues have different evaluation criteria. If all goals are mixed in one prompt, the model may focus only on the most obvious problems, leaving the review without clear priorities.
A better approach is to run multiple rounds:
- Round 1: Review only code structure and readability;
- Round 2: Review only performance and resource usage;
- Round 3: Check error handling and boundary conditions;
- Round 4: Aggregate issues and remove duplicates.
This makes the evaluation criteria clearer at each stage and makes it easier to control the output length for each type of task.
4. Designing High-Quality Review Output
If the model is only asked to “find problems,” the results often include vague descriptions, confused priorities, or recommendations that cannot be implemented. A unified output format is recommended, for example:
Issue ID:File location:Issue type:Risk level:Description:Impact analysis:Recommended change:Example change:Tests needed:
Risk levels can be divided as follows:
- High: may cause data errors, serious performance problems, permission bypasses, or service unavailability;
- Medium: increases maintenance cost or causes exceptions in specific scenarios;
- Low: mainly affects readability, standards compliance, and long-term maintenance efficiency.
The model should also be required to distinguish between “confirmed issues” and “potential risks.” For example, if repeated computation is found in a loop, it can be described directly as a confirmed efficiency issue. But without runtime data, the model should not assert that it will definitely cause a serious performance drop; instead, it should mark the issue as “requires benchmark verification.”
In addition, code modification recommendations should not overemphasize refactoring. Review reports should prioritize minimal-change solutions and state whether they may affect interfaces, data formats, or compatibility. Larger refactors should be listed separately as follow-up tasks rather than mixed into ordinary defect lists.
5. Further Controlling Token Consumption
Token optimization can start from three aspects: input, process, and output.
1. Optimize input content
Provide only the files necessary to complete the current task, and avoid repeatedly passing project descriptions, irrelevant configurations, and historical output. For very long files, split them first by function or class, and read the full context only when necessary.
2. Optimize the execution process
Set a maximum reading scope, maximum recursion depth, and clear stopping conditions for agents. For example:
- Stop after finding enough high-value issues;
- Analyze the same file at most once;
- Do not continue expanding when there is no direct call relationship;
- Mark issues that cannot be confirmed as pending verification instead of tracing them indefinitely.
3. Optimize output results
Require the model to output only new issues and avoid repeatedly describing the same defect; low-risk style issues can be merged and summarized; code examples should show only key fragments rather than repeating complete files.
It is important to note that compressing tokens must not come at the expense of accuracy. Overly restricting context may prevent the model from understanding call relationships and lead to incorrect recommendations. The right approach is to have the model first perform low-cost filtering, then invest limited context resources in deeper analysis of high-risk issues.
6. How to Evaluate Whether an AI Code Review Succeeded
Do not look only at token consumption, and do not look only at how many issues were found. Evaluation should consider the following dimensions:
- Coverage: whether key directories and core modules were checked;
- Accuracy: whether the issues actually exist and are supported by sufficient evidence;
- Effectiveness: whether recommendations can be directly translated into code changes;
- Duplication rate: whether different agents or stages repeatedly report the same issue;
- Verifiability: whether the issue can be verified through tests, static checks, or benchmark data;
- Cost efficiency: whether the context resources consumed match the actual benefit;
- Human acceptance: whether developers are willing to adopt and maintain the recommendations.
An ideal AI code review does not replace human review. Instead, it helps developers quickly find issues that are easy to miss and provides structured analysis material. Final technical decisions should still take business constraints, runtime data, compatibility requirements, and team standards into account.
7. Conclusion
For AI review tasks in large codebases, the difficulty is not only whether the model can understand the code, but also how to organize context reasonably, divide task boundaries, and control execution cost. A review experience involving nearly 1.6 million tokens shows that directly asking the main agent to scan the entire project from start to finish can easily lead to context expansion and repeated analysis.
A more feasible approach is to adopt a workflow of “project index—scope filtering—module-based review—category analysis—unified aggregation,” while using the subagent mechanism to clarify responsibilities. At the same time, file reading scope should be limited, standardized output formats should be designed, confirmed issues should be distinguished from potential risks, and key conclusions should be verified with tests and benchmark data.
When AI code review shifts from a one-time large task into multiple controllable, verifiable, and reusable small workflows, developers can not only reduce token consumption but also obtain more stable, clearer, and easier-to-implement review results. This approach is also applicable to other software development scenarios such as code migration, technical debt inventories, test completion, and documentation generation.
