---
id: gh-rust-async-patterns
name: "rust-async-patterns"
url: https://skills.yangsir.net/skill/gh-rust-async-patterns
author: wshobson
domain: ai-backend-engineering
tags: ["rust", "async", "tokio", "concurrency", "backend"]
install_count: 15400
rating: 4.50 (120 reviews)
github: https://github.com/wshobson/agents/tree/main/plugins/systems-programming/skills/rust-async-patterns
---

# rust-async-patterns

> 此技能提供 Rust 异步编程的生产级模式，涵盖 Tokio 运行时、任务、通道、流和错误处理。它能帮助开发者构建高性能、高并发的异步 Rust 应用，有效处理并发服务中的错误，并优化代码性能，从而提升开发效率和系统稳定性。

**Stats**: 15,400 installs · 4.5/5 (120 reviews)

## Before / After 对比

### 异步代码调试效率

**Before**:

在没有明确异步模式指导下，Rust 开发者常面临复杂的并发问题调试、死锁和性能瓶颈，导致开发周期延长和系统不稳定。

**After**:

通过应用这些经过验证的异步模式，开发者能显著减少调试时间，避免常见的并发问题，并以更高的信心和效率构建健壮、高性能的 Rust 服务。

| Metric | Before | After | Change |
|---|---|---|---|
| 并发问题调试时间 | 60分钟 | 10分钟 | -83% |

### 异步代码错误率

**Before**:

缺乏标准化的异步编程实践，容易引入难以发现的竞态条件和逻辑错误，导致生产环境中的高错误率和系统崩溃。

**After**:

遵循推荐的异步模式和最佳实践，可以有效预防和减少异步代码中的错误，提高代码的可靠性和稳定性，降低维护成本。

| Metric | Before | After | Change |
|---|---|---|---|
| 异步代码错误率 | 30% | 5% | -83% |

## Readme

# Rust Async Patterns

Production patterns for async Rust programming with Tokio runtime, including tasks, channels, streams, and error handling.

## When to Use This Skill

- Building async Rust applications
- Implementing concurrent network services
- Using Tokio for async I/O
- Handling async errors properly
- Debugging async code issues
- Optimizing async performance

## Core Concepts

### 1. Async Execution Model

```
Future (lazy) → poll() → Ready(value) | Pending
                ↑           ↓
              Waker ← Runtime schedules
```

### 2. Key Abstractions

| Concept    | Purpose                                  |
| ---------- | ---------------------------------------- |
| `Future`   | Lazy computation that may complete later |
| `async fn` | Function returning impl Future           |
| `await`    | Suspend until future completes           |
| `Task`     | Spawned future running concurrently      |
| `Runtime`  | Executor that polls futures              |

## Quick Start

```toml
# Cargo.toml
[dependencies]
tokio = { version = "1", features = ["full"] }
futures = "0.3"
async-trait = "0.1"
anyhow = "1.0"
tracing = "0.1"
tracing-subscriber = "0.3"
```

```rust
use tokio::time::{sleep, Duration};
use anyhow::Result;

#[tokio::main]
async fn main() -> Result<()> {
    // Initialize tracing
    tracing_subscriber::fmt::init();

    // Async operations
    let result = fetch_data("https://api.example.com").await?;
    println!("Got: {}", result);

    Ok(())
}

async fn fetch_data(url: &str) -> Result<String> {
    // Simulated async operation
    sleep(Duration::from_millis(100)).await;
    Ok(format!("Data from {}", url))
}
```

## Detailed patterns and worked examples

Detailed pattern documentation lives in `references/details.md`. Read that file when the navigation tier above is insufficient.

## Best Practices

### Do's

- **Use `tokio::select!`** - For racing futures
- **Prefer channels** - Over shared state when possible
- **Use `JoinSet`** - For managing multiple tasks
- **Instrument with tracing** - For debugging async code
- **Handle cancellation** - Check `CancellationToken`

### Don'ts

- **Don't block** - Never use `std::thread::sleep` in async
- **Don't hold locks across awaits** - Causes deadlocks
- **Don't spawn unboundedly** - Use semaphores for limits
- **Don't ignore errors** - Propagate with `?` or log
- **Don't forget Send bounds** - For spawned futures


---
*Source: https://skills.yangsir.net/skill/gh-rust-async-patterns*
*Markdown mirror: https://skills.yangsir.net/api/skill/gh-rust-async-patterns/markdown*