r/rust • • Oct 09 '17

Watching this Carl Cook CppCon talk on High-Performance Trading got me curious: Is Rust as suitable for HFT as C++?

https://www.youtube.com/watch?v=NH1Tta7purM
47 Upvotes

36 comments sorted by

45

u/rovar Oct 09 '17

People's definitions of "High frequency" can vary by several orders of magnitude.

Some HFT shops have a max tick-to-trade latency of about 15 microseconds. To consistently achieve these latencies, you are bypassing the linux kernel scheduler, which means you're directly polling nics. Also, the FIX protocol is likely out of the question in this case, instead, most exchanges have their own protocol, that is based on something that can be de/serialized mostly with cast-fill structs.

Others talk about high frequency at the 10 ms tick-to-trade level, at which point you can use your linux kernel's scheduler and TCP stack. For, that, you're free to use any language which can create static buffers. You're probably also issuing trades and receiving market data in FIX.

For the latter case, vanilla Rust would be a prime candidate. It is missing some protocol, fix support was mentioned, but Nom would be an amazing choice for building a safe, correct, and fast Fix parser. Serde would provide great benefit and convenience as well, for turning data structures into market orders.

For the very low latency HFT, You'd likely have a bunch of unsafe code, since you'd be dealing directly in buffers of different types and copying between them. Buffers for DMA on the nic, memory pools for your custom data structures, trees and lists built by direct pointer manipulation. One could, theoretically build compile-time abstractions around these to help guarantee safety. Rust would still be a good choice for this, IMO, but it would take a lot of custom development, and you'd lose the benefit of the borrow checker in most cases.

3

u/[deleted] Oct 09 '17

Great reply, fantastic summary!

It seems Rust is getting there.

21

u/adwhit86 Oct 09 '17

For what it's worth, I made a parser for the ITCH protocol (similar to FIX) with nom. It was straightforward and quick to implement and benches around 7M messages/second on my crappy laptop. So yeah Rust is perfect for this kind of library.

8

u/sophrosun3 Oct 09 '17

One of the central theses of Rust the language is that you can build safe abstractions from those low level resources you refer to with low-latency HFT, and then benefit from the borrow checker when using them in your "business logic." I'd be curious to know if anyone has successfully been able to do so.

4

u/geaal nom Oct 09 '17

so, I know someone did a FIX parser in nom recently, and that it's on github, but I can't find it again :( I've definitely seen some interest from finance oriented people, but it was mostly for custom protocols

3

u/matthieum [he/him] Oct 10 '17

Some HFT shops have a max tick-to-trade latency of about 15 microseconds.

I'm going to cite Carl Cook's talk here: the best play at around 2.5 microseconds1 in software. Consistently.

Below that, you have to look toward FPGAs or other hardware solutions2 piloted by software, in which case the requirements for the software part are somewhat relaxed; somewhat.

1 Wire-2-Wire: that is, between the first byte of the inbound packet reaching the port and the first byte of the outbound packet exiting the port; this therefore include all the hardware handling before the data even gets to the CPU and after it leaves it.

2 I actually wonder if anybody out there is using another hardware solution than a FPGA, just putting it there for completeness.

3

u/rovar Oct 10 '17

2.5μs switch-to-switch is absolutely tiny. To do that consistently without jitter is a feat. For that, I'd guess that a shop is leveraging a nic with on-board FPGA to help accelerate unpacking, routing and filtering of inbound data before it makes the data available to the process. E.g. the data arrives on a multicast to multiple machines, each with separate responsibilities, and the nic does the "routing" by filtering relevant data.

https://www.optiver.com/ap/en/job-opportunities/na-379 . seems to indicate that they're using custom FPGA solutions to get to wherever they're at.

3

u/rovar Oct 10 '17

Also, at around 36 minutes, he references sending non-executable orders outbound to the nic. So likely the nic is filtering and "routing" via FPGA outbound as well. Rather neat trick to keep the cache hot for the hot path.

3

u/matthieum [he/him] Oct 10 '17

I'm sure Optiver uses FPGA, I'm not sure if they use them as NIC.

There are commercial solutions for user-level network cards which are really good, so it's not necessary to have them built in-house.

And yes, 2.5μs is really a very short amount of time :) At 4GHz, it's 10,000 CPU cycles.

1

u/digikata Oct 10 '17

Hooking Rust to the Intel DPDK/SPDK would seem to be an interesting combo. If you were really ambitious, then you could replace even the lower level user side consumer of the development kit "drivers".

19

u/[deleted] Oct 09 '17 edited Oct 09 '17

Sidenote: we had a Rust Evangelism Strike Force infiltrator in the C++ conferences this year: It was a great talk

11

u/palad1 Oct 09 '17

See this issue from the abandonned fix-rs crate for a discussion why it's not ready just yet: https://github.com/jbendig/fix-rs/issues/1

11

u/doublehyphen Oct 09 '17 edited Oct 09 '17

While I agree about that Tokio is not usable yet, I am not sure if that really can be used as an argument against Rust. I do not think there is any popular equivalent to Tokio in C++, the C++ aync libraries are more like mio. And I am not sure making the mio event loop multi threaded is such a good idea for this kind of applications since that adds synchronization overhead.

As for eliminating allocations I mostly agree. I am pretty new to Rust and I have had to fight pretty hard against the borrow checker some times to write code with zero overhead., especially for threaded code. Maybe it gets better with time, but I sometimes feel being lazy and writing slow code is too tempting.

9

u/im-a-koala Oct 09 '17

