Code Review and Optimization Prompt

Perform code reviews with security analysis, performance checks, architecture tradeoffs, and actionable fixes

5 min read

Perform code reviews with security analysis, performance checks, architecture tradeoffs, and actionable fixes

The Prompt

You are a Principal Software Engineer with experience in code quality, security, and performance optimization. Conduct a thorough code review following this framework:

## Review Dimensions

### 1. Code Quality Analysis
- **Readability**: Variable naming, function clarity, comment quality
- **Maintainability**: Code complexity, duplication, modularity
- **Design Patterns**: Appropriate pattern usage, SOLID principles
- **Error Handling**: Exception management, edge cases, recovery

### 2. Security Audit
- **Vulnerability Scan**: SQL injection, XSS, CSRF, authentication issues
- **Data Protection**: Encryption, PII handling, access controls
- **Dependency Check**: Outdated packages, known vulnerabilities
- **Secret Management**: API keys, credentials, sensitive data

### 3. Performance Optimization
- **Time Complexity**: Algorithm efficiency, optimization opportunities
- **Space Complexity**: Memory usage, data structure choices
- **Database Queries**: N+1 problems, indexing, query optimization
- **Caching Strategy**: Cache implementation, invalidation logic

### 4. Architecture Assessment
- **Scalability**: Bottlenecks, horizontal scaling readiness
- **Testability**: Test coverage, mockability, dependency injection
- **Coupling**: Module dependencies, interface design
- **Documentation**: API docs, inline comments, README quality

## Review Output Format

### Priority Issues (Must Fix)

🔴 CRITICAL: [Issue description] Location: [File:Line] Impact: [Security/Performance/Reliability] Suggested Fix: [Specific solution]


### Improvements (Should Fix)

🟡 IMPORTANT: [Issue description] Location: [File:Line] Rationale: [Why this matters] Recommendation: [Better approach]


### Suggestions (Nice to Have)

🟢 SUGGESTION: [Enhancement idea] Benefit: [Expected improvement] Implementation: [How to implement]


### Code Examples
Provide refactored code snippets for critical issues

### Metrics Summary
- Security Score: X/10
- Performance Score: X/10
- Maintainability Score: X/10
- Test Coverage: X%
- Technical Debt Estimate: X hours

Code to Review:
```[language]
[Paste your code here]

Context:

  • Language/Framework:
  • Purpose/Feature:
  • Performance Requirements:
  • Security Considerations:

## How to Use This Prompt

1. Provide complete code context including imports
2. Specify the programming language and framework
3. Mention specific concerns you want addressed
4. Include performance requirements if applicable
5. Note any security compliance requirements


## Example Input

Language/Framework: Python/FastAPI Purpose: User authentication endpoint Performance: <100ms response time Security: OWASP compliance required

@app.post('/login')
def login(username: str, password: str, db: Session = Depends(get_db)):
    user = db.query(User).filter(User.username == username).first()
    if user and user.password == password:
        token = jwt.encode({'user_id': user.id}, 'secret', algorithm='HS256')
        return {'token': token}
    return {'error': 'Invalid credentials'}



## Example Output

## Code Review Results

### Priority Issues (Must Fix)

🔴 **CRITICAL: Plain text password comparison**
Location: Line 4
Impact: Security - Passwords stored/compared in plain text
Suggested Fix: Use bcrypt or argon2 for password hashing
```python
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=['bcrypt'], deprecated='auto')

if user and pwd_context.verify(password, user.hashed_password):

🔴 CRITICAL: Hardcoded JWT secret Location: Line 5 Impact: Security - JWT tokens can be forged Suggested Fix: Use environment variable

from config import settings
token = jwt.encode({'user_id': user.id}, settings.JWT_SECRET, algorithm='HS256')

🔴 CRITICAL: SQL Injection vulnerability Location: Line 3 Impact: Security - Direct string interpolation in query Suggested Fix: Use parameterized queries (already correct with SQLAlchemy ORM)

Improvements (Should Fix)

🟡 IMPORTANT: No rate limiting Location: Endpoint level Rationale: Prevents brute force attacks Recommendation: Implement rate limiting

from slowapi import Limiter
limiter = Limiter(key_func=get_remote_address)

@app.post('/login')
@limiter.limit('5/minute')

🟡 IMPORTANT: Generic error message Location: Line 7 Rationale: Reveals username existence Recommendation: Use consistent error for both cases

raise HTTPException(status_code=401, detail='Invalid credentials')

🟡 IMPORTANT: Missing JWT expiration Location: Line 5 Rationale: Tokens valid indefinitely Recommendation: Add expiration claim

import datetime
payload = {
    'user_id': user.id,
    'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=24)
}

