serverless-edge-computing-cloud-infrastructure

Serverless & Edge Computing với Node.js: Deploy Ứng Dụng Nhanh Hơn, Rẻ Hơn, Gần User Hơn

Serverless và Edge Computing đang thay đổi cách deploy ứng dụng Node.js. Từ AWS Lambda đến Cloudflare Workers — học cách xây dựng apps có latency cực thấp, auto-scale, và chỉ trả tiền khi có người dùng.

Viết bởi admin
June 20, 2026 8 phút đọc 1 lượt xem

48.7% developers toàn cầu sử dụng Node.js (Stack Overflow Survey 2025). Nhưng cách họ deploy đang thay đổi triệt để: từ VPS truyền thống sang serverless functionsedge computing — nơi code chạy ngay cạnh người dùng, ở 300+ locations trên thế giới.

Serverless là gì? Edge Computing là gì?

📊
Thống kê 2025: 48.7% developers toàn cầu sử dụng Node.js (Stack Overflow Survey 2025). Trong đó, 63% deploy ít nhất một phần ứng dụng qua serverless — pattern đã trở thành mainstream.

Serverless

Bạn viết function, cloud provider lo mọi thứ còn lại: server, scaling, patching, monitoring. Bạn chỉ trả tiền khi function thực sự chạy — không có traffic = $0.

Edge Computing

Code của bạn không chạy ở 1 data center xa xôi — nó được deploy đến hàng trăm locations trên toàn thế giới. User ở Việt Nam? Code chạy ở Singapore. User ở Pháp? Code chạy ở Paris. Latency giảm từ 200ms xuống dưới 20ms.

So sánh các nền tảng Serverless cho Node.js

// So sánh nhanh các platform phổ biến nhất (2026)
//
// Platform         | Cold Start | Max Exec  | Free Tier       | Edge?
// ─────────────────|──────────--|───────────|─────────────────|──────
// AWS Lambda       | 100-500ms  | 15 min    | 1M req/tháng    | Không*
// Vercel Functions | 50-200ms   | 60s       | 100K req/tháng  | Có
// Cloudflare Workers| <1ms      | 30s/50ms  | 100K req/ngày   | Có
// Netlify Functions| 100-300ms  | 26s       | 125K req/tháng  | Không
// Google Cloud Run | 100-400ms  | 60 min    | 2M req/tháng    | Không
//
// * AWS Lambda@Edge có hỗ trợ edge nhưng giới hạn hơn
aws-lambda-serverless-deployment
AWS Lambda — nền tảng serverless phổ biến nhất với 10+ năm sản xuất

Hands-on: Deploy API lên AWS Lambda

Bước 1: Viết Lambda function

// handler.mjs — ES Module cho Node.js 24
export const handler = async (event) => {
  const { httpMethod, path, queryStringParameters, body } = event;

  // Router đơn giản
  if (httpMethod === "GET" && path === "/api/articles") {
    const page = parseInt(queryStringParameters?.page) || 1;
    const articles = await fetchArticles(page);

    return {
      statusCode: 200,
      headers: {
        "Content-Type": "application/json",
        "Cache-Control": "public, max-age=60", // Cache 1 phút
      },
      body: JSON.stringify({
        data: articles,
        page,
        total: articles.length,
      }),
    };
  }

  if (httpMethod === "POST" && path === "/api/contact") {
    const data = JSON.parse(body);
    await sendEmail(data);

    return {
      statusCode: 200,
      body: JSON.stringify({ message: "Đã gửi thành công!" }),
    };
  }

  return { statusCode: 404, body: "Not Found" };
};

Bước 2: Deploy với Serverless Framework

# Cài đặt
npm install -g serverless

# serverless.yml
service: techher-api
frameworkVersion: "4"

provider:
  name: aws
  runtime: nodejs24.x
  region: ap-southeast-1  # Singapore — gần Việt Nam nhất
  memorySize: 256
  timeout: 10

functions:
  api:
    handler: handler.handler
    events:
      - httpApi:
          path: /api/{proxy+}
          method: ANY

# Deploy
serverless deploy
cloudflare-workers-edge-network
Cloudflare Workers với cold start dưới 1ms — nhanh hơn bất kỳ platform serverless nào khác

Cloudflare Workers: Edge Computing thực thụ

🎯
Chọn platform: Nếu bạn mới bắt đầu, hãy dùng Vercel (tích hợp Next.js tuyệt vời) hoặc Cloudflare Workers (edge thực sự, free tier rộng). AWS Lambda phù hợp cho enterprise với yêu cầu phức tạp.

Cloudflare Workers là nền tảng edge ấn tượng nhất: cold start dưới 1ms, deploy đến 300+ locations, free tier 100K requests/ngày.

// worker.js — Cloudflare Worker
export default {
  async fetch(request, env) {
    const url = new URL(request.url);

    // API endpoint
    if (url.pathname === "/api/hello") {
      // Lấy vị trí địa lý của user (Cloudflare tự động cung cấp)
      const country = request.cf?.country || "Unknown";
      const city = request.cf?.city || "Unknown";
      const colo = request.cf?.colo; // Data center đang xử lý

      return new Response(JSON.stringify({
        message: `Xin chào từ ${city}, ${country}!`,
        processedAt: colo, // Ví dụ: "SIN" (Singapore), "CDG" (Paris)
        latency: "< 20ms", // Edge = gần user
        timestamp: new Date().toISOString(),
      }), {
        headers: { "Content-Type": "application/json" },
      });
    }

    // KV Storage — database ở edge
    if (url.pathname === "/api/visits") {
      const count = parseInt(await env.VISITS.get("count") || "0") + 1;
      await env.VISITS.put("count", count.toString());

      return new Response(JSON.stringify({ visits: count }), {
        headers: { "Content-Type": "application/json" },
      });
    }

    return new Response("Not Found", { status: 404 });
  },
};

