Skip to content

A comprehensive, production-ready Rust web application blueprint built with modern technologies and best practices.

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT
Notifications You must be signed in to change notification settings

philodi-dev/rust-production-web-app

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Rust Web App Blueprint for Production Coding

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

πŸš€ Features

  • 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

πŸ“ Project Structure

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

πŸ› οΈ Technology Stack

  • 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

πŸš€ Quick Start

Prerequisites

  • Rust (latest stable)
  • PostgreSQL
  • Docker (optional, for database)

1. Start the 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

2. Run the Application

# 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

3. Test the Application

# Run the quick development example
cargo run -p web-server --example quick_dev

# Run all tests
cargo test -- --nocapture

πŸ”§ Development

Development with Watch Mode

# 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"

Running Tests

# 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"

Database Management

# 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';

πŸ—οΈ Architecture

Core Libraries

  • 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

Key Features

Authentication System

  • Multi-scheme password hashing (Argon2, Blake3)
  • JWT token management
  • Secure session handling

Database Layer

  • Type-safe database operations with SQLx
  • MongoDB-like query filters with ModQL
  • Transaction support
  • Migration management

JSON-RPC API

  • Dynamic routing
  • Comprehensive error handling
  • Type-safe request/response handling

Development Tools

  • Hot reloading with cargo-watch
  • Key generation utility
  • Comprehensive test suite

πŸ“š Examples

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

πŸ› οΈ Tools

Key Generation

cargo run -p gen-key

πŸš€ Deployment

Docker Deployment

Build Docker Image

# 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

# 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:

Kubernetes Deployment

Basic Kubernetes Manifests

# 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

Deploy to Kubernetes

# 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 Deployment

AWS ECS with Fargate

# 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"
        }
      }
    }
  ]
}

AWS EKS Deployment

# 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

AWS Lambda (Serverless)

# 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
}

GCP Deployment

Google Cloud Run

# 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

Google Kubernetes Engine (GKE)

# 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/

Google Cloud Functions (Serverless)

// 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)
}

Environment Variables

# 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

Health Checks

The application includes health check endpoints:

  • GET /health - Liveness probe
  • GET /ready - Readiness probe

Monitoring and Logging

# 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/

πŸ“– Documentation

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.

🀝 Contributing

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.

πŸ“„ License

This project is licensed under either of

at your option.


More resources for Rust for Production Coding

This repo on GitHub

About

A comprehensive, production-ready Rust web application blueprint built with modern technologies and best practices.

Topics

Resources

License

Apache-2.0, MIT licenses found

Licenses found

Apache-2.0
LICENSE-APACHE
MIT
LICENSE-MIT

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published