Skip to content
Hamza The ProDeSquare Mughal edited this page Nov 1, 2025 · 2 revisions

Axumite Documentation

Version: 0.1.0
Author: ProDeSquare
License: GNU General Public License v3.0 (GPL-3.0)
Website: https://prodesquare.com
Contact: hamza@prodesquare.com

Overview

Axumite is a lightweight, high-performance API framework built on top of Axum and Tower. It provides a structured, production-ready foundation for building database-backed web APIs in Rust with built-in rate limiting, connection pooling, distributed caching, request tracing, and graceful shutdown capabilities.

Originally crafted for personal use, Axumite embodies a preferred architecture for service designβ€”simple, predictable, and efficient. Anyone is free to use, modify, or extend it for both personal and commercial projects under the GPL-3.0 license.


Core Features

πŸš€ Framework & Routing

  • Built on Axum 0.8.6 - Leverages Axum's ergonomic routing and handler system
  • Tower Middleware Integration - Composable middleware stack using Tower 0.5.2
  • Structured Route Organization - Modular route definitions with easy extensibility
  • Custom Error Handling - Centralized error handling with proper logging
  • 404 Fallback Handler - Graceful handling of unknown routes with JSON responses

πŸ’Ύ Database & Caching

  • PostgreSQL Connection Pooling - Powered by Deadpool (deadpool-postgres 0.14.1)
    • Configurable pool size (default: 16 connections)
    • Fast recycling method for optimal performance
    • Automatic connection health checks
  • Redis Connection Manager - Async Redis integration (redis 0.32.7)
    • Connection manager for efficient connection reuse
    • Built-in connection recovery
    • Tokio-compatible async operations

πŸ›‘οΈ Rate Limiting

  • Environment-Aware Rate Limiting - Automatic configuration based on environment
    • Development Mode: Global key extractor (no IP tracking)
    • Production Mode: Smart IP key extractor with real IP detection
  • Configurable Limits:
    • 10 requests per second per key
    • Burst capacity of 20 requests
  • Built with Governor & Tower-Governor - Industry-standard rate limiting

πŸ“Š Observability & Performance

  • Distributed Tracing - Built-in request tracing with tracing 0.1.41
    • Configurable log levels via RUST_LOG environment variable
    • Request/response logging with Tower HTTP trace layer
    • Automatic span creation for all HTTP requests
  • Response Compression - Full compression support (gzip, br, deflate, zstd)
  • Environment-Based Configuration - All settings via environment variables

πŸ”§ Production Optimizations

  • Optimized Release Profile:
    • Link-Time Optimization (LTO) enabled
    • Single codegen unit for maximum optimization
    • Panic abort for smaller binary size
    • Debug symbols stripped
  • Graceful Shutdown - Proper signal handling (Ctrl+C) with connection draining
  • Health Check Endpoint - Built-in /health endpoint for load balancers

Architecture

Project Structure

axumite/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ main.rs              # Entry point
β”‚   β”œβ”€β”€ app.rs               # Application initialization & server setup
β”‚   β”œβ”€β”€ config.rs            # Configuration management
β”‚   β”œβ”€β”€ state.rs             # Shared application state
β”‚   β”œβ”€β”€ error.rs             # Error handling
β”‚   β”œβ”€β”€ controllers/         # Request handlers
β”‚   β”‚   β”œβ”€β”€ mod.rs
β”‚   β”‚   β”œβ”€β”€ root_controller.rs
β”‚   β”‚   β”œβ”€β”€ health_controller.rs
β”‚   β”‚   └── error_controller.rs
β”‚   β”œβ”€β”€ routes/              # Route definitions
β”‚   β”‚   β”œβ”€β”€ mod.rs
β”‚   β”‚   └── health_routes.rs
β”‚   β”œβ”€β”€ models/              # Data models
β”‚   β”‚   β”œβ”€β”€ mod.rs
β”‚   β”‚   └── health_model.rs
β”‚   β”œβ”€β”€ middleware/          # Custom middleware
β”‚   β”‚   β”œβ”€β”€ mod.rs
β”‚   β”‚   └── rate_limit.rs
β”‚   └── db/                  # Database connections
β”‚       β”œβ”€β”€ mod.rs
β”‚       β”œβ”€β”€ postgres.rs
β”‚       └── redis.rs
β”œβ”€β”€ Cargo.toml
└── .env.example

Middleware Stack

Requests flow through the following middleware layers (in order):

  1. Rate Limiter - Enforces request rate limits based on environment
  2. Trace Layer - Logs request/response information
  3. Compression Layer - Compresses responses when supported by client
  4. Router - Routes requests to appropriate handlers

