Cloudflare Workers: Edge Computing không cần server

Cloudflare Workers là nền tảng edge computing serverless cho phép bạn chạy JavaScript, TypeScript, Python và WebAssembly ngay tại edge — gần người dùng cuối nhất, không phải ở một data center duy nhất. Với hơn 300 locations toàn cầu và V8 isolate-based execution model, Workers khởi động trong chưa đầy 5ms — tức thời so với Lambda hay các platform serverless truyền thống.

Edge computing thay đổi hoàn toàn cách bạn build ứng dụng web. Thay vì server trung tâm ở một vùng địa lý, code chạy tại 300+ cities trên toàn thế giới — request đi thẳng đến location gần nhất, latency giảm đến 50-70% so với traditional serverless.

Cloudflare Workers architecture diagram - V8 isolates trên edge network

Cách Workers hoạt động

Workers không chạy trong containers hay virtual machines. Mỗi request được handle bởi V8 isolate — lightweight execution context của V8 engine (cùng engine Chrome/Node.js). Isolate khởi động gần như instant, sử dụng memory tối thiểu, và giúp Cloudflare xử lý hàng triệu requests trên cùng một server vật lý.

Request lifecycle cơ bản:

  • Request arrives tại Cloudflare edge location gần nhất
  • V8 isolate spins up trong <5ms (cold start gần như bằng 0)
  • Worker script executes, xử lý request logic
  • Response returned đến client — cacheable, có thể serve từ Cloudflare cache
  • Isolate có thể persisted hoặc được destroy tùy platform

Không cần quản lý servers, không cần định nghĩa region, không cần worry về scale-to-zero. Worker code tự động deploy toàn cầu.

Wrangler CLI: Tool chính thức

Wrangler là CLI tool để develop, test và deploy Workers. Cài đặt nhanh chóng:

npm install -g wrangler
# hoặc
npm create cloudflare@latest

Tạo Worker đầu tiên:

wrangler init my-worker --type javascript --git

File src/index.js sẽ trông như sau:

export default {
  async fetch(request, env, ctx) {
    return new Response("Hello from Cloudflare Workers!");
  },
};

Deploy local dev server:

wrangler dev

Deploy lên production:

wrangler deploy

Workers KV: Lưu trữ key-value toàn cầu

Workers KV là key-value store eventual-consistency phục vụ reads cực nhanh — trong vài milliseconds từ bất kỳ edge location nào. Use case phổ biến:

  • Cache API responses
  • Feature flags, A/B testing config
  • Session data không cần persistence mạnh
  • Rate limiting counters
  • Static assets metadata
// Ghi KV
await env.MY_KV.put("config", JSON.stringify({ theme: "dark", version: 2 }));

// Đọc KV
const raw = await env.MY_KV.get("config");
const config = JSON.parse(raw);

// Đọc với metadata (TTL, expiration)
const { value, metadata } = await env.MY_KV.get("config", { type: "json", cacheTtl: 300 });

KV bổ sung cho Workers AI — lưu model prompts, user preferences, cached inference results.

Cloudflare edge network map - 300+ locations worldwide infrastructure

Durable Objects: Trạng thái real-time

Durable Objects là trạng thái persist được đảm bảo strong consistency — điểm khác biệt lớn so với KV. Durable Objects giống như small persistent compute units, mỗi object có unique ID.

Use case phổ biến:

  • WebSocket server — Durable Object quản lý connection, broadcast message
  • Coordination — distributed locks, leader election
  • Gaming backend — room state, matchmaking
  • Real-time collaboration — CRDT merge, presence tracking
// worker.ts
export default {
  async fetch(request, env) {
    const id = env.CHAT_ROOM.idFromName("lobby");
    const room = env.CHAT_ROOM.get(id);
    return room.fetch(request);
  },
};
// chat-room.ts (Durable Object)
export class ChatRoom {
  constructor(state, env) {
    this.state = state;
    this.env = env;
    this.state.blockConcurrencyWhile(async () => {
      this.messages = await this.state.storage.get("messages") || [];
    });
  }

  async fetch(request) {
    const url = new URL(request.url);
    if (url.pathname === "/message") {
      const { text } = await request.json();
      this.messages.push(text);
      await this.state.storage.put("messages", this.messages);
      return new Response("OK");
    }
    return new Response(JSON.stringify(this.messages));
  }
}

D1, R2 và Hyperdrive: Lưu trữ mạnh mẽ

Cloudflare cung cấp đầy đủ storage solutions tại edge:

  • D1 — SQLite-based relational database. Tích hợp với Drizzle ORM, đây là lựa chọn yêu thích cho dự án Next.js tại Việt Nam
  • R2 — Object storage S3-compatible, không có egress fees. Lý tưởng cho lưu trữ static assets lớn
  • Hyperdrive — Connection pooler cho PostgreSQL/MySQL truyền thống, giảm latency kết nối từ edge đến database

So sánh với AWS Lambda và Vercel Edge

Feature Cloudflare Workers AWS Lambda Vercel Edge
Cold start <5ms (V8 isolate) 50-500ms (container) ~100ms
Global edge 300+ locations Single region default ~100 edge locations
Max runtime 30s (Free), 5min (Paid) 15min 25s (Edge), 10min (Serverless)
Pricing model Requests + CPU ms Requests + GB-seconds Requests + GB-seconds
Free tier 100k req/day 1M req/month 125k req/month
Built-in storage KV, D1, R2, Durable Objects S3, DynamoDB, RDS (riêng) Blob, KV, Postgres
Git integration Manual deploy CodePipeline Automatic (Git push)

Chi tiết: Workers Limits, Workers AI blog.

Kết luận

Cloudflare Workers mang đến edge computing đơn giản nhất cho developers: khởi động gần như instant, deploy toàn cầu tự động, tích hợp đầy đủ storage và AI. Kết hợp Workers với Vercel cho frontend, Drizzle ORM cho database, bạn có full-stack application chạy toàn cầu mà không cần server riêng — đúng nghĩa của “bạn code, Cloudflare vận hành”.

Dành cho dự án edge-first hiện đại, Workers là nền tảng không thể bỏ qua. Xem thêm về công nghệ edge và serverless khác trên chuhung.net.

Tôi là một lập trình viên IOS. Code chính là IOS nhưng thỉnnh thoảng vẫn đá sang Android hoặc web. Mặc dù không quá thông thạo nhưng tôi sẽ chia sẻ những kiến thức mà mình đã tìm hiểu, áp dụng qua.

Bài viết liên quan

FPGA cho developer: Lập trình phần cứng tái cấu hình

FPGA cho developer: Lập trình phần cứng tái cấu hình FPGA (Field-Programmable Gate Array) đang trở thành công cụ mạnh mẽ cho developer muốn tối ưu hiệu năng phần cứng…

Xem thêm

ClickHouse: OLAP database siêu nhanh cho analytics và logs

ClickHouse là gì? ClickHouse là OLAP database mã nguồn mở được thiết kế cho truy vấn phân tích (analytical queries) tốc độ cực cao trên dữ liệu cột (column-oriented). Khác…

Xem thêm

Deno Runtime: JavaScript TypeScript an toàn thay Node.js

Deno là gì? Deno là runtime JavaScript/TypeScript an toàn do Ryan Dahl — tác giả Node.js — tạo ra năm 2018. Được viết bằng Rust, Deno hướng đến việc sửa…

Xem thêm
0 0 đánh giá
Article Rating
Theo dõi
Thông báo của
guest
0 Comments
Cũ nhất
Mới nhất Được bỏ phiếu nhiều nhất