NewCode CLOUD — 20% off your first month on all cloud VPSClaim

Rust Axum API on Hong Kong VPS: Ultra-High Performance REST (2026)

· 4 min read

Rust is the language for when performance and reliability are non-negotiable — zero garbage collection pauses, memory safety without a runtime, and single-binary deployment with no runtime dependency. Axum, built by the Tokio team, is the ergonomic async HTTP framework for Rust. Deployed on a Hong Kong VPS, a Rust Axum API serves hundreds of thousands of requests per second on modest hardware with sub-millisecond latency overhead — ideal for high-frequency trading APIs, real-time data feeds, and performance-critical microservices serving Asia-Pacific.


When Rust Axum Makes Sense

  • APIs with tight latency SLAs (p99 < 5ms) where GC pauses are unacceptable
  • High-concurrency endpoints with 10,000+ simultaneous connections
  • Financial data services where memory safety prevents critical bugs
  • CPU-intensive operations (parsing, hashing, cryptography) where Rust’s speed matters
  • Small VPS deployment — Rust binary uses 10–30 MB RAM vs 300 MB+ for a JVM service

Step 1: Install Rust on VPS

<code">curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
source ~/.cargo/env
rustup update stable

rustc --version   # 1.79+
cargo --version

Step 2: Create Axum Project

