💻 Dev

🛠️ 처음부터 만드는 Concurrency Limiter — p-limit 스타일 동시성 제어기 15줄 구현

왜 필요한가?


API 100개를 동시에 호출하면? 서버가 429를 뱉거나 메모리가 터진다.
동시 실행 수를 N개로 제한하는 게 Concurrency Limiter의 역할이다.

15줄 구현


```js
function createLimit(concurrency) {
const queue = [];
let active = 0;
function run() {
if (active >= concurrency || !queue.length) return;
active++;
const { fn, resolve, reject } = queue.shift();
fn().then(resolve, reject).finally(() => { active--; run(); });
}
return (fn) => new Promise((resolve, reject) => {
queue.push({ fn, resolve, reject });
run();
});
}
```

사용법


```js
const limit = createLimit(3); // 동시 최대 3개
const urls = Array.from({ length: 20 }, (_, i) =>
`https://api.example.com/item/${i}`);
const results = await Promise.all(
urls.map(url => limit(() => fetch(url).then(r => r.json())))
);
// 20개 요청이 3개씩 순차 실행됨
```

핵심 원리


1. — 모든 작업을 큐에 넣고 대기
2. 활성 카운트 — `active`가 `concurrency` 미만일 때만 꺼내 실행
3. 자동 순환 — `finally`에서 카운트를 줄이고 `run()` 재호출 → 다음 작업이 자동 시작
4. Promise 래핑 — 호출자에게는 일반 Promise처럼 보임. `await`만 하면 됨
> p-limit, bottleneck, fastq 등 인기 라이브러리의 핵심이 이 패턴이다.
> `finally` 한 줄이 큐 전체를 굴리는 엔진이라는 점이 포인트.
💬 0
👁 0 views

Comments (0)

💬

No comments yet.

Be the first to comment!