all Technical posts

Variables in Parallel For-each Loops

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

Variables 01

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.

Variables 02

Conclusion

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

Cheers,
Toon

Subscribe to our RSS feed

Thanks, we've sent the link to your inbox

Invalid email address

Submit

Your download should start shortly!

Stay in Touch - Subscribe to Our Newsletter

Keep up to date with industry trends, events and the latest customer stories

Invalid email address

Submit

Great you’re on the list!