0Pricing
Edge Computing with Cloudflare Workers & Deno · Lektion

Caching-Strategien

Implementieren Sie effektive Caching-Mechanismen mit dem CDN von Cloudflare und der Workers Cache API, um die Latenz zu reduzieren.

Caching-Strategien ist eine kostenlose Edge Computing with Cloudflare Workers & Deno-Lektion auf CoddyKit. Dies ist Lektion 1 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Edge Computing with Cloudflare Workers & Deno-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Edge Computing with Cloudflare Workers & Deno-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

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!

Häufig gestellte Fragen

Ist die Lektion „Caching-Strategien“ kostenlos?

Ja — der vollständige Text von „Caching-Strategien“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Edge Computing with Cloudflare Workers & Deno-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Edge Computing with Cloudflare Workers & Deno-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „Caching-Strategien“?

Implementieren Sie effektive Caching-Mechanismen mit dem CDN von Cloudflare und der Workers Cache API, um die Latenz zu reduzieren. Du übst Edge Computing with Cloudflare Workers & Deno mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um Edge Computing with Cloudflare Workers & Deno zu starten?

Keine Vorkenntnisse erforderlich. Edge Computing with Cloudflare Workers & Deno auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 1 von 4.

Wie lange dauert die Lektion „Caching-Strategien“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser Edge Computing with Cloudflare Workers & Deno-Lektion Code schreiben und ausführen?

Ja. Jede Edge Computing with Cloudflare Workers & Deno-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Caching-Strategien
  2. Cold Starts und Warmups
  3. Monitoring und Logging
  4. Bundle-Größe und Code-Optimierung
← Zurück zu Edge Computing with Cloudflare Workers & Deno