SlideShare a Scribd company logo
Brought to you by
Rust Is Safe. But Is It Fast?
Glauber Costa
Author and Maintainer of Glommio
Founder/CEO ChiselStrike
Glauber Costa
■ Author and maintainer of Glommio Rust async executor.
■ Veteran of low-latency high performance systems.
● Linux Kernel, ScyllaDB, Datadog.
■ Founder/CEO ChiselStrike.
Why Rust?
■ A … less powerful C++?
■ “All” pointers are smart pointers.
● Exceptions explicitly use unsafe keyword.
Lifetimes
■ RAII rules define minimum lifetime.
■ Borrow checker enforce lifetimes for references.
● Live as-long-as. Leaks still possible.
● But no use-after-free!
let a = Object::new();
let b = &a;
drop(a);
use(b); // impossible
Trait system
■ Similar to C++ concepts.
■ Specify “trait bounds”.
fn function<T>(arg: T) {
println!(“value: {}”, arg);
}
fn function<T: Display>(arg: T) {
println!(“value: {}”, arg);
}
Fails Succeeds
Special lifetimes
■ static:
● As a reference: “entire lifetime of the program”.
● As a trait bound: “never becomes invalid”.
■ owned data as well as static references.
fn background<T: ‘static>(foo: T) { … }
let a = T::new();
background(a); // Ok!
background(&a); // Fails!
Dealing with references in static contexts
■ Clone trait bound.
● Think shared pointers.
● Each user extends the life of the data: memory safe.
● Remember: leaks still possible.
fn background<T: ‘static + Clone>(foo: &T) {
let f = foo.clone(); // Ok, new object is created
}
let a = T::new();
background(a); // Ok!
background(&a); // Ok too!
Dealing with multiple threads
■ Send trait bound.
● Types that can be transferred across thread boundaries.
● Nothing said about access.
● Reference counted pointer (Rc): NOT Send.
■ Special “Atomic Rc” (Arc) is Send.
Async Rust
■ Implemented through the Trait system.
pub trait Future {
type Output; // Return value
pub fn poll(
self: Pin<&mut Self>,
cx: &mut Context<'_> // state
) -> Poll<Self::Output>; // Ready<T> or Pending
Driving Futures
■ No standard way, bring your own.
■ Tokio, async-std, Glommio.
■ “Simple” event loop calling poll continuously.
● But in practice: I/O, channels, timers, core types, etc.
Rust basic Futures
■ Akin to co-routines.
■ No parallelism between x and y.
let x = foo.await;
let y = bar.await;
x + y
Rust basic Futures
■ select-like multi-future possible.
■ More common, spawn tasks.
let x = spawn(async move { // code });
Tokio spawn
■ Can be executed in any thread (Send).
■ Indeterminate lifetime (static).
■ Scoping harder than it seems.
● See https://itnext.io/async-rust-history-strikes-back-d69aced6760
pub fn spawn<T>(future: T) -> JoinHandle<T::Output>
where
T: Future + Send + 'static,
T::Output: Send + 'static,
Glommio spawn
■ Nothing is Send.
■ Internal state machine is almost entirely free of atomics.
pub fn local<T>(future: T) -> JoinHandle<T::Output>
where
T: Future + 'static,
T::Output: 'static,
Glommio x-thread wake
Glommio Executor
Task
State
Foreign Executor
Clone: Atomic reference count
mpsc lockless
queue
Wake: push to queue
Results
https://github.com/fujita/greeter - “minimum” baseline removed for clarity
Unfortunate reality
■ Swapping executors kind of ok.
● Lack of timer trait is a problem, though.
■ But tokio and async-std depend heavily on Send.
● Not possible to inherit traits.
● In practice many libraries do too.
The challenge with File I/O
■ Tokio File I/O uses a thread-pool.
■ Newer Optane thread-pool results underwhelming.
■ linux-aio hard to get right.
■ Enters io_uring.
https://www.scylladb.com/2020/05/05/how-io_uring-and-ebpf-will-revolutionize-programming-in-linux/
Glommio File I/O
■ io_uring natively.
■ Incentivizes Direct I/O, but works with buffered I/O too.
■ Positional reads:
● read_at(pos, sz) -> ReadResult;
● io_uring pre-mapped registered buffers.
■ Stream Writer, Stream Reader:
● AsyncWrite, AsyncRead.
Newer developments
■ Tokio recently announced tokio-uring.
■ Similar design, looking forward!
Buffer lifetimes
■ Hard to zero-copy.
■ Infamous Rust “cancellation problem”.
● Tasks can die at any time, kernel keeps writing to the buffer.
impl AsyncRead for DmaStreamReader {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8], // not guaranteed stable.
) -> Poll<io::Result<usize>> {
AsyncBufRead ?
■ Better, as it returns a buffer.
■ Higher-level functions will likely still copy.
impl AsyncBufRead for StreamReader {
fn poll_fill_buf<'a>(
mut self: Pin<&'a mut Self>,
cx: &mut Context<'_>,
) -> Poll<io::Result<&'a [u8]>>
Summary
■ Reference Count explosion limits scalability.
● Possible to avoid with TPC executor.
● But currently hard to swap executors.
■ File I/O performance a concern.
● io_uring increased adoption bridges that gap.
● tokio-uring exciting news.
■ Still hard to do real zero-copy I/O.
● Async workgroup has good proposals for this.
Brought to you by
Glauber Costa
glauber@chiselstrike.com
@glcst

More Related Content

PDF
BGP Unnumbered で遊んでみた
PDF
BPF / XDP 8월 세미나 KossLab
PPTX
Ceph アーキテクチャ概説
PPTX
フロー技術によるネットワーク管理
PDF
P2P Container Image Distribution on IPFS With containerd and nerdctl
PDF
Neutron packet logging framework
PPTX
Ceph and Openstack in a Nutshell
BGP Unnumbered で遊んでみた
BPF / XDP 8월 세미나 KossLab
Ceph アーキテクチャ概説
フロー技術によるネットワーク管理
P2P Container Image Distribution on IPFS With containerd and nerdctl
Neutron packet logging framework
Ceph and Openstack in a Nutshell

What's hot (20)

PPTX
Deep Dive into Apache Kafka
PDF
DPDKによる高速コンテナネットワーキング
PPTX
[OpenStack 하반기 스터디] Interoperability with ML2: LinuxBridge, OVS and SDN
PDF
Disaster Recovery Plans for Apache Kafka
PDF
TCAMのしくみ
PDF
eBPF - Rethinking the Linux Kernel
PDF
CERN Data Centre Evolution
PDF
Ceph Block Devices: A Deep Dive
PDF
UM2019 Extended BPF: A New Type of Software
PDF
Xdp and ebpf_maps
PDF
IoT時代におけるストリームデータ処理と急成長の Apache Flink
PDF
EBPF and Linux Networking
PDF
Blazing Performance with Flame Graphs
PPTX
Kafka 101
PDF
CXL_説明_公開用.pdf
PDF
Microservices
PDF
[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...
PDF
エンジニアなら知っておきたい「仮想マシン」のしくみ v1.1 (hbstudy 17)
PDF
How VXLAN works on Linux
PDF
Ceph issue 해결 사례
Deep Dive into Apache Kafka
DPDKによる高速コンテナネットワーキング
[OpenStack 하반기 스터디] Interoperability with ML2: LinuxBridge, OVS and SDN
Disaster Recovery Plans for Apache Kafka
TCAMのしくみ
eBPF - Rethinking the Linux Kernel
CERN Data Centre Evolution
Ceph Block Devices: A Deep Dive
UM2019 Extended BPF: A New Type of Software
Xdp and ebpf_maps
IoT時代におけるストリームデータ処理と急成長の Apache Flink
EBPF and Linux Networking
Blazing Performance with Flame Graphs
Kafka 101
CXL_説明_公開用.pdf
Microservices
[OpenInfra Days Korea 2018] Day 2 - CEPH 운영자를 위한 Object Storage Performance T...
エンジニアなら知っておきたい「仮想マシン」のしくみ v1.1 (hbstudy 17)
How VXLAN works on Linux
Ceph issue 해결 사례
Ad

Similar to Rust Is Safe. But Is It Fast? (20)

PDF
Dynamic Change Data Capture with Flink CDC and Consistent Hashing
PDF
Dynamic Change Data Capture with Flink CDC and Consistent Hashing
PDF
Ruxmon.2013-08.-.CodeBro!
PDF
Atmosphere Conference 2015: Need for Async: In pursuit of scalable internet-s...
PPTX
Parallel computing in bioinformatics t.seemann - balti bioinformatics - wed...
PDF
Node.js for Rubists
PPTX
Traitement temps réel chez Streamroot - Golang Paris Juin 2016
PDF
The art of concurrent programming
PPTX
C100 k and go
PDF
MOVED: The challenge of SVE in QEMU - SFO17-103
PPTX
lec5 - The processor.pptx
PDF
Need for Async: Hot pursuit for scalable applications
PDF
"Lightweight Virtualization with Linux Containers and Docker". Jerome Petazzo...
PPTX
Adventures in Thread-per-Core Async with Redpanda and Seastar
PDF
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
PDF
Kernel Recipes 2018 - Zinc: minimal lightweight crypto API - Jason Donenfeld
PDF
inside-linux-kernel-rng-presentation-sept-13-2022.pdf
PDF
Lightweight Virtualization with Linux Containers and Docker I YaC 2013
PDF
Lightweight Virtualization with Linux Containers and Docker | YaC 2013
PDF
Stripe CTF3 wrap-up
Dynamic Change Data Capture with Flink CDC and Consistent Hashing
Dynamic Change Data Capture with Flink CDC and Consistent Hashing
Ruxmon.2013-08.-.CodeBro!
Atmosphere Conference 2015: Need for Async: In pursuit of scalable internet-s...
Parallel computing in bioinformatics t.seemann - balti bioinformatics - wed...
Node.js for Rubists
Traitement temps réel chez Streamroot - Golang Paris Juin 2016
The art of concurrent programming
C100 k and go
MOVED: The challenge of SVE in QEMU - SFO17-103
lec5 - The processor.pptx
Need for Async: Hot pursuit for scalable applications
"Lightweight Virtualization with Linux Containers and Docker". Jerome Petazzo...
Adventures in Thread-per-Core Async with Redpanda and Seastar
Asynchronous IO in Rust - Enrico Risa - Codemotion Rome 2017
Kernel Recipes 2018 - Zinc: minimal lightweight crypto API - Jason Donenfeld
inside-linux-kernel-rng-presentation-sept-13-2022.pdf
Lightweight Virtualization with Linux Containers and Docker I YaC 2013
Lightweight Virtualization with Linux Containers and Docker | YaC 2013
Stripe CTF3 wrap-up
Ad

More from ScyllaDB (20)

PDF
Understanding The True Cost of DynamoDB Webinar
PDF
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
PDF
Database Benchmarking for Performance Masterclass: Session 1 - Benchmarking F...
PDF
New Ways to Reduce Database Costs with ScyllaDB
PDF
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
PDF
Powering a Billion Dreams: Scaling Meesho’s E-commerce Revolution with Scylla...
PDF
Leading a High-Stakes Database Migration
PDF
Achieving Extreme Scale with ScyllaDB: Tips & Tradeoffs
PDF
Securely Serving Millions of Boot Artifacts a Day by João Pedro Lima & Matt ...
PDF
How Agoda Scaled 50x Throughput with ScyllaDB by Worakarn Isaratham
PDF
How Yieldmo Cut Database Costs and Cloud Dependencies Fast by Todd Coleman
PDF
ScyllaDB: 10 Years and Beyond by Dor Laor
PDF
Reduce Your Cloud Spend with ScyllaDB by Tzach Livyatan
PDF
Migrating 50TB Data From a Home-Grown Database to ScyllaDB, Fast by Terence Liu
PDF
Vector Search with ScyllaDB by Szymon Wasik
PDF
Workload Prioritization: How to Balance Multiple Workloads in a Cluster by Fe...
PDF
Two Leading Approaches to Data Virtualization, and Which Scales Better? by Da...
PDF
Scaling a Beast: Lessons from 400x Growth in a High-Stakes Financial System b...
PDF
Object Storage in ScyllaDB by Ran Regev, ScyllaDB
PDF
Lessons Learned from Building a Serverless Notifications System by Srushith R...
Understanding The True Cost of DynamoDB Webinar
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
Database Benchmarking for Performance Masterclass: Session 1 - Benchmarking F...
New Ways to Reduce Database Costs with ScyllaDB
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Powering a Billion Dreams: Scaling Meesho’s E-commerce Revolution with Scylla...
Leading a High-Stakes Database Migration
Achieving Extreme Scale with ScyllaDB: Tips & Tradeoffs
Securely Serving Millions of Boot Artifacts a Day by João Pedro Lima & Matt ...
How Agoda Scaled 50x Throughput with ScyllaDB by Worakarn Isaratham
How Yieldmo Cut Database Costs and Cloud Dependencies Fast by Todd Coleman
ScyllaDB: 10 Years and Beyond by Dor Laor
Reduce Your Cloud Spend with ScyllaDB by Tzach Livyatan
Migrating 50TB Data From a Home-Grown Database to ScyllaDB, Fast by Terence Liu
Vector Search with ScyllaDB by Szymon Wasik
Workload Prioritization: How to Balance Multiple Workloads in a Cluster by Fe...
Two Leading Approaches to Data Virtualization, and Which Scales Better? by Da...
Scaling a Beast: Lessons from 400x Growth in a High-Stakes Financial System b...
Object Storage in ScyllaDB by Ran Regev, ScyllaDB
Lessons Learned from Building a Serverless Notifications System by Srushith R...

Recently uploaded (20)

PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Spectroscopy.pptx food analysis technology
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPT
Teaching material agriculture food technology
PDF
Encapsulation theory and applications.pdf
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Programs and apps: productivity, graphics, security and other tools
Reach Out and Touch Someone: Haptics and Empathic Computing
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
sap open course for s4hana steps from ECC to s4
Spectroscopy.pptx food analysis technology
“AI and Expert System Decision Support & Business Intelligence Systems”
Teaching material agriculture food technology
Encapsulation theory and applications.pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Building Integrated photovoltaic BIPV_UPV.pdf
Spectral efficient network and resource selection model in 5G networks
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Digital-Transformation-Roadmap-for-Companies.pptx

Rust Is Safe. But Is It Fast?

  • 1. Brought to you by Rust Is Safe. But Is It Fast? Glauber Costa Author and Maintainer of Glommio Founder/CEO ChiselStrike
  • 2. Glauber Costa ■ Author and maintainer of Glommio Rust async executor. ■ Veteran of low-latency high performance systems. ● Linux Kernel, ScyllaDB, Datadog. ■ Founder/CEO ChiselStrike.
  • 3. Why Rust? ■ A … less powerful C++? ■ “All” pointers are smart pointers. ● Exceptions explicitly use unsafe keyword.
  • 4. Lifetimes ■ RAII rules define minimum lifetime. ■ Borrow checker enforce lifetimes for references. ● Live as-long-as. Leaks still possible. ● But no use-after-free! let a = Object::new(); let b = &a; drop(a); use(b); // impossible
  • 5. Trait system ■ Similar to C++ concepts. ■ Specify “trait bounds”. fn function<T>(arg: T) { println!(“value: {}”, arg); } fn function<T: Display>(arg: T) { println!(“value: {}”, arg); } Fails Succeeds
  • 6. Special lifetimes ■ static: ● As a reference: “entire lifetime of the program”. ● As a trait bound: “never becomes invalid”. ■ owned data as well as static references. fn background<T: ‘static>(foo: T) { … } let a = T::new(); background(a); // Ok! background(&a); // Fails!
  • 7. Dealing with references in static contexts ■ Clone trait bound. ● Think shared pointers. ● Each user extends the life of the data: memory safe. ● Remember: leaks still possible. fn background<T: ‘static + Clone>(foo: &T) { let f = foo.clone(); // Ok, new object is created } let a = T::new(); background(a); // Ok! background(&a); // Ok too!
  • 8. Dealing with multiple threads ■ Send trait bound. ● Types that can be transferred across thread boundaries. ● Nothing said about access. ● Reference counted pointer (Rc): NOT Send. ■ Special “Atomic Rc” (Arc) is Send.
  • 9. Async Rust ■ Implemented through the Trait system. pub trait Future { type Output; // Return value pub fn poll( self: Pin<&mut Self>, cx: &mut Context<'_> // state ) -> Poll<Self::Output>; // Ready<T> or Pending
  • 10. Driving Futures ■ No standard way, bring your own. ■ Tokio, async-std, Glommio. ■ “Simple” event loop calling poll continuously. ● But in practice: I/O, channels, timers, core types, etc.
  • 11. Rust basic Futures ■ Akin to co-routines. ■ No parallelism between x and y. let x = foo.await; let y = bar.await; x + y
  • 12. Rust basic Futures ■ select-like multi-future possible. ■ More common, spawn tasks. let x = spawn(async move { // code });
  • 13. Tokio spawn ■ Can be executed in any thread (Send). ■ Indeterminate lifetime (static). ■ Scoping harder than it seems. ● See https://itnext.io/async-rust-history-strikes-back-d69aced6760 pub fn spawn<T>(future: T) -> JoinHandle<T::Output> where T: Future + Send + 'static, T::Output: Send + 'static,
  • 14. Glommio spawn ■ Nothing is Send. ■ Internal state machine is almost entirely free of atomics. pub fn local<T>(future: T) -> JoinHandle<T::Output> where T: Future + 'static, T::Output: 'static,
  • 15. Glommio x-thread wake Glommio Executor Task State Foreign Executor Clone: Atomic reference count mpsc lockless queue Wake: push to queue
  • 17. Unfortunate reality ■ Swapping executors kind of ok. ● Lack of timer trait is a problem, though. ■ But tokio and async-std depend heavily on Send. ● Not possible to inherit traits. ● In practice many libraries do too.
  • 18. The challenge with File I/O ■ Tokio File I/O uses a thread-pool. ■ Newer Optane thread-pool results underwhelming. ■ linux-aio hard to get right. ■ Enters io_uring. https://www.scylladb.com/2020/05/05/how-io_uring-and-ebpf-will-revolutionize-programming-in-linux/
  • 19. Glommio File I/O ■ io_uring natively. ■ Incentivizes Direct I/O, but works with buffered I/O too. ■ Positional reads: ● read_at(pos, sz) -> ReadResult; ● io_uring pre-mapped registered buffers. ■ Stream Writer, Stream Reader: ● AsyncWrite, AsyncRead.
  • 20. Newer developments ■ Tokio recently announced tokio-uring. ■ Similar design, looking forward!
  • 21. Buffer lifetimes ■ Hard to zero-copy. ■ Infamous Rust “cancellation problem”. ● Tasks can die at any time, kernel keeps writing to the buffer. impl AsyncRead for DmaStreamReader { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], // not guaranteed stable. ) -> Poll<io::Result<usize>> {
  • 22. AsyncBufRead ? ■ Better, as it returns a buffer. ■ Higher-level functions will likely still copy. impl AsyncBufRead for StreamReader { fn poll_fill_buf<'a>( mut self: Pin<&'a mut Self>, cx: &mut Context<'_>, ) -> Poll<io::Result<&'a [u8]>>
  • 23. Summary ■ Reference Count explosion limits scalability. ● Possible to avoid with TPC executor. ● But currently hard to swap executors. ■ File I/O performance a concern. ● io_uring increased adoption bridges that gap. ● tokio-uring exciting news. ■ Still hard to do real zero-copy I/O. ● Async workgroup has good proposals for this.
  • 24. Brought to you by Glauber Costa glauber@chiselstrike.com @glcst