Suggestions (Nice to Have)

🟢 SUGGESTION: Add refresh token mechanism Benefit: Better security with short-lived access tokens Implementation: Return both access and refresh tokens

🟢 SUGGESTION: Add login attempt logging Benefit: Security monitoring and audit trail Implementation: Log failed attempts with IP and timestamp

Refactored Code

from fastapi import HTTPException, Depends, status
from fastapi.security import OAuth2PasswordBearer
from passlib.context import CryptContext
from datetime import datetime, timedelta
import jwt
from config import settings

pwd_context = CryptContext(schemes=['bcrypt'], deprecated='auto')

@app.post('/login', response_model=TokenResponse)
@limiter.limit('5/minute')
async def login(
    credentials: LoginCredentials,
    db: Session = Depends(get_db),
    request: Request = None
):
    # Log login attempt
    logger.info(f'Login attempt for user: {credentials.username} from IP: {request.client.host}')

    # Fetch user with proper error handling
    user = await db.query(User).filter(User.username == credentials.username).first()

    # Verify password with timing attack protection
    if not user or not pwd_context.verify(credentials.password, user.hashed_password):
        # Log failed attempt
        logger.warning(f'Failed login attempt for user: {credentials.username}')
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail='Invalid credentials',
            headers={'WWW-Authenticate': 'Bearer'}
        )

    # Check if account is active
    if not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail='Account disabled'
        )

    # Generate tokens
    access_token = create_access_token(user.id)
    refresh_token = create_refresh_token(user.id)

    # Update last login
    user.last_login = datetime.utcnow()
    await db.commit()

    return {
        'access_token': access_token,
        'refresh_token': refresh_token,
        'token_type': 'bearer'
    }

Metrics Summary

  • Security Score: 2/10 → 9/10 (after fixes)
  • Performance Score: 7/10 (add caching for user lookup)
  • Maintainability Score: 6/10 → 9/10
  • Test Coverage: 0% (needs unit tests)
  • Technical Debt: ~4 hours to implement all fixes

Practical Variations for Code Review and Optimization Prompt

  • Review mode: Paste the smallest relevant code slice, expected behavior, and known failure. Ask for findings ordered by severity before any rewrite.
  • Implementation mode: Give the target API, framework constraints, edge cases, and test expectations. Ask for a minimal implementation plan before code.
  • Debugging mode: Include the error message, reproduction steps, inputs, and recent changes. Ask the model to separate evidence from hypotheses.

Follow-Up Prompts

Use these after the first answer:

  • “Rewrite this using only the context I provided. Label assumptions instead of hiding them.”
  • “Give me a conservative version, a direct version, and a version optimized for speed.”
  • “Create a final review checklist I can use before I publish, send, ship, or present this.”

What Makes This Page Different

This page is useful when you are working on code review & optimizer and need more than a blank chat box. It gives you a starting prompt, context checklist, review criteria, and practical variations so the answer can be tested instead of merely accepted. If your task is broader, start with a workflow guide first, then come back to this prompt once the input, audience, and success criteria are clear.

Input checklist

Before You Run This Prompt

  • Define the exact outcome you want from Code Review and Optimization Prompt.
  • Add the audience, use case, constraints, deadline, and preferred format.
  • Include one strong example of the style or quality level you expect.
  • State what the AI should avoid, such as unsupported claims, generic advice, or off-brand tone.

Quality bar

What a Good Output Should Include

  • A clear structure that can be used without heavy rewriting.
  • Specific recommendations tied to your provided context.
  • Tradeoffs, assumptions, and missing information called out explicitly.
  • Next steps or validation checks so you can judge whether the output is usable.

Iteration workflow

How to Improve the First Answer

1. Tighten the context

Ask the AI to identify missing inputs before it rewrites the answer.

2. Request alternatives

Generate two or three variants for different audiences, tones, or levels of detail.

3. Run a critique pass

Ask for risks, weak assumptions, and edits that would make the result more actionable.

Best Use Cases

  • Projects where Coding context needs a repeatable starting point.
  • Projects where Code Quality context needs a repeatable starting point.
  • Workflows where you want a reusable template instead of starting from a blank chat.
  • Situations where the output still needs human review before publishing or sending.

When to Be Careful

  • Do not treat the answer as final when legal, medical, financial, or safety decisions are involved.
  • Check facts, names, links, prices, dates, and citations before using the output externally.
  • Remove any invented evidence, exaggerated claims, or details that were not present in your input.

Workflow guides

Make This Prompt More Reliable

Use This Prompt Responsibly

AI output quality depends on the context you provide. Treat this template as a structured starting point, then review the result for accuracy, tone, originality, and fit before using it in real work.

Related Prompts