680 points · by mmcclure · 7y ago · 220 comments
Don’t get me wrong, I'm not suggesting that everyone should be building their site like it’s Facebook or Google, but when every public website is already sat on a proverbial motorway, it can be dangerously shortsighted to build your site to only meet demand with no room to scale. CGI falls under that category. There are plenty of platforms that are still very easy to build and deploy, developer friendly, and still runs circles around the performance of CGI.
(Please note that I am talking about public sites specifically and not intranets or other IP white listed resources)
fork() only takes around 8ms on my Linux machine and I can get 100,000 posix_spawn() per second there with 100MB RSS.
That's "fast enough" for a large number of applications.
†: fork() is a lot slower (over 20x) on Windows
On the other hand a Node.js or Go program can have a preestablished pool of keep alive connections to the backends already ready to go and reuse that connection pool for many hundreds or even thousands of concurrent websocket connections. You can approximate something like this with the fork() model by having a local daemon process that manages the connection pool and have your forked process talk to that local helper daemon when it needs a connection, but you are still going to pay a penalty for that compared with having a fully preestablished connection ready to use right there in the process already
fasthttp(go) can do around 80k/sec on my laptop; dash(C) can do almost 88k/sec on my laptop†. As soon as dash does IPC, it drops to around 51k/sec, and as soon as it needs a reply, we're down to 25k/sec††. I see no reason to believe fasthttp would do any faster.
That means I'm spending around 70% of my time in IPC -- something posix_spawn() would let me avoid (if my application were designed to do so). My same laptop will do 100k/sec posix_spawn() so I'd find this difficult to believe (1-4 msec per call) fork() or exec() is the bottleneck for any application with this architecture. Do you think posix_spawn() represents 70% of your costs? If our goal is to beat 51k/sec requests, sure, but NodeJS on my laptop (btw) gets 10k/sec, so if it's a contender, I'd say posix_spawn() is as well.
† https://github.com/geocar/dash/blob/master/README.techempowe...
What is just another way to make a NxM server, so maybe forget about it...
That means it's only viable for connections where the connection is very long lived and messages are very sparse (because context switches).
--
Meta observation:
Maybe this is the bane of smartphone era and small screens, but the context of the discussion seems to disappear instantly.
Subject: websockets > forking processes > .. aaand the websocket context is lost and we are talking generally about forks in web applications with growing thread.
It also means you should use posix_spawn instead of fork+exec since you can control when the page faults occur better.
In an ideal scenario, you shouldn't have more active processes than you have CPU cores. As soon as that happens, context switching kicks in and performance degrades sharply.
You were right about performance being relative. And of course the trade off between ease of development, use and performance. At the end of the day, practical considerations are going to determine what is "expensive".
Also depends what you're pinging. I'm in the UK, so everything in America is 30-80msec away anyway.
It certainly would hold up inordinately poor to a DDoS attack.
But CGI doesn't fork per TCP connection; it forks per HTTP request/response.
2) that's a default - most systems allow tuning
You can have pretty decent performance with forking models if you 1) have an upper bound for # of concurrent processes 2) have an input queue 3) cache results and serve from cache even for very small time windows. Not execve'ing is also a major benefit, if your system can do that (e.g. no mixing of threads with forks). In forking models, execve+runtime init is the largest overhead.
It will not beat other models, but forking processes offer other benefits such as memory protection, rlimits, namespace separation, capsicum/seccomp-bpf based sandboxing, ...
YMMV
IRC shows us that maintaining a reliable socket for most folks is next to impossible.
That they're visible to clients is an issue with how channels spans servers and how operator status and channel membership is tied to who happens to be on a channel on a specific partition at a certain time, and how messages are propagated when splits resolve, and how inter-server communications happens.
So it has plenty of lessons if you want to build a chat network, but nothing with it suggests maintaining a connection is otherwise a big problem.
In general what it boils down to is the word "reliable": You would want to write your app so that a client that disconnects and reconnects gets a sensible behavior on reconnecting, e.g. by queuing messages when it makes sense, and discard them if it does not, to paper over temporary connection failures.
But you would need to do that if you were to use stateless request/response pairs anyway.
Anyhoo - same arguments about forking, process & memory limits arose ; so things like FastCGI and ISAPI were the solution to reduce/avoid some of those overheads.
I suspect Rust based CGI endpoints would have similar <quote>issues<unquote>.
But I've been thinking about this CGI comeback from time to time - the left side of backend infrastructure (load balancerss, reverse proxies etc) and middle tier machine resources are much better now. Docker containers and lambda spin up is similar to some degree in terms of topology but maybe with even more overhead?
..so does does make one wonder if cgi like simplicity make a comeback with today's order of magnitude better infrastructure? I keep waiting for someone to come up with "lambdaGI" ..with will lead to "fastLambdaGI" and so on (and that's not a snarky comment).
Here's my point of view:
1. Forking is first and foremost a system call. (To be fair, I realize even memory allocation is much of the time, but still.) The kernel is going to do a bunch of work (as fast as it can, of course) and you're going to end up with two different OS level tasks by the end.
2. Those two tasks are now scheduled in tandem by the OS scheduler. For two tasks, this is fine. For hundreds of tasks, it becomes less effective. Threads will rapidly go in and out of I/O wait and the scheduler has to balance all of this.
3. CGI dies right here, though: CGI is not just a fork. It is a fork and exec! The exec, of course, also run in the kernel. It's going to effectively load the binary from scratch. Then you probably hit the linker in usermode, which has to go through the shared library resolution, resolving and mapping shared objects into memory and filling out import tables. This stuff has some caching as far as I know, but still... it's not free.
4. Now you are in the entrypoint of your program... or are you? If you are using CGI with Perl or Python or even Bash, we're not done yet because the script interpreter has to load all of its state from scratch, parse your script, bla bla, and THEN finally we can run your program.
5. Your application now has to do all of its common setup. Every. Connection. If you need to connect to a database, you can't connection pool: you have to open a new socket every time. Redis? same thing. Need to read a config file? Yep, every dang time. You can hack around some of this but in general it's probably going to be like this for most CGI applications. There's a reason why FastCGI exists after all.
The forking model of servers is elegant... but it doesn't work so well in my opinion. The cost of OS-level context switching is non-trivial, forking is relatively expensive, and things get worse when you are talking about something like CGI where your app effectively gets loaded from scratch each time.
My favorite model is definitely the Go model, where the language schedules lightweight threads or fibers across n OS threads (where n = number of logical threads.) It is cheap for the OS scheduler, and the language scheduler can very efficiently deal with things like I/O blocking and GC without huge latency hits.
But you can go about it many ways. Node.JS's event loop model proves pretty effective. Node is far from perfect but I think I would bet on a Node.JS server with a proper event loop over a CGI server forking a C program, myself.
Of course I'm really no expert. But, I think the jump from CGI to FastCGI told me all I need to know: CGI just didn't scale well at all. FastCGI was a much better experience for me, though I no longer use it.
Surprisingly, even thousands of threads can often have better throughput than using event loops and non-blocking IO: https://www.slideshare.net/e456/tyma-paulmultithreaded1
> The cost of OS-level context switching is non-trivial
On modern hardware it's non-zero but trivial: https://eli.thegreenplace.net/2018/measuring-context-switchi...
Edit: If you think I am wrong, could you please explain what is wrong?
Erlang's don't, thus processes. Go's do, thus threads.
Erlang processes are threads as seen by the OS, but the Erlang runtime implements process-y restrictions that enforce isolation and forbid shared memory between Erlang processes that do infact exist as threads inside te Erlang VM.
The programming model, as seen by the Erlang/Elixir prgrammer, is thus anologous to Unix processes, just with lower overheads.
This and "async is always faster" are two things which are no longer true on modern hardware.
Forking a process on Linux uses the same clone() syscall as creating a thread so forking a small binary takes only tens of microseconds, leaving plenty of time for <1ms total response times.
https://eli.thegreenplace.net/2018/launching-linux-threads-a...
And even forgetting the costs of forking, threads are not necessarily much better anyways. I can easily have a single Go program scheduling literally hundreds of thousands of Goroutines across just a few OS level threads and have no problems whatsoever, and in fact I've done exactly that in production, whereas I would never even dream of doing that with threads.
Node.JS's event loop model also doesn't need to spawn threads per connections.
When I say processes and forking are relatively expensive, I don't mean compared to doing the exact same thing with threads; I mean compared to more modern alternatives, like using an event loop or Goroutines.
Event loops and userland cooperative multitasking like Goroutines predate Linux 2.6 kernel threads. They're not "more modern".
The conclusion to be drawn is "Linux threads are costly", not "Linux processes are cheap".
https://github.com/blitmap/lua-snippets/blob/master/scgi-ser...
*On the Windows subsystem, of course. There's the lower level ZwCreateProcess function which can/could be used to fork, but it's undocumented and I believe it only existed for the old SfU. Now that that's gone and Linux Subsystem uses something called Pico Processes, I'm guessing this old fork flag is pretty much unsafe to use for anything at all.
These days, folks often write the app to contain a web server. Write your app in JavaScript, pull in a dependency that serves HTTP, write enough code to route requests and start the server listening- welcome to Node. Python and Ruby offer the same. Swift gets this functionality from Kitura and Vapor. I’ve experienced C and C++ varieties.
Back in the day when Apache was seriously hot, mimicking today’s architecture would have meant writing an Apache module - the app would then live within the server and no communication channel/pipe/socket/fork/spawn would be required.
https://github.com/joewalnes/websocketd/wiki/FAQ#how-can-i-s...
That should provides reliable framing on both sides. But as shown in the linked it page it also comes with the downside of not being able to send raw websocket messages which contain a new line - so it's not possible to port existing applications from other websocket servers to this one without having to change communication.
For example, my browser sends:
This is line one...
...and this is line two
as a string ("This is line one...\n...and this is line two") and the websocketd receives that, and passes along This is line one...\\n...andthis is line two\n
to the STDIN.It knows that the message is one thing, so the newlines aren't the same as the end of message, right?
It'd also be nice to use EOF as the indicator to flush STDOUT to the client, so the program can also emit newlines without needing to escape them first.
All that being said, this is nifty. I think I can use this for some low-volume ideas I have on an internal app. The newline handling isn't a problem because I'm not replacing anything that already exists.
https://github.com/joewalnes/websocketd/wiki/Ten-minute-tuto...
Websocket isn’t a stream, it is framed. Obviously it can be used like a stream but that depends on the client and server. The issue here is that all the client side (browser) APIs expose frames instead of streams.
Suppose I send a JSON object I have no idea what framing this socket server will use and if it’ll break it up into multiple pieces and require the client to reassemble it. If I send two JSON objects in a row does it arrive in two websocket frames or could it buffered into one?
Secondly the websocket protocol is much more complex than a tcp stream. It has keep alive packets that can be sent, it has close packets that allow a connection to terminate with a given code that can be handled by the client. How are these exposed?
However it looks like the Daemon might wait for a newline until it forwards everything as a message. Which at least fixes this problem, but might have other side effects.
That you can't put newlines in messages — whether input or output, you've got to modify the protocol to escape them somehow due to intermediate implementation details.
WebSocket is implemented on top of TCP/IP, which is stream based.
Author is extremely nice as well.
Answer: Websocketd came first.
The variable `count` appears to be incremented non-atomically from two different threads. Is that safe in C++?
count++;
pthread_mutex_lock(&m);
since the reader already holds the mutex while reading `count`.That said, building a FCGI "bridge" isn't hard, it's just that nobody cared enough to do it.
we often download the files post viewing on streams also. mostly it’s exceptions so we’d easily notice missing lines in stacks
for example... simply accept stdin and stdout as I/O streams by default, but don't provide a network mechanism.
Why not extend xinetd so that it can interact with websockets?
For communication servers, this could prove a challenge – you'll probably want to use some kind of pub-sub architecture. By the time you've gone down that road, you could've gone down one of the more robust paths.
Still, this looks great for smaller apps. And, it seems a great way to prototype – especially if your favourite language doesn't have great websocket support.
Totally agree. inetd is a pretty good model, it just falls down in the face of thousands of slow, low-computational effort connections tying up gigabytes of RAM. That and most schedulers seem to struggle with that number of threads.
1: https://en.wikipedia.org/wiki/Unix_domain_socket
2: http://docs.gunicorn.org/en/stable/deploy.html?highlight=soc...
>Each inbound WebSocket connection runs your program in a dedicated process.
Not the best design decision
The location of the server is a factor??
It's the first time I hear anyone mention it. It would be great if OP had some supporting link.
edit: okay this is pretty cool, what use cases is there?
The compiled Linux x86_64 binary is 7 megabytes. All of System V combined was not that big.
This is a program built around executing programs and communicating over pipes. It's composing programs together. I think that's certainly UNIX-ish.
No, but literally the first point is:
> Make each program do one thing well. To do a new job, build afresh rather than complicate old programs by adding new features.
It's not hard to see how this would apply to libraries, and how including third party code in your binary would break this idea because you're essentially "freezing" the application in time.
Your definition regarding "composing programs together" is not all that makes a program UNIX-ish.
I have a fairly simple web-app written in go – no websockets, just net/http. I just checked and the binary size is 6.8 megabytes.
There's a lot in there. For starters, there's the go runtime. Then there's the HTTP server.
I suspect there may be ways to improve on the binary size if it mattered so much. xz gets it down to 2.1MB, suggesting there's some redundancy in there.
Probably unavoidable for this kind of app though. Unicode alone involves a whole lot of data tables that are going to be hard to get rid of unless they're dynamically linked.
7MB is still a lot smaller than Docker containers :)
`go build -ldflags="-s -w"`
And why should it be criticized? Outside AT&T, people were writing OSes in high level languages since 1961.
I hear that representing the absence of value as a number was invented about 6000 years ago, perhaps we should abandon that as antiquated as well..
also, to wit, a Unix kernel of recent vintage:
$ uname -msr
OpenBSD 6.3 amd64
$ du -skc bsd.rd bsd
9664 bsd.rd
12912 bsd
22576 total
vs, say, a Linux kernel of recent vintage: $ uname -msr
Linux 4.9.0-8-amd64 x86_64
$ du -skc /boot/vmlinuz-4.9.0-8-amd64 /boot/initrd.img-4.9.0-8-amd64 /lib/modules/4.9.0-8-amd64
4152 /boot/vmlinuz-4.9.0-8-amd64
21616 /boot/initrd.img-4.9.0-8-amd64
212248 /lib/modules/4.9.0-8-amd64
238016 total
yes, there are likely more drivers in the latter.
highly doubt there is an order of magnitude more though.not to mention some 'modern' npm+webpack monstrosity.
that said, given the latter, i can hardly fault a <10Mb go executable as 'excessive', so you're right on that front.
That's exactly what they are; ~180M of those 212M are in drivers/. And even outside that, it includes stuff like fs/ocfs2, which I don't think OpenBSD supports.
Curious people can read more about it at https://en.wikipedia.org/wiki/Unix_philosophy or https://homepage.cs.uri.edu/~thenry/resources/unix_art/ch01s...
The websocketd site outlines this fairly well with the big quote on their homepage.
Looked at another way, a Unix-like ecosystem satisfies two of the principles of a SOLID software architecture: the Single Responsibility Principle and (arguably) the Open-Closed Principle.
If websocketd focuses on handling the nuts and bolts of websocket connections and invoking other programs and piping data into and out of them over a standard interface, then it's a Unix-like architecture, even if it's a fat, monolithic, statically linked binary.
I see you and 10,900 other "software developers" get the point of WebSocket. It's especially "impressive" when you written the whole thing in Go and could have used goroutines and channels, which could easily handle hundreds of thousand of connections (maybe millions). Terrible design!
For a long time I thought every software developer must be smart, but a lot of them don't see the big picture very often.
Why this bothers me so much? You created something that a lot of developers think is good enough, so less innovation will happen and more and more slow websites will appear because of tech like this...
And sure you might be upset by "slow" websites, but for the small consultancy productising their scripts, it might make them - dare I say it, a quick buck. In the end the invisible hand of the market decides how much money is invested making websites fast and that is what guides the design of the technology being developed.
Perhaps it is you who fail to see the big picture.