Skip to content

Repository files navigation

Rust Web Services Starter Template

A production-ready, enterprise-grade Rust web services starter template with domain-driven design, comprehensive security, and first-class idempotency support.

🚀 Features

Phase 1: Core Infrastructure (COMPLETED)

  • Domain-Driven Design: Clean architecture with clear separation of concerns
  • Axum Web Framework: Production-ready HTTP server with middleware support
  • Configuration Management: Environment-based configuration with validation
  • Structured Logging: JSON/Pretty logging with tracing support
  • Error Handling: Comprehensive error types with HTTP response mapping
  • Health Checks: Ready/Live endpoints for monitoring
  • Docker Support: Multi-stage Dockerfiles and docker-compose setup

🔄 Upcoming Phases

  • Phase 2: Security & Authentication + Idempotency Framework
  • Phase 3: Advanced Features (Circuit Breakers, Message Queues, Observability)
  • Phase 4: Developer Experience (Hot Reload, Coverage, API Client Generation, Feature Flags)
  • Phase 5: Testing & Documentation
  • Phase 6: Additional Framework Support (Actix-Web)

📁 Project Structure

src/
├── main.rs                          # Application entry point
├── lib.rs                           # Library exports
├── config/                          # Configuration management
│   ├── app_config.rs               # Application settings
│   ├── database.rs                 # Database configuration
│   └── observability.rs            # Metrics/tracing config
├── infrastructure/                  # External integrations
│   ├── database/                   # Database abstraction
│   │   └── traits.rs               # Repository traits
│   └── observability/              # Metrics and tracing
│       └── tracing.rs              # Tracing setup
├── application/                     # Application services
│   ├── services/                   # Business logic services
│   └── dto/                        # Data transfer objects
├── domain/                         # Core business logic
│   ├── entities/                   # Domain entities
│   ├── repositories/               # Repository traits
│   └── errors/                     # Domain errors
├── presentation/                   # HTTP layer
│   ├── handlers/                   # HTTP handlers
│   │   └── health_handlers.rs      # Health check endpoints
│   ├── middleware/                 # HTTP middleware
│   │   ├── correlation_id.rs       # Request correlation
│   │   └── logging_middleware.rs   # Request/response logging
│   └── frameworks/                 # Framework implementations
│       └── axum_impl.rs            # Axum server implementation
└── shared/                         # Shared utilities
    ├── errors.rs                   # Global error types
    ├── constants.rs                # Application constants
    ├── utils.rs                    # Utility functions
    └── types.rs                    # Common type definitions

🛠️ Technology Stack

  • Web Framework: Axum (with Actix-Web support planned)
  • Async Runtime: Tokio
  • Database: SQLx with PostgreSQL (MySQL, SQLite support planned)
  • Serialization: Serde
  • Logging: Tracing with structured output
  • Configuration: Config crate with environment variable support
  • Security: JWT, Argon2, input validation
  • Observability: Prometheus metrics, OpenTelemetry integration
  • Testing: Comprehensive unit, integration, and smoke tests

🚀 Quick Start

Prerequisites

  • Rust 1.75+
  • Docker and Docker Compose
  • PostgreSQL (or use Docker)

1. Clone and Setup

git clone <repository-url>
cd rust_webservices_starter
cp .env.example .env.local

2. Configure Environment

Edit .env.local with your settings:

# Server
APP_SERVER__HOST=0.0.0.0
APP_SERVER__PORT=8080

# Database
APP_DATABASE__HOST=localhost
APP_DATABASE__USERNAME=postgres
APP_DATABASE__PASSWORD=password
APP_DATABASE__DATABASE=app_db

# JWT Secret (minimum 32 characters)
APP_AUTH__JWT_SECRET=your-super-secret-jwt-key-change-this-in-production-minimum-32-characters

3. Run with Docker Compose

# Start all services (app, postgres, redis, prometheus, grafana)
docker-compose up -d

# View logs
docker-compose logs -f app

4. Run Locally

# Start dependencies
docker-compose up postgres redis -d

# Run the application
cargo run --bin server

5. Test the Service

# Health check
curl http://localhost:8080/health

# Readiness check (includes dependency health)
curl http://localhost:8080/health/ready

# Liveness check
curl http://localhost:8080/health/live

📊 Monitoring

🔧 Development

Build

cargo build

Test

cargo test

Check

cargo check

Format

cargo fmt

Lint

cargo clippy

📝 Configuration

The application uses environment-based configuration with the following sources (in order of precedence):

  1. Environment variables with APP_ prefix
  2. config/local.toml (for local overrides)
  3. config/{environment}.toml (development/staging/production)
  4. config/default.toml (defaults)

Key Configuration Sections

  • Server: Host, port, timeouts, connection limits
  • Database: Connection details, pool configuration
  • Authentication: JWT settings, token expiration
  • Observability: Logging format, metrics, tracing
  • Feature Flags: Enable/disable specific features

🔒 Security Features

  • CORS: Configurable cross-origin resource sharing
  • Request Logging: Comprehensive request/response logging with correlation IDs
  • Error Handling: Secure error responses without information leakage
  • Input Validation: Built-in validation framework
  • Security Headers: Standard security headers applied

🏗️ Architecture Principles

Domain-Driven Design

  • Domain Layer: Core business logic and entities
  • Application Layer: Use cases and application services
  • Infrastructure Layer: External integrations and persistence
  • Presentation Layer: HTTP handlers and framework-specific code

Dependency Direction

Presentation → Application → Domain
     ↓              ↓
Infrastructure ← ← ← ←

Key Patterns

  • Repository Pattern: Abstract data access
  • Dependency Injection: Clean separation of concerns
  • Error Propagation: Comprehensive error handling
  • Configuration: Environment-based settings

🧪 Testing Strategy

# Unit tests
cargo test --lib

# Integration tests
cargo test --test integration

# All tests
cargo test

🤝 Contributing

  1. Follow the established project structure
  2. Add comprehensive tests for new features
  3. Update documentation for significant changes
  4. Ensure all checks pass: cargo check, cargo test, cargo clippy

📄 License

MIT License - see LICENSE file for details

🗺️ Roadmap

Phase 2: Security & Authentication (Next)

  • JWT authentication middleware
  • Input validation and sanitization
  • Rate limiting implementation
  • Idempotency framework with Redis/Database storage

Phase 3: Advanced Features

  • Message queue abstraction (SQS, RabbitMQ, Redis Streams)
  • Circuit breaker with jitter
  • Comprehensive observability (Prometheus metrics)
  • Advanced health checks

Phase 4: Developer Experience

  • Hot reload development server
  • Code coverage integration
  • OpenAPI schema generation
  • API client generation (TypeScript, Python, Rust)
  • Built-in feature flags system

Phase 5: Testing & Documentation

  • Comprehensive test suite
  • CI/CD pipeline
  • Interactive setup script
  • Complete documentation

Phase 6: Framework Support

  • Actix-Web implementation
  • Alternative database drivers
  • Additional message queue providers

📞 Support

For questions, issues, or contributions, please visit our GitHub repository.

About

A starter template for webservices built in rust

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages