{"componentChunkName":"component---src-templates-blog-post-js","path":"/blog/dataverse-plugins-vs-power-automate-logica-negocio/","result":{"data":{"markdownRemark":{"frontmatter":{"title":"Dataverse plugins vs Power Automate: onde colocar a lógica de negócio","description":"Plugin registrado no Dataverse ou fluxo do Power Automate? Comparamos latência, transação, sincronismo e governança para decidir onde vive cada regra crítica.","date":"19 de agosto de 2026","thumbnail":null},"html":"<p>Toda equipe que opera Dataverse em escala esbarra na mesma pergunta de arquitetura: quando uma regra de negócio deve ser um <strong>plugin registrado no Dataverse</strong>, quando deve ser um <strong>fluxo do Power Automate</strong> e quando basta uma <strong>business rule</strong> ou uma <strong>classic workflow</strong>? A resposta errada aparece meses depois, na forma de registros salvos pela metade, latência que o usuário sente ou lógica que roda fora da transação e não pode ser desfeita. Este post é um guia de decisão para quem já passou do estágio de \"funciona no meu ambiente\".</p>\n<p><strong>O event framework do Dataverse é o ponto de partida</strong></p>\n<p>Plugins não são \"código solto\": eles se registram em estágios específicos do pipeline de execução do Dataverse, e entender esses estágios é o que separa uma decisão sólida de uma aposta.</p>\n<ul>\n<li><strong>Pre-validation (estágio 10)</strong> — roda antes da transação de banco, inclusive antes das validações de segurança em alguns casos. Bom para bloquear operações cedo e barato, mas cuidado: nem sempre está dentro da transação principal.</li>\n<li><strong>Pre-operation (estágio 20)</strong> — dentro da transação, antes do commit. É onde você altera valores do próprio registro antes de ele ser gravado (setar um campo derivado, normalizar dados) sem precisar de um segundo Update.</li>\n<li><strong>Post-operation (estágio 40)</strong> — dentro da transação, após o commit lógico. É onde você cria registros relacionados, dispara integrações e aplica efeitos colaterais. Se você lançar exceção aqui, o rollback desfaz tudo — inclusive o registro original.</li>\n</ul>\n<p>A execução pode ser <strong>síncrona</strong> (o usuário espera, tudo na mesma transação, rollback automático em caso de erro) ou <strong>assíncrona</strong> (enfileirada no System Job, não bloqueia o usuário, mas não participa da transação do registro original).</p>\n<p><strong>Plugin síncrono: para o que precisa ser atômico e imediato</strong></p>\n<p>Use plugin síncrono quando a regra precisa de duas garantias ao mesmo tempo: acontecer <strong>antes de o usuário ver o resultado</strong> e estar <strong>dentro da transação</strong> para que uma falha desfaça a operação inteira. Exemplos:</p>\n<ul>\n<li>Validação complexa que depende de múltiplas tabelas e não cabe numa business rule (ex.: impedir aprovação de um pedido se o limite de crédito consolidado do grupo econômico for excedido).</li>\n<li>Cálculo de campo derivado que precisa estar correto no exato momento em que o registro é salvo, sem depender de um job de rollup posterior.</li>\n<li>Enforcement de integridade que precisa valer para <em>toda</em> origem — model-driven app, API, importação de dados, fluxo — porque o plugin roda no nível da plataforma, não da interface.</li>\n</ul>\n<p>O custo é latência: tudo que roda no plugin síncrono soma no tempo de resposta do salvamento. Há limite prático de <strong>2 minutos</strong> por transação de plugin síncrono antes de timeout, e o corpo do código roda em sandbox isolado, sem acesso a arquivos ou rede fora de endpoints permitidos.</p>\n<p><strong>Power Automate: para orquestração, integração e o que pode esperar</strong></p>\n<p>O fluxo do Power Automate brilha quando a lógica é <strong>assíncrona por natureza</strong> e envolve orquestração entre sistemas ou pessoas. Sinais de que a regra deve ser um fluxo, não um plugin:</p>\n<ul>\n<li>Envolve espera humana (aprovações), delays, ou agendamento.</li>\n<li>Integra com serviços externos via conectores prontos (SharePoint, Teams, Outlook, APIs de terceiros) sem que você precise escrever e manter chamadas HTTP em C#.</li>\n<li>É mantida por quem não é desenvolvedor pro-code, e precisa ser legível e ajustável sem deploy de assembly.</li>\n<li>Não precisa participar da transação do registro — se falhar, você trata com retry e notificação, não com rollback do dado original.</li>\n</ul>\n<p>O trade-off é que o fluxo roda <strong>fora da transação</strong> e de forma <strong>eventualmente consistente</strong>: entre o Create do registro e o disparo do gatilho \"When a row is added\" há uma latência que pode ir de segundos a mais, dependendo de throttling e carga. Nunca dependa de um fluxo para garantir invariantes que precisam valer no instante do commit.</p>\n<p><strong>E as business rules e classic workflows?</strong></p>\n<p>Antes de escrever qualquer código, esgote as opções declarativas:</p>\n<ul>\n<li><strong>Business rules</strong> — validações e cálculos simples aplicados na interface e (em parte) no servidor. Ótimas para \"campo X obrigatório quando Y\", mostrar/ocultar campos, valores default. Limitação: não cobrem lógica cross-table complexa e nem toda regra roda em operações via API.</li>\n<li><strong>Classic (background) workflows</strong> — ainda úteis para automações assíncronas simples ligadas a eventos de tabela, mas a Microsoft direciona novos cenários para Power Automate. Evite iniciar projetos novos apoiados neles.</li>\n</ul>\n<p><strong>Um roteiro de decisão prático</strong></p>\n<ol>\n<li>A regra é uma validação/cálculo simples de campo? → <strong>Business rule</strong>.</li>\n<li>Precisa ser atômica, imediata e valer para toda origem (API, import, UI)? → <strong>Plugin síncrono</strong> (pre-operation para alterar o próprio registro, post-operation para efeitos colaterais).</li>\n<li>Pode acontecer logo depois, envolve integração com conectores ou espera humana? → <strong>Power Automate</strong>.</li>\n<li>É processamento pesado, em lote ou de longa duração disparado por evento de dados? → <strong>Plugin assíncrono</strong> ou fluxo, conforme quem vai manter e o que precisa integrar.</li>\n</ol>\n<p>Um erro comum é resolver tudo com Power Automate porque é low-code — e descobrir tarde que uma regra crítica de integridade não rodava quando o dado entrava via importação em massa, porque ninguém garantiu que o gatilho cobria aquela origem. Outro erro é escrever plugin para orquestração de aprovação, prendendo lógica de processo em assembly que exige um desenvolvedor e um deploy para cada ajuste de negócio.</p>\n<p><strong>Governança e ALM não são detalhe</strong></p>\n<p>Seja plugin ou fluxo, a lógica deve viver dentro de uma <strong>solução gerenciada</strong> e passar pelo pipeline Dev/Test/Prod. Plugins exigem step registrations versionados e cuidado com ordem de execução (rank) quando há múltiplos plugins na mesma mensagem. Fluxos exigem connection references e environment variables para não vazar credenciais entre ambientes. Misturar as duas abordagens sem uma convenção clara de \"onde cada tipo de regra vive\" é o que transforma um Dataverse maduro em uma caixa-preta que ninguém consegue mais depurar.</p>\n<p>Estruturar essa camada de lógica de negócio — decidir o que é plugin, o que é fluxo, o que é declarativo — é uma das decisões de arquitetura que mais impactam a manutenibilidade de uma solução Power Platform em escala. Se sua empresa está nesse ponto de maturidade e quer revisar a arquitetura antes que o débito técnico cresça, a consultoria e os planos de suporte da Dynamic Soluções ajudam a colocar essa camada em ordem, com ALM e governança de verdade.</p>\n<p>Every team running Dataverse at scale hits the same architecture question: when should a business rule be a <strong>plugin registered in Dataverse</strong>, when should it be a <strong>Power Automate flow</strong>, and when is a <strong>business rule</strong> or a <strong>classic workflow</strong> enough? The wrong answer shows up months later as half-saved records, latency the user actually feels, or logic that runs outside the transaction and can't be rolled back. This post is a decision guide for those already past the \"works on my environment\" stage.</p>\n<p><strong>The Dataverse event framework is the starting point</strong></p>\n<p>Plugins aren't \"loose code\": they register at specific stages of the Dataverse execution pipeline, and understanding those stages is what separates a solid decision from a gamble.</p>\n<ul>\n<li><strong>Pre-validation (stage 10)</strong> — runs before the database transaction, and in some cases even before security checks. Good for blocking operations early and cheaply, but be careful: it isn't always inside the main transaction.</li>\n<li><strong>Pre-operation (stage 20)</strong> — inside the transaction, before commit. This is where you change values on the record itself before it's written (set a derived field, normalize data) without needing a second Update.</li>\n<li><strong>Post-operation (stage 40)</strong> — inside the transaction, after the logical commit. This is where you create related records, trigger integrations and apply side effects. If you throw an exception here, the rollback undoes everything — including the original record.</li>\n</ul>\n<p>Execution can be <strong>synchronous</strong> (the user waits, everything in the same transaction, automatic rollback on error) or <strong>asynchronous</strong> (queued as a System Job, doesn't block the user, but doesn't take part in the original record's transaction).</p>\n<p><strong>Synchronous plugin: for what must be atomic and immediate</strong></p>\n<p>Use a synchronous plugin when the rule needs two guarantees at once: happening <strong>before the user sees the result</strong> and being <strong>inside the transaction</strong> so a failure undoes the whole operation. Examples:</p>\n<ul>\n<li>Complex validation that spans multiple tables and doesn't fit in a business rule (e.g., blocking approval of an order if the consolidated credit limit of the economic group is exceeded).</li>\n<li>Derived field calculation that must be correct at the exact moment the record is saved, without relying on a later rollup job.</li>\n<li>Integrity enforcement that must apply to <em>every</em> origin — model-driven app, API, data import, flow — because the plugin runs at the platform level, not the UI level.</li>\n</ul>\n<p>The cost is latency: everything running in a synchronous plugin adds to the save response time. There's a practical <strong>2-minute</strong> limit per synchronous plugin transaction before timeout, and the code runs in an isolated sandbox, with no file or network access beyond allowed endpoints.</p>\n<p><strong>Power Automate: for orchestration, integration and what can wait</strong></p>\n<p>A Power Automate flow shines when the logic is <strong>asynchronous by nature</strong> and involves orchestration across systems or people. Signs the rule should be a flow, not a plugin:</p>\n<ul>\n<li>It involves human waiting (approvals), delays, or scheduling.</li>\n<li>It integrates with external services through ready-made connectors (SharePoint, Teams, Outlook, third-party APIs) without you writing and maintaining HTTP calls in C#.</li>\n<li>It's maintained by someone who isn't a pro-code developer and needs to be readable and adjustable without deploying an assembly.</li>\n<li>It doesn't need to take part in the record's transaction — if it fails, you handle it with retry and notification, not with a rollback of the original data.</li>\n</ul>\n<p>The trade-off is that the flow runs <strong>outside the transaction</strong> and is <strong>eventually consistent</strong>: between the record Create and the \"When a row is added\" trigger firing there's a latency that can range from seconds to more, depending on throttling and load. Never rely on a flow to enforce invariants that must hold at the instant of commit.</p>\n<p><strong>What about business rules and classic workflows?</strong></p>\n<p>Before writing any code, exhaust the declarative options:</p>\n<ul>\n<li><strong>Business rules</strong> — simple validations and calculations applied in the UI and (partly) on the server. Great for \"field X required when Y\", show/hide fields, default values. Limitation: they don't cover complex cross-table logic and not every rule runs on API operations.</li>\n<li><strong>Classic (background) workflows</strong> — still useful for simple asynchronous automations tied to table events, but Microsoft steers new scenarios toward Power Automate. Avoid starting new projects built on them.</li>\n</ul>\n<p><strong>A practical decision guide</strong></p>\n<ol>\n<li>Is the rule a simple field validation/calculation? → <strong>Business rule</strong>.</li>\n<li>Must it be atomic, immediate and apply to every origin (API, import, UI)? → <strong>Synchronous plugin</strong> (pre-operation to change the record itself, post-operation for side effects).</li>\n<li>Can it happen shortly after, involving connector integration or human waiting? → <strong>Power Automate</strong>.</li>\n<li>Is it heavy, batch or long-running processing triggered by a data event? → <strong>Asynchronous plugin</strong> or flow, depending on who maintains it and what it needs to integrate with.</li>\n</ol>\n<p>A common mistake is solving everything with Power Automate because it's low-code — and discovering late that a critical integrity rule didn't run when data came in via bulk import, because nobody made sure the trigger covered that origin. Another mistake is writing a plugin for approval orchestration, locking process logic into an assembly that requires a developer and a deploy for every business tweak.</p>\n<p><strong>Governance and ALM aren't a detail</strong></p>\n<p>Whether plugin or flow, the logic must live inside a <strong>managed solution</strong> and go through the Dev/Test/Prod pipeline. Plugins require versioned step registrations and care with execution order (rank) when multiple plugins share the same message. Flows require connection references and environment variables so credentials don't leak between environments. Mixing both approaches without a clear convention of \"where each type of rule lives\" is what turns a mature Dataverse into a black box no one can debug anymore.</p>\n<p>Structuring this business logic layer — deciding what's a plugin, what's a flow, what's declarative — is one of the architecture decisions that most affects the maintainability of a Power Platform solution at scale. If your company is at this maturity point and wants to review the architecture before technical debt grows, Dynamic Soluções' consulting and support plans help put this layer in order, with real ALM and governance.</p>"}},"pageContext":{"slug":"/blog/dataverse-plugins-vs-power-automate-logica-negocio/","previousPost":null,"nextPost":{"frontmatter":{"title":"Copilot Studio vs Copilot padrão: quando customizar de fato"},"fields":{"slug":"/blog/copilot-studio-vs-copilot-m365-quando-customizar/"}}}},"staticQueryHashes":["2269431855"]}