Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Implement Rust async code with Tokio, handle concurrency primitives, and avoid common async pitfalls.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
SKILL.md
1---2name: rust-async-patterns3description: 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.4---56# Rust Async Patterns78Production patterns for async Rust programming with Tokio runtime, including tasks, channels, streams, and error handling.910## When to Use This Skill1112- Building async Rust applications13- Implementing concurrent network services14- Using Tokio for async I/O15- Handling async errors properly16- Debugging async code issues17- Optimizing async performance1819## Core Concepts2021### 1. Async Execution Model2223```24Future (lazy) → poll() → Ready(value) | Pending25↑ ↓26Waker ← Runtime schedules27```2829### 2. Key Abstractions3031| Concept | Purpose |32| ---------- | ---------------------------------------- |33| `Future` | Lazy computation that may complete later |34| `async fn` | Function returning impl Future |35| `await` | Suspend until future completes |36| `Task` | Spawned future running concurrently |37| `Runtime` | Executor that polls futures |3839## Quick Start4041```toml42# Cargo.toml43[dependencies]44tokio = { version = "1", features = ["full"] }45futures = "0.3"46async-trait = "0.1"47anyhow = "1.0"48tracing = "0.1"49tracing-subscriber = "0.3"50```5152```rust53use tokio::time::{sleep, Duration};54use anyhow::Result;5556#[tokio::main]57async fn main() -> Result<()> {58// Initialize tracing59tracing_subscriber::fmt::init();6061// Async operations62let result = fetch_data("https://api.example.com").await?;63println!("Got: {}", result);6465Ok(())66}6768async fn fetch_data(url: &str) -> Result<String> {69// Simulated async operation70sleep(Duration::from_millis(100)).await;71Ok(format!("Data from {}", url))72}73```7475## Detailed patterns and worked examples7677Detailed pattern documentation lives in `references/details.md`. Read that file when the navigation tier above is insufficient.7879## Best Practices8081### Do's8283- **Use `tokio::select!`** - For racing futures84- **Prefer channels** - Over shared state when possible85- **Use `JoinSet`** - For managing multiple tasks86- **Instrument with tracing** - For debugging async code87- **Handle cancellation** - Check `CancellationToken`8889### Don'ts9091- **Don't block** - Never use `std::thread::sleep` in async92- **Don't hold locks across awaits** - Causes deadlocks93- **Don't spawn unboundedly** - Use semaphores for limits94- **Don't ignore errors** - Propagate with `?` or log95- **Don't forget Send bounds** - For spawned futures96