Cloudflare Workers: serverless chạy ở edge, cold start dưới 1ms - developer cần biết năm 2026

Cloudflare Workers chạy JavaScript/TypeScript trực tiếp ở 330+ data center toàn cầu - không phải trên một server cố định. Dùng V8 isolates (cùng engine Chrome) thay vì container, nên không có cold start. Free tier: 100,000 requests/ngày. Phù hợp cho API nhẹ, middleware, proxy, A/B testing, và bất kỳ logic nào cần latency thấp. ---

Vấn đề với serverless truyền thống

AWS Lambda, Azure Functions - serverless tốt nhưng có vấn đề:

Cold start. Lần đầu invoke sau khi idle, function cần khởi động container → latency tăng 200–2000ms. User thấy timeout, developer bực bội.

Single region. Function deploy ở một region (us-east-1). User ở Việt Nam request đến us-east-1, chịu thêm latency network xuyên lục địa.

Pricing model phức tạp. Tính theo GB-seconds, invocations, data transfer - khó predict cost.

Cloudflare Workers giải quyết cả ba:

  • Không cold start - V8 isolates start trong microseconds, không phải giây
  • Global by default - deploy một lần, chạy ở 330+ location gần user nhất
  • Giá đơn giản - 100k requests/ngày free, sau đó $0.50/triệu requests

Workers hoạt động thế nào

User (Hà Nội) → Cloudflare Edge HAN (Singapore/HCM)
              → Worker code chạy tại đây
              → Response trả về ngay từ edge
              (không cần về origin server)

Workers dùng V8 Isolates - mỗi request chạy trong một isolate riêng, lightweight hơn container nhiều lần. Isolate spin up trong < 1ms, không có cold start theo nghĩa truyền thống.

Mỗi Worker có giới hạn:

  • CPU time: 10ms (free) / 30s (paid)
  • Memory: 128MB
  • Không có filesystem access (dùng KV, R2 thay thế)
  • Không hỗ trợ Node.js built-in modules (dùng Workers-compatible alternatives)

Hello World: Worker đầu tiên

Dùng Wrangler CLI (tool chính thức của Cloudflare):

# Cài Wrangler
npm install -g wrangler

# Login
wrangler login

# Tạo project mới
npm create cloudflare@latest my-worker
cd my-worker

File src/index.ts mặc định:

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    const url = new URL(request.url);
    
    return new Response(JSON.stringify({
      message: "Hello from Cloudflare Workers!",
      path: url.pathname,
      region: request.cf?.region,
      city: request.cf?.city,
    }), {
      headers: { "Content-Type": "application/json" },
    });
  },
};

Deploy:

wrangler deploy
# → https://my-worker.yoursubdomain.workers.dev

Cloudflare Workers tự động trả về thông tin geo của request qua request.cf - city, country, region, timezone, ASN. Không cần GeoIP service ngoài.


Use case 1: API middleware / proxy

Worker đứng trước API origin - xử lý auth, rate limit, transform response:

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // 1. Validate API key
    const apiKey = request.headers.get("X-API-Key");
    if (!apiKey || apiKey !== env.VALID_API_KEY) {
      return new Response("Unauthorized", { status: 401 });
    }

    // 2. Forward đến origin với header thêm vào
    const modifiedRequest = new Request(request, {
      headers: {
        ...Object.fromEntries(request.headers),
        "X-Forwarded-By": "cloudflare-worker",
        "X-User-Country": request.cf?.country ?? "unknown",
      },
    });

    const response = await fetch(`https://api.origin.com${new URL(request.url).pathname}`, modifiedRequest);

    // 3. Thêm CORS header vào response
    const modifiedResponse = new Response(response.body, response);
    modifiedResponse.headers.set("Access-Control-Allow-Origin", "*");
    modifiedResponse.headers.set("X-Cache-Status", "worker-proxy");

    return modifiedResponse;
  },
};

Use case 2: A/B testing ở edge

