Ruby concurrency is hard: how I became a Ruby on Rails contributor
mensfeld.pl
mensfeld.pl
1. Every time you have a shared data structure, put a Mutex around it's usage (even in POC examples so people learn the properly). In the reproduction example line 4 you have `ids = Set.new` (the shared data structure) and on line 9 `ids << semaphores['test'].object_id`, since this is within a thread you need to put a Mutex around the push to `ids`. You can still have `semaphores['test'].object_id` outside the Mutex, assigning that to a variable and then push that to `ids` in the synchronize block to achieve the same result. If you have both inside the Mutex it would hide the presented issue.
2. Write stress tests that loop through your multithreaded code multiple times with trivial workloads; 100 times might not be enough to trigger a concurrency issue, you might need tens of thousands, or millions of iterations, or more. So don't be afraid to have the loop size configurable and just run it for a longer period of time, just to make sure. In CI you can tweak the loop size to have it running for let's say 3-5 minutes. That should make it relevant and still keep it fast/cheap enough.
Additionally, ruby now has Ractors, but still marked as experimental. These are amazing as you not only get safe parallelism (not just concurrency, true parallelism), but also data safety as a piece of data is either copied deeply, or ownership is passed to one single Ractor. Fingers crossed we see it stable soon.
It has proved successful so far. The shared-nothing, short-lived process avoids classes of issues such as with slow memory leaks, accidentally blocking event loops, and shared memory threading issues.
Most PHP sites will utilise php-fpm, so it isn't really true that each request will spawn another PHP process.
The language historically hasn't been that great, but its shared-nothing architecture has always been the good part.
for the rest of the listed languages, definitely agree.
Java concurrency got a lot better with JSR 166, by accreting new APIs. But those require awareness of their existence and purpose, the langage baseline is no better.
Project loom does not fundamentally change any of that. It’s goal is to increase efficiency, aka get more wrong answers faster.
I spent years working on concurrent Java apps post JSR 166, and the only concurrency issues I met were PEBKAC, and some of the awful things people did with Vert.x and it's event bus.
I always remembered the same, but was recently in a conversation with Java devs who contradicted it, and could not articulate well why this is the case. and could not find good resources on it.
It has proved a very successful model, combined with tools that cache PHP bytecode like opcache, and keep a pool of reusable PHP workers like php-fpm.
I've done both Haskell and Erlang/Elixir and yet I don't really see what you're referring to concretely. There was hope that automatic parallelization would be a big win for pure functional, but I don't think it's really worked out in practice, because of the overhead and difficulty of predicting if parallelizing something would make it faster or slower.
For example, .map and .filter are now in almost every language, because they are much easier than for-loops. You see them and you know "aha, this collection will be transformed, the number of elements stays the same" or "this collection will be filtered and the elements will look the same, but some might be gone and no new ones will have been added".
Pure functional programming is similar, just that the scope is suddenly "the whole runtime/machine" instead of "a small piece of code that somehow does a loop".
I don't entirely disagree, but I also don't think it would be a game changer for a couple reasons...
- It's already well established practice to separate pure and impure modules in Erlang/Elixir projects, even without a type system to enforce it. Take Ecto for instance, it has a clean split of side-effects (Ecto.Repo) and pure logic (Ecto.Changeset). Very different from things like ActiveRecord or Django ORM. [1]
- BEAM programs (and libraries) use a lot of concurrency and message passing, and I think you would have to use an escape hatch ala unsafePerformIO more often than a typical Haskell program, otherwise the IO would "infect" most of the code. Things like instrumentation, fetching app environment, calling the code server, using process dict...
Joe Armstrong kind of mentions the latter problem in his thesis [2]:
Notice that I have chosen a particularly simple definition of “dirty.” At first sight it might appear that it would be better to recursively define a module as being dirty if any function in the module calls a “dangerous” BIF or a dirty function in another module. Unfortunately with such a definition virtually every module in the system would be classified as dirty.
The reason for this is that if you compute the transitive closure of all functions calls exported from a particular module, the transitive closure will include virtually every module in the system. The reason why the transitive closure is so large is due to “leakage” which occurs from many of the modules in the Erlang libraries.
We take the simplifying view that all modules are well-written and tested, and that if they do contain side-effects, that the module has been written in such a way so that the side effects do not leak out from the module to adversely affect code which calls the module.
He is of course talking about "dirty" _modules_. Working at the function level, the leakage wouldn't be quite as bad... but I think it may still be enough to limit how useful IO annotations would be. Code that "has been written in such a way so that the side effects do not leak out" is quite common on BEAM.Who knows though. Maybe we'll see interesting things in Gleam in the future :)
[1] "To spawn, or not to spawn?" is a good article on the practice of separating I/O (GenServer) code and pure code: https://www.theerlangelist.com/article/spawn_or_not
No, not quite. Pure functional programming is a specific style or paradigm. It's about writing referential transparent expressions only. Tagging something is "impure" is absolutely not the same, even though doing so and/or separating pure and impure functions is a good first step on the way to pure functional programming.
> Who knows though. Maybe we'll see interesting things in Gleam in the future :)
Would be nice and might make me switch ecosystems. As of now, there don't seem to be concrete plans:
> Yes, Gleam is an impure functional language like OCaml or Erlang. Impure actions like reading to files and printing to the console is possible without special handling. > We may later introduce an effects system for identifying and tracking any impure code in a Gleam application, though this is still an area of research.
Incidentally that's the root of the misconception that pure functional languages are easier to reason about. It's operational reasoning that's problematic, because simulating a nontrivial state machine in one's mind is a great cognitive challenge for those of us who are less bright than John von Neumann. However, the Dutch basically solved this problem and provided a logical framework for reasoning about imperative programs in a way based off the program text, with no need for attempting to mentally simulate the probably infinite set of possible processes it describes.
Do you mind clarifying what the framework is that you mean? A pointer would be helpful for me.
But the way of how you can and will describe how the runtime should execute code in a concurrent way is highly dependant on the language. Compare Assembly and Go or Rust or Erlang. Completely differnt worlds, don't you think so?
> Incidentally that's the root of the misconception that pure functional languages are easier to reason about.
It's not a misconception. People are different, but at least I can say after many years of experience in both worlds that pure functional programming is much much more productive than any kind of other approach that I have tried when it comes to dealing with concurrency, parallelism and effects.
I hear you, but you’re missing the point. The sole reason why you find pure functional programs easier to reason about is because that is one strategy for avoiding operational reasoning. However it’s equally possible to avoid operational reasoning about imperative programs. Hence my claim that it’s a misconception.
Elixir has been my primary language since 2016 because it makes concurrency so easy.
I'm also a little confused how it's not functional enough for you.
Your original statement lacks any nuance except "E are bad because no pure functional programming". Any attempts to clarify resolve to basic "it's for the good of the whole program".
Whereas easy-to-use concurrency primitives, effortless parallelisation and concurrency, and even the most basic stuff like ability to put a logging statement anywhere in the code without re-engineering half of your program trump whatever imagined advantages of pure functional programming you may come up with. Any day of the week, and twice on Fridays.
In theory, theory beats practice. But in practice...
> ability to put a logging statement anywhere in the code without re-engineering half of your program
Let me ask you a question: does it change the semantics of your (whole) program if that logline, that you are talking about, is not executed for some reason - or if it is executed more than once?
If your answer is "it doesn't really matter, might at most be a bit annoying but it's just a log, no stakeholder of the program can ever notice" then there is no problem with putting this logline into the program. No need to re-engineer anything.
If, however, this logline is critical and will be e.g. parsed and used by another system and actions might be taken due to it, then I would argue it is good if you are forced to consider the potential impacts to your program. If that means that you need to re-engineer half your program then there is a good reason for that, since the potential impact is huge. Such a thing has never happened to me in many years while working on different kind of applications. Sometimes a couple of 100 lines need to be rewritten - that is the max that I ever had to do. And indeed sometimes this rewrite in fact caused me to find and resolve problems that would have otherwise been introduce by accident.
Because yes, it's a fact that in a "pure functional program" you need to re-engineer half of the program if you need to put the log somewhere where it's "oh so pure", and where you didn't need logging before [1]. Or thread IO through the entire program to begin with.
> Sometimes a couple of 100 lines need to be rewritten - that is the max that I ever had to do.
Where in a pragmatical language you just add `Logger.log` or equivalent
[1] Spare me the pontification of "if you need logging, you're doing something wrong, this must be covered by tests or type systems". There are things you must log like metrics, audit logging, tracing values through the system, and it is a 100% certainty that you will add logs to places where no logging existed before.
I did not. I wrote that it amounts to demagoguery.
The reason is simple: a pragmatic language lets you write a single `Logger.log` line without pseudo philosophical discussions on the semantics of a program and "sometimes re-writing 100 lines of code".
It's no wonder any discussion on "how to do logging in Haskell", for example, devolves into discussing the merits of various types of monads and "composable co-monadic contravariants" with 15 equally cumbersome ways of using them.
"All for want of a nail"
I much rather prefer to evaluate the impact in advance rather than having to find and figure it in production.
See, this is exactly the zealotry and demagoguery I am talking about.
99% of use cases: we need to add a single line of logging here
Pure functional programming cultists: first we must consider the semantics of the program and the implication of logging on the grand scheme of things. Consider the criticality of a log line. What is a log line? ... <two hours later> ... an lo, once you've done the refactoring to consider the co-variants ... <another two hours later>
Edit. I'll reiterate:
Easy-to-use concurrency primitives, effortless parallelisation and concurrency, and even the most basic stuff like ability to put a logging statement anywhere in the code without re-engineering half of your program trump whatever imagined advantages of pure functional programming you may come up with. Any day of the week, and twice on Fridays.
For example, if this is a log line for audit logging in an enterprise product then it's clearly relevant. If this is a trace log line in case you need to debug some minor issue, then that's a different story. Has nothing to do with zealotry, just common sense. If you don't understand that there is a difference between those two cases then the discussion ends for me here.
I don't.
> Has nothing to do with zealotry, just common sense.
Ah yes. "does it change the semantics of your (whole) program if that logline, that you are talking about, is not executed for some reason - or if it is executed more than once?" vs. "this logline is critical and will be e.g. parsed and used by another system and actions might be taken due to it, then I would argue it is good if you are forced to consider the potential impacts to your program. "
etc. etc.
And yet the fact is that if you need to log something your precious "mah purity" function is doing, you're stuck with "sometimes a couple of 100 lines need to be rewritten".
Where as non-cultists just do a `Log.info` etc.
If you can't understand that, well :shrug:
Edit. I just re-read that inane pseudo philosphical bullshit about "the semantics of the whole program a log line". No, I definitely don't need to consider the semantics of the whole program to add a bloody log line.
It's most certainly not a fact. It's trivial to insert Debug.trace, for example.
Optimally also stdlib functions and an ecosystem that help. Those can be rebuilt, but most people consider them tightly related to the language, so without it, it couldn't probably be called great support.
Applications these days - well, a large number of them - need to be realtime. Server push. Websockets. Push notifications. Scheduled jobs. Long running background jobs. Calls into other services. Presence awareness. The list just goes on and on. And sure, you can somehow deal with all of this in Rails - hell, you can do anything in any language given enough time and effort - but you are absolutely going against the grain, and you're not using Rails anymore, you're using Rails + sidekiq + node + some other thing + xyz. I thought Rails was supposed to be the simple option?
Rails still might be the best choice, if you're sure your domain will never need to do anything long-lasting or concurrent. Internal admin apps or simple e-commerce would be good examples. But if it's going to be more than that then Rails might save you some time at the beginning only to bite you badly later on.
Phoenix 1.7 is out now and I basically recommend all rails developers to start learning it. It is going to be a bit of a learning curve, and it's not quite as lovable as ruby and its near-perfect syntax, but it is vastly more capable and is, IMO, the way forward. Frankly, I don't understand why it isn't much, much more popular.
Frankly, I don't understand why it isn't much, much more popular.
It's been a few years since I walked away from Elixir and Phoenix for recreational projects so I've forgotten the finer points. The two things that bothered me the most were that a.) Erlang treats BSD as a second class citizen and b.) I got the sense that there was a lot of cargo culting going on. Getting an informed answer felt like it was just that much more difficult than with say Ruby.Professionally, as an ops monkey, I wouldn't want to be on the hook for supporting an Erlang or Elixir app. There's definitely a chicken-egg problem and I'd worry about finding coworkers who would be comfortable with Elixir, but there are also simply far too many moving parts. Like. Yeah okay channels are cool, in-place upgrades are cool, and a well disciplined team could make good use of them but to me that all sounds like a lot of very tempting footguns. All of a sudden I'm not just supporting an app, I'm supporting an entire runtime on top of Linux. I'd much rather deal with a single binary like e.g. go or rust provide, and I'd much rather not deal with Erlang processes and whatnot.
That said the language itself is great. At the time I started dicking around with Phoenix I was working with a guy who was making a big push to use clojure for internal tooling. I liked the Elixir syntax which felt like a great mashup of Ruby and Clojure.
Cargo cult as you said...
(Not trying to be argumentative.)
We have been quite ok just deploying our elixir stuff as containers per anything else (seems this is even common for go services - even though just the binary is enough theoretically). Connecting a cluster of beam-containers is not really any different to a cluster of go-containers, etc. Possibly when you last used Phoenix it didn't have built in releases (portable, compiled packaged dir + binary) - and a Dockerfile generator.
I likely lack the perspective you have, but I think you can discard a lot of the beams "classical" deployment story for something that's no different to Rails/Go/etc and I don't think you lose anything besides hot-code-upgrades which I think aren't really that needed in todays multi-node infrastructure. A container going down isn't any different to a raw beam node going down so its much-for-muchness.
A large number of applications where and for what purpose? I think a large number of applications don't need to be realtime. The majority of applications exist that we never see, or frankly never know exist: SMBs that we've never heard of that are approaching (or have approached) the seven-figure revenue mark.
I do think, though, that a large number of developers have had their perception poisoned by this very crowd: that they need real-time, or a front-end framework, or plans for massive scale because they think they have to build the next Stripe or Twitter or FAANG-scale thing. Many of us, just like many applications, aren't going to scale like that, or hold those jobs.
The internet blossomed without real-time just fine. I think that it'd be just fine without it.
I did say that Rails is perfectly adequate for certain classes of applications. I guess the point I was trying to make, poorly as it turns out, is that for consumer applications at least, Rails is no longer the "sweet spot" and you hit up against its limitations earlier than ever and will, not might, will be forced to deploy ever more complex workarounds for basic functionality that you get out of the box in something like Phoenix. OK, forget websockets. How about scheduling a daily summary email? Daily reports? Anything other than a build-the-world, serve-request, tear-down-the-world HTTP query? Now you're running some separate thing and boom, there goes the simplicity.
I get you. I'm the "use boring tools" guy as well. But the tools have to be actually capable of doing the job, and the job has changed, well the kind of things I seem to be involved with have changed, and the Rails productivity "edge" lasts weeks at best.
This is the first time I've ever seen Go called a low level high performance language. Maybe compared to Python or Ruby I guess, which is fair.
Ah yeah, was generalising somewhat. You're right, it's perhaps a "mid" level language. Maybe even high level in areas it is intended for, such as channel tooling, etc. Regardless, it's much more verbose than true high-level languages such as Ruby and I would not consider it a good choice for a startup unless they were specifically writing actual infrastructure code.
Regardless - it's certainly implicated in the cargo cult of "dozens of golang microservices all talking to each other in a combinatory explosion of GRPC" antipattern i've seen startups succumb to before. One of them ran out of runway with less than 10 actual customers, after spending 18 months building an MVP that would "scale".
Maybe I can propose a new law: "If you have more microservices than you have customers, you are scaling prematurely".
This is a breeze in Ruby. You really think Ruby devs don't do periodic jobs? There are many many good battle tested solutions for that in Ruby.
There's plenty of real issues with Ruby (and with Elixir), but what you're arguing here is simply non issues imo.
As for monitoring, it's better than it used to be - Elixir's Telemetry library is pretty awesome. There's even some UIs built for it:
- https://elixirschool.com/blog/instrumenting-phoenix-with-liv... - https://craft.mirego.com/2022-09-10-telemetry-ui
Forgive me if I'm wrong (I don't know Phoenix that well), but don't you need some external library like Exq do perform background jobs? How is Phoenix+Exq different from Rails+Sidekiq?
In my experience a bog-standard vanilla Rails + Postgres setup provides all of the things you mentioned (except presence awareness, which is pretty tricky).
* Server push. Websockets. Push notifications. => ActionCable
* Scheduled jobs. Long running background jobs. => ActiveJob
* Calls into other services. => Pick your preferred HTTP library (or just use Net::HTTP)
All of the above have been part of Rails for years. The only additional Gem I would add is good_job to be the ActiveJob backend.
Now, if you start to bump up against what vertically scaling Postgres can handle, or you want some of the _additional features_ of a 3rd party dependencies (Redis, Sidekiq, Webpack, etc. etc.) you can easily add them, but it's realllly unnecessary for 99% of apps out there.
> Phoenix Presence is a feature which allows you to register process information on a topic and replicate it transparently across a cluster. It's a combination of both a server-side and client-side library, which makes it simple to implement. A simple use-case would be showing which users are currently online in an application.
The argument for using Elixir/Erlang is also more difficult when you have large companies like Github and Shopify demonstrating that Ruby can scale.
EDIT:
Let's not forget that it's mostly the DB that slows CRUD apps down. Not the language or the framework.
Edit: this is also why I mentioned GoodJob, it supports the full ActiveJob API (delays, retries, etc), even comes with a nice Web UI, and it only requires Postgres.
https://github.com/quantum-elixir/quantum-core
^ obviously it won't fit every use case (where you need 100% durability) but for that there's Oban which is awesome:
It might depend which languages you already know, but if you've done modern JavaScript a lot of the function elements will be familiar.
This is a wonderful resource:
There's more to a non-trivial project than what the language itself provides.
Much has been written about this.
2. Concurrency is built in so thoroughly that there is an entire framework called OTP that provides powerful tools and supervisor processes and so forth to really take concurrency to the next level.
3. Once I got the hang of OTP, similar to when I got the hang of functional programming, it felt like a huge weight off my shoulders again. OTP makes concurrency so easy and lightweight that you think nothing of spinning up three dozen processes just to handle some trivial calculation or data transformation -- processes are like objects that are actually alive and useful and doing things, and OTP is like an orchestrator.
It just feels to me like everything is clearer, simpler, and more robust when I use Elixir and the BEAM/OTP ecosystem.
Also, writing a web application in Elixir means writing a program that you then fire up and which stays up until you bring it down or it crashes for some reason. In Rails on the other hand, you write a script that is fired up every time an http request arrives, builds it's entire context for everything, handles the request, and then dies split second later, only to start the whole process over again a split second after that. There is a certain simplicity in only firing things up once and then just keeping your context alive in perpetuity.
I thought similar things in 2016 when I started learning Elixir and Phoenix but after 2 years, building multiple apps, dabbling with it for years afterwards (up until about last year) and giving it everything I had (and more). It wasn't for me.
The conclusion I came to was Elixir makes certain things that are hard in other languages easier and there's certain things in other languages that are simple but much different in Elixir. For the apps I build (typical web apps like GitHub, etc.) I found that I ran into more scenarios where Elixir as a language made it harder for me to build the things I wanted. For things that Elixir made easier, other languages have "good enough" solutions.
If the goal of all of this is to build things to provide value for others, choosing a stack with a larger ecosystem of tools and community support wins in my book when you've reached the point of "good enough" in other things. Responding back in <= 100ms for the p95 case is "good enough" and most web tech stacks can do this without a huge amount of server costs or extra effort if you're talking about million dollar business sized apps where you might be dealing with a few hundred thousand visitors a month for a typical SAAS app.
Things like Hotwire[0] are also tech stack agnostic. You can build really nice feeling apps with minimal effort. I spent about a week upgrading one of my apps to use it while learning as I went and it made a massive difference. Conceptually it was low effort to understand and didn't require rewriting everything. That has been the polar opposite experience I've had when I used LiveView.
Pity hardly any of the 129 comments before me bothered to address it.