126 points · by dgudkov · 3y ago · 85 comments
Disruptor and most other data structures that come from trading are designed to run with thread-per-core systems. This means systems where there will be no preemption during a critical section. They can get away with a lot of shenanigans on the concurrency model due to this. If you are using these data structures and have a thread-per-request model, you're probably going to have a bad time.
You are essentially asking the operating system to do the scheduling for you. But the OS will never be able to do it perfectly as it has no knowledge of what your application is doing.
The main advantage of OS scheduling is that you get pretty good results without having to think about it at all. Pretty good, but never perfect.
From LMAX presentations, it looks like they want you to split your application into tasks [1], define a graph of task dependencies, have each core process a particular kind of task and have task processors communicate their producers via a ring buffer.
In particular, the allocation of tasks is static. The use of a ring buffer means that there is very little contention, and task processing is very efficient, but some cores might end up underutilized.
On the other hand, if you have a thread per request, and allow them to migrate between cores, idle cores can steal tasks from busy ones. So in theory you could get better utilization, but task processing is less efficient since you need to share more data between cores.
("threads" don't need to be OS threads, they can be green threads)
That said, I am not sure if GP meant this by thread-per-request, or "legacy" applications that use a thread pool, or something else.
[1]: https://www.slideshare.net/trishagee/introduction-to-the-dis...
I have gotten latencies to 50 nanoseconds and up.
disruptor-multi.c(SPMC) and disruptor-multi-producer.c (MPSC) https://GitHub.com/samsquire/assembly
I am trying to work out how to support multiple producers and multiple readers (MPMC) at low latency that's what I'm literally working on today.
The MPSC and SPMC seem to be working at low latencies.
I am hoping to apply actor model to the ringbuffer for communication.
I'm also working on nonblocking lock free barrier. This has latency as low as 42 nanoseconds and up.
I’ve been down the path you’re on a few times and I love the pursuit. Have built my own over the years about 4 times.
Hardware was much slower in those days so my lower barrier was 650ns. Things got worse appreciably as a function of the number of producers I found.
Some of my most sleepless nights. The funnest nights.
I have pinned threads to even numbered cores with pthread_setaffinity_np and that seems to have evened out the MPMC ringbuffer - 2 producers 2 consumers to under 400 nanoseconds, usually under 1000 nanoseconds. I think hyperthreading causes problems.
EDIT: Would you like to chat about this? I would like to! My email is in my profile.
https://doc.rust-lang.org/std/collections/vec_deque/index.ht...
(Aside, generic atomic operation pro-tip: don't if you can help it. Load + local modify + store is always faster than atomic modify, if you can make the memory ordering work out. And if you can't do away with an atomic modify, batch your updates locally to issue fewer of them at least.)
I don’t know why I never thought of this, brilliant!
Disruptor: High performance alternative to bounded queues - https://news.ycombinator.com/item?id=36073710 - May 2023 (1 comment)
LMAX Disruptor: High performance method for exchanging data between threads - https://news.ycombinator.com/item?id=30778042 - March 2022 (1 comment)
The LMAX Architecture - https://news.ycombinator.com/item?id=22369438 - Feb 2020 (1 comment)
You could have invented the LMAX Disruptor, if only you were limited enough - https://news.ycombinator.com/item?id=17817254 - Aug 2018 (29 comments)
Disruptor: High performance alternative to bounded queues (2011) [pdf] - https://news.ycombinator.com/item?id=12054503 - July 2016 (27 comments)
The LMAX Architecture (2011) - https://news.ycombinator.com/item?id=9753044 - June 2015 (4 comments)
LMAX Disruptor: High Performance Inter-Thread Messaging Library - https://news.ycombinator.com/item?id=8064846 - July 2014 (2 comments)
Serious high-performance and lock-free algorithms (by LMAX devs) - https://news.ycombinator.com/item?id=4022977 - May 2012 (17 comments)
The LMAX Architecture - 100K TPS at Less than 1ms Latency - https://news.ycombinator.com/item?id=3173993 - Oct 2011 (53 comments)
One of those things to remember is that Java I/O layering (stuff like JPA) is really terrible. And people in my known Java world tend to prefer the abstractions while the people in the trading world try to use GC-less code (unboxed primitives and byte arrays).
Unless you have verified your E2E I/O to be really fast (possible off heap), you're just pushing a few bytes here and there, your latencies are all in check - this library is not for you. Do all that work first, then use this library.
I didn't know they even claimed to attempt being the fastest exchange in the world. They're very far from being so and it's quite clear that there are architectural decisions in that platform that would prevent that.
From a quick reading it's just a standard spmc queue with some mpmc capabilities. Queues (preferably lock-free and bounded) are a basic component of any low-latency distributed software system. They seem to understand the basics right, nothing too outstanding, some decisions quite suboptimal.
Myself I use spsc task queues for inter-thread communication (because in that scenario you know who you're sending tasks to, and you can easily just attach multiple spsc queues for pseudo-mpsc capabilities), and mpmc message queues for inter-process communication (because that scenario is more of a message bus, and you don't know who's talking to who).
I have built these kinds of things many times together with bespoke threading and scheduling models, as have others at all of the trading shops I've seen, so I'd say it's a pretty standard thing in the industry.
Open-source frameworks of interest would be Seastar or DPDK.
However, while a good threading model helps, it's far from sufficient to be the highest performance trading exchange. You also need to think hard about networking, be it the protocols, the software, the hardware and the topology. For example key factors in trading are deterministically publishing data to all participants at the same time, ensuring private information is not published before its public equivalent, making sure that whoever sent their packet first gets processed first. Even something as simple as the kind of switches you use has a huge impact.
At the end of the day, it is a specialised ring buffer that happens to be useful for many use cases.
This has led participants wishing to compete there on speed to use some pretty advanced custom ASICs.
https://martinfowler.com/articles/lmax.html
It includes lots of diagrams and citations.
One term I always loved re: LMAX is “mechanical sympathy.” Covered in this section:
https://martinfowler.com/articles/lmax.html#QueuesAndTheirLa...
“Disruptor is a fairly presumptuous name for a package” I thought. So I looked into it. It fed musings and thought experiments for many walks to and from the T. I love the balance between simplicity and subtlety in the design.
If i recall, it was a dependency for log4j, which makes sense for high volume logging.
Any domain with synchronous/serializable semantics can modeled as a single writer, with an MPSC queue in front of it. Things like game worlds, business decision systems, database engines, etc. fit the mold fairly well.
The busy-spin strategy can be viewed as a downside, but I can't ignore the latency advantages. In my experiments where I have some live "analog" input like a mouse, the busy wait strat feels 100% transparent. I've tested it for hours without it breaking into the millisecond range (on windows 10!). For gaming/real-time UI cases, you either want this or yield. Sleep strategies are fine if you can tolerate jitter in the millisecond range.
Great library which makes processing concurrent streams incredibly easy.
* full kernel bypass (I even implemented driver for the networking hardware)
* everything that could disrupt the application disabled (like SME interrupts, etc.) Memory mapped as huge buffers to prevent tlb lookup failures, etc.
* application consists of threads pinned to specified cores
* each thread on the path of market data to sending the order is never calling the operating system for anything. When not processing anything it is busy spinning.
* all memory preallocated carefully to have it pinned to the local core
* data flows from the networking hardware into one core and then passess through cores using disruptor, each core doing further processing and publishing signals to the next core
* the main insight was that rather than wait for market signals to then decide what to do, you can precalculate your responses up to and including the actual message to be sent to the exchange.
I saw a talk about this dialed up to eleven: the entire processing occurred in a "smart NIC" instead of the CPU. The response would start getting sent even as the inbound packet was still being received. The go/no-go decision was effectively just sending the final CRC bytes correctly or deliberately incorrectly, thus invalidating the outbound packet that was already 99% sent.
Before that talk I couldn't figure out why there was a market for NICs with embedded FPGAs, CPUs and memory.
Day traders basically subsidised these things, and now they do efficient packet switching for large cloud providers.
Reminds me of how crypto-mining subsidised a lot of GPU development, and now we have 4K ray tracing and AIs thanks to that.
This trick will get you banned on some of exchanges now :)
Another one, which is public knowledge for years, and also often penalized, is to send TCP fragment with header of the message well in advance, "booking" place in the queue. Then send the finishing fragment with the real order after doing all the calculations.
My solution wasn't as fast and it could never do what you describe (start sending bytes before the packet was fully received). The market signal messages were actually batched together (usually one to 5), compressed with zlib and sent as a single multicast packet.
Ah those nasty market opens in the morning and trying to get a good spot in the queue
In fact, you can't guarantee 5us for anything, at least not on common operating systems. You would have to run your code with the interrupt flag cleared to prevent any IPIs or hrticks getting in the way. But that would be opening a scary can of worms.
Absolutely not true. I explained, risk is calculated concurrently and compiled to decision tree and then inserted in the path in the form of "if X happens do Y".
The fact it was PoC has nothing to do with it, in fact it showed that yes, it is possible to do so. That's entire point of the PoC.
> In fact, you can't guarantee 5us for anything, at least not on common operating systems.
Oh yes you can, with a screen-sized kernel cmdline, some proper configuration, both hardware and software, and a bit of luck.
I don’t doubt it, but from my reading of OP’s post, it sounds they were skipping most of the kernel and OS.
You do drop copy completely separately, that's the whole point of it.
Simple C is most likely, ASM is possible, a language such as OCaml generating C to hook into the low level buffers would be intriguing ... the list is long and largely determined by the experience preference of whoever tackles it.
The major features for performance are to allocate and manage all memory from the start .. determine your thresholds of performance and put everything required together on cold start so as to avoid any thrashing at runtime.
[1] e.g. https://marketswiki.com/wiki/TRADExpress ; though they've been absorbed into Nasdaq now and my visibility into CFT ended with that, no idea how much of their software is still running