139 points · by rck · 13y ago · 129 comments
Also, that's kind of a lot of code. Here's my rewrite of the server: http://play.golang.org/p/hKztKKQf7v
It doesn't return the exact same result, but since you're not verifying the results, it is effectively the same (4 bytes in, 4 bytes back out). I did slightly better with a hand-crafted one.
A little cleanup on the client here: http://play.golang.org/p/vRNMzBFOs5
I'm guessing scala's hiding some magic, though.
I made a small change to the way the client is working, buffering reads and writes independently (can be observed later) and I get similar numbers (dropped my local runs from ~12 to .038). This is that version: http://play.golang.org/p/8fR6-y6EBy
Now, I don't know scala, but based on the constraints of the program, these actually all do the same thing. They time how long it takes to write 4 bytes * N and read 4 bytes * N. (my version adds error checking). The go version is reporting a bit more latency going in and out of the stack for individual syscalls.
I suspect the scala version isn't even making those, as it likely doesn't need to observe the answers.
You just get more options in a lower level language.
Your modified Go server doesn't return "Pong" for "Ping". It returns "Ping". And the "a small change" version is nonsense. It's fundamentally different. - you're firing off all your requests before waiting for any replies, and so hiding the latency in the more common RPC style request-response chain, which is a real problem.
You speculate a lot ("hiding some magic" "likely doesn't need to observe the answers") when you haven't offered any insight.
EDIT: Nagle doesn't matter here - it doesn't delay any writes once you read (waiting server response). It only affects 2+ consecutive small writes (here I'm trusting http://en.wikipedia.org/wiki/Nagle's_algorithm - my own recollection was fuzzy). If Go sleeps client threads between the ping and the read-response call then I suppose it would matter (but only a little? and other comments say that Go defaults to no Nagle alg. anyway).
Really, the most plausible explanation? I'd say the most plausible explanation is that M:N scheduling has always been bad at latency and fair scheduling. That's why everybody else abandoned it when that matters. It's basically only good for when fair and efficient scheduling doesn't matter, like maths for instance, which is why it's still used in Haskell and Rust. I wouldn't be surprised to see Rust at least abandon M:N soon though once they start really optimizing performance.
I thought the difference might partly be in socket buffering on the client, so I printed the size of the send and receive buffers on the socket in the scala client, and set them the same on the socket in the go client. This didn't actually bring the time down. Huh.
My next thought was that scala is somehow being more parallel when it evaluates the futures in Await.result. Running `tcpdump -i lo tcp port 1201` seems to confirm this. The scala client has a lot more parallelism (judging by packet sequence ids). Is that really because go's internal scheduling of goroutines is causing lock contention or lots of context switching?
And...googling a bit, it looks like that is the case: https://docs.google.com/document/d/1TTj4T2JO42uD5ID9e89oa0sL...
> Current goroutine scheduler limits scalability of concurrent programs written in Go, in particular, high-throughput servers and parallel computational programs. Vtocc server maxes out at 70% CPU on 8-core box, while profile shows 14% is spent in runtime.futex(). In general, the scheduler may inhibit users from using idiomatic fine-grained concurrency where performance is critical.
Userland scheduling is still nice for optimizing synchronous RPC-style message sends so that they can switch directly to the target task without a trip through the scheduler. It's also nice when you want to implement work stealing.
Configuration rarely impacts such trivial cases. I would rather bet on a thread affinity or page locality.
Really? For example buffered vs unbuffered communication won't impact such a case?
One should only assume "thread affinity or page locality" after checking the configuration options (and maybe even later, after profiling).
The program doesn't read the result, so it doesn't matter. Returning Pong isn't harder, but why write all that code if it's going to be ignored anyway?
> It's fundamentally different. - you're firing off all your requests before waiting for any replies, and so hiding the latency in the more common RPC style request-response chain, which is a real problem.
As I said, the program isn't correlating the responses with the requests in the first place -- or even validating it got one. I don't know scala, but I've done enough benchmarking to watch even less sophisticated compilers do weird things with ignored values.
I made a small change that produced semantically the same program (same validation, etc...). It had similar performance to the scala one. If you don't think that's helpful, then add further constraints.
[Send 4 bytes * 200, then (round trip latency later) receive 4 bytes * 200] is fundamentally different than [(send 4 bytes, then (round trip latency later) receive 4 bytes) * 200]. Whether the message content is "ignored" is irrelevant.
Or, put another way, it's ridiculous for you to modify the Go program in that way (which will very likely send and receive only a single TCP segment over the localhost "network") and report the faster time as if it means anything. If you modify both programs in that way, fine. But it's something completely different.
Another let's rape localhost:8080 on a MacBook Pro™ benchmark
GP: Please use the word rape to the full extent provided by the english language, and let those who don't like the word deal with it.
As for the benchmark, who writes their own load balancer? Isn't this generally a solved problem? If the point is to extract max performance from a simple ping-pong server then I'd go right to C and epoll/libevent/etc. I'm guessing that the team is somehow trying to extrapolate data from a ping-pong server to the actual problem they're trying to solve which is dare I say, stupid.
In general the best way to solve this problem is use whatever language the team / person writing the software likes because having them write it faster generally outweighs whatever server costs one will run into, whenever this is not the case the best answer is 99% of the time: write it in C.
You'd be surprised, but no, it isn't a solved problem because the problem can't be solved in a general way and a lot of people are writing their own load balancers.
> If the point is to extract max performance from a simple ping-pong server then I'd go right to C and epoll/libevent/etc.
For a ping-pong server, sure, but a ping-pong server has no value in real life. The point of building your own load balancer is for doing custom load balancing and routing, based on individual needs of the project.
The complexity grows exponentially and while big companies are building such things in C, mere mortals do not have the resources for it. And in fact building on top of libevent is not going to give you performance advantages over Java NIO. The only thing that sucks about building on top of the JVM (compared to C) is the garbage collector, that can lead to unpredictable latencies related to blocking the whole process during the marking phase, even with CMS, although it is manageable and much better productivity-wise than to deal with GLibc incompatibilities or with multi-threading in C, plus I hear that G1 from JDK7 for large heaps and CPUs with multiple cores, or Azul's pauseless GC are awesome.
There's always a tradeoff of course, but sometimes the best path for many projects is the solution that makes the best compromises between productivity and performance and that's why I'm a happy Scala user and love the JVM.
Not really. Ravish might. But other than on, say, gamer message boards, 'rape' doesn't have many other meanings than forcible sexual assault. Take a look at the usage in print and find casual uses of 'rape' in that context.
You wouldn't expect people to react positively to violent body language while you deliver a nonviolent sentence, why should you expect them to react positively to you using violent metaphors in a nonviolent sentence?
* What's the concurrency like between two servers? (you need to test both low and high concurrent loads)
* What's the difference between the two in creating new connections and/or threads?
* What's the performance like when you up the number of packets per connection? (a simple ping pong hiding buffering performance etc).
* What's the performance like on the host platforms? (I'm going to assume that they're not the same OS on their Macbooks as they will be on their load balancers).
Of course, arguing a case of using Scala because it's a language they're already proficient in is itself a perfectly valid reason. But my issue is they seemed more interested in picking either language based on the best performance without actually evaluating the performance of either in any detail.
Sure this is a fairly simplistic first step, but so should all first steps be as you gain understanding, and it's proved its worth by producing a surprising result in a very simple case, that's worth understanding before moving on to more complicated tests.
What you've got here is engineering, rather than just making it up as you go along.
And that aside, it still fails as an experiment because the results are neither provable nor repeatable. There is not enough information about the environment used to run the test and there is no detailed test output. We get two numbers ("average round trip" for each implementation), but we can't check that they are correct, and we can't look at the distribution or calculate other, potentially more useful metrics. Even the code provided is different from the code used in the actual test.
Seriously, it goes beyond the underlying I/O API that you're using. If anywhere in the code you're reading from an InputStream or you're writing to an OutputStream that's connected to an open socket, then that's a blocking call that can crush your server. Right now, every Java Servlets container that's not compatible with the latest Servlets API 3.1 can be brought down with Slowloris, even if under the hood they are using NIO.
Option A for writing a server in Scala is Netty [2].
Option B for writing a server in Scala is the new I/O layer in Akka [3].
[1] http://ha.ckers.org/slowloris/
[2] http://netty.io/
No no no. Assuming your production code runs on Linux THAT is where you need to do this test. It is extremely naive to assume that either the JVM or the Go runtime will perform system interfacing tasks even remotely similar between OSX and Linux. Linux is what you will use in production. Linux is almost always faster (more effort from devs both on the kernel TCP/IP side and the runtime/userspace side).
Write your Scala, Java, Go wherever you want, but please, benchmark it in a clone of your production environment!
P.S. In production I assume your client and server will not be local... don't do this, kernels do awesome/dirty optimizations over loop-back interfaces, sometimes even bypassing large parts of the TCP/IP stack, parts you want included in any meaningful benchmark.
Go server vs Go client: 10ms
Scala server vs Scala client: 3ms
Go server vs Scala client: 4ms
Scala server vs Go client: ????
Scala server against the Go client is really slow (?). I reduced the ping count by a factor of 100, and extrapolating I think it would have reported around 670ms. What gives?I don't know much about Scala Futures, but isn't Scala's client doing something completely different than the Go client? Scala's client with Future.sequence looks like it's calling each `ping` method sequentially.
Printing the connection identifier {0,100} on open & close shows that while it isn't completely sequential, only about a handful of connections are open at a time.
On the other hand, the Go client appears to switch amongst goroutines more frequently. All the connections open before any connection closes.
In other words, the I think the difference in performance is due to the difference in how randomly the connections are shuffled. The terrible performance time in the last case I think shows a bottleneck in the Scala server rather than the Go client.
I fail to see how Go being slower than Java relates to C being faster than Java.
Writing a "ping-pong"? And not using the same client to test both servers?
It would not have been too hard to write a simple proxy in both languages. Not even worrying about parsing HTTP headers, just testing TCP, that is really easy.
Now, if you really want to test the performance, you have to implement it differently. Just two small features you would need in both:
* non blocking IO: right now, you're starting a new future in Scala, that's easy to write but not really efficient (it might work better with goroutines) * zero copy: if you're load balancing, you will spend your time moving bits, so you'd better make sure that you don't copy them too much. It is possible with Scala, but it looks like Go does not support it
Now, when you have reasonable testing grounds (that woudn't be more that a hundred lines in both languages), better get your statistics right.
"The client would make 100 concurrent connections and send a total of 1 million pings to the server, evenly distributed over the connections. We measured the average round trip time" -> that is NOT how you should test. Here, you would want to know what is the nominal pressure the balancer could handle, so you must measure a lot of metrics:
* RTT * bandwidth (per user and total) * time to warmup (the JVM optimizes a lot of things on the fly, you have to wait for it) * operational limits (what is the maximal bandwidth for which the performance crashes? same for number of users)
And then, you don't measure only the average values. You must measure the standard deviation. Because you could have a good average, but wildly varying data, and that is not good.
Last thing: the macbook may not be a good testing system.
I think we'll see the Go runtime gaining Single System Image distribution, performance improvements and libraries not services (e.g. groupcache) making it a very different world to develop in than Scala.
200Mb for such a crappy server with only hundred connections.
So, it is not about whose wrapper around epoll is thinner, but about how the data are represented and copied.
Yes, and almost a megabyte of disk space for a "hello world" program. C++ is so inefficient, right?
That's not the way you judge the performance of a program and/or it's memory use -- and neither is comparing the 200MB of the JVM with the 10MB of Go here...
Why so-called performance of a wrapper around OS syscalls is more important than resource costs of having a pending connection?)
It would have been interesting to have a C/C++ benchmark for reference.
If you don't do buffering in user space, the context switches in/out of the kernel will kill you when you do many small read or writes.
No idea if that's it, but that's the first place I tend to look when troubleshooting networking app performance as so many people just blindly use syscalls as if they're free.
p.s. to parent: "the JVM TCP stack?" really?
But you're wrong that better performance implies less buffering. A typical way to write such applications to do less buffering is to do select() or poll() or equivalent followed by a large non-blocking read, and then picking your data out of that buffer.
As pointed out above, if this "benchmark" does ping/pong's in lockstep across a single connection, then buffering vs no-buffering will make exactly no difference, as there's no additional data available to read. But in scenarios where the amount of data is larger, the time saved from fewer context switches quickly adds up and gives you far more time to actually process the data. Usually your throughput will increase, but your latency will also tend to drop despite the buffering as long as the buffers are of a reasonable size.
Buffering is a problem when the buffers grows to large multiples of the typical transaction size, but for typical application level protocols that takes really huge buffers.
That doesn't even make sense. The Scala version can simply spin up more threads. It's not an issue of parallelism, the Scala version just happens to be faster, throwing more Go processes at the problem won't help. Go is already multithreaded. You don't need multiple processes to use the cores on the box. The JVM scales memory usage by default (heap size etc.) based on the amount of memory on the host. If you're going to worry about 100 MB RAM it's easy to constrain the JVM with -Xmx
Any way to see the actual test code?
EDIT: Any good references out there? Thanks!
require "socket" s = TCPServer.new 'localhost', 1201 loop do c = s.accept if c.read(4) c << 'Pong' end c.close end
In short, every round is fully served, and the concurrency level is 100.
dial tcp 127.0.0.1:1201: connection refused
i changed 'localhost' to '127.0.0.1' and now I see a whole lot of dial tcp 127.0.0.1:1201: connection reset by peer
some connections were successful though.In any case, your benchmark is flawed (as virtually all benchmarks are). The reason Go the client is slower is because it tries to pervasively "thread" via the M:N scheduler -- every wait check causes it to yield the actual thread and switch goroutine, creating a large amount of overhead. The Scala cases, on the other hand, is dramatically more limited and will not yield this overhead.
The Go server does not have this fault, and is likely top performance. And aren't we talking about a server anyways?
Now as to the client, while we could naively criticize M:N scheduling based upon this, try giving it a more realistic workload (unless you seriously plan on load balancing pongs): Instead of ping/pong, return larger lengths of data preferably over actual network connections (not localhost) - e.g. 32KB.
The Go client will catch up if not shoot into the lead. M:N scheduling is optimal for most real-world workloads, though it is less optimal for spin-off-a-million-goroutines that do nothing type tests.
This is not a test of TCP overhead, or a realistic test, but instead demonstrates the small overhead of goroutines when you give each a minuscule amount of wait work.
tcpAddr, _ := net.ResolveTCPAddr("tcp4", "localhost:1201")
conn, _ := net.DialTCP("tcp", nil, tcpAddr)
Vs. val socket = new Socket("localhost", 1201)
Edit: Go has e.g. net.Dial("tcp", "localhost:1201") and as someone pointed out elsewhere for a more accurate bench in both clients why not use the numerical address instead?I got somewhere between 2.0 and 2.2 "milliseconds per ping" for Scala 2.9, and somewhere between 3.5 and 3.7 for Go 1.1. This is not the 10x difference that the authors reported, but it is something. The difference may be due in part to the different platform and hardware I am using.
Contrary to what I wrote earlier, I noticed that GOMAXPROCS=8 did seem to be slower than GOMAXPROCS=4 here. I got around 4 "milliseconds per ping" with GOMAXPROCS=8. Using a mutex and explicit condition variable shaved off maybe 0.2 milliseconds on average (very rough estimation).
Again contrary to what I wrote earlier, Nagle on versus off didn't seem to matter in the Go code. I still think you should always have it off for a test like this, but on my setup I did not see a difference.
I still don't think this benchmark is showing what they think it is. I have a hunch that this is more of a scheduler benchmark than a TCP benchmark at all. I think I'd have to haul out vtune to get any further, and I'm getting kind of tired (after midnight here).
Unless you have evidence that Go has MacOS-only bugs, this is meaningless speculation (though I agree that it's possible that there's no problem on Linux and that people don't generally run mac servers, I'm not sure why we should privilege your hypothesis).
Agreed about GOMAXPROCS=4 - that seemed questionable to me (I don't know what it does, precisely, but I don't see a 4-anything limit in the Scala code).
To explain the Nagle algorithm's irrelevance to this case, we have to understand how it works. It doesn't delay any writes once you read. It only affects two consecutive small writes (my memory was fuzzy so I checked http://en.wikipedia.org/wiki/Nagle's_algorithm ). Odds of preemption between the client's write and its read seem small, so it shouldn't matter whether you Nagle or not.
Re: MacOS, I do know that some of the Go developers use Macs as their primary desktops. So I don't think they neglect it, but given that they're targeting the server space, it makes sense to optimize Linux more.
I still haven't seen any really good explanation of these results. I don't buy the argument that the JVM is providing the advantage here. The main thing that the JVM is able to do is dynamically recompile code, and this shouldn't be a CPU-bound task.
The latest Scala is 2.10, which has a number of optimizations over 2.9...