Rust cho Web: So sanh Actix Web va Axum cung Cau hoi Phong van 2026

So sanh thuc te Actix Web 4.14 va Axum 0.8 cho phat trien web Rust nam 2026. Kien truc, benchmark TechEmpower Round 23, trai nghiem nha phat trien, va cau hoi phong van cho vi tri backend Rust.

So sanh Rust Actix Web va Axum

Viec ap dung framework web Rust da tang manh trong nam 2026, va hai framework thong tri cac trien khai production: Actix Web 4.14 va Axum 0.8. Viec lua chon giua chung anh huong den moi thu tu qua trinh onboarding doi ngu den throughput production, va cau hoi nay thuong xuat hien trong cac cuoc phong van backend Rust.

Khung Quyet dinh Nhanh

Actix Web 4.14 dan dau ve raw throughput (10-15% request/giay nhieu hon duoi tai nang). Axum 0.8 cung cap ergonomi tot hon thong qua native async traits, kha nang to hop middleware Tower, va tich hop Tokio chat che hon. Voi hau het cac doi bat dau du an moi vao nam 2026, Axum la lua chon thuc te tru khi yeu cau throughput cuc cao quyet dinh khac di.

Su Khac biet Kien truc giua Actix Web va Axum

Su phan ky kien truc giua hai framework nay giai thich phan lon cac danh doi ve hieu suat va ergonomi.

Actix Web khoi chay N runtime Tokio don luong, moi runtime cho moi core vat ly. Cac task duoc gim vao thread ma khong co di chuyen du lieu giua cac thread. Dieu nay loai bo overhead work-stealing va cache-line bouncing, giai thich loi the throughput nhat quan duoi tai lien tuc.

Axum chay tren mot runtime Tokio da luong duy nhat voi work-stealing. Doi Tokio xay dung Axum dac biet de gioi thieu kha nang cua runtime, nen moi quyet dinh thiet ke toi uu hoa cho tinh to hop voi he sinh thai Tokio rong hon. Handler la cac ham async thuan tuy, va middleware su dung trait Service cua Tower.

actix_hello.rs - Actix Web minimal serverrust
use actix_web::{web, App, HttpServer, HttpResponse};

async fn health() -> HttpResponse {
    HttpResponse::Ok().json(serde_json::json!({ "status": "ok" }))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/health", web::get().to(health))
    })
    .bind("0.0.0.0:8080")?
    .run()
    .await
}
axum_hello.rs - Axum minimal serverrust
use axum::{Router, Json, routing::get};
use serde_json::{json, Value};

async fn health() -> Json<Value> {
    Json(json!({ "status": "ok" }))
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/health", get(health));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:8080")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Ca hai vi du deu co the bien dich va chay, nhung su khac biet da the hien. Actix Web su dung macro #[actix_web::main] rieng cua no va tra ve std::io::Result. Axum su dung #[tokio::main] chuan va xay dung route thong qua struct Router. Handler cua Axum tra ve typed extractor (Json<Value>) thay vi xay dung HttpResponse thu cong.

Benchmark Hieu suat: Actix Web 4.14 vs Axum 0.8

Du lieu benchmark tu TechEmpower Round 23 (Thang 1/2026) cung cap phep so sanh dang tin cay nhat. Ca hai framework deu xep hang tier cao nhat o tat ca cac danh muc.

Chi tieuActix Web 4.14Axum 0.8.9
Plaintext (req/s)~7.100.000~6.200.000
JSON serialization (req/s)~1.200.000~1.050.000
DB single query (req/s)~190.000~175.000
Memory usage (hello world)~8 MB~6 MB
P99 latency (JSON)1,1 ms1,3 ms

Actix Web duy tri loi the throughput 10-15% tren tat ca cac danh muc. Axum su dung it bo nho hon mot chut do shared Tokio runtime. De tham khao, ca hai framework deu vuot troi hon HTTP server chuan cua Go 2-3 lan va Node.js 5-8 lan tren phan cung tuong duong.

Khoang cach hieu suat quan trong cho ad serving, pipeline phan tich thoi gian thuc, va gateway giao dich tan suat cao. Voi REST API thong thuong phuc vu 10.000 request/giay, ca hai framework deu vuot xa bottleneck, ma se la database hoac cac cuoc goi dich vu ben ngoai.

So sanh Extractor va Xu ly Request

Extractor dinh nghia cach framework phan tich cac request den. Axum 0.8 da thuc hien cai tien dang ke o day bang cach loai bo #[async_trait] de uu tien native async traits va gioi thieu OptionalFromRequestParts de xu ly Option<T> tot hon.

