SlideShare a Scribd company logo
Asynchronous I/O in Rust
Enrico Risa - OrientDB
ROME 24-25 MARCH 2017
About You
• Any async I/O ?
• … with Rust?
• … maybe Node.js
About Me
• Java/Javascript developer at OrientDB
@wolf4ood
• Nightly Rust developer
This Talk
• Async I/O for network
• Current status in standard library
• Crates available for doing async I/O
The std::{io,net} way
use std::io::prelude::*;
use std::net::TcpStream;
fn main() {
let mut stream = TcpStream::connect(“127.0.0.1:2424").unwrap();
let _ = stream.read_exact(&mut [0; 128]);
}
Simple Server
use std::io::Write;
use std::net::TcpListener;
use std::thread;
fn main() {
let listener = TcpListener::bind(“127.0.0.1:9123").unwrap();
println!("listening started, ready to accept”);
for stream in listener.incoming() {
thread::spawn(|| {
let mut stream = stream.unwrap();
stream.write(b"Hello Worldrn").unwrap();
});
}
}
Simple Web Server
(Hyper 0.10.x)
extern crate hyper;
use hyper::server::{Server, Request, Response};
fn main() {
let server = Server::http(“127.0.0.1:8080").unwrap();
let _guard = server.handle(|mut req: Request, mut res: Response| {
res.send(b"Hello Rust");
});
println!("Listening on http://127.0.0.1:8080");
}
Based on Hyper
• Iron
• Rocket
• Nickel
• Pencil
Sync Architecture
Process / Thread per connection
Async Architecture
Process / Thread handles multiple connections
Non Blocking “Event Driven”
Web Server Comparison
https://help.dreamhost.com/hc/en-us/articles/215945987-Web-server-performance-comparison
Advantages of async I/O
• Throughput
• Lower Memory usage
• Latency
• Scalability
Async I/O Model
• Readiness
• Completion
READINESS
read -> EWOULDBLOCK
poll for readiness
sockets ready
read -> data
COMPLETION
read -> OK
fired in background
do some stuff
Poll for completion notifications
Async I/O with Rust
MIO
Metal I/O (mio)
• I/O Abstraction over OS
• Zero Cost Abstraction
• Readiness Model
• Event Loop
• Handler with tokens
https://github.com/carllerche/mio
Metal I/O (mio)
• Very Low level
• Manually tracking I/O events
• Wire up a state machine
Solid foundation of async in Rust
Abstraction over the metal
for
handling async computation
Something like
• JS Promise
• Java CompletableFuture
Future
• Database Query
• HTTP Request
• CPU computation
• Timeout
• Read from a socket
• ….
FUTURES
Futures
• Composability
• Error handling / Timeout / Cancellation
• Ergonomics
• Readiness / No Callback
• Zero Cost
https://aturon.github.io/blog/2016/08/11/futures/
How it looks in Rust
pub trait Future {
type Item;
type Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error>;
}
How it looks in Rust
pub enum Async<T> {
Ready(T),
NotReady,
}
pub type Poll<T, E> = Result<Async<T>, E>;
Composition
f.and_then(|val| new_future(val))
Mapping
f.map(|val| some_new_value(val))
Joining
f.join(g)
Selecting
f.select(g)
Executors
• Current thread
• Thread Pool
• Event Loop
Combining Example
fn get_person(id : i32) -> Box<Future<Item=Person,Error=()>>
fn hello_person(person : Person) -> Box<Future<Item=String,Error=()>>
get_person(1)
.and_then(hello_person)
.map(|s|{
let result: Result<String, ()> =
Ok(format!("{} from Codemotion",s));
result
});
Combining Example
let pool = CpuPool::new_num_cpus();
let combined =
get_person(1).and_then(hello_person).map(|s|{
let result: Result<String, ()> =
Ok(format!("{} from Codemotion",s));
result
});
let future = pool.spawn(combined);
println!("{:?}",future.wait().unwrap());
Streams
pub trait Stream {
type Item;
type Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error>;
}
Stream Example
let (mut tx, rx) = mpsc::channel(10);
thread::spawn(move ||{
let mut sender = tx;
for i in 0..10 {
sender = sender.send(i).wait().unwrap();
}
});
rx.for_each(|val|{
println!("Got {:?}",val);
Ok(())
}).wait();
Zero Cost
• No Allocation in composition
• One dynamic dispatch
• No Synchronisation
https://aturon.github.io/blog/2016/09/07/futures-design
Benchmark
https://aturon.github.io/blog/2016/08/11/futures/
Is it enough?
Hello Tokio
Mio Futures
Tokio
What is?
Tokio is a platform for writing fast networking code in Rust.
Tokio (Core)
• Built on top of mio and futures
• Lower Level
• Tcp Handlers
• Timeout
• Event Loop
https://medium.com/@carllerche/announcing-tokio-df6bb4ddb34#.g9ugbqg71
Event Loop
loop {
let event = next_event();
dispatch(event);
}
Tokio Event Loop
• Core
• Handle
• Remote
Echo Server (Core)
let mut core = Core::new().unwrap();
let handle = core.handle();
let address = "127.0.0.1:8080".parse().unwrap();
let acceptor = TcpListener::bind(&address,&handle).unwrap();
let server = acceptor.incoming().for_each(|(socket,address)|{
let (reader, writer) = socket.split();
let future = copy(reader,writer).then(|result|{
println!("{:?}", result);
Ok(())
});
handle.spawn(future);
Ok(())
});
core.run(server).unwrap();
Codec
• Encoder
• Decoder
Describe how to encode and decode the frames via buffers
Codec Declaration
pub struct ExampleCodec;
impl Encoder for ExampleCodec {
type Item = String;
type Error = io::Error;
fn encode(&mut self, msg: String, buf: &mut BytesMut)
-> io::Result<()> {}
}
impl Decoder for ExampleCodec {
type Item = String;
type Error = io::Error;
fn decode(&mut self, buf: &mut BytesMut)
-> io::Result<Option<String>> {
}
}
Codec Usage
let ( writer , reader) = 

socket.framed(CodemotionCodec).split();
Tokio Architecture
Mio Futures
Tokio Core
Tokio Proto
Tokio Service
Tokio Proto
• Transport: 

encoding/deconding frames to the I/O source
• Protocol:

codec + protocol specification

Tokio Service
• Higher level
• Handle Request/Response in async way
Proto Impl
struct ExampleProto;
impl<T: Io + 'static> ServerProto<T> for ExampleProto {
type Request = String;
type Response = String;
type Transport = Framed<T, ExampleCodec>;
type BindTransport = Result<Self::Transport, io::Error>;
fn bind_transport(&self, io: T) -> Self::BindTransport {
Ok(io.framed(ExampleCodec))
}
}
Service Impl
pub struct ExampleService;
impl Service for ExampleService {
type Request = String;
type Response = String;
type Error = io::Error;
type Future = BoxFuture<String, io::Error>;
fn call(&self, req: String) -> Self::Future {
let res = format!("{} from Codemotion",req)
future::finished(res).boxed()
}
}
Hyper + Tokio = ♥
Hyper Service
#[derive(Clone, Copy)]
struct Hello;
impl Service for Hello {
type Request = Request;
type Response = Response;
type Error = hyper::Error;
type Future = FutureResult<Response, hyper::Error>;
fn call(&self, _req: Request) -> Self::Future {
let response = "Hello Rust!";
futures::future::ok(
Response::new()
.with_header(ContentLength(response.len() as u64))
.with_header(ContentType::plaintext())
.with_body(response)
)
}
}
Hyper Server
fn main() {
let addr = “127.0.0.1:8080".parse().unwrap();
let server = Http::new().bind(&addr,|| Ok(Hello)).unwrap();
println!("Listening on port 8080”);
server.run().unwrap();
}
Tokio Based Projects
• Tokio Postgres
• Tokio Redis
• Tokio Memcache
• Hyper
• Tokio Curl
• Telebot
• Tokio IRC
• ….more
Rust Rome
https://www.meetup.com/it-IT/Rust-Roma
Thank You
• Question ?
• https://github.com/carllerche/mio
• https://github.com/alexcrichton/futures-rs
• https://tokio.rs

More Related Content

What's hot (20)

ODP
Gsummit apis-2013
Gluster.org
 
PPTX
Practical Glusto Example
Gluster.org
 
PPTX
Developing High Performance Application with Aerospike & Go
Chris Stivers
 
PPTX
Optimizing Communicating Event-Loop Languages with Truffle
Stefan Marr
 
ODP
Rust Primer
Knoldus Inc.
 
PDF
The Parenscript Common Lisp to JavaScript compiler
Vladimir Sedach
 
PDF
Ai meetup Neural machine translation updated
2040.io
 
PDF
Node intro
cloudhead
 
PDF
Golang concurrency design
Hyejong
 
PDF
Profiling and optimizing go programs
Badoo Development
 
PPTX
Async await in C++
cppfrug
 
PDF
AIMeetup #4: Neural-machine-translation
2040.io
 
PDF
[POSS 2019] OVirt and Ceph: Perfect Combination.?
Worteks
 
PPTX
zmq.rs - A brief history of concurrency in Rust
Fantix King 王川
 
PDF
Restinio - header-only http and websocket server
corehard_by
 
PDF
Node36
beshoy semsem
 
KEY
Pylons + Tokyo Cabinet
Ben Cheng
 
PDF
Practical SystemTAP basics: Perl memory profiling
Lubomir Rintel
 
PDF
My talk about Tarantool and Lua at Percona Live 2016
Konstantin Osipov
 
PDF
Arbiter volumes in gluster
itisravi
 
Gsummit apis-2013
Gluster.org
 
Practical Glusto Example
Gluster.org
 
Developing High Performance Application with Aerospike & Go
Chris Stivers
 
Optimizing Communicating Event-Loop Languages with Truffle
Stefan Marr
 
Rust Primer
Knoldus Inc.
 
The Parenscript Common Lisp to JavaScript compiler
Vladimir Sedach
 
Ai meetup Neural machine translation updated
2040.io
 
Node intro
cloudhead
 
Golang concurrency design
Hyejong
 
Profiling and optimizing go programs
Badoo Development
 
Async await in C++
cppfrug
 
AIMeetup #4: Neural-machine-translation
2040.io
 
[POSS 2019] OVirt and Ceph: Perfect Combination.?
Worteks
 
zmq.rs - A brief history of concurrency in Rust
Fantix King 王川
 
Restinio - header-only http and websocket server
corehard_by
 
Pylons + Tokyo Cabinet
Ben Cheng
 
Practical SystemTAP basics: Perl memory profiling
Lubomir Rintel
 
My talk about Tarantool and Lua at Percona Live 2016
Konstantin Osipov
 
Arbiter volumes in gluster
itisravi
 

Similar to Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017 (20)

PDF
Rust With async / .await
Mario Alexandro Santini
 
PPTX
Rust Melbourne MeetUp - Rust Web Development
Bastian Gruber
 
PDF
Rust's Journey to Async/await
C4Media
 
PDF
Rust Is Safe. But Is It Fast?
ScyllaDB
 
PDF
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
apidays
 
PDF
Rust + io_uring + ktls: How Fast Can We Make HTTP?
ScyllaDB
 
PDF
Rust Synchronization Primitives
Corey Richardson
 
PDF
Porting a Streaming Pipeline from Scala to Rust
Evan Chan
 
PDF
Rust: Reach Further (from QCon Sao Paolo 2018)
nikomatsakis
 
PDF
Building Web APIs that Scale
Salesforce Developers
 
PDF
Rust_Threads.pdf
Mario Alexandro Santini
 
PPTX
C++ scalable network_io
Arindam Mukherjee
 
PDF
The Talk You've Been Await-ing For
C4Media
 
PPT
JS everywhere 2011
Oleg Podsechin
 
KEY
Concurrency in ruby
Marco Borromeo
 
PDF
The Rust Programming Language
Mario Alexandro Santini
 
PDF
Practical Rust 1x Cookbook Rustacean Team
mavukahimota22
 
PDF
Highly concurrent yet natural programming
Infinit
 
PDF
Communicating State Machines
srirammalhar
 
PPT
Server side JavaScript: going all the way
Oleg Podsechin
 
Rust With async / .await
Mario Alexandro Santini
 
Rust Melbourne MeetUp - Rust Web Development
Bastian Gruber
 
Rust's Journey to Async/await
C4Media
 
Rust Is Safe. But Is It Fast?
ScyllaDB
 
Apidays Paris 2023 - Forget TypeScript, Choose Rust to build Robust, Fast and...
apidays
 
Rust + io_uring + ktls: How Fast Can We Make HTTP?
ScyllaDB
 
Rust Synchronization Primitives
Corey Richardson
 
Porting a Streaming Pipeline from Scala to Rust
Evan Chan
 
Rust: Reach Further (from QCon Sao Paolo 2018)
nikomatsakis
 
Building Web APIs that Scale
Salesforce Developers
 
Rust_Threads.pdf
Mario Alexandro Santini
 
C++ scalable network_io
Arindam Mukherjee
 
The Talk You've Been Await-ing For
C4Media
 
JS everywhere 2011
Oleg Podsechin
 
Concurrency in ruby
Marco Borromeo
 
The Rust Programming Language
Mario Alexandro Santini
 
Practical Rust 1x Cookbook Rustacean Team
mavukahimota22
 
Highly concurrent yet natural programming
Infinit
 
Communicating State Machines
srirammalhar
 
Server side JavaScript: going all the way
Oleg Podsechin
 
Ad

More from Codemotion (20)

PDF
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Codemotion
 
PDF
Pompili - From hero to_zero: The FatalNoise neverending story
Codemotion
 
PPTX
Pastore - Commodore 65 - La storia
Codemotion
 
PPTX
Pennisi - Essere Richard Altwasser
Codemotion
 
PPTX
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Codemotion
 
PPTX
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Codemotion
 
PPTX
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Codemotion
 
PPTX
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Codemotion
 
PDF
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Codemotion
 
PDF
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Codemotion
 
PDF
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Codemotion
 
PDF
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Codemotion
 
PDF
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Codemotion
 
PDF
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Codemotion
 
PPTX
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Codemotion
 
PPTX
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
Codemotion
 
PDF
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Codemotion
 
PDF
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Codemotion
 
PDF
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Codemotion
 
PDF
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Codemotion
 
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Codemotion
 
Pompili - From hero to_zero: The FatalNoise neverending story
Codemotion
 
Pastore - Commodore 65 - La storia
Codemotion
 
Pennisi - Essere Richard Altwasser
Codemotion
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Codemotion
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Codemotion
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Codemotion
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Codemotion
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Codemotion
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Codemotion
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Codemotion
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Codemotion
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Codemotion
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Codemotion
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Codemotion
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
Codemotion
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Codemotion
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Codemotion
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Codemotion
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Codemotion
 
Ad

Recently uploaded (20)

PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
Complete Network Protection with Real-Time Security
L4RGINDIA
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
PDF
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Wojciech Ciemski for Top Cyber News MAGAZINE. June 2025
Dr. Ludmila Morozova-Buss
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
Complete Network Protection with Real-Time Security
L4RGINDIA
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
 
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Wojciech Ciemski for Top Cyber News MAGAZINE. June 2025
Dr. Ludmila Morozova-Buss
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Building Resilience with Digital Twins : Lessons from Korea
SANGHEE SHIN
 

Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017