229 points · by signa11 · 6y ago · 40 comments
That's fine but I feel like it might not be the best introduction for a novice as a lot of concepts are mixed together and they might miss the bigger picture. Context is not just for web servers. You don't have to know how net/http works.
You could simply demonstrate the usefulness of the context package with showing how to properly clean up your program on a sigterm. Or even gracefully stop a long running operation so you are not afraid to stop/start your program at the "wrong" time.
This is one of my major pain points with Go's contexts. Where I work we do have an "application wrapper" that gets cancelled on various signals, and it's very handy for some things. But one thing it's not good at is shutting things down safely!
Something we do pretty commonly is start multiple servers (e.g. a public and a private HTTP server, or an HTTP server and DB background task, etc.) When we get SIGINT, we want to cancel both's context (easy), then wait for both to stop before continuing with our exit process (hard). Yes, this is the canonical case for sync.WaitGroup, but those are hard to use correctly when you need to transition into and out of "acceptable" states rather than just count down (well, hard to use correctly period, to be honest - probably half the time I see a junior dev using them they increment within the goroutine). And hard to timeout waiting for the waitgroup when you want to continue despite unclean shutdown - WaitGroup.Done doesn't itself take a context.
This is further complicated by the fact that for servers you often don't really want to use the "application context" as the parent of the request contexts. Rather you want the server to shut down cleanly when that context is cancelled, processing all pending requests to completion but without immediately cancelling them. So the base request context is ideally something like "cancelling X seconds after the application context" which is not part of the standard context toolbox.
And of course different libraries are not really consistent in how they shut down - http.Server lets you close it with a timeout and so returns an error but also you need to check the error return of the Serve method (and you can't distinguish a graceful stop from a hard stop from try to restart a stopped server), grpc.Server offers only hard and graceful stops with no timeout and only the Serve method returns an error, and sarama.Client provides only a synchronous close that returns an error.
I've not used them but I'm told C#'s cancellation tokens akin to Go context but are closely integrated with their async task state machine, such that it's easy to hand out cancellation tokens and wait for the tasks waiting for those tokens to finish.
Indeed. But I think the seminal blog post¹ on the matter has somewhat skewed perception initially. The first sentence reads:
> In Go servers, each incoming request is handled in its own goroutine. Request handlers often start additional goroutines to access backends such as databases and RPC services.
That pretty much sets a mental context (pun unintended) within the server paradigm. People then just overlook the fact that any Go app can (and often probably should) make use of `context` — CLI anyone? Unless I'm mistaken, `context` is fundamentally about the underlying machine, not network (it just adds to confusion that the latter is represented as "context" within the former, i.e. files and folders and variables in a POSIX environment).
> You could simply demonstrate the usefulness of the context package with showing how to properly clean up your program on a sigterm.
Very nice one! I never saw a book titled "Linux Mechanics" but this would be akin to applying F⁻¹ to some object whose inherent motion comes from F. Like, the basics, "how do I stop this thing?" This is a cultural approach to computers that I think is fading along with the desktop culture, which itself got blurred by tons of layers of abstraction (think 1980-2020).
In that vein I think it's very interesting to experiment with Linux namespaces² (notably cgroups and network namespaces). Create elementary "container components" (i.e. network namespace, UTS..) with Go and see from there how context applies (or not). You'll be effectively clean-rooming³ Docker, in some abstract sense. Distribute it and you've got a skeleton for Kubernetes. It's a really logical conclusion/next step when diving deep into Linux in the current context — DevOps etc. You just see that culture emerging from the tech.
I think Go is incredibly well-positioned to learn these things as we speak: simple, efficient, easy to read, asks you to consider every step carefully (error handling), fluent with OS calls, etc.
[1]: https://blog.golang.org/context
[2]: http://man7.org/linux/man-pages/man7/namespaces.7.html
[3]: Ignoring common licensing or business concerns atrributed this approach, playing with "clean room" work is excellent technical training to master topics beyond intermediary level, well into expertise — that which no one can really directly impart on you, that which you must build for yourself, quite literally so at times. Can you build it, given Search and enough time?
The main benefit seems to be convenience. I can upgrade and graceful-restart nginx instead of having to rebuild and redeploy the Go server (involving a full app restart). Not having to worry about goroutine leaks because some jerk decided to send the request line @ 1 byte/sec is just an added bonus.
Typically, you need to consider the total amount of memory you want your web server to use, how much of that memory one request can use, and how long a request can use that memory. (File descriptors must also be considered.)
Envoy has a section in their documentation about this here: https://www.envoyproxy.io/docs/envoy/latest/configuration/be...
nginx similarly has a number of knobs to turn: https://www.nginx.com/blog/tuning-nginx/
I use Envoy as my web proxy and nginx to serve static content. My envoy configuration is complicated and my nginx configuration is simple, as a result. I imagine that if you are hosting a serious amount of traffic with Nginx as the edge proxy, more tuning is required. I've never tried, so I don't really know.
If you have a reasonable amount of ram, and a reasonable way to manage the slow connections, chances are a Slowloris attack is going to use more resources on the attackers side and not be effective. Async i/o in C based servers works pretty well. FreeBSD accept filters can work if protocol appropriate; the kernel doesn't return the socket to accept until data matching a pattern has been sent, see accf_http; but that doesn't work if the client sends the handshake quickly and further data slowly. If you really need to use a stack that doesn't work for this, putting a proxy that captures whole requests at whatever speed and then sends them as fast requests works too.
Not necessarily. It's just free webservers don't bother dealing with it, but there are plenty of simple approaches. Like just dropping connections that are sending requests slower than some threshold or dropping the slowest connection when some total number of connections is reached. Or more complicated, which also works to protect from all kinds of attacks, dropping the highest malicious score or the lowest reputation score client when some resource usage threshold is reached.
None of these are easy to implement with synchronous multithreaded networking code though, like in Go. Realistically it's only viable with asynchronous single threaded programming models or an actor model.
It's hard to see why synchronous multi-threaded code would find these things any more difficult than async or actor models.
All three models are equally able to access shared data structures to keep track of resource usage statistics, per-connection statistics, and timers.
OS kernels do this routinely, and are essentially multi-threaded on SMP architectures or with kernel pre-emption.
We don't know for sure it was a 28.8K modem, it just appeared to be, given the speed they uploaded and the slight variances we saw in the speed (if it was a throttled upload, they tend to be pretty rigid in performance).
One of the main things it exposed was that certain libraries we used had buffers in them. We'd proxy the data from the customer to another back end service. By default the library would open the connection to the back end, and wait for the small buffer to fill before sending the data. The back end service would terminate a connection if the connection was open but idle for $x number of seconds. The user was on the threshold of that timeout. Probably half the time they PUT, they'd be slow enough to trigger that back-end timeout, resulting in them getting a 500. I believe eventually they put a small buffer on the ingestion path too before pushing along to the back end, but given those PUTs could get really large, we couldn't buffer the entire content before sending along.
That slowAPICall function should look like:
func slowAPICall(ctx context.Context) string {
d := rand.Intn(5)
t := time.NewTimer(time.Duration(d) * time.Second)
defer t.Stop()
...
}All you have to do is make sure is to pass to the library the context that carries your timeout or cancellation signal. The "rule" that everyone seems to follow is to always take as first argument a context.Context if your library handles cancellation.
when doing DB work with these, I'm a little shakier -- once I start a multistep DB write, I probably want it to finish. Yes I can use a transaction to roll back the whole thing, but I think there are cases where rollback is wrong and I'd rather keep the write.
so while cancellation is cool, it's also a little fraught and hard to test.
It's not actually unskippable, but on mobile you have to zoom out to click the X at top right.