axum_extractors.rs - Axum 0.8 extractor patternrust
use axum::{
    extract::{Path, Query, State, Json},
    routing::get,
    Router,
};
use serde::Deserialize;
use std::sync::Arc;

#[derive(Deserialize)]
struct Pagination {
    page: Option<u32>,    // defaults to None if missing
    per_page: Option<u32>,
}

// State shared across handlers
struct AppState {
    db_pool: sqlx::PgPool,
}

// Axum 0.8: /{id} syntax (replaced /:id)
async fn get_user(
    State(state): State<Arc<AppState>>,
    Path(user_id): Path<i64>,
    Query(pagination): Query<Pagination>,
) -> Json<serde_json::Value> {
    let page = pagination.page.unwrap_or(1);
    // Query database using state.db_pool
    Json(serde_json::json!({
        "user_id": user_id,
        "page": page
    }))
}
actix_extractors.rs - Actix Web extractor patternrust
use actix_web::{web, HttpResponse};
use serde::Deserialize;

#[derive(Deserialize)]
struct Pagination {
    page: Option<u32>,
    per_page: Option<u32>,
}

struct AppState {
    db_pool: sqlx::PgPool,
}

async fn get_user(
    state: web::Data<AppState>,
    path: web::Path<i64>,
    query: web::Query<Pagination>,
) -> HttpResponse {
    let user_id = path.into_inner();
    let page = query.page.unwrap_or(1);
    HttpResponse::Ok().json(serde_json::json!({
        "user_id": user_id,
        "page": page
    }))
}

Extractor cua Axum su dung tuple destructuring truc tiep trong tham so ham. Actix Web boc moi thu trong web::Path, web::Query, v.v., yeu cau goi .into_inner(). Ca hai cach tiep can deu type-safe tai thoi diem bien dich, nhung cach tiep can cua Axum doc tu nhien hon.

Thay doi Breaking cua Axum 0.8

Tham so path da chuyen tu cu phap /:id sang /{id} trong Axum 0.8 (thong qua matchit 0.8). Dieu nay phu hop voi cu phap path cua OpenAPI. Escape su dung dau ngoac nhon kep: {{ cho literal {.

Kien truc Middleware: Tower vs Actix Middleware

To hop middleware la noi su khac biet kien truc tao ra tac dong thuc te lon nhat.

Axum su dung trait Service va Layer cua Tower. Bat ky middleware nao tuong thich voi Tower deu hoat dong voi Axum, bao gom rate limiter, tracing, nen, va cac layer xac thuc duoc xay dung cho cac dich vu dua tren Tower khac. Tinh to hop nay vuot ra ngoai HTTP; cung mot middleware co the boc cac dich vu gRPC thong qua Tonic.

axum_middleware.rs - Tower middleware compositionrust
use axum::{
    Router, middleware,
    routing::get,
    extract::Request,
    response::Response,
};
use tower_http::{
    cors::CorsLayer,
    compression::CompressionLayer,
    trace::TraceLayer,
};
use std::time::Instant;

// Custom middleware as a plain async function
async fn timing_middleware(
    request: Request,
    next: middleware::Next,
) -> Response {
    let start = Instant::now();
    let response = next.run(request).await;
    let duration = start.elapsed();
    tracing::info!("Request took {:?}", duration);
    response
}

fn build_router() -> Router {
    Router::new()
        .route("/api/data", get(|| async { "ok" }))
        .layer(middleware::from_fn(timing_middleware))
        .layer(CompressionLayer::new())
        .layer(CorsLayer::permissive())
        .layer(TraceLayer::new_for_http())
}

Actix Web su dung he thong middleware rieng voi trait Transform va Service (khong phai cua Tower). Middleware tu he sinh thai Tower rong hon yeu cau adapter hoac viet lai.

Voi cac doi da dau tu vao he sinh thai Tower thong qua Tonic (gRPC) hoac Hyper, middleware cua Axum la loi the dang ke. Voi cac doi xay dung dich vu HTTP doc lap, he thong middleware cua Actix Web cung co kha nang tuong duong, chi la khong the hoan doi cho nhau.

Actix Web 4.14 gioi thieu xac thuc route middleware se panic neu handler duoc them sau khi boc middleware, bat loi cau hinh tai startup thay vi runtime.

Sẵn sàng chinh phục phỏng vấn Rust?

Luyện tập với mô phỏng tương tác, flashcards và bài kiểm tra kỹ thuật.

Tich hop Co so Du lieu voi SQLx

Ca hai framework deu ket hop tot voi SQLx, bo cong cu SQL async-first xac thuc query tai thoi diem bien dich. Mau tich hop co doi chut khac biet.

shared_db.rs - SQLx with compile-time query validationrust
use sqlx::PgPool;

// This struct works identically with Actix Web and Axum
#[derive(sqlx::FromRow, serde::Serialize)]
struct User {
    id: i64,
    email: String,
    created_at: chrono::NaiveDateTime,
}

// sqlx::query_as! validates against a live DB at compile time
async fn find_user_by_email(
    pool: &PgPool,
    email: &str,
) -> Result<Option<User>, sqlx::Error> {
    sqlx::query_as!(
        User,
        "SELECT id, email, created_at FROM users WHERE email = $1",
        email
    )
    .fetch_optional(pool)
    .await
}

Tang database van giu nguyen bat ke lua chon framework. Macro query_as! cua SQLx ket noi voi database live tai thoi diem bien dich va xac thuc ten cot, kieu, va su ton tai cua bang. Loi go ten cot tao ra loi bien dich, khong phai crash runtime.

So sanh Cac Mau Xu ly Loi

Xu ly loi the hien triet ly thiet ke khac nhau. Actix Web su dung trieu khai trait ResponseError. Axum dua vao IntoResponse ket hop voi kieu Result.

axum_errors.rs - Axum error handling with IntoResponserust
use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};

// Define application-level errors
enum AppError {
    NotFound(String),
    DatabaseError(sqlx::Error),
    ValidationError(String),
}

// Convert errors into HTTP responses
impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound(msg) => (
                StatusCode::NOT_FOUND, msg
            ),
            AppError::DatabaseError(_) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Internal server error".to_string(),
            ),
            AppError::ValidationError(msg) => (
                StatusCode::BAD_REQUEST, msg
            ),
        };
        (status, Json(serde_json::json!({ "error": message })))
            .into_response()
    }
}

