A comprehensive, production-ready Rust web application blueprint built with modern technologies and best practices.
Author: Philodi
Email: me@philodi.com
Website: https://philodi.com
- Modern Web Framework: Built with Axum for high-performance async web applications
- Database Integration: PostgreSQL with SQLx for type-safe database operations
- Authentication System: Multi-scheme password hashing and JWT token management
- JSON-RPC API: Dynamic routing with comprehensive error handling
- Workspace Architecture: Multi-crate organization for maintainable code
- Production Ready: Includes logging, middleware, and development tools
- Type Safety: Full Rust type safety throughout the application stack
rust-web-app/
βββ crates/
β βββ libs/ # Shared libraries
β β βββ lib-auth/ # Authentication & authorization
β β βββ lib-core/ # Core business logic & models
β β βββ lib-rpc-core/ # JSON-RPC utilities
β β βββ lib-utils/ # Common utilities
β β βββ lib-web/ # Web framework utilities
β βββ services/
β β βββ web-server/ # Main web application
β βββ tools/
β βββ gen-key/ # Key generation utility
βββ sql/ # Database schemas and migrations
βββ web-folder/ # Static web assets
- Web Framework: Axum
- Database: PostgreSQL with SQLx
- Query Builder: Sea-Query
- ORM: ModQL (MongoDB-like filters)
- Authentication: Multi-scheme password hashing (Argon2, Blake3)
- Serialization: Serde
- Async Runtime: Tokio
- Logging: Tracing
- Rust (latest stable)
- PostgreSQL
- Docker (optional, for database)
# Using Docker (recommended)
docker run --rm --name pg -p 5432:5432 \
-e POSTGRES_PASSWORD=welcome \
postgres:17
# Or connect to your existing PostgreSQL instance
# Development mode with hot reload
cargo watch -q -c -w crates/services/web-server/src/ -w crates/libs/ -x "run -p web-server"
# Or run directly
cargo run -p web-server
# Run the quick development example
cargo run -p web-server --example quick_dev
# Run all tests
cargo test -- --nocapture
# Terminal 1: Run the server with hot reload
cargo watch -q -c -w crates/services/web-server/src/ -w crates/libs/ -w .cargo/ -x "run -p web-server"
# Terminal 2: Run quick_dev example with hot reload
cargo watch -q -c -w crates/services/web-server/examples/ -x "run -p web-server --example quick_dev"
# Run all tests
cargo test -- --nocapture
# Run specific test
cargo test -p lib-core test_create -- --nocapture
# Watch mode for tests
cargo watch -q -c -x "test -- --nocapture"
# Connect to PostgreSQL (if using Docker)
docker exec -it -u postgres pg psql
# Enable SQL statement logging (for debugging)
ALTER DATABASE postgres SET log_statement = 'all';
- lib-auth: Handles password hashing, JWT tokens, and authentication
- lib-core: Contains business models, database operations, and core logic
- lib-rpc-core: JSON-RPC utilities and response handling
- lib-utils: Common utilities like base64 encoding and time handling
- lib-web: Web framework utilities, middleware, and logging
- Multi-scheme password hashing (Argon2, Blake3)
- JWT token management
- Secure session handling
- Type-safe database operations with SQLx
- MongoDB-like query filters with ModQL
- Transaction support
- Migration management
- Dynamic routing
- Comprehensive error handling
- Type-safe request/response handling
- Hot reloading with cargo-watch
- Key generation utility
- Comprehensive test suite
The project includes several examples demonstrating different aspects:
- quick_dev: Basic CRUD operations and API usage
- Database operations: Transaction handling and complex queries
- Authentication: User registration and login flows
cargo run -p gen-key
# Build the application
cargo build --release
# Create Dockerfile
cat > Dockerfile << 'EOF'
FROM rust:1.75-slim as builder
WORKDIR /app
COPY . .
RUN cargo build --release --bin web-server
FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY --from=builder /app/target/release/web-server .
COPY --from=builder /app/web-folder ./web-folder
EXPOSE 8080
CMD ["./web-server"]
EOF
# Build Docker image
docker build -t rust-web-app .
# Run container
docker run -p 8080:8080 \
-e DATABASE_URL="postgresql://user:password@host:5432/dbname" \
rust-web-app
# docker-compose.yml
version: '3.8'
services:
app:
build: .
ports:
- "8080:8080"
environment:
- DATABASE_URL=postgresql://postgres:welcome@db:5432/rust_web_app
depends_on:
- db
restart: unless-stopped
db:
image: postgres:17
environment:
- POSTGRES_PASSWORD=welcome
- POSTGRES_DB=rust_web_app
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
volumes:
postgres_data:
# k8s/namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
name: rust-web-app
# k8s/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: rust-web-app-config
namespace: rust-web-app
data:
DATABASE_URL: "postgresql://postgres:welcome@postgres-service:5432/rust_web_app"
RUST_LOG: "info"
# k8s/secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: rust-web-app-secrets
namespace: rust-web-app
type: Opaque
data:
# Base64 encoded secrets
JWT_SECRET: <base64-encoded-jwt-secret>
# k8s/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: rust-web-app
namespace: rust-web-app
spec:
replicas: 3
selector:
matchLabels:
app: rust-web-app
template:
metadata:
labels:
app: rust-web-app
spec:
containers:
- name: rust-web-app
image: rust-web-app:latest
ports:
- containerPort: 8080
env:
- name: DATABASE_URL
valueFrom:
configMapKeyRef:
name: rust-web-app-config
key: DATABASE_URL
- name: RUST_LOG
valueFrom:
configMapKeyRef:
name: rust-web-app-config
key: RUST_LOG
- name: JWT_SECRET
valueFrom:
secretKeyRef:
name: rust-web-app-secrets
key: JWT_SECRET
resources:
requests:
memory: "128Mi"
cpu: "100m"
limits:
memory: "512Mi"
cpu: "500m"
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
# k8s/service.yaml
apiVersion: v1
kind: Service
metadata:
name: rust-web-app-service
namespace: rust-web-app
spec:
selector:
app: rust-web-app
ports:
- protocol: TCP
port: 80
targetPort: 8080
type: ClusterIP
# k8s/ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: rust-web-app-ingress
namespace: rust-web-app
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- host: rust-web-app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: rust-web-app-service
port:
number: 80
# Apply manifests
kubectl apply -f k8s/namespace.yaml
kubectl apply -f k8s/configmap.yaml
kubectl apply -f k8s/secret.yaml
kubectl apply -f k8s/deployment.yaml
kubectl apply -f k8s/service.yaml
kubectl apply -f k8s/ingress.yaml
# Check deployment status
kubectl get pods -n rust-web-app
kubectl get services -n rust-web-app
# aws/task-definition.json
{
"family": "rust-web-app",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "256",
"memory": "512",
"executionRoleArn": "arn:aws:iam::ACCOUNT:role/ecsTaskExecutionRole",
"containerDefinitions": [
{
"name": "rust-web-app",
"image": "ACCOUNT.dkr.ecr.REGION.amazonaws.com/rust-web-app:latest",
"portMappings": [
{
"containerPort": 8080,
"protocol": "tcp"
}
],
"environment": [
{
"name": "RUST_LOG",
"value": "info"
}
],
"secrets": [
{
"name": "DATABASE_URL",
"valueFrom": "arn:aws:secretsmanager:REGION:ACCOUNT:secret:rust-web-app/database-url"
},
{
"name": "JWT_SECRET",
"valueFrom": "arn:aws:secretsmanager:REGION:ACCOUNT:secret:rust-web-app/jwt-secret"
}
],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/rust-web-app",
"awslogs-region": "REGION",
"awslogs-stream-prefix": "ecs"
}
}
}
]
}
# Create EKS cluster
eksctl create cluster --name rust-web-app --region us-west-2 --nodegroup-name standard-workers --node-type t3.medium --nodes 3 --nodes-min 1 --nodes-max 4
# Deploy to EKS
kubectl apply -f k8s/
# Create Load Balancer
kubectl expose deployment rust-web-app --type=LoadBalancer --port=80 --target-port=8080
# Cargo.toml additions for Lambda
[dependencies]
lambda_runtime = "0.8"
tokio = { version = "1", features = ["full"] }
// lambda/main.rs
use lambda_runtime::{service_fn, LambdaEvent, Error};
use serde_json::{json, Value};
async fn handler(event: LambdaEvent<Value>) -> Result<Value, Error> {
let payload = event.payload;
let response = json!({
"statusCode": 200,
"body": "Hello from Rust Lambda!"
});
Ok(response)
}
#[tokio::main]
async fn main() -> Result<(), Error> {
lambda_runtime::run(service_fn(handler)).await
}
# Build and push to Google Container Registry
gcloud builds submit --tag gcr.io/PROJECT_ID/rust-web-app
# Deploy to Cloud Run
gcloud run deploy rust-web-app \
--image gcr.io/PROJECT_ID/rust-web-app \
--platform managed \
--region us-central1 \
--allow-unauthenticated \
--set-env-vars RUST_LOG=info \
--set-secrets DATABASE_URL=database-url:latest \
--set-secrets JWT_SECRET=jwt-secret:latest
# Create GKE cluster
gcloud container clusters create rust-web-app \
--zone us-central1-a \
--num-nodes 3 \
--machine-type e2-medium
# Get credentials
gcloud container clusters get-credentials rust-web-app --zone us-central1-a
# Deploy to GKE
kubectl apply -f k8s/
// functions/main.rs
use cloud_functions::function_handler;
use serde_json::{json, Value};
#[function_handler]
async fn handler(req: Value) -> Result<Value, Box<dyn std::error::Error>> {
let response = json!({
"statusCode": 200,
"body": "Hello from Rust Cloud Function!"
});
Ok(response)
}
# Required environment variables
DATABASE_URL=postgresql://user:password@host:5432/dbname
JWT_SECRET=your-jwt-secret-key
RUST_LOG=info
# Optional environment variables
PORT=8080
HOST=0.0.0.0
The application includes health check endpoints:
GET /health
- Liveness probeGET /ready
- Readiness probe
# View application logs
kubectl logs -f deployment/rust-web-app -n rust-web-app
# Monitor resource usage
kubectl top pods -n rust-web-app
# Set up Prometheus monitoring
kubectl apply -f https://raw.githubusercontent.com/prometheus-operator/kube-prometheus/main/manifests/setup/
kubectl apply -f https://raw.githubusercontent.com/prometheus-operator/kube-prometheus/main/manifests/
This blueprint demonstrates production-ready Rust web development patterns. The codebase serves as comprehensive documentation with examples and best practices for building scalable web applications with Rust.
This is a blueprint project demonstrating production-ready Rust web development patterns. Feel free to use it as a starting point for your own projects.
This project is licensed under either of
- Apache License, Version 2.0, (LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or https://opensource.org/licenses/MIT)
at your option.
More resources for Rust for Production Coding