🏗️ Architecture

Edge Function

Edge Function

A serverless function that runs on edge servers. Code runs at hundreds of PoPs (Points of Presence) worldwide, delivering ultra-low-latency responses from the location closest to the user.

📖 Detailed Explanation

How Edge Functions Work differs from traditional serverless. AWS Lambda runs only in a specific region (e.g., ap-northeast-2), whereas Edge Functions are deployed and run simultaneously at more than 200 edge locations worldwide. User requests are routed to the nearest edge via DNS.

V8 Isolate-based execution is the core technology. Cloudflare Workers and Deno Deploy use Isolates of the Chrome V8 engine. Because they run in a lightweight isolated environment instead of a container or VM, cold starts are close to 0ms. Compared with the 100-500ms cold starts of traditional Lambda, this is a dramatic difference.

The restricted runtime environment must be understood. Most Edge Functions support only Web APIs (fetch, Request, Response, crypto, etc.). System APIs such as Node.js's fs, net, and child_process cannot be used. This is an intentional design for security and performance.

The way state is managed is distinctive. Edge functions are stateless by default, but state can be managed through edge-specific storage such as KV Store (Cloudflare KV), Durable Objects, and Edge Config (Vercel). These are replicated globally and accessible from any edge.

The main use cases are diverse. They include A/B testing (per-request bucket assignment), authentication/authorization (JWT verification), localization (country-specific content), image optimization (resizing, format conversion), bot defense (CAPTCHA insertion), and API gateways (rate limiting, request transformation).

💻 Code Example

// Cloudflare Workers - 완전한 API 예제
// wrangler.toml과 함께 배포

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);

    // 라우팅
    switch (url.pathname) {
      case '/api/geo':
        return handleGeo(request);
      case '/api/kv':
        return handleKV(request, env);
      case '/api/cache':
        return handleCache(request, ctx);
      default:
        return new Response('Not Found', { status: 404 });
    }
  },
};

// 1. 지리 정보 기반 응답
function handleGeo(request) {
  const cf = request.cf || {};

  const geoData = {
    ip: request.headers.get('CF-Connecting-IP'),
    country: cf.country,
    city: cf.city,
    region: cf.region,
    timezone: cf.timezone,
    latitude: cf.latitude,
    longitude: cf.longitude,
    asn: cf.asn,
    colo: cf.colo, // 엣지 데이터센터 코드
  };

  return Response.json(geoData, {
    headers: {
      'Cache-Control': 'private, no-store',
    },
  });
}

// 2. KV Store 활용 - 글로벌 키-값 저장소
async function handleKV(request, env) {
  const url = new URL(request.url);
  const key = url.searchParams.get('key');

  if (request.method === 'GET') {
    // KV에서 읽기 (전 세계 엣지에 캐시됨)
    const value = await env.MY_KV.get(key, { type: 'json' });

    if (!value) {
      return Response.json({ error: 'Key not found' }, { status: 404 });
    }

    return Response.json({
      key,
      value,
      source: 'edge-kv',
    });
  }

  if (request.method === 'PUT') {
    const body = await request.json();

    // KV에 쓰기 (60초 후 전 세계 동기화)
    await env.MY_KV.put(key, JSON.stringify(body), {
      expirationTtl: 3600, // 1시간 후 만료
      metadata: { updatedAt: Date.now() },
    });

    return Response.json({ success: true, key });
  }

  return new Response('Method not allowed', { status: 405 });
}

