So You Wanna Go Fast? Learn High Performance Go
Want to writer high-performance Go? Here's an overview of maintaining performance with Go.
Join the DZone community and get the full member experience.Join For Free
i originally proposed this as a gophercon talk on writing “high-performance go,” which is why it may seem rambling, incoherent, and—at times—not at all related to go. the talk was rejected (probably because of the rambling and incoherence), but i still think it’s a subject worth exploring. the good news is, since it was rejected, i can take this where i want. the remainder of this piece is mostly the outline of that talk with some parts filled in, some meandering stories which may or may not pertain to the topic, and some lessons learned along the way. i think it might make a good talk one day, but this will have to do for now.
we work on some interesting things at workiva —graph traversal, distributed and in-memory calculation engines, low-latency messaging systems, databases optimized for two-dimensional data computation. it turns out, when you want to build a complicated financial reporting suite with the simplicity and speed of microsoft office, and put it entirely in the cloud, you can’t really just plumb some crap together and call it good. it also turns out that when you try to do this, performance becomes kind of important, not because of the complexity of the data—after all, it’s mostly just numbers and formulas—but because of the scale of it. now, distribute that data in the cloud, consider the security and compliance implications associated with it, add in some collaboration and control mechanisms, and you’ve got yourself some pretty monumental engineering problems.
as i hinted at, performance starts to be really important, whether it’s performing a formula evaluation, publishing a data-change event, or opening up a workbook containing a million rows of data (accountants are weird). a lot of the backend systems powering all of this are, for better or worse , written in go. go is, of course, a garbage-collected language, and it compares closely to java (though the latter has over 20 years invested in it while the former has about seven).
at this point, you might be asking, “why not c?” it’s honestly a good question to ask, but the reality is there is always history. the first solution was written in python on google app engine (something about mvps, setting your customers’ expectations low, and giving yourself room to improve?). this was before go was even a thing though java and c were definitely things, but this was a startup. and it was python. and it was on app engine. i don’t know exactly what led to that combination of things—i wasn’t there—but, truthfully, app engine probably played a large role in the company’s early success. python and app engine were fast . not like “this code is fucking fast” fast—what we call performance —more like “we need to get this shit working so we have jobs tomorrow” fast—what we call delivery . i don’t envy that kind of fast, but when you’re a startup trying to disrupt, speed to market matters a hell of a lot more than the speed of your software.
i’ve talked about app engine at length before. ultimately, you hit the ceiling of what you can do with it, and you have to migrate off (if you’re a business that is trying to grow, anyway). we hit that migration point at a really weird , uncomfortable time. this was right when docker was starting to become a thing, and microservices were this thing that everybody was talking about but nobody was doing. google had been successfully using containers for years, and netflix was all about microservices. everybody wanted to be like them, but no one really knew how —but it was the future ( unikernels are the new future, by the way).
the problem is—coming from a paas like app engine that does your own laundry—you don’t have the tools, skills, or experience needed to hit the ground running, so you kind of drunkenly stumble your way there. you don’t even have a devops team because you didn’t need one! nobody knew how to use docker, which is why at the first dockercon, five people got on stage and presented five solutions to the same problem. it was the blind leading the blind. i love this article by jesper l. andersen, how to build stable systems , which contains a treasure trove of practical engineering tips. the very last paragraph of the article reads:
docker is not mature (feb 2016). avoid it in production for now until it matures. currently docker is a time sink not fulfilling its promises. this will change over time, so know when to adopt it.
trying to build microservices using docker while everyone is stumbling over themselves was, and continues to be, a painful process, exacerbated by the heavy weight suddenly lifted by leaving app engine. it’s not great if you want to go fast. app engine made scaling easy by restricting you in what you could do, but once that burden was removed, it was off to the races. what people might not have realized, however, was that app engine also made distributed systems easy by restricting you in what you could do . some seem to think the limitations enforced by app engine are there to make their lives harder or make google richer (trust me, they’d bill you more if they could), so why would we have similar limitations in our own infrastructure? app engine makes these limitations, of course, so that it can actually scale . don’t take that for granted.
app engine was stateless, so the natural tendency once you’re off it was to make everything stateful. and we did . what i don’t think we realized was that we were, in effect, trading one type of fast for the other—performance for delivery. we can build software that’s fast and runs on your desktop pc like in the 90’s, but now you want to put that in the cloud and make it scale ? it takes a big infrastructure investment. it also takes a big time investment. neither of which are good if you want to go fast, especially when you’re using enough microservices, docker, and go to rattle the hacker news fart chamber. you kind of get caught in this endless rut of innovation that you almost lose your balance. leaving the statelessness of app engine for more stateful pastures was sort of like an infant learning to walk. you look down and it dawns on you—you have legs ! so you run with it, because that’s amazing, and you stumble spectacularly a few times along the way. finally, you realize maybe running full speed isn’t the best idea for someone who just learned to walk.
we were also making this transition while go had started reaching critical mass. every other headline in the tech aggregators was “why we switched to go and you should too.” and we did . i swear this post has a point.
tips for writing high-performance go
by now, i’ve forgotten what i was writing about, but i promised this post was about go. it is, and it’s largely about performance fast, not delivery fast—the two are often at odds with each other. everything up until this point was mostly just useless context and ranting. but it also shows you that we are solving some hard problems and why we are where we are. there is always history.
i work with a lot of smart people. many of us have a near obsession with performance, but the point i was attempting to make earlier is we’re trying to push the boundaries of what you can expect from cloud software. app engine had some rigid boundaries, so we made a change. since adopting go, we’ve learned a lot about how to make things fast and how to make go work in the world of systems programming.
go’s simplicity and concurrency model make it an appealing choice for backend systems, but the larger question is how does it fare for latency-sensitive applications? is it worth sacrificing the simplicity of the language to make it faster? let’s walk through a few areas of performance optimization in go—namely language features, memory management, and concurrency—and try to make that determination. all of the code for the benchmarks presented here are available on github .
channels in go get a lot of attention because they are a convenient concurrency primitive, but it’s important to be aware of their performance implications. usually, the performance is “good enough” for most cases, but in certain latency-critical situations, they can pose a bottleneck. channels are not magic. under the hood, they are just doing locking. this works great in a single-threaded application where there is no lock contention, but in a multithreaded environment, performance significantly degrades. we can mimic a channel’s semantics quite easily using a lock-free ring buffer .
the first benchmark looks at the performance of a single-item-buffered channel and ring buffer with a single producer and single consumer. first, we look at the performance in the single-threaded case ( gomaxprocs=1 ).
benchmarkchannel 3000000 512 ns/op benchmarkringbuffer 20000000 80.9 ns/op
as you can see, the ring buffer is roughly six times faster (if you’re unfamiliar with go’s benchmarking tool, the first number next to the benchmark name indicates the number of times the benchmark was run before giving a stable result). next, we look at the same benchmark with gomaxprocs=8 .
benchmarkchannel-8 3000000 542 ns/op benchmarkringbuffer-8 10000000 182 ns/op
the ring buffer is almost three times faster.
channels are often used to distribute work across a pool of workers. in this benchmark, we look at performance with high read contention on a buffered channel and ring buffer. the gomaxprocs=1 test shows how channels are decidedly better for single-threaded systems.
benchmarkchannelreadcontention 10000000 148 ns/op benchmarkringbufferreadcontention 10000 390195 ns/op
however, the ring buffer is faster in the multithreaded case:
benchmarkchannelreadcontention-8 1000000 3105 ns/op benchmarkringbufferreadcontention-8 3000000 411 ns/op
lastly, we look at performance with contention on both the reader and writer. again, the ring buffer’s performance is much worse in the single-threaded case but better in the multithreaded case.
benchmarkchannelcontention 10000 160892 ns/op benchmarkringbuffercontention 2 806834344 ns/op benchmarkchannelcontention-8 5000 314428 ns/op benchmarkringbuffercontention-8 10000 182557 ns/op
the lock-free ring buffer achieves thread safety using only cas operations. we can see that deciding to use it over the channel depends largely on the number of os threads available to the program. for most systems, gomaxprocs > 1 , so the lock-free ring buffer tends to be a better option when performance matters. channels are a rather poor choice for performant access to shared state in a multithreaded system.
defer is a useful language feature in go for readability and avoiding bugs related to releasing resources. for example, when we open a file to read, we need to be careful to close it when we’re done. without deferring , we need to ensure the file is closed at each exit point of the function.
this is really error-prone since it’s easy to miss a return point. defer solves this problem by effectively adding the cleanup code to the stack and invoking it when the enclosing function returns.
at first glance, one would think defer statements could be completely optimized away by the compiler. if i defer something at the beginning of a function, simply insert the closure at each point the function returns. however, it’s more complicated than this. for example, we can defer a call within a conditional statement or a loop. the first case might require the compiler to track the condition leading to the defer . the compiler would also need to be able to determine if a statement can panic since this is another exit point for a function. statically proving this seems to be, at least on the surface, an undecidable problem.
the point is defer is not a zero-cost abstraction. we can benchmark it to show the performance overhead. in this benchmark, we compare locking a mutex and unlocking it with a defer in a loop to locking a mutex and unlocking it without defer .
benchmarkmutexdeferunlock-8 20000000 96.6 ns/op benchmarkmutexunlock-8 100000000 19.5 ns/op
using defer is almost five times slower in this test. to be fair, we’re looking at a difference of 77 nanoseconds , but in a tight loop on a critical path, this adds up. one trend you’ll notice with these optimizations is it’s usually up to the developer to make a trade-off between performance and readability. optimization rarely comes free.
reflection and json
reflection is generally slow and should be avoided for latency-sensitive applications. json is a common data-interchange format, but go’s encoding/json package relies on reflection to marshal and unmarshal structs. with ffjson , we can use code generation to avoid reflection and benchmark the difference.
benchmarkjsonreflectionmarshal-8 200000 7063 ns/op benchmarkjsonmarshal-8 500000 3981 ns/op benchmarkjsonreflectionunmarshal-8 200000 9362 ns/op benchmarkjsonunmarshal-8 300000 5839 ns/op
code-generated json is about 38% faster than the standard library’s reflection-based implementation. of course, if we’re concerned about performance, we should really avoid json altogether. messagepack is a better option with serialization code that can also be generated. in this benchmark, we use the msgp library and compare its performance to json.
benchmarkmsgpackmarshal-8 3000000 555 ns/op benchmarkjsonreflectionmarshal-8 200000 7063 ns/op benchmarkjsonmarshal-8 500000 3981 ns/op benchmarkmsgpackunmarshal-8 20000000 94.6 ns/op benchmarkjsonreflectionunmarshal-8 200000 9362 ns/op benchmarkjsonunmarshal-8 300000 5839 ns/op
the difference here is dramatic. even when compared to the generated json serialization code, messagepack is significantly faster.
if we’re really trying to micro-optimize, we should also be careful to avoid using interfaces, which have some overhead, not just with marshaling but also method invocations. as with other kinds of dynamic dispatch, there is a cost of indirection when performing a lookup for the method call at runtime. the compiler is unable to inline these calls.
benchmarkjsonreflectionunmarshal-8 200000 9362 ns/op benchmarkjsonreflectionunmarshaliface-8 200000 10099 ns/op
we can also look at the overhead of the invocation lookup, i2t, which converts an interface to its backing concrete type. this benchmark calls the same method on the same struct. the difference is the second one holds a reference to an interface which the struct implements.
benchmarkstructmethodcall-8 2000000000 0.44 ns/op benchmarkifacemethodcall-8 1000000000 2.97 ns/op
sorting is a more practical example that shows the performance difference. in this benchmark, we compare sorting a slice of 1,000,000 structs and 1,000,000 interfaces backed by the same struct. sorting the structs is nearly 92% faster than sorting the interfaces.
benchmarksortstruct-8 10 105276994 ns/op benchmarksortiface-8 5 286123558 ns/op
to summarize, avoid json if possible. if you need it, generate the marshaling and unmarshaling code. in general, it’s best to avoid code that relies on reflection and interfaces and instead writes code that uses concrete types. unfortunately, this often leads to a lot of duplicated code, so it’s best to abstract this with code generation. once again, the trade-off manifests.
go doesn’t actually expose heap or stack allocation directly to the user. in fact, the words “heap” and “stack” do not appear anywhere in the language specification . this means anything pertaining to the stack and heap are technically implementation-dependent. in practice, of course, go does have a stack per goroutine and a heap. the compiler does escape analysis to determine if an object can live on the stack or needs to be allocated in the heap.
unsurprisingly, avoiding heap allocations can be a major area of optimization. by allocating on the stack, we avoid expensive malloc calls, as the benchmark below shows.
benchmarkallocateheap-8 20000000 62.3 ns/op 96 b/op 1 allocs/op benchmarkallocatestack-8 100000000 11.6 ns/op 0 b/op 0 allocs/op
naturally, passing by reference is faster than passing by value since the former requires copying only a pointer while the latter requires copying values. the difference is negligible with the struct used in these benchmarks though it largely depends on what has to be copied. keep in mind there are also likely some compiler optimizations being performed in this synthetic benchmark.
benchmarkpassbyreference-8 1000000000 2.35 ns/op benchmarkpassbyvalue-8 200000000 6.36 ns/op
however, the larger issue with heap allocation is garbage collection. if we’re creating lots of short-lived objects, we’ll cause the gc to thrash. object pooling becomes quite important in these scenarios. in this benchmark, we compare allocating structs in 10 concurrent goroutines on the heap vs. using a sync.pool for the same purpose. pooling yields a 5x improvement.
benchmarkconcurrentstructallocate-8 5000000 337 ns/op benchmarkconcurrentstructpool-8 20000000 65.5 ns/op
it’s important to point out that go’s sync.pool is drained during garbage collection. the purpose of sync.pool is to reuse memory between garbage collections. one can maintain their own free list of objects to hold onto memory across garbage collection cycles though this arguably subverts the purpose of a garbage collector. go’s pprof tool is extremely useful for profiling memory usage. use it before blindly making memory optimizations.
when performance really matters, you have to start thinking at the hardware level. formula one driver jackie stewart is famous for once saying, “you don’t have to be an engineer to be a racing driver, but you do have to have mechanical sympathy.” having a deep understanding of the inner workings of a car makes you a better driver. likewise, having an understanding of how a computer actually works makes you a better programmer. for example, how is memory laid out? how do cpu caches work? how do hard disks work?
memory bandwidth continues to be a limited resource in modern cpu architectures, so caching becomes extremely important to prevent performance bottlenecks. modern multiprocessor cpus cache data in small lines, typically 64 bytes in size, to avoid expensive trips to main memory. a write to a piece of memory will cause the cpu cache to evict that line to maintain cache coherency. a subsequent read on that address requires a refresh of the cache line. this is a phenomenon known as false sharing , and it’s especially problematic when multiple processors are accessing independent data in the same cache line.
imagine a struct in go and how it’s laid out in memory. let’s use the ring buffer from earlier as an example. here’s what that struct might normally look like:
the queue and dequeue fields are used to determine producer and consumer positions, respectively. these fields, which are both eight bytes in size, are concurrently accessed and modified by multiple threads to add and remove items from the queue. since these two fields are positioned contiguously in memory and occupy only 16 bytes of memory, it’s likely they will be stored in a single cpu cache line. therefore, writing to one will result in evicting the other, meaning a subsequent read will stall. in more concrete terms, adding or removing things from the ring buffer will cause subsequent operations to be slower and will result in lots of thrashing of the cpu cache.
we can modify the struct by adding padding between fields. each padding is the width of a single cpu cache line to guarantee the fields end up in different lines. what we end up with is the following:
how big a difference does padding out cpu cache lines actually make? as with anything, it depends. it depends on the amount of multiprocessing. it depends on the amount of contention. it depends on memory layout. there are many factors to consider, but we should always use data to back our decisions. we can benchmark operations on the ring buffer with and without padding to see what the difference is in practice.
first, we benchmark a single producer and single consumer, each running in a goroutine. with this test, the improvement between padded and unpadded is fairly small, about 15%.
benchmarkringbufferspsc-8 10000000 156 ns/op benchmarkringbufferpaddedspsc-8 10000000 132 ns/op
however, when we have multiple producers and multiple consumers, say 100 each, the difference becomes slightly more pronounced. in this case, the padded version is about 36% faster.
benchmarkringbuffermpmc-8 100000 27763 ns/op benchmarkringbufferpaddedmpmc-8 100000 17860 ns/op
false sharing is a very real problem. depending on the amount of concurrency and memory contention, it can be worth introducing padding to help alleviate its effects. these numbers might seem negligible, but they start to add up, particularly in situations where every clock cycle counts.
lock-free data structures are important for fully utilizing multiple cores. considering go is targeted at highly concurrent use cases, it doesn’t offer much in the way of lock-freedom. the encouragement seems to be largely directed towards channels and, to a lesser extent, mutexes.
that said, the standard library does offer the usual low-level memory primitives with the atomic package . compare-and-swap, atomic pointer access—it’s all there. however, use of the atomic package is heavily discouraged :
we generally don’t want sync/atomic to be used at all…experience has shown us again and again that very few people are capable of writing correct code that uses atomic operations…if we had thought of internal packages when we added the sync/atomic package, perhaps we would have used that. now we can’t remove the package because of the go 1 guarantee.
how hard can lock-free really be, though? just rub some cas on it and call it a day, right? after a sufficient amount of hubris, i’ve come to learn that it’s definitely a double-edged sword. the lock-free code can get complicated in a hurry. the atomic and unsafe packages are not easy to use, at least not at first. the latter gets its name for a reason. tread lightly—this is dangerous territory. even more so, writing lock-free algorithms can be tricky and error-prone. simple lock-free data structures, like the ring buffer, are pretty manageable, but anything more than that starts to get hairy.
the ctrie , which i wrote about in detail , was my foray into the world of lock-free data structures beyond your standard fare of queues and lists. though the theory is reasonably understandable, the implementation is thoroughly complex. in fact, the complexity largely stems from the lack of a native double compare-and-swap , which is needed to atomically compare indirection nodes (to detect mutations on the tree) and node generations (to detect snapshots taken of the tree). since no hardware provides such an operation, it has to be simulated using standard primitives ( and it can ).
the first ctrie implementation was actually horribly broken , and not even because i was using go’s synchronization primitives incorrectly. instead, i had made an incorrect assumption about the language. each node in a ctrie has a generation associated with it. when a snapshot of the tree is taken, its root node is copied to a new generation. as nodes in the tree are accessed, they are lazily copied to the new generation (à la persistent data structures), allowing for constant-time snapshotting. to avoid integer overflow, we use objects allocated on the heap to demarcate generations. in go, this is done using an empty struct. in java, two newly constructed objects are not equivalent when compared since their memory addresses will be different. i made a blind assumption that the same was true in go, when in fact, it’s not. literally the last paragraph of the go language specification reads:
a struct or array type has size zero if it contains no fields (or elements, respectively) that have a size greater than zero. two distinct zero-size variables may have the same address in memory.
oops. the result was that two different generations were considered equivalent, so the double compare-and-swap always succeeded. this allowed snapshots to potentially put the tree in an inconsistent state. that was a fun bug to track down. debugging highly concurrent, the lock-free code is hell. if you don’t get it right the first time, you’ll end up sinking a ton of time into fixing it, but only after some really subtle bugs crop up. and it’s unlikely you get it right the first time. you win this time, ian lance taylor.
but wait! obviously, there’s some payoff with complicated lock-free algorithms or why else would one subject themselves to this? with the ctrie, lookup performance is comparable to a synchronized map or a concurrent skip list. inserts are more expensive due to the increased indirection. the real benefit of the ctrie is its scalability in terms of memory consumption, which, unlike most hash tables, is always a function of the number of keys currently in the tree. the other advantage is its ability to perform constant-time, linearizable snapshots. we can compare performing a “snapshot” on a synchronized map concurrently in 100 different goroutines with the same test using a ctrie:
benchmarkconcurrentsnapshotmap-8 1000 9941784 ns/op benchmarkconcurrentsnapshotctrie-8 20000 90412 ns/op
depending on access patterns, lock-free data structures can offer better performance in multithreaded systems. for example, the nats message bus uses a synchronized map-based structure to perform subscription matching. when compared with a ctrie-inspired, lock-free structure, throughput scales a lot better. the blue line is the lock-based data structure, while the red line is the lock-free implementation.
avoiding locks can be a boon depending on the situation. the advantage was apparent when comparing the ring buffer to the channel. nonetheless, it’s important to weigh any benefit against the added complexity of the code. in fact, sometimes lock-freedom doesn’t provide any tangible benefit at all!
a note on optimization
as we’ve seen throughout this post, performance optimization almost always comes with a cost. identifying and understanding optimizations themselves is just the first step. what’s more important is understanding when and where to apply them. the famous quote by c. a. r. hoare, popularized by donald knuth, has become a longtime adage of programmers:
the real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or, at least, most of it) in programming.
though the point of this quote is not to eliminate optimization altogether, it’s to learn how to strike a balance between speeds—speed of an algorithm, speed of delivery, the speed of maintenance, the speed of a system. it’s a highly subjective topic, and there is no single rule of thumb. is premature optimization the root of all evil? should i just make it work, then make it fast? does it need to be fast at all? these are not binary decisions. for example, sometimes making it work then making it fast is impossible if there is a fundamental problem in the design.
however, i will say focus on optimizing along the critical path and outward from that only as necessary. the further you get from that critical path, the more likely your return on investment is to diminish and the more time you end up wasting. it’s important to identify what adequate performance is. do not spend time going beyond that point. this is an area where data-driven decisions are key—be empirical, not impulsive. more important, be practical . there’s no use shaving nanoseconds off of an operation if it just doesn’t matter . there is more to going fast than fast code.
if you’ve made it this far, congratulations, there might be something wrong with you. we’ve learned that there are really two kinds of fast in software—delivery and performance. customers want the first, developers want the second, and ctos want both. the first is by far the most important, at least, when you’re trying to go to market. the second is something you need to plan for and iterate on. both are usually at odds with each other.
perhaps more interestingly, we looked at a few ways we can eke out that extra bit of performance in go and make it viable for low-latency systems. the language is designed to be simple, but that simplicity can sometimes come at a price. like the trade-off between the two fasts, there is a similar trade-off between code lifecycle and code performance. speed comes at the cost of simplicity, at the cost of development time, and at the cost of continued maintenance. choose wisely.
Published at DZone with permission of Tyler Treat, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.