(해석 또는 이해가 잘못된 부분이 있다면 댓글로 편하게 알려주세요.)
Cached copies might not all be consistent with the documents on the server. After all, documents do change over time. Reports might change monthly. Online news papers change daily. Financial data may change every few seconds. Caches would be useless if they always served old data. Cached data needs to maintain some consistency with the server data.
캐싱된 사본이 서버에 있는 문서와 전부 일치하지 않을 수도 있습니다.
결국 문서는 시간이 흐름에 따라 바뀔 수 있습니다.
보고서는 달마다 변화할 것이고 온라인 신문은 매일 변화할 것입니다.
금융 데이터는 몇 초마다 한 번씩 변화할 수도 있습니다.
캐시가 항상 오래된 데이터만 전송하게 된다면 아무런 쓸모가 없게 됩니다.
캐싱된 데이터는 원본 서버의 데이터와 일관성(Consistency)를 유지해야만 합니다.
HTTP includes simple mechanisms to keep cached data sufficiently consistent with servers, without requiring servers to remember which caches have copies of their documents. HTTP calls these simple mechanisms document expiration and server revalidation.
HTTP는 서버가 어느 캐시에 사본이 있는지 기억할 필요없이 캐싱된 데이터를 서버와 충분히 동기화하기 위한 간단한 매커니즘을 제공하고 있습니다.
이러한 매커니즘을 문서 만료(Document Expiration) 및 서버 재검증(Server Revalidation)이라고 합니다.
HTTP lets an origin server attach an “expiration date” to each document, using special HTTP Cache-Control and Expires headers (Figure7-13). Like an expiration date on a quart of milk, these headers dictate how long content should be viewed as fresh.
HTTP는 원본 서버가 각각의 Document에 "만료일자"를 붙이도록 합니다. 이때 HTTP Cache-Control과 Expires 헤더를 사용합니다. (Figure 7-13)
만료일자는 마치 우유의 유통기한처럼 해당 콘텐츠가 얼마나 오랜 시간 Fresh 상태를 유지하는지를 나타냅니다.
Until a cache document expires, the cache can serve the copy as often as it wants, without ever contacting the server—unless, of course, a client request includes headers that prevent serving a cached or unvalidated resource. But, once the cached document expires, the cache must check with the server to ask if the document has changed and, if so, get a fresh copy (with a new expiration date).
캐시의 문서가 만료될 때까지 캐시는 서버와 연결하지 않고도 사본을 마음껏 제공할 수 있습니다. (물론 클라이언트가 캐싱 리소스나 재검증이 이루어지지 않은 리소스의 제공을 금지하는 헤더를 포함하고 있다면 서버와의 연결이 필요합니다.)
캐싱된 문서가 만료되고 나면 캐시는 해당 문서에 수정사항이 있는지 확인해야 합니다.
그리고 만약 변경이 발생했다면 만료일자가 갱신된 최신 사본을 가져옵니다.
Servers specify expiration dates using the HTTP/1.0+ Expires or the HTTP/1.1 Cache-Control: max-age response headers, which accompany a response body. The Expires and Cache-Control: max-age headers do basically the same thing, but the newer Cache-Control header is preferred, because it uses a relative time instead of an absolute date. Absolute dates depend on computer clocks being set correctly. Table7-2 lists the expiration response headers.
서버는 HTTP/1.0+의 Expires 헤더나 HTTP/1.1의 Cache-Control: max-age 응답 헤더를 사용하여 만료일시를 표기합니다.
Expires와 Cache-Control: max-age 헤더는 기본적으로 동일하지만 비교적 최신 헤더인 Cache-Control의 사용이 권장됩니다.
Cache-Control은 절대적인 시간 대신 상대적인 시간을 사용하기 때문입니다.
절대 일자는 컴퓨터의 시간이 올바르게 설정되어 있는지에 따라 달라집니다.
Table 7-2는 만료 응답 헤더를 나열한 것입니다.
Let’s say today is June 29, 2002 at 9:30 am Eastern Standard Time (EST), and Joe’s Hardware store is getting ready for a Fourth of July sale (only five days away). Joe wants to put a special web page on his web server and set it to expire at midnight EST on the night of July 5, 2002. If Joe’s server uses the older-style Expires headers, the server response message (Figure7-13a) might include this header:*
Expires: Fri, 05 Jul 2002, 05:00:00 GMT
지금이 2002년 6월 29일 오전 9시 30분(EST)라고 가정해봅시다.
Joe's Hardware Store가 7울 4일 세일을 준비하고 있습니다. 고작 5일밖에 남지 않은 상황입니다.
Joe는 그의 웹 서버에 특별한 웹 페이지를 게시하고 만료일자를 2002년 7월 5일 자정(EST)으로 설정하려고 합니다.
만약 Joe의 서버가 구버전의 Expires 헤더를 사용하고 있다면 서버의 응답 메시지는 다음과 같은 헤더를 포함할 것입니다. (Figure 7-13a)
Expires: Fri, 05 Jul 2002, 05:00:00 GMT
If Joe’s server uses the newer Cache-Control: max-age headers, the server response message (Figure7-13b) might contain this header:
Cache-Control: max-age=484200
In case that wasn’t immediately obvious, 484,200 is the number of seconds between the current date, June 29, 2002 at 9:30 am EST, and the sale end date, July 5, 2002 at midnight. There are 134.5 hours (about 5 days) until the sale ends. With 3,600 seconds in each hour, that leaves 484,200 seconds until the sale ends.
484,200은 현재 일시인 2002년 6월 29일 오전 9시 30분(EST)와 판매 종료 일시인 2002년 7월 5일 자정 사이의 시간을 초 단위로 나타낸 것입니다.
판매 종료일까지는 134.5시간(약 5일)이 남아 있고 한 시간은 3,600초기 때문에 484,200초가 남았다고 볼 수 있습니다.
Just because a cached document has expired doesn’t mean it is actually different from what’s living on the origin server; it just means that it’s time to check. This is called “server revalidation,” meaning the cache needs to ask the origin server whether the document has changed:
• If revalidation shows the content has changed, the cache gets a new copy of the document, stores it in place of the old data, and sends the document to the client.
• If revalidation shows the content has not changed, the cache only gets new headers, including a new expiration date, and updates the headers in the cache.
만료된 캐싱 사본이 원본 서버의 문서와 항상 다른 것은 아닙니다.
단지 사본이 만료되었다는 것은 다시 확인을 할 때가 되었음을 의미합니다.
이것을 "서버 재검증(Server Revalidation)"이라고 부르며, 캐시가 원본 서버에 문서의 수정 여부를 확인해야 하는 상황을 나타냅니다.
만약 재검증 결과 콘텐츠가 수정되었음이 확인되면 캐시는 문서의 새로운 사본을 가져와 이전 데이터를 대치합니다. 그리고 클라이언트에게 새로운 사본을 전달합니다.
콘텐츠가 수정되지 않았다면 캐시는 새로운 만료일시가 포함된 헤더들만 돌려받아 캐시의 헤더를 업데이트합니다.
This is a nice system. The cache doesn’t have to verify a document’s freshness for every request—it has to revalidate with the server only once the document has expired. This saves server traffic and provides better user response time, without serving stale content.
이것은 효율적인 시스템입니다.
캐시가 문서의 Freshness를 매 요청마다 확인하지 않아도 됩니다.
서버 재검증은 오직 문서가 만료되었을 때만 이루어지면 되는 것입니다.
이러한 시스템은 Stale 콘텐츠를 제공하지 않으면서도 서버 트래픽을 절감하고 응답 지연을 해소할 수 있게 합니다.
The HTTP protocol requires a correctly behaving cache to return one of the following:
• A cached copy that is “fresh enough”
• A cached copy that has been revalidated with the server to ensure it’s still fresh
• An error message, if the origin server to revalidate with is down*
• A cached copy, with an attached warning that it might be incorrect
HTTP’s conditional methods make revalidation efficient. HTTP allows a cache to send a “conditional GET” to the origin server, asking the server to send back an object body only if the document is different from the copy currently in the cache. In this manner, the freshness check and the object fetch are combined into a single conditional GET. Conditional GETs are initiated by adding special conditional headers to GET request messages. The web server returns the object only if the condition is true.
HTTP의 조건부 메서드는 더 효율적인 재검증을 가능하게 합니다.
HTTP는 캐시가 "조건부 GET" 메서드를 원본 서버에 전송할 수 있게 합니다.
이 메서드는 문서가 현재 캐시에 저장된 사본과 다를 때에만 서버로부터 오브젝트를 반환하게 합니다.
Freshness Check와 오브젝트 조회가 하나의 조건부 GET 메서드로 결합되는 것입니다.
조건부 GET 메서드는 GET 요청 메시지에 특수한 조건부 헤더를 추가하여 작성됩니다.
오직 이 조건이 true인 경우에만 서버가 오브젝트를 반환합니다.
HTTP defines five conditional request headers. The two that are most useful for cache revalidation are If-Modified-Since and If-None-Match.* All conditional headers begin with the prefix “If-”. Table7-3 lists the conditional response headers used in cache revalidation.
HTTP는 다섯 가지의 조건부 요청 헤더를 정의하고 있습니다.
캐시 재검증에 가장 자주 사용되는 두 가지 헤더는 If-Modified-Since와 If-None-Match입니다.
참고로 모든 조건부 헤더는 "If-" 접두사로 시작합니다.
Table 7-3에서 캐시 재검증에 사용되는 조건부 응답 헤더를 확인할 수 있습니다.
캐싱된 사본을 최신 상태로 유지하기 위해 사용하는 매커니즘
Expires | Cache-Control:max-age |
---|---|
HTTP/1.0+ | HTTP/1.1 |
절대 시간(Fri, 05 Jul 2002, 05:00:00 GMT) | 상대 시간(484200) |
(표를 이따구로 그리는 게 맞나,, 마크다운 어렵)
사실 지난 포스팅에 Stale-While-Revalidate의 동작 방식을 찾아보면서 Cache-Control: max-age를 예습한 거나 다름없었다.
이왕 말 나온 김에 SWR 전략에 대해서도 조금 덧붙여서 정리하자면, SWR에서는 Cache-Control에 max-age와 stale-while-revalidate까지 추가로 들어간다. max-age 필드가 문서의 만료일시를 상대 시간으로 정의한다면, stale-while-revalidate 필드는 이미 만료된 문서 중에서 클라이언트에 캐싱 사본을 전달할 기간을 상대 시간으로 정의한다. 말로 풀어 쓰니 조잡한데 예시를 들면 간단하다.
Cache-Control: max-age=1, stale-while-revalidate=59
이 문서는 max-age가 1초이므로 원본 서버가 응답을 생성한 시점으로부터 1초가 지나면 서버에 재검증 요청을 보내야 한다. 그러나 stale-while-revalidate가 59초로 설정되어 있으므로 1초부터 60초 사이에는 캐싱된 사본을 클라이언트에게 반환하며 백그라운드에서 재검증 요청을 수행하게 된다. 60초가 지나면 캐싱 사본을 전달하지 않고 원본 서버의 문서를 전달해야 한다.
서버를 개발하다 보면 온갖 이유로 지연이 발생하게 되는데, 그 중 개발자가 제어할 수 없는 영역이 바로 거리에 따른 물리적인 지연이다. 다른 부분이 아무리 최적화가 잘 되어 있어도 통신이 이루어지는 컴퓨터간의 거리가 멀면 정말 어쩔 수가 없다. 빛의 속도보다 빠른 걸 만들 수는 없지 않겠는가. 초광속 중성미자가 진짜였으면 아인슈타인이 눈을 세모나게 뜨고 우리를 쳐다봤을 것이다.
아무튼 그런 점에서 프록시는 개발자가 제어할 수 없는 물리적인 지연을 해소해주는 아주 고마운 녀석이다. 배우는 재미가 쏠쏠하다.
안녕하세요! 개발자 준비하시는 분이나 현업에 종사하고 계신 분들만 할 수 있는 시급 25달러~51달러 LLM 평가 부업 공유합니다~ 제 블로그에 자세하게 써놓았으니 관심있으시면 한 번 읽어봐주세요 :)