Show HN: Drogon – A C++14/17 based high performance HTTP application framework
github.com
github.com
a) Show me the code to start with, don't send me digging for it. A SimpleController example as the very first thing would help give a feel for the project, and makes me more likely to consider the project.
b) If there's an easier way (like the drogon_ctl utility at the start of Quickstart [0]), show that first, and the more detailed way second.
Other than that, it looks great. I've used libmicrohttpd a few times, so a bit less of an overhead always looks great.
But one thing that surprises me is that folks are essentially sleeping on HTTP/2. HTTP/2 is just a hell of a lot better in most every dimension. It's better for handshake latency, it's better for bandwidth in most cases, it's better for eliminating excess SSL overhead and also, it's kinda easier to write client libraries for, because it's so much simpler (although the parallel and concurrent nature of connections will challenge a lot of programmers).
It's not bad to see a new contender in this space, but it's surprising that it isn't http/2 first. Is there a good reason for this? It's busted through 90% support on caniuse, so it's hard to make an argument that adoption holds it back.
The migration to IP6 shows how quick the industry is moving to new protocols.
This is rather questionable assumption. For almost everyone in the world it's not faster/cheaper/better than HTTP/1.1, definitely not worthy enough to even bother with it. So, the only way it can get anywhere is if Google abuses its position and forces everyone to adopt it. Which they probably won't do for such a silly thing, they get more out of it by coming up with more useless mediocre "faster/cheaper/better" protocols HTTP/[4567], because this pressures competition to waste resources on that, instead of on something that can compete with Google.
Now if HAProxy makes multiple connections to the backend each one gets served by its own thread+socket and that's going to load much faster because at the very least it's going to get more attention from the OS. Furthermore, if you use the keepAlive header, and set long timeouts, then you don’t even have to pay the connection penalty. So essentially you’ve shifted thread management to HAProxy by virtue of its parallel connections which keeps the webserver code pretty simple. And in a C++ program simplicity is key to correctness
> Now if HAProxy makes multiple connections to the backend each one gets served by its own thread+socket and that's going to load much faster because at the very least it's going to get more attention from the OS.
I'm not sure what you're basing this on. What is the technical definition of "more attention from the OS." If anything, limiting things down to a single process over one connection will improve latency. It'll can help minimize memory copies if you get volume because you'll get more than one frame per read (and you certainly aren't serving a L>4 protocol out of your NIC). Most importantly, it'll remove connection establishment and teardown costs. These aren't free.
Now, if you really are loading backends so that responsiveness is a problem, you'll need to appeal to whatever load balancing solution you have on hand. But most folks agree that this is faster.
> Furthermore, if you use the keepAlive header, and set long timeouts, then you don’t even have to pay the connection penalty.
But you still have head-of-line blocking, so you're still spamming N connections per client to get that concurrency factor. Connections aren't free, they have state and take up system resources. You'll serve more clients with one backend if you take up less resources per connection.
> So essentially you’ve shifted thread management to HAProxy by virtue of its parallel connections which keeps the webserver code pretty simple.
I don't think this is true at all. If you want to serve connections in parallel or access resources relevant to your service in parallel, you're going to need to do that. You can of course choose to NOT do this and spam a billion processes rather than use concurrency.
> And in a C++ program simplicity is key to correctness
I don't think this is unique to C++, but I'm also not sure it's really relevant here. From an application backend's perspective, it's very much the same model. They need a model that supports re-entrant request serving.
Http1.1 brought pipelining where you could use the keepalive header and send req1, req2, recN and then expect to recieve reply1, reply2, replyN. The replies are expected in the order they are requested.
Http2 adds a bunch of things. For one, the requests are in a binary format instead of a text in order to acheive better compression. Another thing is that it allows multiplexing. This is different from pipelining because now you can recieve replies out of order which allows small files not to get stalled out by large files.
However, HAProxy will Demux the http2 requests and separate them into multiple parallel connections to the backend server where each connection supports pipelining so as not to close immediately. Each request will use a connection that’s free (ie doesnt already have a pipelined req in progess) so this is effectively the same as http2 multiplexing since HAProxy will send them back to the client in the order they are recieved from the backend (which isnt necessarily the requested order aka multiplexed)
The benefit here is that
1) If you have multiple webservers, they dont have to each deal with the muxing/demuxing of streams and converting the binary to http.(might be possible to skip binary translation but code will be ugly)
2) If you have parallel connections each using threatpools to handle each request stream then you could start running into thread contention problems
3) You protect your C++ webservice with a battle tested service like HAProxy
Remember though that because of the model, you cannot possibly serve these in parallel. You must serve them serially to be on spec.
> Each request will use a connection that’s free (ie doesnt already have a pipelined req in progess) so this is effectively the same as http2 multiplexing
It's not the same at all though, is it? HTTP/2 doesn't wait for each request to return. You could easily do exactly that same process with HTTP/2, and by decoupling the notion of "utilization" from "that connection is busy", you can actually balance to servers based on more sophisticated metrics.
> 2) If you have parallel connections each using threatpools to handle each request stream then you could start running into thread contention problems
You already have these problems with resource management for application services.
> You protect your C++ webservice with a battle tested service like HAProxy
Why does the http/2 architecture not get a load balancer but the HTTP 1.1 architecture does?
In response to your first 2 questions:
In front of HAProxy is HTTP2 and in the backend is say 32 long-lived HTTP1.1 connections to your web server each handled on its own thread. HAProxy demuxes the HTTP2 request and then parallelizes the parts over the 32 connections. Then whichever order they come back from the backend is the order in which they are returned to the sender. HAProxy also knows that the connection that just returned is now available to immediately work on a new request. It is not necessary to wait for a request to finish before scheduling the next request on a connection by virtue of pipelining. If you were round robin-ing through your connections and reusing available connections before pipelining, then head-of-line blocking will be fairly rare.
In response to question 3:
Now it's important to remember that thread performance is directly related to the number of physical cores. If the system has 4 cores, then running the web server with 4 threads will perform better than running with 40 threads due to the overhead of context switching. If you have 4 HTTP2 connections using a shared thread-pool to handle the multiplexed requests then there will be a performance hit as each connection waits for a thread to be available as another connection might use multiple threads simultaneously. In the solution I propose, since HTTP1.1 requests are already sequential in nature, each connection can be given its own thread and run as fast as it can. You can't do that with HTTP2 because then you would lose all ability to parallelize over a single connection. Really what it comes down to is scheduling tasks for CPU cores and a thread that has constant work in its queue will work faster than one that continuously returns a value and waits to be given another request to process. However, HTTP2 does have the advantage of scheduling on the thread-level vs the connection level. I suspect this results in better performance under very high loads and when there is a significant size/time-complexity differential between various assets which causes frequent head-of-line blocking.
In response to question 4:
I figured that if you already implemented HTTP2 and you were that concerned with speed that you wouldn't want to introduce a middleman, but HAProxy's overhead is pretty low.
If that was true, I'd be convinced by it. But is it true? HTTP 1.1 is a pretty big and complicated spec.
HTTP/3 (QUIC) is genuinely exciting and I'm very eager to see it. But given it's even more different from http/2 than http/2 is from http 1.1, it's probably gonna be another 3-4 years before we see good load open source balancer performance in front of it.
What makes it simpler? I thought it was the other way around.
Even though HTTP/2 is usable, adoption is still low (last I checked it was around 25%), and any server that supports 2 needs to support 1 for backwards compatability. It's also more complicated to implement, so I can see why you'd want to start with HTTP/1.
As for client libraries for APIs, it's a non-issue. There's plenty of flexibility on backends.
I'm not saying you'd skip "HTTP/1" but I certainly wouldn't put a lot of effort into it.
Revproxies are essentially awful, ugly lynchpins in your distributed architecture. You want to be as low as you can afford to be on utilization for them, because if they have a bad day you have no product.
I am certainly NOT advocating for their lack. I'm not even sure how that could realistically work.
https://github.com/TechEmpower/FrameworkBenchmarks/tree/mast...
Absolutely not true for C++. The language was invented to guarantee memory safety, like Rust was. (The fact that people ignore the safety features when coding is irrelevant, people liberally throw 'unsafes' around in Rust and Haskell too.)
The fact that people can ignore the safety features is the point. Unsafe is a contract, and it only opens a small number of extra "features". It forms the axioms of a proof the your code correctly uses memory. C++ is essentially just patched with safer abstractions, some of which are major improvements, but there is no proof, no rigorous check for safety until runtime from asan or a fuzzer, or other tools that aren't a part of core C++.
The biggest issue with the safety of C++, however, is the size of the language. It has become so big and so complicated, and the rules that govern things we take for granted like function name lookups are horrendously unintuitive and lead to unintended consequences.
Plenty of interviews where he states this, including some of his books.
int foo(int x) {
return x+1;
}
leads to undefined behavior (aka the standard says the program can delete your hard drive) if x is too big, that's not a language that guarantees memory safety.But to list some direct memory unsafety possibilities: indexing off the end of an array, indexing off the end of a vector, dereferencing a bad pointer, dereferencing a null pointer, dereferencing a bad iterator, double delete.
Well, that's indeed a nice feature in debug mode. Mostly wraparound is undesired and wraparound bugs are pretty common. Shame the performance cost is too much to do same in release.
Whenever wraparound semantics it is actually wanted, one can use an appropriate type.
The risk of security issues of such framework, since it uses C++, might be quite high. I'm not into security a lot, so don't trust my word, but I'd be very cautious.
Generally, I guess higher performance means lower security.
Both handle HTTP requests, but nginx mostly forwards requests to other stacks.
Using Nginx modules and LuaJIT, you kind of can. OpenResty is a web framework built using this principle.
app.get("/test", [](drogon::Request & req, drogon::Response & res) {
// Business Logic Goes Here?
});
I'm going to be honest, I'm turned off by the macros and general API style of endpoint definition. I know, I know...> Don't be scared by the code.
I can't help it!
drogon::app.registerHttpMethod("/test",
[=](const HttpRequestPtr& req,
const std::function<void (const HttpResponsePtr &)> & callback)
{
Json::Value json;
json["result"]="ok";
auto resp=HttpResponse::newHttpJsonResponse(json);
callback(resp);
},
{Get,"LoginFilter"});
The method in the readme file is for decoupling. Imagine a scene with dozens of path handlers. Isn't it better to disperse them in their respective classes?Of course, for very simple logic, the interface you are talking about is really more intuitive, I will consider adding such an interface. Thank you for your comment.
What is "NIO" here? I am familiar with NIO as New Input-Output from Java, which was the extension of the standard library to cover asynchronous I/O. Is the author using "NIO" to mean asynchronous IO? Their use of '"JSP-like" CSP file' elsewhere hints at a Java background.
However, the callback has an odd interface.
why not pass a universal ref T&& vs a const T&
most of your code is like this.
``` auto resp = HttpResponse::newHttpJsonResponse(json); callback(resp); ```
which means callback can reuse the buffer if it wanted to rather than making a copy because it's const ref.
PS: did you benchmark it against Folly/Proxygen (facebook) and Seastar
Also, this would be super cool if it were in Rust. As it stands writing web services in C++ is basically programming malpractice at this point. Would love to see the author contributing to tokio or hyper and helping us get rid of all this legacy inheritancey impl junk.
This is the kind of extremism that makes people hate Rust. Please don't make people hate Rust.
Open source software is only one facet; there are plenty of companies with millions of lines of C++ internally, some of which making up parts of their infrastructure.
I'm being intentionally very non exhaustive for two reasons:
1, I don't feel I should have to explain this. It's self explanatory that these two extremely complicated things can't be compared like integers
2, because it's very much subjective. If you are starting a completely greenfield project Rust might be a good idea. I am a huge fan of what Rust has to offer. But it has it's kludges and kinks to work out, whereas companies have had decades to work out and improve their usage of C++. In particular, linting and coding standards for modern C++ projects generally go very far in improving memory safety even if they don't provide strong guarantees like Rust can. With enforced coding standards you can virtually eliminate risks like buffer overflow and discourage risks like data races. In addition to the ecosystem of libraries, there's a lot of excellent tooling for C++, for static analysis and debugging.
I fear now that I have elaborated the first instinct you will have is to poke holes in individual points. Please don't. All I'm trying to illustrate is that switching to Rust costs time+effort, and it is seriously not better than C++ in every way, in the same way that Go isn't.
My general point is that people should make a commitment to upgrade, and set a course in that direction. The opposite approach is the wait and see mentality, which leads companies waiting in perpetuity because they collectively never adopt better languages due to the sunk cost fallacy.
It's exactly the big companies that need to commit, because they have the resources to invest in sanding down the kludges and kinks and making Rust really better than C++ in every way, and it's in the early stages of Rust's development were senior C++ talent could really help set the direction of Rust based on what we've learned from C++.
The team is largely volunteers, though several companies sponsor people as well. Some people who are sponsored are only part time, or only on the bits relevant to that company. Mozilla sponsors the most full-time people at the moment. We’re working on getting more full-time people, there are some challenges there.
Go and Rust on the other hand are new enough to have coherency taken as a whole.
I like Rust, yet I would be very masochistic to drop the C++ tooling support to write native libraries to plug into Java or .NET applications, and drag our customers and team alongside, just in name of coherency.
I have seen too many coherent languages fail to survive the adoption curve, because their communities failed to focus on the essencials to actually adopt them.
In other words, I'm confident if I write my code in C++ today, it will work in the next 30 years, while I can't say the same for Rust or Go.
checkmate atheists
Literally anything would be better than C++ at this point though. I'd take D or Nim over C++ in a heartbeat, which is drowning in the weight of its own specification, coupled with a desire to keep programmers in the dark ages of memory safety by convention and the C preprocessor. It's also impossible to find a C++ code base that doesn't have some sort of safety issue even with smart pointers and RAII. Fuzzing, testing, and trying to patch things up simply isn't enough.
The software landscape has changed, there are now more reasons than every to chose a language based on safety and efficiency than can run everywhere than ever before.
(Rust is good idea, but about 10 years immature. Come back in 2029.)
Except for, you know, the part where Rust is actually memory-safe and C++ isn't.