Async Rust with Tokio: async fn in traits, cancellation-safe select!, timeouts, bounded channels for backpressure, blocking work and async tests.
.cursor/rules/rust-async-programming.mdc. Downloaded files need to be placed in that repository path.---
description: "Async Rust with Tokio: async fn in traits, cancellation-safe select!, timeouts, bounded channels for backpressure, blocking work and async tests."
globs: "**/*"
alwaysApply: false
---
Apply these rules when writing async Rust.
## Runtime
- Use the runtime the project already uses. For new code, Tokio is the common choice. `async-std` has been discontinued by its maintainers, who recommend `smol`; do not add it to new projects.
- Do not block the runtime: move CPU-heavy or blocking calls (synchronous file or database drivers, compression) to `tokio::task::spawn_blocking` or a dedicated thread pool.
## Async traits
- `async fn` in traits is stable since Rust 1.75. For public traits whose futures must be `Send`, use the `trait-variant` crate to generate a `Send` variant. Traits with `async fn` are not dyn-compatible; use generics, or the `async-trait` crate when you need `dyn Trait`.
## Cancellation and select!
- Any `.await` can be the last one: a future can be dropped at an await point. Keep invariants valid across awaits and release resources through `Drop`.
- In `tokio::select!` loops, only use cancel-safe operations in branches that may lose the race (for example `mpsc::Receiver::recv`, `TcpListener::accept`). `read_exact`, `write_all` and `Mutex::lock` are not cancel-safe; pin the future outside the loop or restructure.
- Use a `CancellationToken` (tokio-util) or a shutdown channel for graceful shutdown, and `JoinSet` to track spawned tasks.
## Timeouts, channels and backpressure
- Wrap network calls and other unbounded waits in `tokio::time::timeout`, and decide what happens on timeout (retry, error, skip).
- Prefer bounded `mpsc` channels so producers wait when consumers fall behind. Use `oneshot` for single replies, `broadcast` for fan-out and `watch` for latest-value state.
- Use `std::sync::Mutex` for short critical sections; switch to `tokio::sync::Mutex` only when the guard must be held across an `.await`.
```rust
use std::time::Duration;
use tokio::{sync::mpsc, time::timeout};
use tokio_util::sync::CancellationToken;
async fn run_worker(mut jobs: mpsc::Receiver<Job>, shutdown: CancellationToken) {
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
job = jobs.recv() => { // recv() is cancel-safe
let Some(job) = job else { break }; // all senders dropped
if timeout(Duration::from_secs(5), job.run()).await.is_err() {
tracing::warn!(job_id = job.id, "job timed out");
}
}
}
}
}
```
## Testing
- Use `#[tokio::test]` for async tests. For time-dependent logic, enable Tokio's `test-util` feature and use `#[tokio::test(start_paused = true)]` so timers advance without real waiting.
- Test the cancellation and timeout paths, not only success.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
language
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A Tokio service has a worker loop that uses select! with read_exact on a socket and an unbounded channel; jobs occasionally lose bytes and memory grows under load.
Using the Rust Async Programming rule, review src/worker.rs and propose changes. Runtime: Tokio 1.x, tokio-util available.
A review that flags read_exact inside select! as not cancel-safe, replaces the unbounded channel with a bounded mpsc, adds a timeout around each job, adds a CancellationToken shutdown branch, moves blocking calls to spawn_blocking, and proposes a #[tokio::test(start_paused = true)] test for the timeout path.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/rust-async-programming.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Rust Async Programming project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these rules when writing async Rust.
## Runtime
- Use the runtime the project already uses. For new code, Tokio is the common choice. `async-std` has been discontinued by its maintainers, who recommend `smol`; do not add it to new projects.
- Do not block the runtime: move CPU-heavy or blocking calls (synchronous file or database drivers, compression) to `tokio::task::spawn_blocking` or a dedicated thread pool.
## Async traits
- `async fn` in traits is stable since Rust 1.75. For public traits whose futures must be `Send`, use the `trait-variant` crate to generate a `Send` variant. Traits with `async fn` are not dyn-compatible; use generics, or the `async-trait` crate when you need `dyn Trait`.
## Cancellation and select!
- Any `.await` can be the last one: a future can be dropped at an await point. Keep invariants valid across awaits and release resources through `Drop`.
- In `tokio::select!` loops, only use cancel-safe operations in branches that may lose the race (for example `mpsc::Receiver::recv`, `TcpListener::accept`). `read_exact`, `write_all` and `Mutex::lock` are not cancel-safe; pin the future outside the loop or restructure.
- Use a `CancellationToken` (tokio-util) or a shutdown channel for graceful shutdown, and `JoinSet` to track spawned tasks.
## Timeouts, channels and backpressure
- Wrap network calls and other unbounded waits in `tokio::time::timeout`, and decide what happens on timeout (retry, error, skip).
- Prefer bounded `mpsc` channels so producers wait when consumers fall behind. Use `oneshot` for single replies, `broadcast` for fan-out and `watch` for latest-value state.
- Use `std::sync::Mutex` for short critical sections; switch to `tokio::sync::Mutex` only when the guard must be held across an `.await`.
```rust
use std::time::Duration;
use tokio::{sync::mpsc, time::timeout};
use tokio_util::sync::CancellationToken;
async fn run_worker(mut jobs: mpsc::Receiver<Job>, shutdown: CancellationToken) {
loop {
tokio::select! {
_ = shutdown.cancelled() => break,
job = jobs.recv() => { // recv() is cancel-safe
let Some(job) = job else { break }; // all senders dropped
if timeout(Duration::from_secs(5), job.run()).await.is_err() {
tracing::warn!(job_id = job.id, "job timed out");
}
}
}
}
}
```
## Testing
- Use `#[tokio::test]` for async tests. For time-dependent logic, enable Tokio's `test-util` feature and use `#[tokio::test(start_paused = true)]` so timers advance without real waiting.
- Test the cancellation and timeout paths, not only success.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.