Solving Concurrency Problems

 

Solving Concurrency Problems with Redis and Golang


During the past few weeks I was doing a Redis course on Udemy (I really recommend it if you want to learn the basics and “not so basics” of Redis) and one of the topics it handled pretty well was the concurrency problems that may arise when working with a distributed system and databases (in this case Redis) and how to solve them. I learned about concurrency in one of my University classes and then had the “luck” to take on some concurrency problems in my work projects later on. I thought I knew most of the techniques like using semaphores, channels, barriers and all that but while I was doing the course I was impressed at all the different solutions Redis offers that I didn’t know about. In this article I will show you all the different concurrency solutions I learned from the course using my beloved Golang.To better undestand the issue, we will use a simple example. Imagine we are building an application that buys stock shares for different companies. Different users can buy a number of shares as long as the company has that remaining number of shares available. Given that statement, we can build a data layer (our Repository) using the goredis client that has the following definition:All that sounds good, but let’s put it to the test. Imagine that multiple users try to buy shares simultaniously. We can simulate this behavior by running this BuyShares function in an asynchronous manner, multiple times. Something like the following:

Post a Comment

0 Comments