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

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

Advertisements

One thought on “Variables in parallel for-each loops

  1. Pingback: Microsoft Integration Weekly Update: Feb 26, 2018 | Hooking Stuffs Together

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s