β‘ Edge Cache Architecture
Γbersicht
Optionaler Cache-Layer auf Cloudflare Workers fΓΌr globale Performance.
Architektur
βββββββββββ ββββββββββββββββββββ βββββββββββββββ
β Client β ββββ β CF Worker (Edge) β ββββ β Backend API β
βββββββββββ ββββββββββββββββββββ βββββββββββββββ
β β
β βΌ
β ββββββββββββββββ
β β KV Store β
β β (Cache) β
β ββββββββββββββββ
β
βββ Response: ~10-50ms (Edge)
vs ~100-500ms (Direct)
Vorteile
| Aspekt | Ohne Edge | Mit Edge Cache |
|---|---|---|
| Latenz | 100-500ms | 10-50ms |
| Global | Single Region | 200+ Locations |
| Backend Load | Hoch | Reduziert |
| Kosten | Pay per Request | 100k free/day |
Implementation
Worker Code (edge/worker.ts)
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const cacheKey = getCacheKey(request);
// Cache Hit?
const cached = await env.CACHE.get(cacheKey, 'json');
if (cached) {
return new Response(JSON.stringify(cached.data), {
headers: { 'X-Cache': 'HIT' }
});
}
// Cache Miss β Backend
const response = await fetch(env.BACKEND_URL + path);
const data = await response.json();
// Store in Cache
await env.CACHE.put(cacheKey, JSON.stringify(data), {
expirationTtl: ttl
});
return new Response(JSON.stringify(data), {
headers: { 'X-Cache': 'MISS' }
});
}
};
Setup
1. Wrangler CLI installieren
2. KV Namespace erstellen
3. wrangler.toml konfigurieren
name = "contract-platform-cache"
main = "edge/worker.ts"
[vars]
BACKEND_URL = "https://api.your-domain.com"
[[kv_namespaces]]
binding = "CACHE"
id = "your-kv-namespace-id"
4. Deploy
Cache Strategie
TTL pro Route
| Route Pattern | TTL | Grund |
|---|---|---|
/api/properties |
1h | Statisch |
/api/contracts |
30min | Selten geΓ€ndert |
/api/integrations/evcc/* |
10s | Realtime |
/api/integrations/sevdesk/* |
10min | Rate Limits |
Cache Invalidation
Optionen fΓΌr Cache-Invalidierung:
- TTL Expiry - Automatisch nach TTL
- API Call - Worker Endpoint
/cache/purge - KV API - Direkt ΓΌber Wrangler CLI
Monitoring
Headers prΓΌfen
Wrangler Logs
Best Practices
Stale-While-Revalidate
FΓΌr bessere UX: Alte Daten sofort liefern, im Hintergrund refreshen.
Keine sensitiven Daten cachen
User-spezifische Daten nie am Edge cachen!
Cache Key Design
Tenant-ID in Cache Key einbauen fΓΌr Multi-Tenant Isolation.