0Pricing
Edge Computing with Cloudflare Workers & Deno · 강의

캐싱 전략

Cloudflare의 CDN과 Workers Cache API를 사용하여 효과적인 캐싱 메커니즘을 구현하고 지연 시간을 줄입니다.

캐싱 전략은(는) CoddyKit의 무료 Edge Computing with Cloudflare Workers & Deno 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Edge Computing with Cloudflare Workers & Deno 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Edge Computing with Cloudflare Workers & Deno 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What is Caching?

Imagine you need to grab a book. If it's on your desk, it's super fast! If it's at the local library, it's still quick. But if you have to order it from a distant warehouse, it takes much longer.

Caching works similarly. It's the process of storing copies of frequently accessed data closer to where it's needed, speeding up future requests.

Why Cache at the Edge?

In edge computing, 'closer' means at the edge of the network, near your users. Caching at the edge offers several key benefits:

  • Reduced Latency: Content reaches users faster.
  • Reduced Origin Load: Your main servers handle fewer requests.
  • Improved User Experience: Websites and applications feel snappier.

Cloudflare CDN Caching

Cloudflare's Content Delivery Network (CDN) is your first line of defense for caching. It automatically stores static assets (like images, CSS files, and JavaScript bundles) at its global network of edge locations.

When a user requests one of these assets, Cloudflare serves it from the nearest edge server, not your origin server.

HTTP Cache-Control Headers

You can tell CDNs and browsers how to cache your content using HTTP Cache-Control headers. These headers are sent with your server's response.

  • max-age=X: Resource is fresh for X seconds.
  • s-maxage=Y: Specifically for shared caches (CDNs), overrides max-age.
  • no-cache: Must revalidate with origin before serving cached content.
  • no-store: Never cache this content.

Workers Cache API Intro

While Cloudflare's CDN handles static assets, what about dynamic content or API responses? That's where the Cloudflare Workers Cache API comes in.

This powerful API allows your Worker to programmatically store and retrieve any HTTP Response object in Cloudflare's global cache, giving you fine-grained control.

Basic Cache API Flow

The Workers Cache API uses a simple key-value pattern:

  • Key: An HTTP Request object (or a URL string).
  • Value: An HTTP Response object.

You use cache.put(request, response) to store and cache.match(request) to retrieve.

Storing with cache.put()

Let's write a Worker that fetches a resource from an origin and then stores a copy of its response in the cache using cache.put(). This makes it available for future requests.

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event));
});

async function handleRequest(event) {
  const request = event.request;
  const cacheKey = new Request(request.url, request); // Key for cache
  const cache = caches.default; // Get default cache storage

  // Fetch from the origin server
  const response = await fetch(request);

  // Store a clone of the response in cache
  // event.waitUntil ensures caching happens in background
  event.waitUntil(cache.put(cacheKey, response.clone()));

  return response; // Return the original response
}

Retrieving with cache.match()

Now, let's modify the Worker to first check if the requested resource is in the cache using cache.match(). If found, we return the cached version immediately. Otherwise, we fetch from the origin and then cache it.

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event));
});

async function handleRequest(event) {
  const request = event.request;
  const cacheKey = new Request(request.url, request);
  const cache = caches.default;

  // Try to find the response in cache
  let response = await cache.match(cacheKey);

  if (response) {
    // Cache hit! Return cached response
    return response;
  }

  // Cache miss. Fetch from origin
  response = await fetch(request);

  // Store the new response in cache for next time
  event.waitUntil(cache.put(cacheKey, response.clone()));

  return response;
}

Cache Invalidation & Best Practices

Effective caching requires managing stale data. Here are some tips:

  • Purging: Use the Cloudflare dashboard or API to invalidate specific URLs.
  • Vary Header: Use the Vary HTTP header (e.g., Vary: Accept-Encoding) to cache different versions based on request headers.
  • Time-based Expiry: Set appropriate Cache-Control headers or options in cache.put() to automatically expire cached items.

Test Your Knowledge

The Cloudflare Workers Cache API allows you to programmatically control caching. Which method is used to store a response in the cache?

Recap: Caching Strategies

In this lesson, we explored powerful caching strategies to optimize performance at the edge:

  • Cloudflare's CDN automatically caches static assets.
  • HTTP Cache-Control headers allow you to define caching behavior.
  • The Workers Cache API provides programmatic control for caching dynamic content.
  • Proper cache invalidation and management are crucial for fresh data.

Mastering caching is key to building fast, efficient edge applications!

자주 묻는 질문

“캐싱 전략” 강의는 무료인가요?

네 — “캐싱 전략” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Edge Computing with Cloudflare Workers & Deno 강의 전체를 잠금 해제할 수 있습니다. Edge Computing with Cloudflare Workers & Deno 강의에는 총 4개의 강의가 포함되어 있습니다.

“캐싱 전략”에서 뭘 배우나요?

Cloudflare의 CDN과 Workers Cache API를 사용하여 효과적인 캐싱 메커니즘을 구현하고 지연 시간을 줄입니다. 브라우저에서 직접 실행하는 실습 코드로 Edge Computing with Cloudflare Workers & Deno을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Edge Computing with Cloudflare Workers & Deno을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Edge Computing with Cloudflare Workers & Deno은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“캐싱 전략” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Edge Computing with Cloudflare Workers & Deno 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Edge Computing with Cloudflare Workers & Deno 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 캐싱 전략
  2. 콜드 스타트 및 워밍업
  3. 모니터링 및 로깅
  4. 번들 크기 및 코드 최적화
← Edge Computing with Cloudflare Workers & Deno(으)로 돌아가기