Tokio for Rust: A Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is Tokio and why do you need it?



Tokio is an asynchronous runtime for the Rust programming language. It provides infrastructure for writing fast, reliable, and scalable network applications. If you are writing something in Rust that works with networks, files, or requires parallel request processing without blocking threads — you need Tokio.



Unlike the traditional multi-threaded approach, where each request is processed in a separate OS thread (which is expensive and limited), Tokio uses an event-driven asynchronous I/O model. A single thread can handle thousands of simultaneously open connections, switching between tasks only when the current task is waiting (for example, reading from a socket).



Tokio is not just a library, it is an ecosystem. It includes:

  • Runtime — task scheduler and event drivers (epoll/kqueue/IOCP)
  • Standard network protocols — TCP, UDP, Unix sockets
  • Timers — sleep, interval, deadline
  • Synchronization — mutexes, semaphores, barriers for asynchronous code
  • File I/O — asynchronous file reading/writing
  • Utilities — channels (mpsc, oneshot, broadcast), buffers, codec


Tokio is the foundation of well-known projects such as the web framework Axum, the HTTP client Reqwest, the WebSocket library Tungstenite, the database library SQLx, and many others.



Installation



Unlike Python (pip) or Node.js (npm), Rust uses the Cargo package system. To install Tokio, add the dependency to your Cargo.toml file:



[dependencies]tokio = { version = "1", features = ["full"] }


The flag features = ["full"] enables all Tokio features. For production projects, it is recommended to select only the necessary features to reduce compilation time and binary size:



[dependencies]tokio = { version = "1", features = ["rt", "macros", "net", "io-util", "time", "sync"] }


Main features:

  • rt — multi-threaded runtime
  • macros — macros #[tokio::main] and tokio::select!
  • net — TCP, UDP, Unix sockets
  • io-util — asynchronous Reader/Writer
  • time — timers and sleep
  • sync — synchronization primitives
  • fs — asynchronous file system operations
  • process — asynchronous command execution
  • signal — OS signal handling


Quick Start



Let's create a simple HTTP server that responds with "Hello, World!" to any request. For this, we will also need the hyper crate (an HTTP library built on top of Tokio):



// Cargo.toml// [dependencies]// tokio = { version = "1", features = ["full"] }// hyper = { version = "1", features = ["server", "http1"] }

use hyper::service::service_fn;use hyper::{Request, Response, Server};use hyper::body::Incoming;use std::convert::Infallible;

async fn handle_request(_req: Request<Incoming>) -> Result<Response<String>, Infallible> { Ok(Response::new("Hello, World!".to_string()))}

#[tokio::main]async fn main() { let addr = ([127, 0, 0, 1], 3000).into(); let server = Server::bind(&addr).serve(service_fn(handle_request)); println!("Server running on http://{}", addr); if let Err(e) = server.await { eprintln!("Server error: {}", e); }}


Run cargo run and open http://127.0.0.1:3000 in your browser. You will see "Hello, World!".



Main Methods and Functions



1. tokio::spawn

Recommendations