Edge Computing
Edge Computing
A distributed computing paradigm that performs computation close to the data source. Processing at the network edge instead of sending data to a central data center reduces latency and saves bandwidth.
Edge Computing
A distributed computing paradigm that performs computation close to the data source. Processing at the network edge instead of sending data to a central data center reduces latency and saves bandwidth.
The core principle of Edge Computing is "process data where it is generated." In the traditional cloud model, all data is sent to a central data center for processing, whereas in edge computing, data is processed close to the user (CDN nodes, IoT gateways, base stations, etc.).
Reduced latency is the biggest advantage. A round trip from Seoul to a data center in the United States takes 100-200ms, but processing on an edge server in Seoul reduces this to 10-20ms. It is essential for latency-sensitive services such as real-time gaming, video conferencing, and autonomous driving.
Lower bandwidth costs are also an important benefit. When IoT sensors generate thousands of data points per second, sending all of the data to the cloud causes costs to surge. If you filter and aggregate at the edge and then send only summary data, you can cut network costs by more than 90%.
It provides offline processing capability. Even in factories, ships, and remote locations with unstable network connections, edge devices can operate independently. When the connection is restored, the data is synchronized.
Use cases are diverse. CDNs (Cloudflare, Akamai) cache static content at the edge and also perform dynamic processing with edge functions. In smart factories, sensor data is analyzed in real time to detect defects immediately. Autonomous vehicles process sensor data inside the vehicle and make decisions in milliseconds.
// Cloudflare Workers - 엣지에서 실행되는 코드
// 전 세계 200+ 엣지 로케이션에서 실행
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
// 1. 지역 기반 콘텐츠 제공
const country = request.cf?.country || 'US';
const city = request.cf?.city || 'Unknown';
// 2. 엣지 캐싱 - KV Store 활용
const cacheKey = `content:${country}:${url.pathname}`;
let cachedContent = await env.EDGE_CACHE.get(cacheKey);
if (cachedContent) {
return new Response(cachedContent, {
headers: {
'Content-Type': 'text/html',
'X-Edge-Cache': 'HIT',
'X-Edge-Location': city,
},
});
}
// 3. 캐시 미스 시 오리진 서버 요청
const originResponse = await fetch(`https://origin.example.com${url.pathname}`);
const content = await originResponse.text();
// 4. 엣지에 캐싱 (TTL: 1시간)
ctx.waitUntil(
env.EDGE_CACHE.put(cacheKey, content, { expirationTtl: 3600 })
);
return new Response(content, {
headers: {
'Content-Type': 'text/html',
'X-Edge-Cache': 'MISS',
'X-Edge-Location': city,
},
});
},
};
// wrangler.toml 설정
/*
name = "edge-app"
main = "src/index.js"
compatibility_date = "2024-01-01"
[[kv_namespaces]]
binding = "EDGE_CACHE"
id = "abc123"
*/
// Vercel Edge Functions - Next.js 엣지 런타임
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export const config = {
matcher: ['/api/:path*', '/dashboard/:path*'],
};
export function middleware(request: NextRequest) {
// 엣지에서 실행 - 오리진 서버 도달 전 처리
// 1. 지역 기반 라우팅
const country = request.geo?.country || 'US';
const region = request.geo?.region || 'unknown';
// 2. A/B 테스트 - 쿠키 기반
const bucket = request.cookies.get('ab-bucket')?.value
|| (Math.random() < 0.5 ? 'control' : 'experiment');
// 3. 인증 체크 (엣지에서 빠르게 거부)
const authToken = request.headers.get('Authorization');
if (request.nextUrl.pathname.startsWith('/api/protected')) {
if (!authToken) {
return new NextResponse(
JSON.stringify({ error: 'Unauthorized' }),
{ status: 401, headers: { 'Content-Type': 'application/json' } }
);
}
}
// 4. 요청 헤더 수정
const requestHeaders = new Headers(request.headers);
requestHeaders.set('X-User-Country', country);
requestHeaders.set('X-User-Region', region);
requestHeaders.set('X-AB-Bucket', bucket);
// 5. 응답에 헤더 추가
const response = NextResponse.next({
request: { headers: requestHeaders },
});
// A/B 테스트 쿠키 설정
if (!request.cookies.has('ab-bucket')) {
response.cookies.set('ab-bucket', bucket, {
maxAge: 60 * 60 * 24 * 7, // 1주일
});
}
return response;
}
// app/api/edge-data/route.ts - Edge API Route
import { NextRequest } from 'next/server';
export const runtime = 'edge'; // 엣지에서 실행
export async function GET(request: NextRequest) {
const start = Date.now();
// 엣지에서 가벼운 연산 수행
const data = {
timestamp: new Date().toISOString(),
location: request.geo?.city || 'Unknown',
country: request.geo?.country || 'Unknown',
latency: `${Date.now() - start}ms`,
};
return Response.json(data, {
headers: {
'Cache-Control': 'public, s-maxage=60',
},
});
}
┌─────────────────────────────────────────────────────────────────┐
│ Edge Computing 아키텍처 │
└─────────────────────────────────────────────────────────────────┘
전통적 클라우드 모델:
┌──────────┐ 인터넷 ┌──────────────────┐
│ 사용자 │ ──────────────────▶ │ 중앙 서버 │
│ (서울) │ 100-200ms │ (미국) │
└──────────┘ ◀────────────────── └──────────────────┘
Edge Computing 모델:
┌──────────┐ ┌───────────────┐ ┌──────────────────┐
│ 사용자 │ │ 엣지 서버 │ │ 중앙 서버 │
│ (서울) │───▶│ (서울) │───▶│ (미국) │
└──────────┘ └───────────────┘ └──────────────────┘
│ │ │
10-20ms 캐싱/처리 필요시만 접근
Edge 위치별 역할:
┌─────────────────────────────────────────────────────────────────┐
│ │
│ Device Edge (1-5ms) Network Edge (10-30ms) │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ - IoT 게이트웨이 │ │ - CDN 노드 │ │
│ │ - 스마트폰 앱 │ │ - 5G 기지국 │ │
│ │ - 차량 컴퓨터 │ │ - ISP 엣지 │ │
│ └─────────────────┘ └─────────────────┘ │
│ │
│ Cloud Edge (30-100ms) Central Cloud (100-300ms) │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ - 리전별 POP │ │ - 메인 데이터센터 │ │
│ │ - Edge Function │ │ - 대용량 처리 │ │
│ │ - 캐시 레이어 │ │ - 데이터 저장 │ │
│ └─────────────────┘ └─────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────┘
Edge Computing 사용 사례:
1. 실시간 게임
사용자 ──▶ 엣지서버(10ms) ──▶ 게임 상태 동기화
└─ 히트박스 계산, 충돌 감지
2. 스마트 팩토리
센서 ──▶ 엣지 게이트웨이 ──▶ 클라우드
└─ 불량 감지 └─ 분석/저장
└─ 장비 제어
3. CDN + Edge Functions
요청 ──▶ 엣지 노드 ──▶ 오리진
├─ 캐시 HIT → 즉시 응답
├─ A/B 테스트
└─ 인증 체크
"Response times for users in Southeast Asia are too slow. Even if we put the origin server in Singapore, it takes over 100ms to reach Vietnam and Indonesia. If we cache API responses at the edge with Cloudflare Workers and also handle user authentication at the edge, the perceived speed will be much faster."
"Factory sensors generate 1000 data points per second, and sending all of it to AWS would cost a fortune. If we filter only anomalies at the edge gateway and aggregate normal data in 1-minute intervals before sending, we can reduce bandwidth costs by 95%."
"Lambda@Edge and Cloudflare Workers are both edge computing, but they have different characteristics. Lambda@Edge integrates well with CloudFront, and Workers makes state management easy with KV Store. Since real-time processing matters more than caching for our service, Workers seems like a better fit."
Edge environments have limited resources. Perform complex ML inference or large-scale data processing on the central server, and handle only caching, routing, and simple transformations at the edge.
Hundreds of edge nodes are distributed, which makes state synchronization difficult. Design to be stateless whenever possible, and if state is needed, use edge-specific storage such as KV Store or Durable Objects.
It is impossible to invalidate the caches of edge nodes around the world at the same time. Set the cache TTL appropriately, and do not cache data that requires real-time updates.
Static content caching, authentication/authorization checks, region-based routing, and A/B testing are the best use cases for the edge. Using Workers or Deno Deploy, which have no cold starts, lets you achieve consistently low latency.