Thay vì A/B testing trong JavaScript client (gây layout shift), làm ở edge:

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    
    // Chỉ A/B test trang chủ
    if (url.pathname !== "/") {
      return fetch(request);
    }

    // Assign variant dựa trên cookie, hoặc random
    let variant = request.headers.get("Cookie")?.match(/ab_variant=([ab])/)?.[1];
    
    if (!variant) {
      variant = Math.random() < 0.5 ? "a" : "b";
    }

    // Fetch variant tương ứng
    const targetUrl = variant === "b" 
      ? "https://origin.com/landing-v2" 
      : "https://origin.com/landing-v1";
    
    const response = await fetch(new Request(targetUrl, request));
    
    // Set cookie để giữ variant nhất quán
    const newResponse = new Response(response.body, response);
    if (!request.headers.get("Cookie")?.includes("ab_variant")) {
      newResponse.headers.append("Set-Cookie", `ab_variant=${variant}; Path=/; Max-Age=86400`);
    }

    return newResponse;
  },
};

Workers Storage: KV, D1, R2

Workers không có filesystem - dùng storage services của Cloudflare:

KV (Key-Value Store)

Phù hợp: config, session, feature flags, cache layer.

// Đọc
const value = await env.MY_KV.get("config:feature-flags");

// Ghi với TTL
await env.MY_KV.put("session:abc123", JSON.stringify(userData), {
  expirationTtl: 3600 // 1 giờ
});

D1 (SQLite Database)

Phù hợp: dữ liệu có quan hệ, query SQL.

const { results } = await env.DB.prepare(
  "SELECT * FROM articles WHERE published = 1 ORDER BY created_at DESC LIMIT ?"
).bind(10).all();

R2 (Object Storage)

Phù hợp: file upload, static assets, backup.

// Upload file
await env.MY_BUCKET.put("uploads/image.jpg", request.body, {
  httpMetadata: { contentType: "image/jpeg" }
});

// Lấy file
const object = await env.MY_BUCKET.get("uploads/image.jpg");
return new Response(object?.body);

So sánh: Workers vs Lambda vs Vercel Functions

Tiêu chí Cloudflare Workers AWS Lambda Vercel Functions
Cold start < 1ms (isolates) 100–2000ms 50–500ms
Locations 330+ global ~30 regions ~70 locations
Free tier 100k req/ngày 1M req/tháng 100GB-hrs
CPU limit 10ms (free) 15 min 10s
Node.js compat Partial Full Full
Giá sau free $0.50/M req ~$0.20/M req Usage-based
Ecosystem Workers-specific AWS-native Next.js-focused

Workers phù hợp nhất khi: latency là ưu tiên, không cần heavy computation, dùng ít Node.js built-in APIs.


Routing với Hono framework

Hono là framework routing nhẹ, chuẩn cho Workers năm 2026:

import { Hono } from "hono";
import { cors } from "hono/cors";
import { bearerAuth } from "hono/bearer-auth";

const app = new Hono<{ Bindings: Env }>();

app.use("/*", cors());
app.use("/api/*", bearerAuth({ token: (c) => c.env.API_TOKEN }));

app.get("/api/products", async (c) => {
  const { results } = await c.env.DB.prepare("SELECT * FROM products").all();
  return c.json(results);
});

app.post("/api/products", async (c) => {
  const body = await c.req.json();
  await c.env.DB.prepare("INSERT INTO products (name, price) VALUES (?, ?)")
    .bind(body.name, body.price)
    .run();
  return c.json({ success: true }, 201);
});

export default app;

Kết

Cloudflare Workers là bước tiến thực sự trong serverless: không cold start, global by default, free tier rộng, và ecosystem storage (KV, D1, R2) đủ để build full-stack app mà không cần server truyền thống. Phù hợp nhất cho API layer, middleware, proxy, và edge logic nói chung.

Bài tiếp: Cloudflare R2 - object storage S3-compatible không có egress fee, tại sao đây là lý do nhiều team chuyển khỏi AWS S3.


Tham khảo


BKGlobal Tech Team

Blog Công nghệ

Xem tất cả