How to ensure an existing ruby app is thread-safe

You’re probably considering switching to puma to solve an issue with a service or you need to review that you’re workers code is thread safe because you want to use Sidekiq.

A first good step would be to use rubocop-thread_safety to make a static analysis. You can also use threads gem if you’ve identified a potentially gnarly bunch of code you want to make thread-safe.

Additionally, you need to make sure you have a comprehensive test suite that will check for any potential issues in the code. For web requests, you want carefully audit any state that the application saves about the web request to avoid leaking data across requests.

After those checks have passed, you can the following process to release it safely:

  1. Use the new code in your local and test environments for a period of time (without releasing it) to ensure the behaviour matches the original.
  2. Before full rollout, make a canary release. By having a portion of your production traffic going to only one or two (vs. N) of the servers using the new code and monitor closely.

I hope you find this guide helpful, if you have any other recommendations or real-life experience with a similar process, please reply!

2 Likes

Nice! :100:

I think (except maybe for the “test environments for a period of time” and “make a canary release” parts) your post could be easily converted into a coding agent SKILL.md

Unfortunately, threading-related bugs tend to mostly show up when the code is running, but the static part could be automated, and who knows.. maybe not too far in the future (i.e. AI costs go down) just let the agents spin up containers and blitz the app to find this kind of errors.

1 Like