Why CSP over thread-per-connection?

Balaji Arumugam
2 min readFeb 14, 2024

--

Photo by Camille Chen on Unsplash

Remember the days when every website took an eternity to load? Yeah, not fun. Thankfully, things have changed, and concurrency is key to keeping our digital world buzzing. But how do we handle all those requests without our servers turning into overstuffed hamsters?

CSP is one of the finest solutions for the problem. CSP uses lightweight goroutines and message pipelines (think fancy tubes) to get things done. Goroutines are like mini-threads, super-efficient and less memory (only 2KB stack / go routine), while channels keep things organized and flowing smoothly.

Here’s the magic: traditional thread-per-connection is a resource hog. Each request gets its own thread, like giving every customer a personal waiter in a packed restaurant. With high traffic, your server resembles a giant, sluggish panda (not ideal!). CSP is way smarter. Goroutines are like having a team of ninjas handling orders, leaving messages for the “kitchen” (your code) to process asynchronously. No waiting, no bottlenecks, just pure efficiency.

But wait, there’s more! CSP promotes non-blocking communication, so imagine those ninjas don’t have to stand around waiting for responses. They leave the message and move on, trusting the system to work its magic. This keeps things flowing like a well-oiled machine, unlike the traditional approach where everyone gets stuck waiting for each other.

Now, CSP isn’t just for Go programmers (though Go does use channels beautifully). Its core principles can be applied in many languages (like Elixir erlang). The key is understanding the power of message passing and lightweight goroutines, ditching the old thread-based ways.

So, is CSP the answer to all your concurrency woes? For highly scalable, crazy-busy applications, absolutely! However, for simpler setups, the old thread approach might still be okay. The best choice depends on your unique needs and priorities.

Reference: CSP by C. A. R. Hoare (Highly recommended read)

--

--

Balaji Arumugam

Occasionally sharing insights and learnings. #software_engineering