디바운스 검색 직접 만들기
AI 의존을 줄이려고 시작한 시리즈의 첫 편입니다. title·tags 검색에 디바운스, Map 캐시, requestId 기반 race condition 방지를 차례로 붙여 SearchEngine을 만듭니다.
요새 너무 AI에 의존해서 뇌와 생각이 멈춘 것 같다는 느낌을 받았습니다. 그래서 초심으로 돌아가 기능을 하나씩 직접 만들어 보려고 이 시리즈를 시작했습니다.
첫 번째로 만들 것은 기본적이면서 실무에서 많이 구현하는 검색 기능입니다. 검색 자체는 단순하지만 디바운스, 캐시, race condition 방지까지 붙이면 생각할 거리가 꽤 생깁니다.
SearchEngine이 지켜야 할 요구사항
요구사항
title·tags 검색에 옵션 세 가지(태그 필터, 디바운스, 캐시)를 얹고, 빠른 연속 입력에서도 최신 결과만 남아야 합니다. 요구사항은 아래처럼 잡고 시작했습니다.
//요구사항
1) 데이터 구조
items = [
{ id, title, tags[] }
]
2) search 기능
search(query, options)
요구사항:
title에서 query 검색
tags에서도 query 검색
대소문자 무시
3) filterTag 옵션
search("apple", { filterTag: "watch" })
4) debounce 옵션
useDebounce: true,
delay: number
5) cache 기능
같은 query + filterTag 조합이면 재계산 X
6) race condition 방지
라이브러리 대신 직접 만들기와 설계 선택
라이브러리를 쓸까, 직접 만들까
디바운스는 lodash 같은 라이브러리 함수를 가져다 쓰면 바로 끝납니다. 하지만 이 시리즈는 AI에 기대지 않고 기능을 직접 만들어 보는 것이 목적이라, 디바운스·캐시·race condition 방지를 모두 직접 구현했습니다.
캐시: Object vs Map
캐시를 Object 대신 Map으로 고른 이유는 이 캐시가 "동적 key 기반의 검색 결과 캐시"였기 때문입니다. Map은 key 타입이 자유롭고, 순서가 보장되고, 삭제·순회가 쉽습니다. 게다가 삽입 순서(insertion order)를 지키므로 나중에 LRU(Least Recently Used)로 확장하기에도 유리해서 캐시 구조에 더 적합하다고 판단했습니다.
race condition: 디바운스만 둘까, requestId를 붙일까
디바운스는 이전 타이머를 지우고 다시 예약할 뿐, 이미 실행된 이전 요청의 결과가 뒤늦게 반영되는 것까지 막지는 못한다고 봤습니다. 그래서 요청마다 번호(requestId)를 붙이고 최신 번호가 아니면 결과를 버리는 방식을 더했습니다. 자세한 이유는 아래 4단계에 있습니다.
SearchEngine 단계별 구현
기본 구조
SearchEngine 클래스 하나에 검색 대상 목록과 디바운스용 타이머를 둡니다.
class SearchEngine {
constructor(items) {
this.items = [...items] // 검색 리스트
this.timer = null; // 디바운스를 위한 타이머
}
search(query, options = {}) {
}
_searchCore(query,filterTag) {
}
}1. title·tags 검색: _searchCore()
검색의 기본이 되는 _searchCore()부터 구현합니다. query와 title·tags를 모두 소문자로 바꿔 대소문자를 무시하고, filterTag가 있으면 그 태그를 가진 항목만 남깁니다.
_searchCore(query,filterTag) {
if (!query || typeof query !== "string") return [];
const q = query.toLowerCase(); // 대소문자 무시
return this.items.filter((item)=>{
const titleMatch = item.title.toLowerCase().includes(q); // 타이틀 검사
const tagMatch = item.tags.some((tag) =>
tag.toLowerCase().includes(q)
); // 태그 검사
const matchesQuery = titleMatch || tagMatch; //태그 존재 검사
if (filterTag) // 필터 태그 검사 조건
{
return item.tags.includes(filterTag) && matchesQuery;
}
return matchesQuery;
})
}2. search()에 디바운스 붙이기
search()는 useDebounce 옵션에 따라 갈립니다. 디바운스를 켜면 이미 예약된 타이머를 지우고 delay 뒤에 다시 예약하므로, 입력이 멈춘 뒤 마지막 요청만 실행됩니다.
search(query, options = {}) {
const { useDebounce = false, delay = 300, filterTag = null } = options;
if (useDebounce) { // 디바운스 조건 분기 처리
if(this.timer) {
clearTimeout(this.timer);// 이미 예약된 타이머 있으면 종료
}
this.timer = setTimeout(() => {
const result = this._searchCore(query, filterTag);
}, delay);// 디바운스 구현
return;
}
return this._searchCore(query, filterTag);
}
3. Map으로 검색 결과 캐시하기
같은 query + filterTag 조합이면 다시 계산하지 않도록, 두 값을 이어 붙인 키로 결과를 저장합니다.
constructor(items) {
this.items = [...items] // 검색 리스트
this.timer = null; // 디바운스를 위한 타이머
this.cache = new Map(); // query + filter 조건 캐시
}
search(query, options = {}) {
const {
useDebounce = false,
delay = 300,
filterTag = null,
} = options;
const key = `${query}-${filterTag || ""}`; // 고유 키 값 생성
// cache hit
if (this.cache.has(key)) {
return this.cache.get(key);
}
const runSearch = () => {
const result = this._searchCore(query, filterTag);
this.cache.set(key, result);// cache set
return result;
};
if (useDebounce) {
if(this.timer){
clearTimeout(this.timer);
}
this.timer = setTimeout(() => {
runSearch();
}, delay);
return;
}
return runSearch();
}
4. requestId로 race condition 막기
캐시까지 붙이고 나니 마지막 요구사항인 race condition이 남았습니다. race condition은 여러 작업이 동시에 실행될 때 완료 순서에 따라 최종 결과가 달라지는 문제입니다.
검색에 디바운스를 적용하면 작업이 setTimeout으로 지연 실행됩니다. 이 작업들은 매크로태스크 큐(macrotask queue)에 등록되고 이벤트 루프를 통해 순차적으로 실행됩니다.
문제는 입력이 빠르게 여러 번 들어오면 여러 setTimeout이 큐에 쌓이고, 작업마다 실행 시점이 달라질 수 있다는 점입니다. 그러면 이전 요청의 결과가 뒤늦게 반영되면서 최신 상태를 덮어쓸 수 있습니다.
예를 들어 입력이 a → ap → app 순서로 빠르게 들어오면, 요청마다 실행 시간이 달라 app이 아닌 이전 요청의 결과가 뒤늦게 반영되는 상황이 생길 수 있습니다.
그래서 요청마다 번호를 붙이고, 실행 시점에 최신 번호가 아니면 결과를 버리도록 바꿨습니다.
constructor(items) {
this.items = [...items] // 검색 리스트
this.timer = null; // 디바운스를 위한 타이머
this.cache = new Map(); // query + filter 조건 캐시
this.requestId = 0; // race 순서
}
search(query, options = {}) {
const {
useDebounce = false,
delay = 300,
filterTag = null,
} = options;
const key = `${query}-${filterTag || ""}`; // 고유 키 값 생성
// cache hit
if (this.cache.has(key)) {
return this.cache.get(key);
}
const runSearch = (id) => {
const result = this._searchCore(query, filterTag);
// 최신 요청만 cache 반영
if (id !== this.requestId) return null;
this.cache.set(key, result);// cache set
return result;
};
if (useDebounce) {
if(this.timer){
const id = ++this.requestId;
clearTimeout(this.timer);
}
this.timer = setTimeout(() => {
runSearch(id);
}, delay);
return;
}
const id = ++this.requestId;
return runSearch(id);
}
requestId를 증가시키며 요청을 식별하고, 실행 시점에 최신 requestId와 비교해 이전 요청의 결과를 무시합니다. 이렇게 race condition을 제어하고 runSearch가 최신 요청 기준으로만 결과를 반영하도록 설계했습니다.
실행 결과로 확인하기
실행 로그
searchEngine.search("a", { useDebounce: true })
searchEngine.search("ab", { useDebounce: true })
searchEngine.search("abc", { useDebounce: true })
searchEngine.search("abc", { useDebounce: false })
searchEngine.search("abc", { useDebounce: false })
---Log---
[SEARCH] q=a, key=a-, id=0
[DEBOUNCE] schedule id=1
[SEARCH] q=ab, key=ab-, id=1
[DEBOUNCE] schedule id=2
[SEARCH] q=abc, key=abc-, id=2
[DEBOUNCE] schedule id=3
[SEARCH] q=abc, key=abc-, id=3
[EXECUTE] id=4, q=abc
[CACHE SET] abc-
[SEARCH] q=abc, key=abc-, id=4
[CACHE HIT] abc-
[EXECUTE] id=3, q=abc
[DROP] stale id=3, latest=4로그를 보면 requestId 덕분에 최신 요청만 유효하게 처리되고, 이전 요청은 DROP되어 race condition이 막힙니다. 같은 검색 키로 다시 검색하면 cache hit가 나서 재계산 없이 결과를 재사용하는 것도 확인할 수 있습니다.
같은 주제의 글
EventEmitter 직접 만들기
on·off·emit·once·onAny를 갖춘 경량 EventEmitter를 만들며 Map·Set을 고른 이유, emit 중 변경을 막는 스냅샷, once의 wrapper 패턴을 정리합니다.
6분 읽기#JavaScript동시 실행 제한 큐 직접 만들기
Promise.all처럼 한꺼번에 실행하지 않고 동시에 N개만 실행하는 ConcurrentQueue를 대기열과 실행 카운터로 만들고, pause·resume·clear까지 구현합니다.
4분 읽기#JavaScript