Rust 웹 개발 완벽 가이드 | Actix-Web·Tokio·Diesel·성능·메모리 안전성
이 글의 핵심
Rust로 안전하고 빠른 웹 API를 구축하는 완벽 가이드입니다. Actix-Web, Tokio, Diesel ORM, 에러 처리, 비동기, 성능 최적화까지 실전 예제로 정리했습니다.
실무 경험 공유: 고성능 API 서버를 Rust로 구축하면서, Go보다 2배 빠른 성능과 메모리 안전성을 확보하고 런타임 에러를 제로로 만든 경험을 공유합니다.
들어가며: “메모리 버그가 너무 많아요”
실무 문제 시나리오
시나리오 1: Segmentation Fault가 발생해요
C/C++는 메모리 버그가 많습니다. Rust는 컴파일 타임에 방지합니다.
시나리오 2: 더 빠른 성능이 필요해요
Go도 빠르지만 더 빠른 게 필요합니다. Rust는 C/C++만큼 빠릅니다.
시나리오 3: 동시성 버그가 걱정돼요
Race condition이 발생합니다. Rust는 컴파일 타임에 방지합니다.
1. Rust란?
핵심 특징
Rust는 메모리 안전성과 성능을 모두 제공하는 시스템 언어입니다.
주요 장점:
- 메모리 안전성: 컴파일 타임 보장
- 최고 성능: C/C++와 동등
- 동시성: 안전한 멀티스레딩
- 제로 코스트 추상화: 추상화 오버헤드 없음
- 강력한 타입 시스템: 버그 조기 발견
성능 비교:
- Node.js: 5,000 req/sec
- Go: 20,000 req/sec
- Rust: 30,000 req/sec
2. 설치
# Windows, macOS, Linux
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# 확인
rustc --version
cargo --version
3. Actix-Web
프로젝트 생성
cargo new myapp
cd myapp
의존성 추가
# Cargo.toml
[dependencies]
actix-web = "4"
tokio = { version = "1", features = [full] }
serde = { version = "1", features = [derive] }
serde_json = "1"
기본 서버
// src/main.rs
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct User {
id: u32,
name: String,
email: String,
}
#[get("/")]
async fn hello() -> impl Responder {
HttpResponse::Ok().json(serde_json::json!({
"message": "Hello World"
}))
}
#[get("/users/{id}")]
async fn get_user(path: web::Path<u32>) -> impl Responder {
let user_id = path.into_inner();
HttpResponse::Ok().json(User {
id: user_id,
name: "John".to_string(),
email: "[email protected]".to_string(),
})
}
#[post("/users")]
async fn create_user(user: web::Json<User>) -> impl Responder {
HttpResponse::Created().json(user.into_inner())
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(hello)
.service(get_user)
.service(create_user)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
4. Diesel ORM
설치
cargo install diesel_cli --no-default-features --features postgres
설정
# .env
DATABASE_URL=postgres://user:password@localhost/mydb
# 초기화
diesel setup
# 마이그레이션 생성
diesel migration generate create_users
마이그레이션
-- migrations/2026-05-06-000000_create_users/up.sql
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR NOT NULL,
email VARCHAR NOT NULL UNIQUE,
created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
-- migrations/2026-05-06-000000_create_users/down.sql
DROP TABLE users;
# 실행
diesel migration run
5. 에러 처리
Result 타입
use actix_web::{Error, HttpResponse};
async fn get_user(id: u32) -> Result<HttpResponse, Error> {
let user = find_user(id).await?;
match user {
Some(u) => Ok(HttpResponse::Ok().json(u)),
None => Ok(HttpResponse::NotFound().json(serde_json::json!({
"error": "User not found"
}))),
}
}
커스텀 에러
use actix_web::{error::ResponseError, http::StatusCode, HttpResponse};
use std::fmt;
#[derive(Debug)]
enum AppError {
NotFound,
Unauthorized,
InternalError,
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
AppError::NotFound => write!(f, "Not found"),
AppError::Unauthorized => write!(f, "Unauthorized"),
AppError::InternalError => write!(f, "Internal error"),
}
}
}
impl ResponseError for AppError {
fn status_code(&self) -> StatusCode {
match self {
AppError::NotFound => StatusCode::NOT_FOUND,
AppError::Unauthorized => StatusCode::UNAUTHORIZED,
AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
6. Middleware
use actix_web::{dev::Service, middleware::Logger};
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
HttpServer::new(|| {
App::new()
.wrap(Logger::default())
.wrap(Logger::new("%a %{User-Agent}i"))
.service(hello)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
7. 비동기 처리
Tokio
use tokio::time::{sleep, Duration};
async fn fetch_data() -> String {
sleep(Duration::from_secs(1)).await;
"Data".to_string()
}
#[get("/data")]
async fn get_data() -> impl Responder {
let data = fetch_data().await;
HttpResponse::Ok().json(serde_json::json!({
"data": data
}))
}
병렬 처리
use tokio::join;
async fn fetch_user(id: u32) -> User { /* ... */ }
async fn fetch_posts(user_id: u32) -> Vec<Post> { /* ... */ }
#[get("/users/{id}/profile")]
async fn get_profile(path: web::Path<u32>) -> impl Responder {
let user_id = path.into_inner();
let (user, posts) = join!(
fetch_user(user_id),
fetch_posts(user_id)
);
HttpResponse::Ok().json(serde_json::json!({
"user": user,
"posts": posts
}))
}
8. 배포
빌드
# Release 빌드
cargo build --release
# 실행
./target/release/myapp
Docker
FROM rust:1.77 as builder
WORKDIR /app
COPY . .
RUN cargo build --release
FROM debian:bookworm-slim
WORKDIR /app
COPY --from=builder /app/target/release/myapp .
EXPOSE 8080
CMD [./myapp]
정리 및 체크리스트
핵심 요약
- Rust: 메모리 안전성 + 최고 성능
- Actix-Web: 가장 빠른 웹 프레임워크
- Diesel: 타입 안전한 ORM
- Tokio: 비동기 런타임
- 에러 처리: Result 타입
- 동시성: 안전한 멀티스레딩
구현 체크리스트
- Rust 설치
- Actix-Web 프로젝트 생성
- Diesel 설정
- CRUD API 구현
- 에러 처리 구현
- 비동기 처리
- Docker 배포
같이 보면 좋은 글
- Go 웹 개발 완벽 가이드
- FastAPI 완벽 가이드
- PostgreSQL 고급 가이드
이 글에서 다루는 키워드
Rust, Actix-Web, Tokio, Diesel, Backend, REST API, Performance, Memory Safety
자주 묻는 질문 (FAQ)
Q. Rust vs Go, 어떤 게 나은가요?
A. Rust가 더 빠르고 메모리 안전합니다. Go가 더 배우기 쉽습니다. 최고 성능이 필요하면 Rust, 빠른 개발이 필요하면 Go를 권장합니다.
Q. 학습 곡선이 가파른가요?
A. 네, Rust는 학습 곡선이 가파릅니다. Ownership, Borrowing 등 새로운 개념이 많습니다.
Q. 웹 개발에 적합한가요?
A. 네, 고성능이 필요한 경우 매우 적합합니다. 하지만 개발 속도는 Python/Node.js보다 느립니다.
Q. 프로덕션에서 사용해도 되나요?
A. 네, Discord, Cloudflare, AWS 등에서 사용합니다.