// 3. Cache API 활용 - 응답 캐싱
async function handleCache(request, ctx) {
  const cache = caches.default;
  const cacheKey = new Request(request.url, request);

  // 캐시 확인
  let response = await cache.match(cacheKey);

  if (response) {
    // 캐시 HIT - 새 헤더 추가하여 반환
    const newHeaders = new Headers(response.headers);
    newHeaders.set('X-Cache', 'HIT');
    return new Response(response.body, {
      status: response.status,
      headers: newHeaders,
    });
  }

  // 캐시 MISS - 오리진에서 가져오기
  const originResponse = await fetch('https://api.example.com/data');
  const data = await originResponse.json();

  response = Response.json(data, {
    headers: {
      'Cache-Control': 'public, max-age=60',
      'X-Cache': 'MISS',
    },
  });

  // 백그라운드에서 캐시 저장
  ctx.waitUntil(cache.put(cacheKey, response.clone()));

  return response;
}
// Deno Deploy - Edge Function 예제
// deploy: deployctl deploy --project=my-app main.ts

import { serve } from "https://deno.land/std@0.208.0/http/server.ts";

// KV Store (Deno KV - 전역 분산 데이터베이스)
const kv = await Deno.openKv();

serve(async (request: Request) => {
  const url = new URL(request.url);

  // 라우팅
  if (url.pathname === "/api/counter") {
    return handleCounter(request);
  }

  if (url.pathname === "/api/user") {
    return handleUser(request);
  }

  if (url.pathname === "/api/stream") {
    return handleStream();
  }

  return new Response("Hello from Deno Deploy!", {
    headers: { "Content-Type": "text/plain" },
  });
});

// 1. Atomic Counter with Deno KV
async function handleCounter(request: Request): Promise {
  const key = ["counters", "visits"];

  if (request.method === "POST") {
    // Atomic increment - 동시성 안전
    const result = await kv.atomic()
      .sum(key, 1n) // BigInt로 카운트
      .commit();

    if (!result.ok) {
      return Response.json({ error: "Conflict" }, { status: 409 });
    }
  }

  // 현재 값 읽기
  const entry = await kv.get(key);
  const count = entry.value?.value ?? 0n;

  return Response.json({
    count: count.toString(),
    timestamp: new Date().toISOString(),
  });
}

// 2. 사용자 세션 관리
async function handleUser(request: Request): Promise {
  const url = new URL(request.url);
  const userId = url.searchParams.get("id");

  if (!userId) {
    return Response.json({ error: "Missing user ID" }, { status: 400 });
  }

  const key = ["users", userId];

  if (request.method === "GET") {
    const entry = await kv.get(key);

    if (!entry.value) {
      return Response.json({ error: "User not found" }, { status: 404 });
    }

    return Response.json(entry.value);
  }

  if (request.method === "PUT") {
    const body = await request.json();

    await kv.set(key, {
      ...body,
      updatedAt: Date.now(),
    }, {
      expireIn: 24 * 60 * 60 * 1000, // 24시간 후 만료
    });

    return Response.json({ success: true });
  }

  return new Response("Method not allowed", { status: 405 });
}

// 3. Streaming Response - 실시간 데이터
function handleStream(): Response {
  const encoder = new TextEncoder();

  const stream = new ReadableStream({
    async start(controller) {
      for (let i = 0; i < 5; i++) {
        const data = {
          event: "update",
          data: { count: i, time: Date.now() },
        };

        controller.enqueue(
          encoder.encode(`data: ${JSON.stringify(data)}\n\n`)
        );

        await new Promise((r) => setTimeout(r, 1000));
      }

      controller.close();
    },
  });

  return new Response(stream, {
    headers: {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
    },
  });
}
┌─────────────────────────────────────────────────────────────────┐
│                   Edge Function 플랫폼 비교                       │
└─────────────────────────────────────────────────────────────────┘

