During the past weeks, I received quite some questions about the behaviour of variables inside a non-sequential for-each loop.  It does not always behave as one might expect.  This post describes a potential issue you might encounter, explains the reason why and provides a solution to get it solved.

The problem

Let’s consider the following scenario

  • The Logic App receives a request that contains an array
  • It iterates with a parallel for-each loop through the array
    • A filename with a @guid() is generated
    • A result array of these file names is composed
  • The Logic App returns that array as a response

Variables01

When running the for-each loop in parallel mode, there is an unexpected behaviour, because some of the filenames contain the same GUID value.

The explanation

The variable is initialized at a global level and not within the for-each loop.  This means that multiple parallel for-each executions are working against the same instance of the global variable.  Depending on race conditions, this might lead to incorrect functioning of your Logic App.

The solution

The issue can be simply resolved by using the Compose action instead of variables.  The Compose is instantiated within each individual for-each iteration, so there’s no possibility that other for-each iterations interfere.

Variables02

Conclusion

Don’t use the Set Variable action within a non-sequential for-each loop!  Use the Compose action, instead!

Cheers,
Toon

ABOUT

MEET THE YOUR AZURE COACH TEAM

Your Azure Coach is specialized in organizing Azure trainings that are infused with real-life experience. All our coaches are active consultants, who are very passionate and who love to share their Azure expertise with you.