// Handlers return Result<T, AppError>
async fn get_user(
    axum::extract::Path(id): axum::extract::Path<i64>,
) -> Result<Json<serde_json::Value>, AppError> {
    if id <= 0 {
        return Err(AppError::ValidationError(
            "ID must be positive".to_string()
        ));
    }
    Ok(Json(serde_json::json!({ "id": id })))
}

Cach tiep can cua Axum to hop tu nhien voi toan tu ? cua Rust va kieu Result. Actix Web dat duoc dieu tuong tu thong qua ResponseError, yeu cau trieu khai ca trait Display va ResponseError. Ca hai deu hoat dong, nhung mau cua Axum cam thay tu nhien hon voi cac nha phat trien Rust quen voi trait From va lan truyen loi.

Khi nao Chon Actix Web thay vi Axum

Actix Web van la lua chon dung trong cac tinh huong cu the:

  • Yeu cau throughput toi da: Ad exchange, real-time bidding, pipeline nhap lieu phan tich noi ma 10-15% req/s nhieu hon la dang danh doi.
  • Ung dung su dung nhieu WebSocket: Ho tro WebSocket cua Actix Web da duoc kiem nghiem trong nhieu trien khai production hon. Ho tro WebSocket cua Axum (thong qua axum::extract::ws) hoat dong tot nhung co track record production ngan hon.
  • Codebase Actix Web hien co: Chuyen tu Actix Web 3.x sang 4.x kha don gian. Viet lai sang Axum mang lai loi ich giam dan cho cac dich vu on dinh.
  • Su quen thuoc cua doi ngu: Neu doi da biet Actix Web, viec chuyen framework de co loi ich ergonomi hiem khi mang lai ket qua trong ngan han.

Khi nao Chon Axum thay vi Actix Web

Axum phu hop hon trong cac boi canh sau:

  • Du an moi vao nam 2026: Su lien ket voi he sinh thai Tokio (Tonic, Hyper, Tower) giam ma sat tich hop.
  • Dich vu ket hop gRPC va HTTP: Middleware Tower hoat dong tren ca hai giao thuc ma khong can lop thich ung.
  • Doi moi voi Rust: Extractor dua tren kieu va thong bao loi compile-time cua Axum cung cap duong cong hoc mem hon. Cu phap path /{id} (phu hop voi OpenAPI) quen thuoc ngay lap tuc.
  • Kien truc microservice: Trait Service cua Tower cho phep tai su dung middleware giua cac dich vu, giam boilerplate.

Cau hoi Phong van: Actix Web va Axum cho Vi tri Backend Rust

Cau hoi phong van Rust backend ngay cang bao gom kien thuc ve web framework. Cac cau hoi nay xuat hien trong cac cuoc phong van backend cap cao va systems engineering.

H: Giai thich su khac biet kien truc giua cac mo hinh runtime cua Actix Web va Axum.

Actix Web khoi chay mot runtime Tokio don luong cho moi core CPU. Task duoc gim vao thread, loai bo overhead work-stealing. Axum chay tren shared runtime Tokio da luong voi work-stealing. Mo hinh cua Actix Web giam cache-line contention duoi tai nang, tao ra throughput cao hon. Mo hinh cua Axum don gian hoa quan ly shared state vi tat ca task chia se mot runtime.

