SiamCafe.net Blog
Technology

Netlify Edge Metric Collection

netlify edge metric collection
Netlify Edge Metric Collection | SiamCafe Blog
2025-10-31· อ. บอม — SiamCafe.net· 8,522 คำ

Netlify Edge Metrics

Netlify Edge CDN Edge Functions Metrics Analytics Performance Monitoring Core Web Vitals Cache Optimization

MetricSourceTargetTool
TTFBEdge Server< 200msNetlify Analytics, RUM
Cache Hit RatioCDN Logs> 90%Log Drains, Netlify API
Edge Function DurationFunction Logs< 50msNetlify Dashboard
LCPBrowser (RUM)< 2.5sweb-vitals, Lighthouse
Error RateAccess Logs< 0.1%Log Drains → Datadog
BandwidthCDNตาม PlanNetlify Dashboard

Edge Functions & Logging

// === Netlify Edge Function with Metrics ===

// netlify/edge-functions/metrics.ts
// import type { Context } from "https://edge.netlify.com";
//
// export default async (request: Request, context: Context) => {
//   const start = Date.now();
//   const url = new URL(request.url);
//   const geo = context.geo;
//   
//   // Get response from origin
//   const response = await context.next();
//   const duration = Date.now() - start;
//   
//   // Log metrics
//   console.log(JSON.stringify({
//     timestamp: new Date().toISOString(),
//     path: url.pathname,
//     method: request.method,
//     status: response.status,
//     duration_ms: duration,
//     country: geo.country?.code || "unknown",
//     city: geo.city || "unknown",
//     user_agent: request.headers.get("user-agent"),
//     cache_status: response.headers.get("x-nf-request-id") ? "HIT" : "MISS",
//   }));
//   
//   // Add custom headers
//   response.headers.set("X-Response-Time", `ms`);
//   response.headers.set("X-Edge-Location", geo.country?.code || "unknown");
//   
//   return response;
// };
//
// // Edge function config
// export const config = { path: "/*" };

// netlify.toml config
// [[edge_functions]]
//   function = "metrics"
//   path = "/*"
//
// [build]
//   command = "npm run build"
//   publish = "dist"
//
// [[headers]]
//   for = "/assets/*"
//   [headers.values]
//     Cache-Control = "public, max-age=31536000, immutable"
//
// [[headers]]
//   for = "/*.html"
//   [headers.values]
//     Cache-Control = "public, max-age=0, must-revalidate"

console.log("=== Edge Function Metrics ===");
console.log("  Logs: JSON structured to console.log");
console.log("  Fields: path, method, status, duration_ms, country, cache");
console.log("  Drain: Netlify Log Drains → Datadog/S3");

Monitoring Dashboard

# === Monitoring Setup ===

from dataclasses import dataclass

@dataclass
class MonitorPanel:
    panel: str
    data_source: str
    query: str
    alert: str
    visualization: str

panels = [
    MonitorPanel("Edge Response Time",
        "Log Drains → Datadog/Grafana",
        "avg(duration_ms) by path, p50 p95 p99",
        "> 500ms p99 → Warning, > 1s → Critical",
        "Time Series: percentile lines"),
    MonitorPanel("Cache Hit Ratio",
        "CDN Logs / Netlify API",
        "count(cache_status=HIT) / count(*) * 100",
        "< 80% → Warning, < 60% → Critical",
        "Gauge: current ratio + trend"),
    MonitorPanel("Geographic Distribution",
        "Edge Function Logs (geo.country)",
        "count(*) group by country",
        "N/A (informational)",
        "World Map: traffic heatmap"),
    MonitorPanel("Error Rate by Status",
        "Access Logs",
        "count(status >= 400) / count(*) * 100",
        "> 1% 4xx → Warning, > 0.1% 5xx → Critical",
        "Stacked Bar: 4xx vs 5xx over time"),
    MonitorPanel("Core Web Vitals",
        "RUM (web-vitals library)",
        "LCP p75, FID p75, CLS p75",
        "LCP > 2.5s, FID > 100ms, CLS > 0.1 → Warning",
        "Gauge: Good/Needs Improvement/Poor"),
    MonitorPanel("Build & Deploy",
        "Netlify API / Webhooks",
        "build_time, deploy_time, success_rate",
        "Build Time > 5min → Warning, Failure → Critical",
        "Line Chart: build time trend"),
]

