Why async?
Async programming lets a single thread handle thousands of concurrent connections without the overhead of OS threads. In a web server this translates directly to throughput.
The async/await model
Rust’s async fn returns a future — a value that represents a computation not yet run. Futures are lazy: nothing happens until you .await them or hand them to an executor.
async fn fetch_user(id: Uuid) -> Result<User, Error> {
sqlx::query_as("SELECT * FROM users WHERE id = $1")
.bind(id)
.fetch_one(&pool)
.await
}
Tokio: the runtime
Tokio is the de-facto async runtime for Rust. It provides the event loop, a thread pool, and utilities like timers and channels. Annotate your main with #[tokio::main] and you’re off.
No comments yet
Leave a comment