Rust กับ Microservices: ระบบที่เบาและเร็วสำหรับโปรดักชัน

Sharing is caring!

📌 ทำไม Rust ถึงเหมาะกับ Microservices?

ในยุคที่ระบบโปรดักชันต้องรองรับโหลดมหาศาลและปล่อยฟีเจอร์ได้อย่างรวดเร็ว Microservices คือสถาปัตยกรรมที่ตอบโจทย์ และ Rust คือภาษาที่ทำให้ microservice มีความเบา เร็ว ปลอดภัย และพร้อมสำหรับ scale จริงใน production

  • ⏱️ ความเร็วระดับ Native (เร็วกว่า Node.js / Python)
  • 🛡️ Memory safety — ป้องกัน crash และ undefined behavior
  • 📦 Binary ขนาดเล็ก — deploy ง่ายใน container
  • 🚀 รองรับ async/await เต็มรูปแบบ

🚀 เริ่มต้น Microservice ด้วย Axum

Axum เป็นหนึ่งในเฟรมเวิร์กยอดนิยมสำหรับเขียน Web API แบบ async ใน Rust

🔧 สร้างโปรเจคใหม่

cargo new rust-microservice
cd rust-microservice
  

📦 แก้ไข Cargo.toml




[dependencies]

axum = “0.7” tokio = { version = “1”, features = [“full”] } serde = { version = “1”, features = [“derive”] } serde_json = “1” tower = “0.4”

📄 สร้าง route แรก

use axum::{
    routing::get,
    Json, Router,
};
use serde::Serialize;

#[derive(Serialize)]
struct Status {
    service: String,
    healthy: bool,
}

async fn healthcheck() -> Json<Status> {
    Json(Status {
        service: "user-api".to_string(),
        healthy: true,
    })
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/health", get(healthcheck));
    axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}
  

🔌 การเชื่อมต่อกับ Microservices อื่น

  • ใช้ HTTP client เช่น reqwest สำหรับ call ภายนอก
  • หรือใช้ tonic สำหรับ gRPC
  • สามารถใช้ Kafka, Redis, Postgres ได้ด้วย crates ecosystem

ตัวอย่างการเรียก service ภายนอก

use reqwest;

async fn call_order_service() {
    let res = reqwest::get("http://orderservice.local/orders")
        .await
        .unwrap()
        .text()
        .await
        .unwrap();
    println!("Response: {}", res);
}
  

📦 แนะนำไลบรารีเสริม

  • tracing — log และ trace แบบ async-aware
  • dotenvy — จัดการ ENV config
  • tokio — ตัวจัดการ async runtime
  • anyhow / thiserror — จัดการ error
  • sqlx / sea-orm — async database ORM

🔐 ความปลอดภัยในระดับ production

  • ใช้ tower_http::cors หรือ headers สำหรับจัดการ CORS และ Auth header
  • สามารถเพิ่ม JWT Auth และ Role-based policy ได้ไม่ยาก
  • มี library เช่น jsonwebtoken, argon2 สำหรับ auth

⚙️ Dockerize Rust Microservice

ตัวอย่าง Dockerfile แบบ minimal:

FROM rust:1.77 as builder
WORKDIR /app
COPY . .
RUN cargo build --release

FROM debian:buster-slim
COPY --from=builder /app/target/release/rust-microservice /usr/local/bin/app
CMD ["app"]
  

⚖️ เปรียบเทียบกับภาษาอื่น

ภาษาStartup TimeBinary SizeMemory Usage
Node.js400ms~80MB~50MB
Python (FastAPI)500ms~70MB~40MB
Rust (Axum)5ms~4MB~8MB

✅ สรุป

Rust ไม่ได้เป็นเพียงภาษา systems programming เท่านั้น แต่เป็นทางเลือกที่น่ากลัวสำหรับ Microservices — โดยเฉพาะในระบบที่ต้องการ performance สูง, memory efficiency และความปลอดภัย การใช้ Rust จะช่วยลดต้นทุนโครงสร้างพื้นฐาน และเพิ่มความมั่นใจให้ระบบ production ได้อย่างแท้จริง


บทความนี้ใช้เวลาอ่านประมาณ 20 นาที โดยทีมงาน poolsawat.com

Leave a Reply

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *