본문으로 건너뛰기 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

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

3. Basic Worker

Hello World

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

Routing

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

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

Usage

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
# wrangler.toml
[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "your-db-id"

Migration

-- 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

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

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.


Frequently Asked Questions (FAQ)

Q. When would I use this in practice?

A. Complete guide to implementing edge computing with Cloudflare Workers.

Q. What should I read before this?

A. Follow the previous article or related articles links at the bottom of each post to learn in sequence.

Q. Where can I study this more deeply?

A. Check cppreference and the relevant library’s official documentation. The reference links at the end of the article are also worth using.


Other articles related to this topic.


Keywords Covered in This Article (Related Search Terms)

This article covers Cloudflare Workers, Edge Computing, Serverless, KV, D1, Backend, Performance.