<code"># Cargo.toml
[package]
name = "hk-api"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = { version = "0.7", features = ["macros"] }
tokio = { version = "1", features = ["full"] }
tower = "0.4"
tower-http = { version = "0.5", features = ["cors", "compression-gzip", "trace"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.7", features = ["runtime-tokio-rustls", "postgres", "uuid", "chrono"] }
uuid = { version = "1", features = ["v4", "serde"] }
chrono = { version = "0.4", features = ["serde"] }
anyhow = "1"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
dotenvy = "0.15"

[profile.release]
opt-level = 3
lto = true
codegen-units = 1
strip = true    # Strip debug symbols — minimise binary size

Step 3: Application Structure

<code"># src/main.rs
use axum::{Router, middleware};
use sqlx::postgres::PgPoolOptions;
use std::net::SocketAddr;
use tower_http::cors::{CorsLayer, Any};
use tower_http::compression::CompressionLayer;
use tower_http::trace::TraceLayer;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

mod models;
mod routes;
mod handlers;
mod errors;

#[derive(Clone)]
pub struct AppState {
    pub db: sqlx::PgPool,
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    dotenvy::dotenv().ok();

    // Structured logging
    tracing_subscriber::registry()
        .with(tracing_subscriber::EnvFilter::new(
            std::env::var("RUST_LOG").unwrap_or_else(|_| "hk_api=info,tower_http=debug".into()),
        ))
        .with(tracing_subscriber::fmt::layer().json())
        .init();

    // Database connection pool
    let database_url = std::env::var("DATABASE_URL")
        .expect("DATABASE_URL must be set");

    let pool = PgPoolOptions::new()
        .max_connections(20)
        .connect(&database_url)
        .await?;

    // Run migrations
    sqlx::migrate!("./migrations").run(&pool).await?;

    let state = AppState { db: pool };

    let app = Router::new()
        .merge(routes::health_routes())
        .merge(routes::product_routes())
        .merge(routes::user_routes())
        .layer(
            tower::ServiceBuilder::new()
                .layer(TraceLayer::new_for_http())
                .layer(CompressionLayer::new())
                .layer(CorsLayer::new().allow_origin(Any))
        )
        .with_state(state);

    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    tracing::info!("Axum API listening on {}", addr);

    let listener = tokio::net::TcpListener::bind(addr).await?;
    axum::serve(listener, app).await?;

    Ok(())
}

Route Handlers

<code"># src/handlers/products.rs
use axum::{extract::{State, Path, Query}, response::Json, http::StatusCode};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use uuid::Uuid;

use crate::{AppState, errors::AppError};

#[derive(Serialize, sqlx::FromRow)]
pub struct Product {
    pub id: Uuid,
    pub name: String,
    pub price: f64,
    pub category: String,
    pub stock: i32,
    pub created_at: chrono::DateTime,
}

#[derive(Deserialize)]
pub struct ProductQuery {
    pub page: Option,
    pub limit: Option,
    pub category: Option,
}

#[derive(Deserialize)]
pub struct CreateProduct {
    pub name: String,
    pub price: f64,
    pub category: String,
    pub stock: i32,
}

pub async fn list_products(
    State(state): State,
    Query(params): Query,
) -> Result<Json<Vec>, AppError> {
    let page = params.page.unwrap_or(1).max(1);
    let limit = params.limit.unwrap_or(20).min(100);
    let offset = ((page - 1) * limit) as i64;

    let products = sqlx::query_as!(
        Product,
        r#"
        SELECT id, name, price, category, stock, created_at
        FROM products
        WHERE active = true
          AND ($1::text IS NULL OR category = $1)
        ORDER BY created_at DESC
        LIMIT $2 OFFSET $3
        "#,
        params.category,
        limit as i64,
        offset,
    )
    .fetch_all(&state.db)
    .await?;

    Ok(Json(products))
}

pub async fn get_product(
    State(state): State,
    Path(id): Path,
) -> Result<Json, AppError> {
    let product = sqlx::query_as!(
        Product,
        "SELECT id, name, price, category, stock, created_at FROM products WHERE id = $1 AND active = true",
        id
    )
    .fetch_optional(&state.db)
    .await?
    .ok_or(AppError::NotFound("Product not found".into()))?;

    Ok(Json(product))
}

pub async fn create_product(
    State(state): State,
    Json(body): Json,
) -> Result<(StatusCode, Json), AppError> {
    let product = sqlx::query_as!(
        Product,
        r#"
        INSERT INTO products (name, price, category, stock)
        VALUES ($1, $2, $3, $4)
        RETURNING id, name, price, category, stock, created_at
        "#,
        body.name, body.price, body.category, body.stock
    )
    .fetch_one(&state.db)
    .await?;

    Ok((StatusCode::CREATED, Json(product)))
}

Step 4: Build for Production

<code"># Cross-compile for Linux if building on macOS/Windows:
rustup target add x86_64-unknown-linux-musl
cargo build --release --target x86_64-unknown-linux-musl

# Build on the VPS directly (recommended — no cross-compile needed)
cargo build --release

# Binary is at: target/release/hk-api
# Size with strip=true: typically 3–8 MB
ls -lh target/release/hk-api

# Copy to deployment directory
cp target/release/hk-api /opt/hk-api/hk-api
chmod +x /opt/hk-api/hk-api

Step 5: Systemd Service

<code">useradd -m -s /bin/bash rust-api
mkdir -p /opt/hk-api

cat > /etc/systemd/system/hk-api.service << 'EOF' [Unit] Description=HK Rust Axum API After=network.target postgresql.service [Service] Type=simple User=rust-api WorkingDirectory=/opt/hk-api EnvironmentFile=/opt/hk-api/.env ExecStart=/opt/hk-api/hk-api Restart=always RestartSec=5 # Security hardening NoNewPrivileges=yes PrivateTmp=yes ProtectSystem=strict ReadWritePaths=/opt/hk-api [Install] WantedBy=multi-user.target EOF cat > /opt/hk-api/.env << 'EOF'
DATABASE_URL=postgresql://api_user:Pass!@localhost/api_db
RUST_LOG=hk_api=info,tower_http=warn
EOF

systemctl enable --now hk-api
journalctl -u hk-api -f

Performance: Axum vs Other Frameworks

Framework Language Requests/sec (single core) Memory (idle)
Axum Rust 150,000–300,000 5–15 MB
Actix-web Rust 200,000–350,000 5–15 MB
Bun/Elysia TypeScript 100,000–160,000 60–100 MB
Go (net/http) Go 80,000–150,000 10–30 MB
FastAPI (uvicorn) Python 15,000–30,000 80–150 MB
Express.js Node.js 30,000–60,000 40–80 MB

Conclusion

A Rust Axum API on a Hong Kong VPS delivers the highest request throughput per VPS dollar in the ecosystem — the compiled binary uses 5–15 MB of RAM, handles 150,000+ requests per second on a single core, and never pauses for garbage collection. The Tokio async runtime scales to tens of thousands of concurrent connections without additional processes or threads. For latency-sensitive APIs serving Asia-Pacific users — financial data, real-time feeds, high-frequency trading — Rust on CN2 GIA-connected Hong Kong infrastructure is a powerful combination.

Deploy maximum performance: Browse Server.HK Hong Kong VPS plans — a 2 GB VPS runs a Rust Axum API, PostgreSQL, and Redis with CPU headroom to spare.

Related articles

More in VPS & ServersServer setup guides