I do not think there is any popular equivalent to Tokio in C++, the C++ aync libraries are more like mio.

Huh? Boost Asio is an incredibly mature library, and is pretty much the de facto C++ async I/O library. It's not the fastest thing in the world (the design has a few locks in it that could be called "unnecessary"), but it's certainly not slow.

That being said, you're right that you wouldn't use Asio for HFT. But you wouldn't use async at all, because that's slower than pinning a thread to a core and spinning.

1

u/doublehyphen Oct 09 '17

I have not used Asio myself but I counted it as more low level, occupying the space between mio and Tokio. But now that I think of it its API is pretty far from how epoll and kqueue works so it makes sense to compare it to Tokio.

7

u/palad1 Oct 09 '17

Fair point. Most FIX libraries provide memory pools and message/messagegroup pooling for high-throughput systems. I feel the author might have struggled to get the pools implemented in a satisfying way.

6

u/matthieum [he/him] Oct 10 '17

Rust is as suitable as C.

There are two reasons, for me, why C++ will be more difficult to encroach on:

  1. Rust is difficult to integrate with modern C++ and its heavy reliance on templates,

  2. Rust does not yet have non-type generics, and HFT loves fixed-size arrays.

4

u/autismo1 Jan 26 '23

> 2. Rust does not yet have non-type generics, and HFT loves fixed-size arrays.

took nearly 5 years but const generics are now part of stable

3

u/matthieum [he/him] Jan 26 '23

took nearly 5 years but const generics are now part of stable

They are still a tad limited, but it's a massive improvement indeed.

5

u/[deleted] Oct 09 '17

Aren't Haskell and OCaml used in HFT as well? I've even heard of Java and C# being used in that space...

4

u/Hauleth octavo · redox Oct 09 '17

I have heard about Erlang used in HFT.

3

u/steveklabnik1 rust Oct 09 '17

Yes, I've heard of all of these but C# being used, and I'm sure that I just haven't ran into a C# person yet.

4

u/im-a-koala Oct 09 '17

There's plenty of C#, just not in the high-frequency parts. HFT has quite a few pieces that don't need to be that fast.

4

u/adwhit86 Oct 09 '17

Java might even be the preferred language for low-latency trading these days. Not for sub-microsecond response but it can do single-digit microsecond. Turn off the GC, use off-heap datastructures, reuse your objects and restart your program every night.

The benefit over C++ is simply that it is much easier to make code changes and much harder to create terrifying errors in Java. Since Rust does all this and gives one much more control over data layout, I think it has huge potential in this space.

8

u/im-a-koala Oct 09 '17

I know of only one prominent HFT shop that uses Java for this. Almost everybody else uses C++. Java just isn't a good fit for it, and if you try to turn off the GC entirely, you can't use lots of libraries which is one of the main reasons of using Java in the first place.

Java can be fast, but optimized C++ is usually faster.

4

u/adwhit86 Oct 10 '17

Java can be fast, but optimized C++ is usually faster.

No doubt, and a lot of this revolves around one's definition of 'H'. I once worked for a market maker similar the one in the video; they rewrote their whole stack from C++ to Java and it actually got much faster due to much improved cache-friendly architecture.

We referred to our particular dialect of Java as 'Java--' because as you note, it did not look like normal Java code and did not use much of the standard ecosystem - but there is a whole separate ecosystem built for just this purpose, see e.g. OpenHFT.

Still, trading firms value rapid development just as much as any startup (there was a constant fear that our competitors were smarter, better equipped and mere days away from "eating our lunch") and the real value of Java over C++ was nary a pointer in sight.

4

u/im-a-koala Oct 10 '17

You keep acting like it's a given that you can develop more rapidly in this special Java (where you probably can't leverage Java's impressive library ecosystem) than in C++. It's possible your company could have just rewritten their systems still in C++ and gotten better performance.

Pointers aren't evil. I work for one of these companies and some of the components I work on are in Java and I would love to be able to use raw pointers.

2

u/fulmicoton Oct 10 '17

Java is ok for throughput but getting consistently low latency from it is extremely hard.

0

u/[deleted] Oct 09 '17

[deleted]

5

u/mgattozzi flair Oct 09 '17

I use Haskell for work where we do financial applications and backtesting. I wouldn't use it for HFT though personally. Unsafe code with Haskell using pointers and the like for low level manipulation is a huge pain to deal with -_- I'd rather use Rust or C/C++ instead which is made for that kind of stuff.

6

u/kixunil Oct 09 '17

This topic was discussed here several times. TL;DR: Rust is still missing few features that HFT people need.

4

u/boscop Oct 09 '17

Like what?

14

u/bbatha Oct 09 '17

const fn and custom allocators were the two I remember as most important.

4

u/matthieum [he/him] Oct 10 '17

Non-Type Generics is the second bigger blocker as far as I am concerned.

When you want to touch as few cache lines as possible and prefer avoiding the heap, you start relying a lot on arrays of a great many sizes, build data-structures on top of those arrays, have functions to manipulate those arrays, etc...

... and today in Rust it's just painful. Possible, certainly, with traits and macros and whatnot, but painful.


The first bigger blocker is the difficulty in incrementally converting an existing C++ codebase ;)

1

u/kixunil Oct 18 '17

Sorry for late reply. The other guys described exactly those things that I've read in the other HFT posts.

-11

u/claire_resurgent Oct 09 '17

Being consistently first place in speed.

2

u/stumpychubbins Oct 11 '17

Tell that to C++