H: Viec loai bo #[async_trait] trong Axum 0.8 anh huong nhu the nao den custom extractor?

Axum 0.8 tan dung return-position impl Trait native trong trait cua Rust (on dinh cuoi 2023). Custom extractor trieu khai FromRequestParts hoac FromRequest bay gio dinh nghia cac phuong thuc async truc tiep ma khong can thuoc tinh #[async_trait]. Dieu nay loai bo phan bo heap tu Box<dyn Future> va cai thien thoi gian bien dich. Cac extractor hien co yeu cau loai bo macro va dieu chinh trieu khai trait.

H: Mo ta cach middleware Tower khac voi middleware Actix Web.

Tower dinh nghia trait Service<Request> tong quat la protocol-agnostic. Layer timeout cua Tower hoat dong voi HTTP (Axum), gRPC (Tonic), va bat ky giao thuc tuy chinh nao. Middleware Actix Web su dung trait Transform va Service dac trung cho framework cua no. Tac dong thuc te: middleware Axum co the tai su dung tren toan bo he sinh thai Tower; middleware Actix Web dac thu cho framework.

H: Xac thuc query compile-time cua SQLx hoat dong nhu the nao, va cac danh doi la gi?

Macro query_as! cua SQLx ket noi voi database PostgreSQL live trong qua trinh bien dich. No xac thuc cu phap SQL, ten cot, kieu, va su ton tai cua bang. Danh doi: build yeu cau truy cap database, gay kho khan cho pipeline CI. SQLx cung cap sqlx prepare de tao metadata query offline, luu ket qua xac thuc trong thu muc .sqlx duoc commit vao version control.

H: Khi nao chon Actix Web thay vi Axum la quyet dinh ky thuat dung?

Actix Web dung khi throughput lien tuc la rang buoc chinh: ad serving, nhap lieu phan tich thoi gian thuc, hoac gateway giao dich tan suat cao. Mo hinh runtime pinned-thread loai bo overhead work-stealing, tao ra 10-15% req/s cao hon duoi tai. Axum dung khi tinh to hop voi he sinh thai Tokio quan trong hon loi ich throughput can bien, dac biet trong kien truc microservice su dung ca HTTP va gRPC.

Loi Thuong gap trong Phong van

Ung vien thuong tuyen bo mot framework tot hon mot cach tuyet doi. Cau tra loi manh thua nhan danh doi: Actix Web toi uu cho throughput, Axum toi uu cho tinh to hop he sinh thai. Lua chon dung phu thuoc vao rang buoc cua he thong, khong phai so thich ca nhan.

Nguon

Diem Quan trong cho Phat trien Web Rust nam 2026

  • Actix Web 4.14 cung cap throughput cao hon 10-15% thong qua mo hinh runtime pinned-thread, tro thanh lua chon dung cho cac dich vu nhay cam voi do tre va throughput cao
  • Axum 0.8 cung cap ergonomi tot hon voi native async traits, cu phap path /{id}, va tinh tuong thich day du voi middleware Tower tren HTTP va gRPC
  • Ca hai framework su dung cung tang database (SQLx voi xac thuc compile-time), nen lua chon khong anh huong den mau truy cap du lieu
  • Voi cac du an web Rust moi vao nam 2026 khong co yeu cau throughput cuc cao, su lien ket he sinh thai cua Axum voi Tokio, Tonic, va Tower giam chi phi bao tri dai han
  • Cau hoi phong van ve chu de nay kiem tra su hieu biet ve cac mo hinh runtime, kien truc middleware, va ly luan danh doi, khong phai so thich framework
  • Chuan bi phong van Rust yeu cau hieu cac quyet dinh kien truc cua ca hai framework, khong chi cu phap API

Bắt đầu luyện tập!

Kiểm tra kiến thức với mô phỏng phỏng vấn và bài kiểm tra kỹ thuật.

Thử thách hôm nay

Bạn có tìm ra lỗi trong Rust không?

Một đoạn mã thật, một lỗi ẩn, mỗi ngày một lượt. Không cần tài khoản để thử.

Anthony Fillion-Maillet

Viết bởi

Anthony Fillion-Maillet

Người sáng lập SharpSkill

Lập trình viên fullstack hơn 10 năm. Anh điều hành SharpSkill và chịu trách nhiệm về mọi nội dung đăng tại đây.

Cập nhật ngày 22 tháng 8, 2026

Thẻ

#rust
#actix-web
#axum
#web-framework
#backend
#comparison

Chia sẻ

Bài viết liên quan