Supercharge Your Power Automate Flows: The Ultimate Developer Cheatsheet and Best Practices
Welcome to the world of Power Automate, where automation empowers your business processes. As you build increasingly sophisticated cloud flows, adhering to coding standards and best practices becomes crucial for creating solutions that are robust, maintainable, and performant. Matthew Devaney, with three years of daily experience building Power Automate flows, has compiled a comprehensive guide of over 60 pages filled with actionable rules and guidelines. This blog post serves as a developer-friendly cheatsheet, drawing upon Devaney’s expertise and best practices highlighted by Microsoft Learn and other community resources, to help you build exceptional Power Automate solutions.
Why Follow Coding Standards?
Implementing consistent coding standards in Power Automate offers numerous benefits. A uniform naming pattern allows other developers (and your future self) to readily understand the purpose of a flow and its individual components without needing to delve into every action’s details. This cleanliness of your Power Automate “code” accelerates development, reduces the likelihood of bugs, and fosters better collaboration. Following guidelines also contributes to improved performance, more effective error handling, and simplified Application Lifecycle Management (ALM).
The Power Automate Developer Cheatsheet & Best Practices
Let’s dive into the essential guidelines for building top-notch Power Automate cloud flows:
๐ Naming Conventions
Consistent naming is the foundation of a well-structured flow.
- Flow Names:
- Should begin with a verb describing the action the flow takes.
- Clearly state the outcome the flow achieves.
- Include the trigger type (e.g., Scheduled, Automated, Instant) at the end, enclosed in parentheses.
- Use Proper Case for readability.
- Strive for conciseness while maintaining clarity.
- Prefix with a group name followed by a colon (or hyphen in the new editor) if the flow belongs to a set of related flows (e.g., “Sales Processing: Update Customer Record (Automated)”). Amy suggests prefixing with an abbreviation of the associated app for easier migration.
- Action Names:
- Start with the action’s original description to quickly identify the connector action used.
- Append more specific details about the action’s role within the current flow, separated by a colon (or hyphen in the new editor, as colons may not be accepted) (e.g., “Get Items: Retrieve all active products”). Olivier Jenkins and Filip Giera discuss the balance between keeping the original name and adding context.
- Use Proper Case.
- Trigger Names:
- For Automated flows, include the table or event name (e.g., “When an item is created: New Sales Order”).
- For Scheduled flows, display the recurrence schedule (e.g., “Recurrence: Runs Daily at 9 AM”).
- For Instant flows, describe the event that triggers them (e.g., “Manually trigger a flow: Request Expense Report Approval”). Ben Pomeroy noted that not all triggers can be renamed.
- For Power Apps flows, describe the event in the app that initiates the flow (e.g., “Power Apps (V2): When a new lead is submitted”).
- Variable Names:
- Begin with the prefix “v” to easily identify them. While some prefer “var”, Devaney opts for the shorter “v”. Jenny finds the “{x}” icon sufficient for identification.
- Describe the variable’s subject or purpose concisely.
- Use camel case (e.g., “vCustomerName”, “vOrderTotal”). Matthew Devaney argues against including the data type in the variable name, suggesting the name should describe the content, similar to not naming pets “dog” or “cat”.
- Connection Reference Names:
- Start with a noun that clearly describes the connected account (e.g., “SvcAcct”).
- Follow with the connection type, the solution name, and a unique identifier (which is automatically added within solutions). Rudi asked about reusing generic connection references, to which Devaney provided insights.
๐ฆ Variables and Data Handling
Strategically managing data within your flows is key.
- Utilize variables to store values that are likely to change or be updated throughout the flow.
- Employ the Compose action for creating static outputs or performing intermediate, unchanging calculations. It’s also favored over declaring variables when creating arrays for performance reasons.
- Leverage environment variables for configuration settings that may differ across development, testing, and production environments. This prevents hardcoding sensitive information and simplifies ALM.
- When retrieving data, work only with relevant data by using filter queries and selecting only necessary columns to improve performance.
๐ Commenting Code
Adding comments enhances the understandability and maintainability of your flows.
- Add notes to actions and scopes to explain their purpose, logic, and any specific configurations.
- Maintain a style guide to document your naming conventions for team reference.
- Devaney advises against using the collaborative comments feature for coding comments.
๐งถ Connection References
Proper management of connections is essential, especially within solutions.
- Always use connection references instead of direct connections, particularly when building flows within a solution.
- Assign connection ownership to service accounts to enhance security and reduce dependency on individual user accounts. Zarko inquired about logging in as a service principal.
- Ensure all necessary connection references are included within the solution the flow resides in.
- Consider removing duplicate connection references from solutions and de-duplicating them in environments.
๐ Error Handling
Robust error handling is critical for ensuring flow reliability.
- Implement the Try, Catch, Finally pattern using Scope actions to gracefully handle errors. Kent Weare and Sandro Pereira emphasize the use of Scopes for this.
- Create a “Try” scope to contain the main actions of your business logic.
- Create a “Catch” scope that is configured to run only if any action within the “Try” scope fails or times out.
- Optionally, create a “Finally” scope that always runs, regardless of the outcome of the “Try” or “Catch” scopes, often used for cleanup tasks.
- Configure the “Run after” settings for each action to define how it should behave based on the outcome of the preceding action (Success, Failed, Skipped, Timed out). Reza Dorrani highlights the importance of this for isolating errors.
- Use the Terminate action within the “Catch” scope to explicitly stop the flow with a status of “Failed” or “Cancelled” upon encountering a critical error.
- Implement logging and notifications within the “Catch” scope to inform relevant stakeholders about flow failures. Include details like the error message and a link to the flow run history. Dorrani demonstrates how to retrieve the error message using the
actions()
expression and the flow run URL using theworkflow()
expression. Darren P and Matthew Devaney discussed different paths to the error message JSON. - Instead of extensive custom logging, consider setting up Application Insights with Power Automate and creating alerts for cloud flow run failures.
- Be mindful of potential performance impacts from excessive custom logging.
- Consider utilizing Retry Policies in the action settings for handling transient failures. You can configure default or custom retry policies with fixed or exponentially increasing intervals.
- For more complex “transaction-like” behavior where multiple actions should succeed or fail together, while Power Automate doesn’t have explicit SQL transactions, the Try-Catch pattern can be used to manually implement rollback logic in the “Catch” scope. Theresa mentioned the introduction of ChangeSets for Dataverse operations, which offer transactional behavior.
โก Performance Optimization
Efficient flow design is crucial for optimal performance.
- Enable Concurrency Control in Apply to Each loops when processing independent items to speed up execution.
- Execute independent sets of actions in Parallel Branches to reduce overall flow duration.
- When retrieving large datasets, use Filter Queries at the data source level to limit the number of records returned.
- Further reduce data transfer by using Select actions to choose only the necessary columns.
- Always be mindful of and stay below the Data Connector API Limits and overall Power Platform request limits to avoid throttling.
- Utilize Process Advisor to identify potential bottlenecks and areas for optimization within your flows.
- Favor the Compose action over initializing variables when creating arrays, as it can be more efficient.
- Where available, exploit Batch Update APIs to perform operations on multiple records in a single call, reducing the number of actions and improving performance.
- Avoid using on-premise actions if possible, as they can introduce latency and potential points of failure.
- Minimize the number of skipped actions; consider using child flows instead of overly complex switch statements to streamline execution paths.
๐ Flow Architecture & Design Tips
Plan your flows for scalability and maintainability.
- Write Reusable Code by creating child flows for repetitive logic. This modular approach makes flows easier to manage and update. Remember to create parent and child flows within the same solution.
- Favor Custom Connectors over the HTTP action for interacting with APIs when the functionality will be reused across multiple flows. This provides a more user-friendly and manageable interface.
- Always Build Flows Inside Of A Solution for better Application Lifecycle Management (ALM) capabilities. Richard Uchytil’s experience highlights the challenges of managing flows outside of solutions for development lifecycle.
- Consider Security Architecture from the outset:
- Utilize secure inputs and outputs for actions handling sensitive data like passwords and API keys to prevent their exposure in run history.
- Enable elevated permissions by configuring “Run As User” if the flow needs to perform actions on behalf of a specific user.
- Be acutely aware of Power Platform Request Limits to prevent throttling and ensure smooth operation.
- Keep the 30 Days Flow Duration Limit in mind for long-running processes.
- Design Flow Triggers efficiently:
- Replace the older Power Apps V1 trigger with V2 for improved performance and capabilities.
- Apply Select and Filter Criteria directly to automated triggers (where available) to reduce the amount of data the flow needs to process initially.
- Create Advanced Trigger Conditions using Flow Expressions to ensure the flow only runs when specific criteria are met.
- Flatten Nested IF Condition Actions for improved readability and reduced complexity.
- Eliminate Unnecessary Apply To Each Loops by processing data in bulk where possible.
- For retrieving data from Dataverse, generate Fetch XML for the List Rows action to create more efficient and specific queries.
- For complex, multi-step processes, consider implementing a State Machine Pattern using variables and conditions to manage the flow’s progression.
- For long-running operations, explore using an asynchronous flow pattern to prevent timeouts.
โ๏ธ Application Lifecycle Management (ALM)
Manage your flows through different environments effectively.
- Develop and edit flows primarily in a dedicated development environment.
- Use solutions to package and move flows, along with their dependencies, across different environments (dev, test/UAT, production).
- Deploy only managed solutions to test and production environments to prevent accidental modifications.
- Utilize environment variables to manage environment-specific configurations (e.g., connection details, URLs) without modifying the flow itself.
- Consider leveraging Power Platform Pipelines for more automated and controlled deployments.
- In production environments, assign service principals as owners of flows instead of individual user accounts for better stability and reduced reliance on specific users.
๐ Security
Protect sensitive data and ensure secure flow execution.
- Avoid Hardcoding Sensitive Information (passwords, API keys, secrets) directly within flow actions or configurations.
- Utilize environment variables or secure services like Azure Key Vault to manage sensitive credentials securely.
- Enable Secure Inputs and Secure Outputs on actions that handle sensitive data to prevent it from being visible in run history and logs.
- Secure HTTP request triggers using methods like Microsoft Entra ID authentication or IP address restrictions.
- Implement Data Loss Prevention (DLP) policies to control which connectors can be used together and prevent unauthorized data exfiltration.
๐งช Testing and Monitoring
Thoroughly test and continuously monitor your flows.
- Test flows extensively during development using the Flow Checker to identify potential errors and best practice violations.
- Ensure that error handling and retry policies are effective by testing scenarios that might lead to failures and resubmitting runs.
- Monitor flow runs regularly using Cloud flow analytics to identify trends and potential issues.
- Set up alerts to proactively notify administrators of flow failures.
- Utilize the Flow remediation email feature to receive automatic notifications for common flow failures.
โจ Other Best Practices
Additional tips for building excellent flows.
- Keep Flow Configuration Generic by using environment variables and service principals, making them easier to deploy across environments.
- Work Only With Relevant Data throughout your flow, using actions like Filter array and Select to minimize data processing.
- Maintain consistent naming across all flow components for clarity.
- Avoid Infinite Loops by implementing proper exit conditions in loops or using terminate actions when necessary.
- Minimize the number of skipped actions to ensure efficient flow execution.
- Grant co-owner permissions judiciously and consider using run-only permissions when sharing flows with end-users who don’t need editing access.
- Be aware of flow definition limits, such as the number of actions and nesting depth, and consider using child flows to stay within these limits.
- For operations involving multiple steps that need to succeed or fail together, consider implementing a rollback mechanism within a Try-Catch pattern to revert any changes made if a subsequent step fails.
- Regularly utilize the Flow Checker to identify and address potential issues early in the development process.
Conclusion
By adhering to these coding standards and best practices, you can significantly enhance the quality, maintainability, and performance of your Power Automate cloud flows. This cheatsheet, inspired by Matthew Devaney’s comprehensive guide and insights from the Power Automate community, provides a solid foundation for building robust automation solutions. Remember that these guidelines are living recommendations and may evolve as the Power Automate platform grows. Embrace these principles, and you’ll be well on your way to mastering Power Automate!