rust-backend-advance

Production-ready Rust backend development with Axum framework and PostgreSQL. Master async patterns, tower middleware, SQLx database operations, authentication (JWT/OAuth), testing strategies, and deployment. Use when building REST APIs, microservices, or any Rust web backend with Axum.

16 stars

Best use case

rust-backend-advance is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Production-ready Rust backend development with Axum framework and PostgreSQL. Master async patterns, tower middleware, SQLx database operations, authentication (JWT/OAuth), testing strategies, and deployment. Use when building REST APIs, microservices, or any Rust web backend with Axum.

Teams using rust-backend-advance should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/rust-backend-advance/SKILL.md --create-dirs "https://raw.githubusercontent.com/diegosouzapw/awesome-omni-skill/main/skills/development/rust-backend-advance/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/rust-backend-advance/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How rust-backend-advance Compares

Feature / Agentrust-backend-advanceStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Production-ready Rust backend development with Axum framework and PostgreSQL. Master async patterns, tower middleware, SQLx database operations, authentication (JWT/OAuth), testing strategies, and deployment. Use when building REST APIs, microservices, or any Rust web backend with Axum.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Rust + Axum Backend Mastery

Production-ready patterns for building scalable Rust backends with Axum and PostgreSQL.

## When to Use This Skill

- Building REST APIs or GraphQL with Axum
- Designing database schemas with SQLx + PostgreSQL
- Implementing authentication (JWT, OAuth 2.1)
- Writing async code with Tokio
- Creating middleware and extractors
- Testing Axum applications
- Deploying to production (Docker, Kubernetes)
- Performance optimization and monitoring

---

## Quick Start

### Minimal Axum Server

```rust
use axum::{routing::get, Router};

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "Hello, Axum!" }));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
```

### Essential Dependencies (Cargo.toml)

```toml
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
tower = "0.4"
tower-http = { version = "0.5", features = ["cors", "trace"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sqlx = { version = "0.7", features = ["runtime-tokio", "postgres", "uuid", "time"] }
uuid = { version = "1", features = ["v4", "serde"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
thiserror = "1"
anyhow = "1"
```

---

## Reference Navigation

### Core Rust Patterns
| Topic | File | Description |
|-------|------|-------------|
| Rust Idioms | [rust-patterns.md](references/rust-patterns.md) | Enums, iterators, error handling |
| Async/Tokio | [async-tokio.md](references/async-tokio.md) | Async patterns, spawn, channels |

### Axum Framework (70%)
| Topic | File | Description |
|-------|------|-------------|
| **Axum Guide** | [axum-complete-guide.md](references/axum-complete-guide.md) | Routing, handlers, state |
| Extractors | [axum-extractors.md](references/axum-extractors.md) | Path, Query, Json, State |
| Middleware | [middleware-patterns.md](references/middleware-patterns.md) | Tower layers, auth middleware |

### Database (PostgreSQL)
| Topic | File | Description |
|-------|------|-------------|
| SQLx | [sqlx-postgresql.md](references/sqlx-postgresql.md) | Queries, transactions, migrations |
| Patterns | [database-patterns.md](references/database-patterns.md) | Connection pools, optimization |

### Architecture
| Topic | File | Description |
|-------|------|-------------|
| Project Structure | [project-structure.md](references/project-structure.md) | Folder organization |
| Patterns | [architecture-patterns.md](references/architecture-patterns.md) | Microservices, modulith |

### Security & Auth
| Topic | File | Description |
|-------|------|-------------|
| Authentication | [authentication.md](references/authentication.md) | JWT, OAuth 2.1, sessions |
| Security | [security-owasp.md](references/security-owasp.md) | OWASP Top 10 for Rust |

### Testing & Quality
| Topic | File | Description |
|-------|------|-------------|
| Testing | [testing-guide.md](references/testing-guide.md) | Unit, integration, E2E |
| Error Handling | [error-handling.md](references/error-handling.md) | HTTP errors, thiserror |

