We discover a bug in our code where it seems like the gateway api is calling the core microservice infinitely.
The problem
We have a background task which creates some entities in the database. This results in eventual consistency. However, the front end does not know when the background task finishes. So when the front end calls the backend endpoint, we decide to retry 3 times if fetching the data returns null. This is the sample of that code.
static object FetchSomeEntity(int tries)
{
Console.WriteLine("Fetching some entity");
object entity = null; // Logics to call some service to get the entity goes here
if (entity == null && tries < 3)
{
entity = FetchSomeEntity(tries++);
}
return entity;
}
At first glance, this code seems ok but when you run it, you’ll get this.
static void Main(string[] args)
{
FetchSomeEntity(0);
Console.ReadLine();
}
This is due to using postfix ++. Using postfix ++ means variable tries will always be 0 in the next retry and hence causes an infinite loop.
Solution
The solution is simple. Replace postfix ++ with prefix ++
static object FetchSomeEntity(int tries)
{
Console.WriteLine("Fetching some entity");
object entity = null; // Logics to call some service to get the entity goes here
if (entity == null && tries < 3)
{
entity = FetchSomeEntity(++tries);
}
return entity;
}
Running this code now fetches the entity once and then retry 3 times if not successful