swr 정책에 대해 알아보자

라따뚜이·2022년 11월 16일
0

stale-while-revalidate


1. swr 시점

캐싱된 데이터가 stale 상태로 얼마나 머물 것인지를 나타내는 파라미터이다.

stale한 상태란, 사용자의 http request가 max-age time이 지난 후이지만, stale-while-revalidate time은 안 지난 상태가 stale한 상태이며, 이 경우에는 우선 캐싱된 데이터(old data)를 사용자에게 response 한 다음 CDN to 서버로 request를 요청하여 서버에서 response한 데이터(fresh data)로 old data를 fresh data로 캐싱된 데이터로 바꾼다.

3가지 경우가 있다.

  1. max-age가 안 지난 시점
  2. swr 시점
  3. swr 이후 시점

방금 위에 설명한 것이 2번째 경우이다.

나머지 1, 3번째 경우에 대해서 알아보자.




2. swr 이후 시점

swr 이후 시점은 아주 간단하다.

바로 사용자의 요청이 서버로 전달되어 컨텐츠를 response한다.





3.max-age 시점


CDN에 저장되어 있는 캐싱된 데이터를 사용자에게 즉시 response한다.




유용한 설정 값


// keep data really fresh, without latency
// 대기 시간 없이 계속 최신 상태로 유지한다.
'Cache-Control' : 'max-age=1, stale-while-revalidate-59'

// data updates roughly once per day; no updates within 1hr 
// 1시간 동안 업데이트 안한다. 23시간동안 stale status
'Cache-Control' : 'max-age=3600, stale-while-revalidate-82800'

// static content (simulator "ISR") - 31 days stale period
'Cache-Control' : 'max-age=60, stale-while-revalidate-2678400'







마치며


react-query, swr는 stale-while-revalidate 을 사용한 데이터 캐싱 도구라고 생각합니다.

서버에 저장된 데이터는 항상 최신 데이터만 저장되어 있습니다. 하지만 클라이언트 데이터는 항상 최신화를 시킬 수 없는 환경 및 데이터 불일치가 발생할 수 있으며, 잦은 request / response로 인한 비용 및 성능 문제를 개발에 스펙에 맞는 react-query, swr 같은 tool을 사용하여 개선할 수 있다고 생각합니다.








참고자료


RFC 5861: HTTP Cache-Control Extensions for Stale Content

How does stale-while-revalidate interact with s-maxage in Cache-Control header?

"Making Slow Responses Seem Fast with Stale while Revalidate" by Scott Smerchek at #RemixConf 💿

stale-while-revalidate 전략은 어떻게 활용되고 있을까

profile
돈만 준다면 해 노예

0개의 댓글