8. HTTP 헤더2 - 캐시와 조건부 요청
캐시 기본 동작
캐시가 없을 때
- 데이터가 변경되지 않아도 계속 네트워크를 통해서 데이터를 다운로드받아야 한다
- 인터넷 네트워크는 매우 느리고 비싸다
- 브라우저 로딩 속도가 느리다
- 느린 사용자 경험
캐시 적용
cache-control: max-age=60 (캐시가 유효한 시간(초))
같은 요청이 들어오면 캐시 유효 시간 검증 → 캐시에서 데이터를 읽어 온다
- 캐시 덕분에 캐시 가능 시간동안 네트워크를 사용하지 않아도 된다
- 비싼 네트워크 사용량을 줄일 수 있다
- 브라우저 로딩 속도가 매우 빠르다
- 빠른 사용자 경험
캐시 유효 시간 검증 → 캐시 시간 초과
→ 다시 요청, 서버에서 star.jpg 응답
캐시 시간 초과
- 캐시 유효 시간이 초과하면 서버를 통해 데이터를 다시 조회하고 캐시를 갱신
- 이때 다시 네트워크 다운로드가 발생한다
만약 클라이언트가 요청하는 데이터와 유효 시간이 만료한 캐시 데이터가 동일하다면 다시 다운로드하는 것은 낭비 → 해결?
검증 헤더와 조건부 요청1
캐시 유효 시간 초과 → 서버에 다시 요청
- 서버에서 기존 데이터 변경
- 서버에서 기존 데이터를 변경하지 않음
- 캐시 만료 후에도 서버에서 데이터를 변경하지 않음
- 데이터를 전송하는 대신에 저장해 두었던 캐시를 재사용
- 단, 클라이언트의 데이터와 서버의 데이터가 같다는 사실을 확인할 수 있는 방법 필요
검증 헤더 추가
Last-Modified: 2020년 11월 10일 10:00:00
- 데이터 최종 수정일
응답 결과를 캐시에 저장, 데이터 최종 수정일을 브라우저 캐시에 기록
캐시 시간 초과, 웹 브라우저 요청 : if-modified-since: 2020년 11월 10일 10:00:00
→ 캐시의 데이터 최종 수정일과 웹 브라우저의 요청의 if-modified-since의 날짜가 동일
서버 응답
HTTP/1.1 304 Not Modified
cache-control
Last-Modified: ~~
**HTTP Body가 없다
웹 브라우저: 응답 결과를 재사용(캐시에서), 헤더 데이터 갱신,
정리
- 캐시 유효 시간이 초과해도, 서버의 데이터가 갱신되지 않으면
- 304 Not Modified + 헤더 메타 정보만 응답 (바디x)
- 클라이언트는 서버가 보낸 응답 헤더 정보로 캐시의 메타 정보 갱신
- 클라이언트는 캐시에 저장되어 있는 데이터 재활용
- 결과적으로 네트워크 다운로드가 발생하지만 용량이 적은 헤더 정보만 다운로드
검증 헤더와 조건부 요청2
검증 헤더
- 캐시 데이터와 서버 데이터가 같은지 검증하는 데이터
- Last-Modified, ETag
조건부 요청 헤더
- 검증 헤더로 조건에 따른 분기
- If-Modified-Since: Last-Modified랑 함께 사용
- If-None-Match: ETag 사용
- 조건이 만족하면 200 OK
- 조건이 만족하지 않으면 304 Not Modified
If-Modified-Since: 이후에 데이터가 수정되었으면? OK, 수정되지 않았으면 304
- 데이터 미변경
- 캐시: 2020-11-10-10:00, 서버:2020-11-10-10:00
- 304 Not Modified, 헤더 데이터만 전송 (BODY 미포함)
- 데이터 변경
- 캐시: 2020-11-10:10:00, 서버:2020-11-10-11:00
- 200 OK, 모든 데이터 전송(BODY 포함)
단점
- 1초 미만 단위로 캐시 조정 불가능
- 날짜 기반의 로직 사용
- 데이터를 수정해서 날짜는 다르지만, 같은 데이터를 수정해서 데이터 결과가 똑같은 경우: 구분 불가
- 서버에서 별도의 캐시 로직을 관리하고 싶은 경우
- 스페이스나 주석처럼 크게 영향이 없는 변경에서 캐시를 유지
ETag, If-None-Match
ETag(Entity Tag)
- 캐시용 데이터에 임의의 고유한 버전 이름을 달아둠
- 예) ETag: “v1.0”, ETag:”a2
~” (해시)
- 예) ETag: “v1.0”, ETag:”a2
- 데이터가 변경되면 이 이름을 바꾸어서 변경 (Hash를 다시 생성)
- 단순하게 ETag만 보내서 같으면 유지, 다르면 다시 받기
If-None-Match 요청
데이터가 수정되지 않았으면 304, 수정되었으면 200
- 캐시 제어 로직을 서버에서 완전히 관리
- 클라이언트는 단순히 이 값을 서버에 제공(클라이언트는 캐시 메커니즘을 모름)
- 예) 애플리케이션 배포 주기에 맞추어 ETag 모두 갱신
캐시와 조건부 요청 헤더
Cach-Control 캐시 제어
- Cache-Control: max-age
- 캐시 유효 시간, 초 단위
- Cache-Control: no-cache
- 데이터는 캐시해도 되지만, 항상 원(origin) 서버에 검증하고 사용
- if-modified-since나 if-none-match를 통해 데이터가 바뀌었는지 확인하고 사용하기
- Cache-Control: no-store
- 데이터에 민감한 정보가 있으므로 저장하면 안됨
- 메모리에서 사용하고 최대한 빨리 삭제
Pragma
- Pragma: no-cache
- HTTP 1.0 하위 호환
Expires
캐시 만료일을 정확한 날짜로 지정
HTTP 1.0부터 사용
지금은 더 유연한 Cache-Control:max-age 권장
Cache-Control:max-age와 함께 사용하면 expires 무시
검증 헤더
- ETag, Last-Modified
조건부 요청 헤더
- If-Match, If-None-Match: ETag 값 사용
- If-Modified-Since, If-Unmodified-Since: Last-Modified 사용
프록시 캐시
웹 브라우저 → 미국에 있는 원 서버: 요청을 받아오는 데 시간이 오래 걸림
웹 브라우저 → *프록시 캐시 서버 → 미국에 있는 원 서버
최초 요청에는 프록시 캐시 서버x → 두 번째부터는 빠르게 받아올 수 있음
웹 브라우저-private 캐시, 프록시 캐시 서버-public 캐시
캐시 지시어
- Cache-Control: public
- 응답이 public 캐시에 저장되어도 됨
- Cache-Control: private
- 응답이 private 캐시에 저장해야함, 응답이 해상 사용자만을 위한 것 (기본값)
- Cache-Control: s-maxage
- 프록시 캐시에만 적용되는 max-age
- Age: 60 (HTTP 헤더)
- 오리진 서버에서 응답 후 프록시 캐시 내에 머문 시간(초)
캐시 무효화
Cache-Control: 확실한 캐시 무효화 응답
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache-HTTP 1.0 하위 호환
- must-revalidate
- 캐시 만료 후 최초 조회시 원 서버에 검증해야 함
- 원 서버 접근 실패시 반드시 오류가 발생해야 함 - 504(Gateway Timeout)
- must-revalidate는 캐시 유효 시간이라면 캐시를 사용
no-cache vs must-revalidate
- no-cache 기본 동작
- 1 캐시 서버 요청 no-cache+ETag
- 2 프록시 캐시: no-cache를 보고 원 서버에 요청, no-cache + ETag
- 3 원서버 검증
- 4 원서버 응답: 304 Not Modified
- 5 캐시 데이터 사용
- 만약에 원 서버에 요청을 보냈는데, 순간 네트워크 단절→ 원 서버 접근 불가
- 캐시 서버 설정에 따라서 캐시 데이터 반환할 수도 있음
- Error or 200 OK(오류보다는 오래된 데이터라도 보여주자)
- must-revalidate
- 원 서버에 접근할 수 없는 경우, 항상 오류가 발생해야함
- 504-Gateway Timeout (매우 중요한 돈과 관련된 결과로 생각해보자)
'CS > Network' 카테고리의 다른 글
[HTTP 웹 기본지식] 7. HTTP 헤더 - 일반 헤더 (0) | 2022.11.14 |
---|---|
[HTTP 웹 기본지식] 6. HTTP 상태코드 (0) | 2022.11.14 |
[HTTP 웹 기본지식] 5. HTTP 메서드 활용 (0) | 2022.11.14 |
[HTTP 웹 기본지식] 4. HTTP 메서드 (0) | 2022.11.14 |
[HTTP 웹 기본지식] 3. HTTP 기본 (0) | 2022.11.14 |