less than 1 minute read

Sometimes we need to work with a variable inside a loop section. Whether it’s a precomputation or just a helper variable. Logic Apps allows us to do so. Yet the variable must be initialized on a global level (above all loops).

Here comes the problem:

By default, foreach runs in parallel, in 20 threads (instances). Now, because there is no such thing as mutex in Logic Apps, there is no way how to create a critical section. Critical section is a section only one thread at a time can enter. That results in dirty reads. We can solve this problem by running the loop synchronously. You can do that by editing settings of the foreach block. Now only one thread at a time will execute the foreach loop and no other thread will modify our variable while we work with it.


Josh T

After an hour of beating my head against the table, I found this. Thank you! Using a variable inside a for each loop is not as straightforward as one might expect, a very odd “default” in my humble opinion. You saved me a lot of time with this.

Matt S

This also fixed an issue that I was having. It reminds me of the issue in vanilla Javascript where you have to wrap the contents of a for loop in a closure if you’re using the var type in your variable. Thanks again for posting this.

John Kennedy

Wow! This ended many hours of being puzzled why various variables were not changing in my nested ForEach loops! Thank you! MS should have a warning in their editors about this.


Another option is to you Compose instead of setting the variables inside the loop. That way you achieve concurrency and also avoid the race condition of variables being set at the global level


Thanks to Jan for this article and to Smithan for the “Compose” alternative. As less technical folks (like me) start using these tools, MSFT should make it clearer that this is what to expect in multi-threaded processing.

Leave a Comment

Your email address will not be published. Required fields are marked *