본문 바로가기
Front-End/React

React Throttle 개념

by SeanK 2021. 11. 21.

 

 

 

오늘은 스로틀(throttle) 개념에 대해 알아보자. 

 

React에서 스로틀이란 어떤 개념을 뜻하는 걸까?

 

 

우선 단어의 의미를 살펴보자. 

 

 

Throttle이란?

 

네이버 사전에서 스로틀에 대한 설명은 아래와 같다. 

 

스로틀 

항공우주공학용어사전

1) 엔진의 실린더로 유입되는 연료.
2) 공기의 혼합물을 조절하여 조종사가 원하는 동력 또는 추력을 조절하기 위한 조종장치.

 

 

Throttle 이미지

 

스로틀은 엔진에 연료가 주입되는 양을 조절하는 장치를 의미하는데, 

 

React에서는 API request 양을 조절하는 개념으로 사용된다. 

 

이름이 매우 적절하다고 생각...

 

Throttle에 대해 아주 자세하고 친절하게 설명한 블로그가 있어서, 

 

번역을 해보려고 한다. 

 

원본은 아래와 같다.

https://dev.to/edefritz/throttle-a-series-of-fetch-requests-in-javascript-ka9

 

 

Throttle a series of fetch requests in JavaScript

 

만약, 아주 대량의 데이터를 API request 해야한다고 생각해보자. 

자바스크립트의 비동기적 특성으로는 병렬로 많은 양의 요청을 보내기 아주 용이할 것이다. 

 

import fetch from "node-fetch";

const data = [{ id: 1 }, { id: 2 }, [+1000 more objects]];

const fetchFromApi = (id) => {
  const url = `https://example.com/api/my-resource/${id}`;

  const response = fetch(url)
    .then((x) => x.json())
    .catch((error) => console.log(error));
  return response;
};

for (const i of data) {
  fetchFromApi(i.id).then((result) => // do something with result);
}

 

HTTP code 429: Too many requests

 

하지만, 대부분의 API 제공자들은 한번에 너무 많은 요청을 쏟아내는 것을 좋아하지 않는다. 

아마 429 HTTP 에러 코드를 받게 될 것이다. 

만약, 다큐먼트를 살펴본다면 제한이 있을 것인데, 초당 5회의 요청이라고 가정해보자. 

설사 내부 API로 별다른 제한이 없더라도 병렬 요청의 양을 줄이고 싶어할 수도 있다. 

 

Wait for the response before making another request?

 

한 가지 해볼만한 해법은 이전 요청이 끝날 때 까지 기다리도록 async/await 구문을 이용해 블로킹 구조를 만드는 것이다.

 

import fetch from "node-fetch";

const data = [{ id: 1 }, { id: 2 }, [+1000 more objects]];

const fetchFromApi = async (id) => {
  const url = `https://example.com/api/my-resource/${id}`;

  const response = fetch(url)
    .then((x) => x.json())
    .catch((error) => console.log(error));
  return response;
};

for (const i of data) {
  const response = await fetchFromApi(i.id);
  // do something with result
}

 

하지만 실행시간은 길고, 문제를 해결하진 못한다. 
API는 재빠르게 요청을 실행할 것이고 초당 5회의 제한을 넘겨버릴 것이다. 

반대로 API가 늦게 실행된다 하더라도 병행의 이점을 전혀 얻지 못해 실행시간만 필요이상 늘어버리게 된다. 

 

 

Semaphore to the rescue

 

Throttling 매커니즘을 이용하면 이러한 문제를 우아하게 해결할 수 있따.

컴퓨터 공학에서는 다량의 프로세스가 하나의 공동 리소스에 접근하는 것을 제어하는 

"semaphore"라는 개념이 있다.

최대 병렬 요청 양을 제한할 수 있는 라이브러리가 있다. 아래와 같이 생겼다. 

 

import fetch from "node-fetch";
import {RateLimit} from "async-sema";

// configure a limit of maximum 5 requests / second
const limit = RateLimit(5);

const data = [{ id: 1 }, { id: 2 }, [+1000 more objects]];

const fetchFromApi = (id) => {
  const url = `https://example.com/api/my-resource/${id}`;

  // use the configured throttle here
  const response = fetch(url)
    .then((x) => x.json())
    .catch((error) => console.log(error));
  return response;
};

for (const i of data) {
  // checks if limit is reached
  await limit()
  fetchFromApi(i.id).then((result) => console.log(result));
}

 

 

 

 

'Front-End > React' 카테고리의 다른 글

[React] React에서 this는 무엇인가?  (0) 2021.12.05
[React] React의 세가지 특성  (0) 2021.12.05
React Debounce개념  (0) 2021.11.21
React Array.prototype.map()  (0) 2021.11.03
React Props/State  (0) 2021.10.30