### DevOps & Production
| Topic | File | Description |
|-------|------|-------------|
| Deployment | [deployment.md](references/deployment.md) | Docker, Kubernetes |
| Monitoring | [monitoring.md](references/monitoring.md) | Tracing, Prometheus |

---

## Decision Guide

### When to Choose Axum (70% - Primary)

```
✅ Choose Axum when:
- Building new Rust web projects
- Need tower ecosystem compatibility
- Want ergonomic, type-safe extractors
- Prefer modular, composable design
- Need excellent async performance
```

### When to Consider Alternatives (30%)

```
Actix-web - When you need:
- Maximum raw performance (benchmarks leader)
- Actor model for complex state
- Established ecosystem with more examples

Rocket - When you need:
- Simplest learning curve
- Most "magical" developer experience
- Rapid prototyping
```

---

## Core Patterns Summary

### Error Handling
```rust
use axum::{http::StatusCode, response::IntoResponse, Json};
use serde_json::json;

pub enum AppError {
    NotFound(String),
    Database(sqlx::Error),
    Unauthorized,
}

impl IntoResponse for AppError {
    fn into_response(self) -> axum::response::Response {
        let (status, message) = match self {
            Self::NotFound(msg) => (StatusCode::NOT_FOUND, msg),
            Self::Database(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
            Self::Unauthorized => (StatusCode::UNAUTHORIZED, "Unauthorized".into()),
        };
        (status, Json(json!({ "error": message }))).into_response()
    }
}
```

### Handler Pattern
```rust
use axum::{extract::{Path, State}, Json};
use uuid::Uuid;

async fn get_user(
    State(pool): State<PgPool>,
    Path(id): Path<Uuid>,
) -> Result<Json<User>, AppError> {
    let user = sqlx::query_as!(User, "SELECT * FROM users WHERE id = $1", id)
        .fetch_optional(&pool)
        .await?
        .ok_or_else(|| AppError::NotFound("User not found".into()))?;
    
    Ok(Json(user))
}
```

### State Management
```rust
use std::sync::Arc;
use sqlx::PgPool;

#[derive(Clone)]
pub struct AppState {
    pub db: PgPool,
    pub config: Arc<Config>,
}

let app = Router::new()
    .route("/users/:id", get(get_user))
    .with_state(AppState { db: pool, config: Arc::new(config) });
```

---

## Examples

- **[axum-starter](examples/axum-starter/)** - Minimal project template
- **[axum-rest-api](examples/axum-rest-api/)** - Complete REST API with auth

---

## Best Practices Checklist

### API Design
- [ ] Use proper HTTP methods (GET, POST, PUT, DELETE)
- [ ] Return appropriate status codes
- [ ] Validate input with extractors
- [ ] Document with OpenAPI/Swagger

### Database
- [ ] Use connection pooling (SQLx built-in)
- [ ] Always use parameterized queries
- [ ] List columns explicitly (no SELECT *)
- [ ] Use transactions for multi-step operations

### Security
- [ ] Validate all input
- [ ] Use Argon2id for passwords
- [ ] Implement rate limiting
- [ ] Set security headers (tower-http)

### Testing
- [ ] Unit tests for business logic
- [ ] Integration tests for handlers
- [ ] Use testcontainers for database tests

### Production
- [ ] Structured logging (tracing)
- [ ] Health check endpoints
- [ ] Graceful shutdown
- [ ] Docker multi-stage builds

---

## Resources

- **Axum**: https://docs.rs/axum
- **Tower**: https://docs.rs/tower
- **SQLx**: https://docs.rs/sqlx
- **Tokio**: https://tokio.rs

Related Skills

senior-backend

16
from diegosouzapw/awesome-omni-skill

Expert backend development covering API design, database architecture, microservices, message queues, caching, and system scalability.

rust

16
from diegosouzapw/awesome-omni-skill

Write production-quality Rust code following industry best practices and idiomatic patterns. Use for any Rust coding task including applications, libraries, refactoring, debugging, or code review — with particular expertise in cross-platform GUI development.

rust-router

16
from diegosouzapw/awesome-omni-skill

