본문으로 건너뛰기
Previous
Next
Complete Cloudflare Workers Complete Guide | Edge Computing

Complete Cloudflare Workers Complete Guide | Edge Computing

Complete Cloudflare Workers Complete Guide | Edge Computing

이 글의 핵심

Complete guide to implementing edge computing with Cloudflare Workers. From serverless functions, KV storage, D1 database to Wrangler with practical exa...

Key Takeaways

Complete guide to implementing edge computing with Cloudflare Workers. From serverless functions, KV storage, D1 database to Wrangler with practical examples.

Real-World Experience: Sharing experience of switching from AWS Lambda to Cloudflare Workers, reducing response time from 200ms to 20ms and achieving 70% cost savings.

Introduction: “Serverless Is Slow”

Real-World Problem Scenarios

Scenario 1: Long Cold Start
Lambda is slow. Workers is 0ms. Scenario 2: Difficult Global Deployment
Region setup is complex. Workers automatically deploys worldwide. Scenario 3: High Costs
Lambda is expensive. Workers is free for 100K requests.

1. What is Cloudflare Workers?

Core Features

Cloudflare Workers is an edge serverless platform. Key Advantages:

  • 0ms Cold Start: Instant execution
  • Global Deployment: 300+ cities
  • Fast Speed: Average 20ms
  • Low Cost: 100K requests free
  • V8 Isolates: Lightweight execution environment

2. Project Setup

Installation

npm create cloudflare@latest

wrangler.toml

Here’s an implementation example using TOML. Try running the code directly to see how it works.

name = "my-worker"
main = "src/index.ts"
compatibility_date = "2024-01-01"
[vars]
ENVIRONMENT = "production"

3. Basic Worker

Hello World

Here’s an implementation example using TypeScript. Perform tasks efficiently with async processing. Try running the code directly to see how it works.

// src/index.ts
export default {
  async fetch(request: Request): Promise<Response> {
    return new Response('Hello Cloudflare Workers!');
  },
};

Routing

Here’s a detailed implementation using TypeScript. Perform tasks efficiently with async processing, perform branching with conditionals. Please review the code to understand the role of each part.

export default {
  async fetch(request: Request): Promise<Response> {
    const url = new URL(request.url);
    if (url.pathname === '/') {
      return new Response('Home');
    }
    if (url.pathname === '/api/users') {
      return Response.json([
        { id: 1, name: 'John' },
        { id: 2, name: 'Jane' },
      ]);
    }
    return new Response('Not Found', { status: 404 });
  },
};

4. KV (Key-Value Storage)

Setup

Here’s a simple TOML code example. Try running the code directly to see how it works.

# wrangler.toml
[[kv_namespaces]]
binding = "MY_KV"
id = "your-kv-id"

Usage

Here’s a detailed implementation using TypeScript. Define classes to encapsulate data and functionality, perform tasks efficiently with async processing, perform branching with conditionals. Please review the code to understand the role of each part.

interface Env {
  MY_KV: KVNamespace;
}
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    // Read
    if (url.pathname === '/api/cache') {
      const value = await env.MY_KV.get('key');
      return Response.json({ value });
    }
    // Write
    if (url.pathname === '/api/cache' && request.method === 'POST') {
      const { key, value } = await request.json();
      await env.MY_KV.put(key, value, { expirationTtl: 3600 });
      return Response.json({ success: true });
    }
    return new Response('Not Found', { status: 404 });
  },
};

5. D1 (SQL Database)

Setup

wrangler d1 create my-database

Here’s an implementation example using TOML. Try running the code directly to see how it works.

# wrangler.toml
[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "your-db-id"

Migration

Here’s an implementation example using SQL. Try running the code directly to see how it works.

-- migrations/0001_create_users.sql
CREATE TABLE users (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  email TEXT UNIQUE NOT NULL,
  name TEXT,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
wrangler d1 migrations apply my-database

Usage

Here’s a detailed implementation using TypeScript. Define classes to encapsulate data and functionality, perform tasks efficiently with async processing, perform branching with conditionals. Please review the code to understand the role of each part.

interface Env {
  DB: D1Database;
}
export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    if (url.pathname === '/api/users') {
      const { results } = await env.DB.prepare('SELECT * FROM users').all();
      return Response.json(results);
    }
    if (url.pathname === '/api/users' && request.method === 'POST') {
      const { email, name } = await request.json();
      await env.DB.prepare('INSERT INTO users (email, name) VALUES (?, ?)')
        .bind(email, name)
        .run();
      return Response.json({ success: true }, { status: 201 });
    }
    return new Response('Not Found', { status: 404 });
  },
};

6. Caching

Here’s a detailed implementation using TypeScript. Perform tasks efficiently with async processing, perform branching with conditionals. Please review the code to understand the role of each part.

export default {
  async fetch(request: Request): Promise<Response> {
    const cache = caches.default;
    let response = await cache.match(request);
    if (!response) {
      response = await fetch('https://api.example.com/data');
      response = new Response(response.body, response);
      response.headers.set('Cache-Control', 's-maxage=3600');
      await cache.put(request, response.clone());
    }
    return response;
  },
};

7. Deployment

Local Development

wrangler dev

Production Deployment

wrangler deploy

Summary and Checklist

Key Summary

  • Cloudflare Workers: Edge serverless
  • 0ms Cold Start: Instant execution
  • Global Deployment: 300+ cities
  • KV: Key-Value storage
  • D1: SQL database
  • Low Cost: 100K requests free

Implementation Checklist

  • Create Cloudflare account
  • Install Wrangler
  • Write Worker
  • Set up KV
  • Set up D1
  • Local testing
  • Deploy

  • Complete AWS Lambda Guide
  • Complete Vercel Guide
  • Edge Computing Guide

Keywords Covered

Cloudflare Workers, Edge Computing, Serverless, KV, D1, Backend, Performance

Frequently Asked Questions (FAQ)

Q. How does it compare to AWS Lambda?

A. Workers is much faster and cheaper. Lambda provides more runtimes and integrations.

Q. Can I use Node.js APIs?

A. Limited. Must use libraries compatible with Web API.

Q. Can I use it for free?

A. Yes, free up to 100K requests/day.

Q. Is it safe to use in production?

A. Yes, many companies like Discord and Shopify use it.


자주 묻는 질문 (FAQ)

Q. 이 내용을 실무에서 언제 쓰나요?

A. Complete guide to implementing edge computing with Cloudflare Workers. From serverless functions, KV storage, D1 databas… 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.

Q. 선행으로 읽으면 좋은 글은?

A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. C++ 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.

Q. 더 깊이 공부하려면?

A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.


이 글에서 다루는 키워드 (관련 검색어)

Cloudflare Workers, Edge Computing, Serverless, KV, D1, Backend, Performance 등으로 검색하시면 이 글이 도움이 됩니다.