Micro-Services, Eventual Consistency and Event sourcing patterns
 

Microservices is a really becoming a famous architectural pattern that most of the new software written these days, just apply them. One of the most important differentiation between the traditional web services and micro-services pattern is the amount of common stuff across different subject areas. This calls for a discussion on how Eventual Consistency pattern is mandatory for successfully implementing microservices.

The micro frontend if gaining lots of popularity.  You can read about microservices principles and micro frontends at

Microservices and Microfrontends

Micro-Service Pattern

Generally, in a micro-service pattern, the API’s are split into small subject areas. For example for a CRM application, the subject areas are

  • Customer information – like name, address, email, phone
  • Appointment information – which customer, salesperson, when, where
  • Relationship management – sales/manager, what products, interests
  • Campaign data – offers, deals etc

Then micro-services are built for each of the subject areas.  The microservices are logically and physically separated from each other. ie there is no sharing (code, database, component etc) between any of these micro-services of these subject areas. Pictorially its looks something like this.

Applying Eventual Consistency Pattern

In Micro-services, there is no data that is shared across the micro services. In order to synchronize the data across these isolated storages of these services, we need to apply the eventual consistency pattern. You can read more about applying the pattern correctly here. The simpler way we can achieve consistency across these micro-services is through Event Sourcing pattern.

Event Sourcing

Event sourcing is a process of capturing application state changes in the form of events.  An example of events are customer created, customer updated, Deal created, etc.  Other systems listen to these events and they take relevant action. You can read more about event sourcing here.

Conclusion

Event sourcing is the new way of storing changes to systems and help in making micro-services eventually consistent. These patterns together form well maintainable, reliable and scalable systems in the modern world.

 

 

Azure Functions in plain English
 

AWS Lambda and Azure functions are truly next generational in the sense of the cloud computing. These services simplify the amount of time it takes to move to a cloud-based solution. Following are some of the advantages of running services directly in functions/Lambda.

  • No infrastructure code
  • Easy scaling
  • Easy deployment
  • Gives focus on the business

In this article, we will explore how to create a simple azure function and execute it in simple 5 steps.

1.  Search for Functions in the Azure Portal and select it.

2. Click on “Create” and Create functions form should appear.

3. Enter the App Name, Subscription, Location and select “Create”. After it is created, you should see a page like this.

4. Select “Functions” from the left menu and on the right side select “Webhook + API” and click on “Create this function”.

5. Below screen appears where you can write code for the function and deploy the same. Edit code and select “Run” to update the deployment and run.

That’s all and functions are as simple as that. Hope this article helps in creating functions with Azure simpler. Please feel free to post your questions in the comments section.

Maintaining IEnumerable-Yield Data Pipeline is Hard
 

C# and .Net had IEnumerable and yield since its early versions. And I think its one of the most misunderstood features of C#. This is because of the pattern of deferred/lazy execution implementation.  Before we delve deep into this let us understand the iterator model.

IEnumerable and IEnumerator:

This is the foundation of the C# Iterator pattern and there are a number of detailed articles about this by Eric Lippert. The simple example is here.

There is a basket full of Oranges.

 
public class Basket
{
    private readonly IEnumerable Oranges;

    public Basket(IEnumerable oranges)
    {
        Oranges = oranges;
    }

    public IEnumerable GetOranges()
    {
        return Oranges;
    }
}

public class Orange
{
    public int NumberOfSlices { get; set; }

    public void Peal()
    {
            
    }

    public void Consume()
    {
            
    }
}

And if we have to consume oranges, we will have to peel each one of them. So we can use a simple iterator pattern on them.

var basket = new Basket(new [] { new Orange(), new Orange(), new Orange() });
foreach (var orange in basket.GetOranges())
{
    orange.Peal();
    orange.Consume();
}

But the problem is, we need not consume all the oranges from the basket at one go (I am not Hungry ;-).
So how can I get one orange from the basket at a time? or whenever I am Hungry?

Yield:

C# Yield keyword provides an answer to this problem. Slightly changing the Basket class using Yield keyword. (signature of the GetOranges Method not changed)

public class Basket
{
    private readonly Orange[] _oranges;

    public Basket(Orange[] oranges)
    {
        _oranges = oranges;
    }