CRITICAL: Use for ALL Rust questions including errors, design, and coding. HIGHEST PRIORITY for: 比较, 对比, compare, vs, versus, 区别, difference, 最佳实践, best practice, tokio vs, async-std vs, 比较 tokio, 比较 async, Triggers on: Rust, cargo, rustc, crate, Cargo.toml, 意图分析, 问题分析, 语义分析, analyze intent, question analysis, compile error, borrow error, lifetime error, ownership error, type error, trait error, value moved, cannot borrow, does not live long enough, mismatched types, not satisfied, E0382, E0597, E0277, E0308, E0499, E0502, E0596, async, await, Send, Sync, tokio, concurrency, error handling, 编译错误, compile error, 所有权, ownership, 借用, borrow, 生命周期, lifetime, 类型错误, type error, 异步, async, 并发, concurrency, 错误处理, error handling, 问题, problem, question, 怎么用, how to use, 如何, how to, 为什么, why, 什么是, what is, 帮我写, help me write, 实现, implement, 解释, explain

rust-pro

16
from diegosouzapw/awesome-omni-skill

Master Rust 1.75+ with modern async patterns, advanced type system features, and production-ready systems programming.

rust-core

16
from diegosouzapw/awesome-omni-skill

Comprehensive Rust development expertise covering core principles, patterns, error handling, async programming, testing, and performance optimization. Use when working on Rust projects requiring guidance on: (1) Language fundamentals (ownership, lifetimes, borrowing), (2) Architectural decisions and design patterns, (3) Web development (Axum, Actix-web, Rocket), (4) AI/LLM integration, (5) CLI/TUI applications, (6) Desktop development with Tauri, (7) Async/await and concurrency, (8) Error handling strategies, (9) Testing and benchmarking, (10) Performance optimization, (11) Logging and observability, or (12) Code reviews and best practices.

rust-async-patterns

16
from diegosouzapw/awesome-omni-skill

Master Rust async programming with Tokio, async traits, error handling, and concurrent patterns. Use when building async Rust applications, implementing concurrent systems, or debugging async code.

rust-async-pattern

16
from diegosouzapw/awesome-omni-skill

高级异步模式专家。处理 Stream 实现, 零拷贝, tokio::spawn 生命周期, 插件系统调度, tonic 流式响应等问题。触发词:async, Stream, tokio::spawn, 零拷贝, 插件系统, tonic, 流式, BorrowedMessage, 异步调度

python-backend

16
from diegosouzapw/awesome-omni-skill

Python dominates backend development for good reason - readable code, massive ecosystem, and frameworks that scale from prototype to production. Django gives you batteries included. FastAPI gives you speed and modern async patterns. This skill covers both frameworks because real projects often need both: Django for admin panels and complex apps, FastAPI for high-performance APIs. The key insight: don't fight the framework. Django's ORM is not SQLAlchemy. FastAPI's Pydantic is not marshmallow. Learn the idioms. 2025 reality: Type hints are mandatory. Async is the default for I/O. Poetry/uv replaced pip for serious projects. If you're not using pyproject.toml, you're living in the past. Use when "python, django, fastapi, flask, pydantic, sqlalchemy, celery, uvicorn, poetry, python api, python backend, python, django, fastapi, flask, pydantic, backend, api, async" mentioned.

python-backend-guidelines

16
from diegosouzapw/awesome-omni-skill

FastAPI/Django backend patterns and best practices

python-backend-expert

16
from diegosouzapw/awesome-omni-skill

Python backend expert including Django, FastAPI, Flask, SQLAlchemy, and async patterns

Python Backend Architecture Review

16
from diegosouzapw/awesome-omni-skill

Comprehensive design architecture review for Python backend applications. Use this skill when users ask you to review, analyze, or provide feedback on backend architecture designs, system design documents, or Python application architecture. Covers scalability, security, performance, database design, API design, microservices patterns, deployment architecture, and best practices.

platform-backend

16
from diegosouzapw/awesome-omni-skill

Server-side architecture and security patterns. Extends core-coding-standards with API, error handling, and security rules. Use when building APIs or server logic.