// wrangler.toml
// name = "techher-edge-api"
// main = "worker.js"
// compatibility_date = "2026-01-01"
//
// [[kv_namespaces]]
// binding = "VISITS"
// id = "your-kv-namespace-id"
serverless-edge-computing-global-network
Edge computing: code chạy ở 300+ locations trên toàn cầu, giảm latency xuống dưới 20ms

Tối ưu Cold Start — Vấn đề số 1 của Serverless

Cold start xảy ra khi function chưa được “warm” — container cần khởi tạo từ đầu. Đây là kẻ thù lớn nhất của serverless performance.

Chiến thuật giảm cold start

// 1. Lazy initialization — chỉ load khi cần
let dbConnection;

async function getDB() {
  if (!dbConnection) {
    // Chỉ connect khi function thực sự cần database
    const { Client } = await import("pg");
    dbConnection = new Client(process.env.DATABASE_URL);
    await dbConnection.connect();
  }
  return dbConnection;
}

// 2. Giảm bundle size — tree-shaking aggressive
// package.json
{
  "dependencies": {
    // ❌ Đừng: import toàn bộ AWS SDK (60MB+)
    // "aws-sdk": "^2.x"

    // ✅ Nên: chỉ import module cần dùng (< 1MB)
    "@aws-sdk/client-s3": "^3.x",
    "@aws-sdk/client-ses": "^3.x"
  }
}

// 3. Provisioned Concurrency (AWS Lambda)
// Giữ N instances luôn warm — xóa cold start hoàn toàn
// Chi phí: ~$15/tháng cho 5 instances

Benchmark cold start theo runtime

// Cold start trung bình (256MB memory):
//
// Node.js 24:     120ms  ← Nhanh nhất trong các runtime phổ biến
// Python 3.12:    180ms
// Java 21 (Snap): 350ms
// .NET 8:         250ms
// Go:             90ms   ← Go vẫn nhanh nhất overall
//
// Kết luận: Node.js là lựa chọn tốt nhất khi cần
// balance giữa cold start + ecosystem + developer experience

Microservices với NestJS trên Serverless

NestJS — framework Node.js phổ biến nhất cho enterprise — hỗ trợ serverless deployment native:

// Cài đặt NestJS cho serverless
npm install @nestjs/platform-express @codegenie/serverless-express

// lambda.ts — NestJS adapter cho AWS Lambda
import { NestFactory } from "@nestjs/core";
import { ExpressAdapter } from "@nestjs/platform-express";
import serverlessExpress from "@codegenie/serverless-express";
import express from "express";
import { AppModule } from "./app.module";

let cachedServer;

async function bootstrap() {
  if (!cachedServer) {
    const app = express();
    const nestApp = await NestFactory.create(
      AppModule,
      new ExpressAdapter(app)
    );
    nestApp.enableCors();
    await nestApp.init();
    cachedServer = serverlessExpress({ app });
  }
  return cachedServer;
}

export const handler = async (event, context) => {
  const server = await bootstrap();
  return server(event, context);
};

Khi nào KHÔNG nên dùng Serverless?

💰
Cảnh báo chi phí: Serverless KHÔNG phải lúc nào cũng rẻ. Ở scale lớn (trên 20M req/tháng) và workload nặng (ML inference, video processing), VPS/container thường rẻ hơn 30-50%. Hãy tính toán kỹ trước khi quyết định.

Serverless không phải silver bullet. Tránh dùng khi:

  • WebSocket connections dài hạn — serverless có timeout (thường 30s-15min)
  • Heavy computation — ML training, video encoding → dùng containers hoặc VPS
  • Consistent low latency — nếu cold start 100ms là không chấp nhận được
  • Chi phí lớn ở scale cao — trên 10M requests/tháng, VPS có thể rẻ hơn
  • Shared state — functions stateless → cần external storage cho mọi state

Chi phí thực tế: Serverless vs VPS

// Scenario: API xử lý 5M requests/tháng, 100ms avg execution
//
// AWS Lambda:
//   Compute: 5M × 100ms × $0.0000166667/GB-s × 0.256GB = $21.33
//   Requests: 5M × $0.20/1M = $1.00
//   Total: ~$22/tháng
//
// DigitalOcean VPS (4GB RAM):
//   $24/tháng (fixed, chạy 24/7)
//
// Kết luận: Ở 5M req/tháng → tương đương
//           Dưới 1M req/tháng → Serverless rẻ hơn nhiều (gần $0)
//           Trên 20M req/tháng → VPS rẻ hơn

“Serverless is not about no servers — it is about no server management. You write code, we handle everything else.” — Werner Vogels, CTO Amazon

Kết luận

Serverless và Edge Computing đang chuyển từ “nice-to-have” sang “default choice” cho hầu hết ứng dụng Node.js. Với cold start ngày càng nhỏ, free tier rộng rãi, và khả năng auto-scale vô hạn — đây là cách deploy thông minh nhất cho 2026. Hãy bắt đầu với Cloudflare Workers (free, edge, < 1ms cold start) hoặc Vercel (tích hợp Next.js tuyệt vời) — và bạn sẽ không bao giờ muốn quay lại quản lý server nữa.

Enjoyed this article?

Get weekly insights on Tech, AI & Beauty — straight to your inbox.

Để lại bình luận

Your email address will not be published. Required fields are marked *