    public IEnumerable GetOranges()
    {
        for (int i = 0; i < _oranges.Length; i++)
        {
            yield return _oranges[i];
        }
    }
}

Now the basket will provide one Orange at a time. ie when MoveNext() Method of the IEnumerator is called. In other words, we have paused execution of the “for” loop in GetOranges method till the time the next Orange is required.

Or in more technical words, until you Enumerate, the data will not be fetched and once Enumerated, there is no data. It all boils down to “when you Enumerate”.

The Maintenance Problem:

This is tricky for developers who are inheriting an existing code base. A developer might accidentally add an Enumeration before the place where it actually has to. The next time or When the original Enumeration happens, it can not find any new data and the iterator just completes without any looping. This can happen very silently without any exceptions. So care to be taken to see where we are yielding and where we are Enumerating.

“Yield return” is a great feature in C#, but use it with caution.  Let me know your thoughts.

Tail Recursion
 

My Kid’s encounter with Iteration

I was teaching the addition of 2 numbers to my 5-year-old kid. The initial approach is to use fingers in the hand, so she could sum 2 numbers which add up to a maximum of 10. When it went beyond 10, she needed a placeholder (a variable in software terms). Now I taught her to have one of the numbers in mind so that she could just count the fingers for the second number. Again if the second number is bigger than 10, she was limited. When I started questioning about what her next approach will be, I was surprised by her answer. She came up with an iteration algorithm! The Idea is to use a counter (0n paper) for the number of times the set of 10 fingers were counted. This triggered my thoughts about iteration and recursion, hence this blog post.

 Iteration & Recursion

Recursion had been there in software for very long time. Recursion in software is derived from its mathematical formulations. Below are the rules of recursion.

  1. A simple base case (or cases)
  2. A set of rules that reduce all other cases toward the base case

If we can categorize each of the iteration into a form of simple base cases, then the iterative operation can be made recursive. In simple form: A function calls itself. A ‘Recursion’ is a special form of Iteration where no one knows the number of times the iteration will happen. Below is an example of recursion based Fibonacci series generator.

 
        public int Fibonacci(int n)
        {
            if (n == 0)
                return 0;
            else if (n == 1)
                return 1;
            else
                return (Fibonacci(n - 1) + Fibonacci(n - 2));
        }

 

 Stack Based Languages/Frameworks

Recursive logic in stack based languages/frameworks(example .net, Java)are limited by the amount of memory available. This is because these frameworks add the method name and the data(value types) to a top of the call stack for every call to a method. This is done to retain the data in the current method (in the stack) so that when the method returns, the data can be popped out the stack for usage.The data in the stack is not useful if they are not used after the method call.

 
public void PrintCallStack()
{
  var stackTrace = new StackTrace();           // get call stack
  var stackFrames = stackTrace.GetFrames();  // get method calls (frames) 
  foreach (StackFrame stackFrame in stackFrames)
  {
    Console.WriteLine(stackFrame.GetMethod().Name); 
  }
}

 

 Tail recursion (example)

A recursive method is called Tail recursive if the last line of the method calls itself. Since there are no other operations done after the recursive call, the stack data is useless. So the stack need not be built for each of the recursive calls. A compiler is said to be Tail recursive if it can identify the above scenario and replace the caller with called, and the current stack is reused. This is a huge performance optimization and you might never encounter Stack Overflow exception during recursion.

 
public int NonTailRecursiveFactorial(int n)
{
    if (n < 2)
        return 1;
    return n * Factorial(n - 1);
}
 
public int TailRecursiveFactorial(n, a)
 {
    if (n == 0) return a;
    return TailRecursiveFactorial(n - 1, n * a);
  }


Tail recursion is some times equivalent to Goto statements

public int factorial(int n, int a) 
{ 
beginning: 
if (n == 0) return a; 
else 
  { 
     a *= n; 
     n -= 1; 
     goto beginning; 
   } 
}

 

 By the way..

Generally Tail recursion (tail call optimization) is attributed to functional programming languages and unfortunately major programming languages like C# and Java does not support Tail Recursion. But this optimization is available in their sister frameworks F# and Scala. Also there are thoughts like Trampolines and Lambda expressions are far superior method to achieve results than other form of iterative programming. But i think that is a separate post altogether.