# Laravel Performance Standard

## 1. Core Principle

Do not optimize blindly.

First identify:

```text
Problem
↓
Evidence
↓
Bottleneck
↓
Optimization
↓
Measurement
```

---

## 2. N+1 Prevention

Always inspect relationship loading for list operations.

Bad:

```php
foreach ($tasks as $task) {
    $task->project->name;
}
```

Prefer appropriate eager loading:

```php
Task::with('project')->get();
```

---

## 3. Query Count Awareness

For performance-sensitive operations consider:

- Number of queries
- Query duplication
- Relationship loading
- Large result sets
- Missing indexes

Do not accept hundreds of unnecessary queries for a single request.

---

## 4. Repository Optimization

Repositories may optimize data retrieval through:

- Eager loading
- Selective columns
- Pagination
- Query scopes
- Conditional relationships
- Aggregation

Do not move business decisions into repositories.

---

## 5. Pagination

Never load unbounded large datasets.

Use:

```text
paginate()
simplePaginate()
cursorPaginate()
```

where appropriate.

---

## 6. Caching

Use cache for expensive and frequently reused data.

Examples:

- Permission matrix
- Configuration
- Reference data
- Expensive calculations

Prefer Redis when project infrastructure supports it.

Every cache must have:

- Key convention
- TTL
- Invalidation strategy

---

## 7. Cache Invalidation

When underlying data changes:

Determine whether related cache must be invalidated.

Do not create cache without knowing how stale data will be handled.

---

## 8. Queue Heavy Work

Move heavy processing to jobs:

- Imports
- Exports
- Reports
- Emails
- Large notifications
- Batch processing

---

## 9. Avoid Premature Optimization

Do not introduce:

- Complex caching
- Unnecessary denormalization
- Premature microservices
- Complex query tricks

without evidence.

---

## 10. Performance Review

For performance-sensitive changes report:

```text
Before:
Query count / response behavior

After:
Query count / response behavior

Optimization:
...
```
