MCP HubMCP Hub
スキル一覧に戻る

edge-computing-patterns

ArieGoldkin
更新日 Today
56 閲覧
5
5
GitHubで表示
その他edgecloudflareverceldenoserverless2025

について

このスキルは、開発者にCloudflare Workers、Vercel Edge、Deno Deployなどのエッジランタイムへアプリケーションをデプロイし、グローバルに分散された低遅延のパフォーマンスを実現する方法を教えます。エッジミドルウェア、ストリーミング、ランタイムの制約内での作業といった必須パターンを網羅しています。50ms未満の遅延が求められるグローバルアプリ、認証、A/Bテスト、ジオルーティング、レスポンス変換にご利用ください。

クイックインストール

Claude Code

推奨
プラグインコマンド推奨
/plugin add https://github.com/ArieGoldkin/ai-agent-hub
Git クローン代替
git clone https://github.com/ArieGoldkin/ai-agent-hub.git ~/.claude/skills/edge-computing-patterns

このコマンドをClaude Codeにコピー&ペーストしてスキルをインストールします

ドキュメント

Edge Computing Patterns

Overview

Edge computing runs code closer to users worldwide, reducing latency from seconds to milliseconds. This skill covers Cloudflare Workers, Vercel Edge Functions, and Deno Deploy patterns for building globally distributed applications.

When to use this skill:

  • Global applications requiring <50ms latency
  • Authentication/authorization at the edge
  • A/B testing and feature flags
  • Geo-routing and localization
  • API rate limiting and DDoS protection
  • Transforming responses (image optimization, HTML rewriting)

Platform Comparison

FeatureCloudflare WorkersVercel EdgeDeno Deploy
Cold Start<1ms<10ms<10ms
Locations300+100+35+
RuntimeV8 IsolatesV8 IsolatesDeno
Max Duration30s (paid: unlimited)25s50ms-5min
Free Tier100k req/day100k req/month100k req/month

Cloudflare Workers

// worker.ts
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url)

    // Geo-routing
    const country = request.cf?.country || 'US'

    if (url.pathname === '/api/hello') {
      return new Response(JSON.stringify({
        message: `Hello from ${country}!`
      }), {
        headers: { 'Content-Type': 'application/json' }
      })
    }

    // Cache API
    const cache = caches.default
    let response = await cache.match(request)

    if (!response) {
      response = await fetch(request)
      // Cache for 1 hour
      response = new Response(response.body, response)
      response.headers.set('Cache-Control', 'max-age=3600')
      await cache.put(request, response.clone())
    }

    return response
  }
}

// Durable Objects for stateful edge
export class Counter {
  private state: DurableObjectState
  private count = 0

  constructor(state: DurableObjectState) {
    this.state = state
  }

  async fetch(request: Request) {
    const url = new URL(request.url)

    if (url.pathname === '/increment') {
      this.count++
      await this.state.storage.put('count', this.count)
    }

    return new Response(JSON.stringify({ count: this.count }))
  }
}

Vercel Edge Functions

// middleware.ts (Edge Middleware)
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
  // A/B testing
  const bucket = Math.random() < 0.5 ? 'a' : 'b'
  const url = request.nextUrl.clone()
  url.searchParams.set('bucket', bucket)

  // Geo-location
  const country = request.geo?.country || 'US'

  const response = NextResponse.rewrite(url)
  response.cookies.set('bucket', bucket)
  response.headers.set('X-Country', country)

  return response
}

export const config = {
  matcher: '/experiment/:path*'
}

// Edge API Route
export const runtime = 'edge'

export async function GET(request: Request) {
  return new Response(JSON.stringify({
    timestamp: Date.now(),
    region: process.env.VERCEL_REGION
  }))
}

Edge Runtime Constraints

✅ Available:

  • fetch, Request, Response, Headers
  • URL, URLSearchParams
  • TextEncoder, TextDecoder
  • ReadableStream, WritableStream
  • crypto, SubtleCrypto
  • Web APIs (atob, btoa, setTimeout, etc.)

❌ Not Available:

  • Node.js APIs (fs, path, child_process)
  • Native modules
  • Some npm packages
  • File system access

Common Patterns

Authentication at Edge

import { verify } from '@tsndr/cloudflare-worker-jwt'

export default {
  async fetch(request: Request, env: Env) {
    const token = request.headers.get('Authorization')?.replace('Bearer ', '')

    if (!token) {
      return new Response('Unauthorized', { status: 401 })
    }

    const isValid = await verify(token, env.JWT_SECRET)
    if (!isValid) {
      return new Response('Invalid token', { status: 403 })
    }

    // Proceed with authenticated request
    return fetch(request)
  }
}

Rate Limiting

export default {
  async fetch(request: Request, env: Env) {
    const ip = request.headers.get('CF-Connecting-IP')
    const key = `ratelimit:${ip}`

    // Use KV for rate limiting
    const count = await env.KV.get(key)
    const currentCount = count ? parseInt(count) : 0

    if (currentCount >= 100) {
      return new Response('Rate limit exceeded', { status: 429 })
    }

    await env.KV.put(key, (currentCount + 1).toString(), {
      expirationTtl: 60 // 1 minute
    })

    return fetch(request)
  }
}

Edge Caching

async function handleRequest(request: Request) {
  const cache = caches.default
  const cacheKey = new Request(request.url, request)

  // Try cache first
  let response = await cache.match(cacheKey)

  if (!response) {
    // Fetch from origin
    response = await fetch(request)

    // Cache successful responses
    if (response.status === 200) {
      response = new Response(response.body, response)
      response.headers.set('Cache-Control', 'max-age=3600')
      await cache.put(cacheKey, response.clone())
    }
  }

  return response
}

Best Practices

  • ✅ Keep bundles small (<1MB)
  • ✅ Use streaming for large responses
  • ✅ Leverage edge caching (KV, Durable Objects)
  • ✅ Handle errors gracefully (edge errors can't be recovered)
  • ✅ Test cold starts and warm starts
  • ✅ Monitor edge function performance
  • ✅ Use environment variables for secrets
  • ✅ Implement proper CORS headers

Resources

GitHub リポジトリ

ArieGoldkin/ai-agent-hub
パス: skills/edge-computing-patterns

関連スキル

ai-native-development

メタ

This skill teaches developers to build AI-first applications using RAG pipelines, vector databases, and agentic workflows. It covers essential techniques like prompt engineering, function calling, and cost optimization for modern AI development. Use it when creating chatbots, semantic search systems, or AI agents that integrate with LLMs.

スキルを見る

type-safety-validation

メタ

This skill enables end-to-end type safety across your entire application stack using Zod, tRPC, Prisma, and TypeScript. It ensures type safety from database operations through API layers to UI components, catching errors at compile time rather than runtime. Use it when building full-stack applications that require robust validation and type-safe data flow.

スキルを見る

streaming-api-patterns

開発

This skill teaches implementation of real-time data streaming using SSE, WebSockets, and ReadableStream APIs. It focuses on critical production concerns like backpressure handling, reconnection strategies, and LLM streaming. Use it for building ChatGPT-style interfaces, live notifications, chat apps, and other 2025+ real-time applications.

スキルを見る

react-server-components-framework

デザイン

This skill teaches developers to implement React Server Components using Next.js 15's App Router. It focuses on server-first architecture, streaming SSR, Server Actions, and modern data fetching patterns. Use it when building Next.js 15+ applications to master component boundaries and server-side mutations.

スキルを見る