边缘计算指南

边缘 vs 源站

边缘源站服务器
延迟<50ms 全球100–500ms
内存128MB 典型GB级
运行时V8 isolates (JS/WASM)Node/Go/Python/Java
冷启动<5ms100ms–2s
联网有限(无原始TCP)完整
文件系统

Cloudflare Workers示例

// Cloudflare Workers (runs in 200+ PoPs globally)
export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url)

    // A/B testing at the edge
    if (url.pathname === '/') {
      const variant = Math.random() < 0.5 ? 'A' : 'B'
      const response = await fetch(`https://origin.example.com/?variant=${variant}`)
      return new Response(response.body, {
        headers: {
          ...Object.fromEntries(response.headers),
          'X-AB-Variant': variant,
        }
      })
    }

    // KV store for caching
    const cached = await env.MY_KV.get(url.pathname)
    if (cached) return new Response(cached, { headers: { 'Content-Type': 'application/json' } })

    const data = await fetch('https://api.example.com' + url.pathname).then(r => r.text())
    await env.MY_KV.put(url.pathname, data, { expirationTtl: 3600 })
    return new Response(data)
  }
}

边缘数据库选项

产品类型适合
Cloudflare KVKey-Value配置、会话、缓存数据
Cloudflare D1SQLite边缘关系型数据
TursoLibSQL/SQLite地理分布式SQLite
Upstash RedisRedis限流、发布订阅
Deno KVKey-ValueDeno Deploy应用
PlanetScaleMySQL分支、全球读取