┌──────────────────┬─────────────────┬─────────────────┬──────────────────┐
│      항목        │ Cloudflare      │ Vercel Edge     │ Deno Deploy      │
│                  │ Workers         │ Functions       │                  │
├──────────────────┼─────────────────┼─────────────────┼──────────────────┤
│ 런타임           │ V8 Isolate      │ V8 Isolate      │ V8 Isolate       │
│ 언어             │ JS/TS/WASM      │ JS/TS           │ JS/TS            │
│ 엣지 로케이션    │ 300+            │ 100+            │ 35+              │
│ 콜드 스타트      │ 0ms             │ ~0ms            │ 0ms              │
│ 실행 제한        │ 10-30ms CPU     │ 30s (Pro)       │ 50ms CPU         │
│ 메모리           │ 128MB           │ 128MB           │ 512MB            │
├──────────────────┼─────────────────┼─────────────────┼──────────────────┤
│ 상태 저장소      │ KV, D1, R2      │ Edge Config     │ Deno KV          │
│                  │ Durable Objects │ Vercel KV       │                  │
│ DB 연결          │ Hyperdrive      │ Edge Functions  │ 직접 연결        │
│ 캐싱             │ Cache API       │ Next.js Cache   │ 수동 구현        │
├──────────────────┼─────────────────┼─────────────────┼──────────────────┤
│ 무료 티어        │ 100K req/day    │ 100K req/month  │ 1M req/month     │
│ 가격 (유료)      │ $5/10M req      │ $20/month~      │ $10/5M req       │
└──────────────────┴─────────────────┴─────────────────┴──────────────────┘


콜드 스타트 비교:
┌─────────────────────────────────────────────────────────────────┐
│                                                                  │
│  AWS Lambda          ███████████████████████████  100-500ms     │
│  Lambda@Edge         ██████████████████  50-200ms               │
│  Cloudflare Workers  █  0-5ms                                   │
│  Vercel Edge         █  0-5ms                                   │
│  Deno Deploy         █  0-5ms                                   │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘


Edge Function 적합 사용 사례:

✅ 적합한 경우:
   - 인증/인가 (JWT 검증, API Key 체크)
   - A/B 테스트 (요청별 버킷 할당)
   - 지역화 (국가별 리다이렉트, 언어 감지)
   - 캐시 레이어 (stale-while-revalidate)
   - Bot 감지 및 차단
   - 요청/응답 변환

❌ 부적합한 경우:
   - 복잡한 비즈니스 로직 (CPU 집약적)
   - 대용량 파일 처리
   - 장시간 실행 작업
   - 레거시 Node.js 의존성 필요
   - 데이터베이스 직접 연결 (일부 제한)

🗣️ How It's Said in Practice

💬 In an API Performance Optimization Meeting
"70% of API responses return the same data, so going all the way to Lambda every time is inefficient. If we cache in KV on Cloudflare Workers, we can cut the average response time from 200ms to 20ms. Let's go to the origin only on a cache miss."
💬 In an Authentication System Refactoring
"If we move JWT verification to an edge function, requests that fail authentication never reach the backend. If we verify tokens in Vercel Middleware and return 401 immediately for expired tokens, the server load drops significantly. The jose library works well at the edge too."
💬 In Global Service Planning
"We need to apply different pricing policies by country. If we detect the country with request.cf.country in an edge function and transform the Price API response, we can localize without changing client code, and we can also handle GDPR compliance at the edge."

⚠️ Cautions & Best Practices

❌
Beware of CPU Time Limits

Edge Functions are limited to 10-50ms of CPU time. Complex computation, JSON parsing, encryption, and the like quickly hit the limit. Delegate heavy work to the backend.

❌
No Node.js API Support

Node.js-specific APIs such as fs, net, and child_process cannot be used. Only pure JS npm packages work as well. Be sure to check compatibility before deployment.

❌
Database Connection Limits

Traditional DB connection pooling is not possible. Use edge-friendly solutions such as HTTP-based DBs (PlanetScale, Neon, Supabase), Cloudflare D1, or Deno KV.

✅
Best Practices

Request filtering, cache layers, and authentication checks are the best use cases for the edge. Processing asynchronous tasks in the background with ctx.waitUntil() and caching responses with the Cache API can maximize performance.

🔗 Related Terms

📚 Learn More