
Nexus: High-Performance Go Concurrency Primitives for Extreme Performance (SPSC, Sharded MPMC Mailbox)
Hey HiLoad community!
TL;DR: I've poured my heart into building a lock-free Go library that absolutely flies – it's up to 10 times faster than standard channels under heavy load (think 32+ cores). Dive in for the benchmarks and the "why" behind the architecture!
I'm super excited to share my latest project, Nexus! It's a Go library packed with high-performance, lock-free concurrency primitives. If you've ever found yourself hitting the limits of standard Go channels or mutexes when you need really high throughput and ultra-low latency, then Nexus might just be your new best friend.
So, what's the big deal? When you're pushing systems to their absolute maximum (especially on those beefy multi-core processors, 32+ cores and beyond!), standard Go synchronization tools like mutexes and channels can actually become the bottleneck. All those atomic operations on shared head and tail counters can lead to a ton of contention for cache lines (what we call "false sharing"), which just grinds performance down and kills scalability.
My Solution: Nexus Nexus is built with a deep understanding of "mechanical sympathy" – meaning it's designed to work with the hardware, not against it. Here's what it brings to the table:
- Truly Lock-Free Design: We're talking pure atomic operations here, which means minimal kernel context switches. It's all about speed!
- Decentralized Architecture: Especially cool in the
ShardedMailbox, there are no central counters or "hint" variables, which eliminates bottlenecks and lets performance scale beautifully with every extra core you throw at it. - Cache-Friendly: I've carefully padded the data structures to prevent false sharing, keeping your CPU caches happy and efficient.
What's inside the box?
spsc: This is a rock-solid, lock-free Single-Producer-Single-Consumer (SPSC) queue. Perfect for those tight pipelines where one goroutine is churning out data and another is gobbling it up.sharded: Meet the Sharded Mailbox! This isn't your grandma's queue. It's a collection of single-element "mailboxes" (shards). It's specifically engineered for super high-throughput message exchange between many producers and many consumers (MPMC).- How does the
ShardedMailboxwork its magic? Each shard is like its own little independent "mailbox" with a simple "empty" or "full" state. Producers and consumers play a clever "casino" strategy: they start by checking their "home" shard, and if that's busy, they gracefully move to adjacent ones. This smartly distributes the load and avoids those nasty "hot spots." The Go runtime then naturally balances everything out: faster goroutines snatch up free/full shards quicker, while slower ones just wait a bit longer. The result? A beautiful self-balancing act where your most performant cores get to do the most work!
- How does the
Let's talk numbers! Benchmarks (on an AMD Ryzen 9 7950X3D 16-Core Processor)
ShardedMailbox (MPMC) vs. a standard channel:
- At 4 cores: The
ShardedMailboxis already ~2.4 times faster than a standard channel. - At 32 cores: This is where Nexus really shines! The
ShardedMailboxis an incredible ~10.5 times faster than a standard channel. Talk about scalability!
SPSCQueue (SPSC) vs. a standard channel:
- At 4 cores: Even in a simple single-producer-single-consumer setup,
SPSCQueueis ~10.6 times faster than a standard channel.
So, when should you reach for Nexus?
- Latency is your enemy: If 50-100 ns of channel latency feels like an eternity.
- Concurrency is off the charts: When you're dealing with 32, 64, or even 128 cores, and standard mutexes are just fighting each other for cache lines.
- Predictability is key: You want to avoid those annoying GC "freezes" caused by unnecessary allocations.
Real-world Use Cases (where Nexus truly shines):
- High-Frequency Trading (HFT): Every microsecond counts when you're transferring market quotes or order execution signals.
- Real-time Game Event Processing: Imagine updating a game world with thousands of players' actions – Nexus keeps things smooth.
- Database and Storage Engines: Perfect for implementing things like Write-Ahead Logs (WAL) or LSM-tree structures.
- Network Proxies and API Gateways: Handling tens of thousands of requests per second? Nexus can build lock-free pipelines that handle immense loads.
- AI/ML Inference Pipelines: Feeding data to your models without CPU-side bottlenecks. If your model is fast but data transport is slow, Nexus is your answer.
When might you stick with standard Go channels?
- Low-load applications: For a simple web service with, say, 10 requests per second, standard channels are perfectly fine and often simpler to maintain.
- Complex
selectlogic: Go channels are unique for theirselectstatement, letting you wait on multiple events. Nexus is more of a "super-fast pipe"; it's all about direct data exchange, not complex selection logic.
Quick Code Example (Sharded Mailbox):
package main
import (
"fmt"
"sync"
"github.com/GenshIv/nexus/sharded"
)
func main() {
mailbox := sharded.NewShardedMailbox[int]()
var wg sync.WaitGroup
numMessages := 100
wg.Add(numMessages * 2)
fmt.Printf("Launching %d producer-consumer pairs on %d shards...\n", numMessages, mailbox.ShardCount())
for i := 0; i < numMessages; i++ {
go func(consumerID int) {
defer wg.Done()
item, err := mailbox.Dequeue(uint64(consumerID))
if err != nil {
fmt.Printf("Consumer %d failed: %v\n", consumerID, err)
return
}
fmt.Printf("Consumer %d received: %d\n", consumerID, item)
}(i)
}
for i := 0; i < numMessages; i++ {
go func(producerID int) {
defer wg.Done()
item := 1000 + producerID
err := mailbox.Enqueue(uint64(producerID), item)
if err != nil {
fmt.Printf("Producer %d failed: %v\n", producerID, err)
return
}
fmt.Printf("Producer %d sent: %d\n", producerID, item)
}(i)
}
wg.Wait()
fmt.Println("\nAll messages have been successfully exchanged.")
mailbox.Close()
}
Installation is a breeze: go get github.com/GenshIv/nexus
I'd absolutely love to hear your thoughts, questions, and any suggestions you might have! Feel free to give Nexus a spin in your own projects and definitely share your results.
Check out the GitHub repo here: https://github.com/GenshIv/nexus