Concurrency and all its Wonderful Nuances
A journey and lesson through concurrency and race conditions, and writing concurrent-safe programs.
Everyone's journey starts by writing code top down. At least mine did. Dumping everythin into public static void main anyone? For you it might have been an emtpy swift file or a single react component. It was easy. Those were the days when things were simple, you opened your practice file and just wrote different pieces you found on some website, a book, or from a youtube video. Yes, even back in 2010, I was watching youtube videos to see what cool new thing I could write in java.
You would just you print that thing and checked the terminal or browser console.
The result was:69!
Complete with the missing space. But you would still get all the dopamine you needed. You made something happen, from piecing together different parts of that coding language inline. Something was magical about it. But thats the thing, there was no magic. It worked exactly like the language told you it would. If it didn't it meant you didn't understand something and you had to figure it out. Things were consistent.
Fast forward a few years later, I was dealing with my first race condition, completely baffled. It needed a different way to think than thinking about code as top down, or function to function, line by line. Everything checks out if you read things line by line, but somehow we can arrive at an inconsistent state in our system. We were used to dealing with solving problems at this point, but there was always light at the end of the tunnel back then, a bug we wrote or how we've misused the language. Now the magic was back, and I'm sorry to say, its the bad kind. Somehow things were magically incorrect despite appearing consistent.
This brings us to the core topic, this post arrives to solve one of the more confusing an unintuitive aspects of software, how concurrent processes causes results that can cause serious issues to your system. This article was written for both beginners to race conditions as well as those that think that have some grasp at dealing with it. It starts slow, but we'll end up tackling races in all the useful ways possible, for both code and databases.
Note: For code I'm using Go, but the patterns apply. For database it's postgres and most of these patterns apply to most sql databases.