print("=== Dashboard Panels ===")
for p in panels:
    print(f"  [{p.panel}] Source: {p.data_source}")
    print(f"    Query: {p.query}")
    print(f"    Alert: {p.alert}")
    print(f"    Viz: {p.visualization}")

Optimization

# === Performance Optimization ===

@dataclass
class Optimization:
    area: str
    technique: str
    config: str
    impact: str

optimizations = [
    Optimization("Cache Headers",
        "Long cache for static, no-cache for HTML",
        "Cache-Control: public, max-age=31536000, immutable (assets)",
        "Cache Hit Ratio 80% → 95%+ ลด Bandwidth 50-70%"),
    Optimization("Image Optimization",
        "Netlify Large Media / next/image / sharp",
        "[build.processing.images] compress = true",
        "ลดขนาดภาพ 40-70% ลด LCP 0.5-2s"),
    Optimization("Minification",
        "Minify HTML CSS JS",
        "[build.processing] skip_processing = false",
        "ลดขนาด 10-30% ลด Transfer Time"),
    Optimization("Preload Critical",
        "Preload fonts CSS above-the-fold",
        "Link: ; rel=preload; as=font",
        "ลด FCP 100-300ms"),
    Optimization("Code Splitting",
        "Lazy load routes components",
        "React.lazy() + Suspense, Dynamic import()",
        "ลด Initial Bundle 40-60%"),
    Optimization("Edge Redirect",
        "Redirect ที่ Edge ไม่ต้องไป Origin",
        "_redirects file หรือ netlify.toml [[redirects]]",
        "Redirect < 10ms แทน 100ms+"),
]

print("=== Optimizations ===")
for o in optimizations:
    print(f"  [{o.area}] {o.technique}")
    print(f"    Config: {o.config}")
    print(f"    Impact: {o.impact}")

เคล็ดลับ

การนำไปใช้งานจริงในองค์กร

สำหรับองค์กรขนาดกลางถึงใหญ่ แนะนำให้ใช้หลัก Three-Tier Architecture คือ Core Layer ที่เป็นแกนกลางของระบบ Distribution Layer ที่ทำหน้าที่กระจาย Traffic และ Access Layer ที่เชื่อมต่อกับผู้ใช้โดยตรง การแบ่ง Layer ชัดเจนช่วยให้การ Troubleshoot ง่ายขึ้นและสามารถ Scale ระบบได้ตามความต้องการ

เรื่อง Network Security ก็สำคัญไม่แพ้กัน ควรติดตั้ง Next-Generation Firewall ที่สามารถ Deep Packet Inspection ได้ ใช้ Network Segmentation แยก VLAN สำหรับแต่ละแผนก ติดตั้ง IDS/IPS เพื่อตรวจจับการโจมตี และทำ Regular Security Audit อย่างน้อยปีละ 2 ครั้ง

Netlify Edge คืออะไร

CDN Edge Computing Edge Functions Deno Runtime A/B Testing Personalization Geolocation Cache HTTP/2 HTTP/3 Brotli Global Network

Metric อะไรที่ต้องเก็บ

TTFB LCP FCP CLS Core Web Vitals Bandwidth Cache Hit Ratio Edge Function Duration Error Rate Geographic Build Time Deploy

เก็บ Metric อย่างไร

Netlify Analytics Server-side Log Drains Datadog S3 API REST Edge Function Custom Log RUM web-vitals Google Analytics Synthetic Checkly

Optimize อย่างไร

Cache Headers immutable Image Optimization Minify Preload Code Splitting Edge Redirect Bundle Size Tree Shaking Lazy Loading Custom Headers

สรุป

Netlify Edge Metric Collection CDN Edge Functions Analytics Cache Hit Ratio Core Web Vitals Log Drains RUM Optimization Production

📖 บทความที่เกี่ยวข้อง

Netlify Edge IoT Gatewayอ่านบทความ → MySQL Replication Metric Collectionอ่านบทความ → Netlify Edge Progressive Deliveryอ่านบทความ → Netlify Edge High Availability HA Setupอ่านบทความ → Supabase Realtime Metric Collectionอ่านบทความ →

📚 ดูบทความทั้งหมด →