Back to Rules
Rust

Rust Async Best Practices: Tokio Runtime, Channels & Concurrency Guidelines

Claude Directory November 29, 2025
0 copies 1 downloads

Unlock efficient Rust async programming with proven rules for Tokio, channels, error handling, testing, and performance tuning to build robust concurrent applications.

Rule Content
## Core Principles
**Do:** Craft readable, modular Rust code using snake_case for functions/variables and PascalCase for types, with descriptive names like `data_ready`.
*Example:*
```rust
async fn process_data(data_ready: bool) -> Result<(), Box<dyn std::error::Error>> {
    // Clear logic here
}
```
**Don't:** Repeat code or use vague names like `x` that hide intent.
*Example (Avoid):*
```rust
let x = true; // Unclear purpose
```

## Async Runtime Usage
**Do:** Rely on Tokio for async tasks, spawning with `tokio::spawn` and branching with `tokio::select!` for clean concurrency.
*Example:*
```rust
use tokio::select;
tokio::select! {
    result = some_async_op() => { /* handle */ },
    _ = tokio::time::sleep(Duration::from_secs(5)) => { /* timeout */ }
}
```
**Don't:** Mix sync blocking calls in async contexts; spawn blocking tasks separately.
*Example (Avoid):*
```rust
async fn bad() {
    std::thread::sleep(Duration::from_secs(1)); // Blocks runtime
}
```

## Channels & Shared State
**Do:** Opt for bounded `tokio::sync::mpsc` channels to enforce backpressure, and `Mutex`/`RwLock` for safe shared data.
*Example:*
```rust
let (tx, mut rx) = tokio::sync::mpsc::channel(100);
tokio::spawn(async move {
    tx.send(data).await.unwrap();
});
```
**Don't:** Use unbounded channels without limits, risking memory issues.
*Example (Avoid):*
```rust
let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); // No backpressure
```

## Error Management
**Do:** Propagate errors with `?` and define custom types via `thiserror` for clarity.
*Example:*
```rust
use thiserror::Error;
#[derive(Error, Debug)]
enum AppError { #[error("IO failure")] Io(#[from] std::io::Error) }
async fn safe_op() -> Result<(), AppError> {
    let data = fs::read_to_string("file").await?;
    Ok(())
}
```
**Don't:** Ignore errors or use panics in production async code.

## Testing Async Code
**Do:** Employ `#[tokio::test]` and `tokio::time::pause` for deterministic tests.
*Example:*
```rust
#[tokio::test]
async fn test_timeout() {
    tokio::time::pause();
    tokio::time::advance(Duration::from_secs(1)).await;
    // Assert behavior
}
```
**Don't:** Rely on real sleeps in tests, causing flakiness.

## Performance Tips
**Do:** Yield with `tokio::task::yield_now().await` in loops and use `tokio::time::interval` for timers.
*Example:*
```rust
while condition {
    tokio::task::yield_now().await;
}
```
**Don't:** Perform CPU-heavy work in async fns; use `tokio::task::spawn_blocking`.

## App Structure
**Do:** Modularize into crates for networking/DB/logic, load configs via `dotenv`, and document with `///`.
**Don't:** Monolithically cram everything into `main.rs`.

Comments

More Rules

View all
AI/ML

GLM-4.7 Optimized Config & System Prompt Designer

Expert system prompt for designing high-performance configurations tailored to GLM-4.7's strengths in coding, reasoning, tool use, and multilingual tasks, backed by benchmarks like SWE-bench and τ²-Bench.

C
Community
AI/ML

GLM-4.7 Open-Source Coding Expert: Optimized System Prompt

Leverage GLM-4.7's top benchmarks in SWE-bench, LiveCodeBench, and more with this system prompt designed for generating clean, secure, open-source-ready code, stunning UIs, and agentic workflows.

C
Community
AI/ML

GLM-4.7 Optimized Coding Agent

This system prompt transforms an AI into GLM-4.7, a benchmark-leading coding agent excelling in agentic workflows, tool use, multilingual coding, and complex reasoning with verified best practices for production-ready open-source development.

C
Community
DevOps

Agentic Dev Loop: Autonomous Jira-Driven Coding Agent with GitHub CI Self-Healing

Ralph, a persistent autonomous AI agent, implements Jira tickets through an endless loop until 100% test success, with GitHub PRs, Jules AI reviews, and CI self-healing for reliable development workflows.

C
Claude Directory
AI/ML

Türk Hukuku Uzmanı AI Agent: Güvenilir Yasal Danışman System Prompt

Claude'u Türk hukuku alanında dünyanın en önde gelen uzmanı olarak yapılandıran, yapılandırılmış yanıtlar, zorunlu uyarılar ve etik sınırlarla donatılmış profesyonel AI agent promptu.

C
Community
Database

PostgreSQL Best Practices: Expert Subagent Guide

Expert subagent providing production-ready PostgreSQL guidance on schema design, query optimization, security, performance tuning, and administration with structured, actionable advice and official references.

C
Claude Directory