---
title: Avoid O(n^2) Algorithms — Design for Scale
impact: CRITICAL
impactDescription: Prevents performance collapse at scale
tags: performance, algorithms, complexity
---
## Паспорт документа

- Статус документа: living standard
- Актуально на: 28 марта 2026 года
- Владелец: backend/platform-команда
- Пересмотр: при изменении инженерной практики, CI/CD, архитектурных правил или локального workflow
- Область применения: внутренние rule/reference-card документы для инженерной команды
- Связанные документы:
  - [Индекс Agents](../README.md)
  - [Команды разработки](../commands.md)
  - [Инженерные принципы](../../governance/engineering-principles.md)

## Avoid O(n^2) Algorithms — Design for Scale

**Impact: CRITICAL**

The platform will grow. What works with 100 items can collapse with 10,000. Performance is something we build correctly from the start.

When building features, always ask: "How does this behave with 10,000 items? 100,000 leads?"

**Common O(n^2) patterns to avoid:**
- Nested array iterations (`.map` inside `.map`)
- `.find`, `.filter`, `.some` inside loops
- Checking every item against every other item
- Chained filters over large lists

**Incorrect (O(n^2)):**

```typescript
// Bad: O(n^2) — checks every item against every subject
const filtered = items.filter(item => {
  return selectedSubjects.some(sub => sub.id === item.subjectId);
});
// For 1000 items and 50 subjects: 50,000 checks
```

**Correct (O(n) with Set):**

```typescript
// Good: O(n) — Set lookup is O(1)
const subjectSet = new Set(selectedSubjects.map(s => s.id));
const filtered = items.filter(item => subjectSet.has(item.subjectId));
// For 1000 items and 50 subjects: ~1,050 operations
```

**Better data structures:**
- **Set/Map**: O(1) lookups instead of `.find` or `.includes` on arrays
- **Sorting + binary search**: For range queries on large datasets
- **Database-level filtering**: Let PostgreSQL do the work — don't fetch all and filter in JS
- **Pagination**: Never load entire tables — always paginate

**Database-level is always better:**

```typescript
// Bad: fetch all, filter in JS
const allItems = await this.itemRepo.findAll();
const filtered = allItems.filter(i => i.subjectId === subjectId);

// Good: filter at database level
const filtered = await this.itemRepo.findBySubject(subjectId, { page, limit });
```