Application State

The AppState struct is shared across all handlers and contains:

pub struct AppState {
    pub db_pool: Arc<DbPool>,      // PostgreSQL connection pool
    pub redis: Arc<RedisPool>,     // Redis connection manager
    pub config: Arc<AppConfig>,    // Application configuration
}

State is cloned efficiently using Arc for thread-safe shared access.


Getting Started

Prerequisites

  • Rust 1.80+ (2024 edition)
  • PostgreSQL 12+
  • Redis 6+

Installation

  1. Clone or copy the Axumite framework:

    git clone <your-repo-url>
    cd axumite
    
  2. Copy the environment configuration:

    cp .env.example .env
    
  3. Configure your environment variables:

    # Application Settings
    APP_NAME="axumite"
    APP_HOST="127.0.0.1"
    APP_PORT="8080"
    APP_ENV="development"  # or "production"
    

    PostgreSQL Configuration

    DATABASE_HOST="127.0.0.1" DATABASE_PORT="5432" DATABASE_USER="postgres" DATABASE_PASS="your_password" DATABASE_NAME="prodesquare"

    Redis Configuration

    REDIS_URL="redis://127.0.0.1:6379"

    Logging Configuration

    RUST_LOG="axumite=debug,tower_http=info"

  4. Build and run:

    # Development
    cargo run
    

    Production (optimized)

    cargo build --release ./target/release/axumite


Configuration Reference

Environment Variables

Variable Required Default Description
APP_NAME No prodesquare_api Application name (used in logs)
APP_HOST No 127.0.0.1 Host address to bind
APP_PORT No 8080 Port to listen on
APP_ENV No production Environment mode (development or production)
DATABASE_HOST No 127.0.0.1 PostgreSQL host
DATABASE_PORT No 5432 PostgreSQL port
DATABASE_USER No postgres PostgreSQL username
DATABASE_PASS No "" PostgreSQL password
DATABASE_NAME No prodesquare PostgreSQL database name
REDIS_URL Yes - Redis connection URL
RUST_LOG No - Log level configuration

Macros

apply_rate_limiter!

Conditionally applies the appropriate rate limiter based on environment.

Usage:

let app = apply_rate_limiter!(routes::create_router())
    .with_state(state);

Behavior:

  • In production: Applies IP-based rate limiter
  • In development: Applies global rate limiter

Best Practices

1. Use AppError for handler errors

Return Result<T, AppError> from handlers to get automatic error logging and consistent error responses.

2. Share expensive resources via Arc

Database pools and Redis connections are already wrapped in Arc in AppState. Clone the state cheaply.

3. Keep handlers thin

Move business logic to separate service modules. Handlers should focus on HTTP concerns.

4. Use proper HTTP status codes

Return appropriate status codes with responses:

  • 200 OK - Successful GET/PUT
  • 201 Created - Successful POST
  • 204 No Content - Successful DELETE
  • 400 Bad Request - Invalid input
  • 404 Not Found - Resource not found
  • 500 Internal Server Error - Server errors

5. Validate input

Use Axum extractors and validation libraries to ensure data integrity before processing.

6. Use connection pools efficiently

Acquire database connections late and release them early. Don't hold connections across await points unnecessarily.

7. Monitor rate limit hits

In production, monitor rate limit rejections to identify potential issues or adjust limits.


Troubleshooting

"Database pool creation failed"

  • Verify PostgreSQL is running and accessible
  • Check DATABASE_* environment variables
  • Ensure database exists and credentials are correct

"Failed to connect to Redis"

  • Verify Redis is running
  • Check REDIS_URL format: redis://host:port
  • Test connection with redis-cli ping

Rate limiting not working as expected

  • Verify APP_ENV is set correctly
  • Check proxy headers if behind reverse proxy
  • Review rate limiter constants in rate_limit.rs

High memory usage

  • Reduce max_size in database pool configuration
  • Check for connection leaks (not releasing pool connections)
  • Monitor active connections in PostgreSQL

License

Axumite is licensed under the GNU General Public License v3.0 (GPL-3.0).

You are free to use, modify, and distribute this software, provided that derivative works remain open source under the same license.

For the full license text, see: https://github.com/ProDeSquare/axumite/blob/master/LICENSE


Support

For questions, issues, or contributions:

  • Website: https://prodesquare.com
  • Email: hamza@prodesquare.com

Built with ❀️ by ProDeSquare