Skip to content

Latest commit

 

History

4 Commits

Folders and files

Repository files navigation

Durable AI Workflow Automation Engine


Table of Contents

  1. Executive Summary
  2. Problem Statement
  3. Why AI Automation Needs Durable Execution
  4. Product Scope
  5. Goals and Non-Goals
  6. Architecture Principles
  7. Functional Requirements
  8. Non-Functional Requirements
  9. C4 Level 1 — System Context
  10. C4 Level 2 — Container Architecture
  11. Control Plane vs Execution Plane
  12. End-to-End Workflow Lifecycle
  13. Workflow State Machine
  14. AI Planning Layer
  15. Plan Representation
  16. Plan Validation
  17. Deterministic Policy Boundary
  18. Workflow Orchestrator
  19. Workflow vs Activity Separation
  20. Determinism Requirements
  21. Activity Architecture
  22. Tool Execution Layer
  23. MCP Tool Plane
  24. Enterprise API Connectors
  25. Human-in-the-Loop
  26. Signals
  27. Queries
  28. Updates / External Commands
  29. Approval Architecture
  30. Exact Action Binding
  31. Separation of Duties
  32. Timers and Waiting
  33. Retry Architecture
  34. Timeout Architecture
  35. Heartbeats
  36. Cancellation
  37. Idempotency
  38. Exactly-Once Illusion
  39. Ambiguous Failure Handling
  40. Compensation and Sagas
  41. Compensation Ordering
  42. Irreversible Actions
  43. Checkpointing
  44. Workflow History
  45. Replay
  46. Workflow Versioning
  47. Worker Versioning
  48. Continue-As-New
  49. Child Workflows
  50. Parent-Child Policies
  51. Search Attributes
  52. Event-Driven Triggers
  53. Scheduled Workflows
  54. Webhook Triggers
  55. Kafka / Event Bus Integration
  56. Data Model
  57. API Design
  58. Event Model
  59. Multi-Tenant Architecture
  60. Authorization
  61. Credential Brokerage
  62. Secret Management
  63. Data Privacy
  64. Threat Model
  65. Prompt Injection
  66. Confused Deputy Prevention
  67. Tool Governance
  68. Rate and Cost Budgets
  69. Reliability Architecture
  70. Dependency Isolation
  71. Circuit Breakers
  72. Bulkheads
  73. Backpressure
  74. Failure-Mode Matrix
  75. Recovery Semantics
  76. Observability
  77. Distributed Tracing
  78. Metrics and Dashboards
  79. SLOs and SLIs
  80. Audit Architecture
  81. Evaluation Architecture
  82. Planner Evaluation
  83. Tool-Trajectory Evaluation
  84. Approval Evaluation
  85. Reliability Evaluation
  86. Security Evaluation
  87. Testing Strategy
  88. Chaos Engineering
  89. Capacity Planning
  90. Latency Modeling
  91. Cost Modeling
  92. Worker Pool Architecture
  93. Kubernetes Deployment
  94. Multi-Region Architecture
  95. Disaster Recovery
  96. CI/CD
  97. Model and Prompt Lifecycle
  98. Tool and Workflow Schema Versioning
  99. Architecture Decision Records
  100. Key Trade-Offs
  101. Production Hardening Roadmap
  102. Operational Runbooks
  103. Principal Engineer Interview Walkthrough
  104. Distinguished-Level Discussion Questions
  105. Resume Positioning
  106. Repository Guide
  107. Local Development
  108. Final Architecture Summary

1. Executive Summary

A naive AI automation system looks like:

user request
 -> LLM creates steps
 -> for loop calls APIs
 -> process crashes
 -> state lost

A production durable AI automation engine looks like:

                        REQUEST / EVENT
                              |
                              v
                       Identity + Policy
                              |
                              v
                         AI Planner
                              |
                       Structured Plan
                              |
                       Plan Validation
                              |
                              v
                    Durable Orchestrator
                              |
       +----------------------+----------------------+
       |                      |                      |
       v                      v                      v
   AI Activity          Tool Activity          Human Approval
       |                      |                      |
       |                      v                      |
       |                Governed Tool Plane          |
       |                      |                      |
       +----------------------+----------------------+
                              |
                    Durable State / History
                              |
                   Retry / Timer / Signal
                              |
                    Verification Activity
                              |
                Compensation if necessary
                              |
                           RESULT

The key insight is that AI reasoning and durable workflow semantics solve different problems.

The model is good at:

  • understanding intent;
  • creating plans;
  • choosing among allowed capabilities;
  • interpreting unstructured results;
  • verifying semantic outcomes.

The workflow engine is responsible for:

  • durable state;
  • timers;
  • retries;
  • signals;
  • cancellation;
  • idempotency;
  • compensation;
  • history;
  • recovery;
  • versioning.

The central architecture principle is:

Use AI for judgment; use deterministic durable infrastructure for execution semantics.


2. Problem Statement

Enterprise automations can last:

milliseconds
minutes
hours
days
weeks

A workflow might:

  1. understand an employee request;
  2. query multiple systems;
  3. create a ticket;
  4. wait three days for approval;
  5. provision access;
  6. verify provisioning;
  7. send a notification;
  8. compensate if a later step fails.

A normal HTTP request/process is not an appropriate durability boundary.

Failures can occur between any two steps:

process crash
network timeout
provider 429
API accepted request but response lost
worker restart
deployment
human approval delay
downstream outage

The workflow must resume safely rather than restart blindly.


3. Why AI Automation Needs Durable Execution

Agent loops typically keep state in:

memory
prompt
local process

That is insufficient for business workflows.

Consider:

Agent calls create_invoice()
server creates invoice
network response is lost
agent retries

Without idempotency/reconciliation:

two invoices

Durable execution does not magically make side effects exactly once.

Instead it provides the machinery to implement:

persisted intent
retries
idempotency
reconciliation
compensation

4. Product Scope

Representative workflows:

  • employee onboarding;
  • IT access requests;
  • customer support escalations;
  • incident remediation;
  • finance approval flows;
  • CRM updates;
  • procurement;
  • compliance review;
  • document processing;
  • scheduled business operations.

The engine supports both:

deterministic workflows

and:

AI-assisted workflows

5. Goals and Non-Goals

Goals

  1. Durable long-running execution.
  2. Structured AI planning.
  3. Governed tool execution.
  4. Human approval.
  5. Safe retries.
  6. Idempotent external mutations.
  7. Compensation.
  8. Workflow versioning.
  9. Multi-tenant isolation.
  10. Full auditability.
  11. Horizontal scalability.
  12. Evaluation of both AI and workflow behavior.

Non-Goals

The engine does not:

  • make external APIs exactly-once;
  • let the model bypass policy;
  • use prompts as the durable state store;
  • expose raw enterprise credentials to the model;
  • automatically compensate irreversible real-world actions;
  • assume every workflow requires AI.

6. Architecture Principles

6.1 Deterministic shell, probabilistic core

Workflow controls:
WHEN and WHETHER execution happens.

AI decides:
WHAT semantic action may best satisfy the goal.

6.2 Side effects belong in activities/tools

Workflow code should not directly perform network calls.

6.3 Every mutation needs a recovery strategy

One of:

idempotency
reconciliation
compensation
manual recovery

6.4 Human approval is durable state

Approval cannot exist only in chat context.

6.5 Policy is external to the model

The LLM may request an action.

It cannot authorize itself.

6.6 History is a source of truth

Execution must be reconstructable.


7. Functional Requirements

ID Requirement
FR-01 Start workflow
FR-02 Generate structured AI plan
FR-03 Validate plan
FR-04 Execute activities
FR-05 Call enterprise tools
FR-06 Retry transient failures
FR-07 Wait on timers
FR-08 Receive human signals
FR-09 Cancel workflows
FR-10 Compensate completed actions
FR-11 Verify outcomes
FR-12 Query workflow status
FR-13 Version workflows
FR-14 Audit decisions/actions
FR-15 Enforce tenant/policy
FR-16 Trigger from events/schedules

8. Non-Functional Requirements

Dimension Requirement
Durability survive process/worker restart
Availability control plane target 99.9%+
Isolation tenant-aware execution
Audit complete side-effect lineage
Scalability horizontal workers
Recovery bounded and explicit
Security credentials outside model
Reproducibility version models/prompts/workflows
Cost per-workflow budgets
Operability searchable state/history

9. C4 Level 1 — System Context

+----------------------+
| User / App / Event   |
+----------+-----------+
           |
           v
+--------------------------------------------------+
| Durable AI Workflow Automation Engine            |
|                                                  |
| Plan -> Execute -> Wait -> Verify -> Compensate  |
+--------+------------------------+----------------+
         |                        |
         v                        v
 Enterprise Systems         Model Providers
 CRM / ITSM / ERP           LLM / Embeddings
         |
         v
 Humans / Approvers

10. C4 Level 2 — Container Architecture

                         API Gateway
                              |
                              v
                        Workflow API
                              |
                              v
                     Temporal-style Engine
                              |
          +-------------------+-------------------+
          |                   |                   |
          v                   v                   v
    Workflow Workers     AI Activities       Tool Activities
          |                   |                   |
          |                   v                   v
          |             Model Provider      Tool Gateway/MCP
          |                                       |
          |                                  Java Tool Plane
          |                                       |
          +----------------------+----------------+
                                 |
                         Enterprise Systems

Supporting:
PostgreSQL
Redis/cache
Artifact store
Policy/Approval service
OTel/Prometheus
Secrets broker

11. Control Plane vs Execution Plane

Control plane

Owns:

workflow definitions
policy
identity
approval
routing
versions
budgets

Execution plane

Owns:

workflow tasks
activities
tool calls
sandboxes/connectors

Separate them so business execution load cannot destabilize administration/configuration.


12. End-to-End Workflow Lifecycle

Request
  |
Authenticate
  |
Create workflow
  |
AI planning activity
  |
Validate structured plan
  |
For each step:
  |
  +-> policy
  |
  +-> approval? ---- yes ----> durable wait
  |                              |
  |                           signal
  |                              |
  +<-----------------------------+
  |
execute activity
  |
verify
  |
next step
  |
failure?
  |
retry / compensate / escalate
  |
complete

13. Workflow State Machine

CREATED
  |
PLANNING
  |
PLAN_VALIDATED
  |
RUNNING
  |
  +--> WAITING_APPROVAL
  |
  +--> WAITING_TIMER
  |
  +--> RETRYING
  |
  +--> COMPENSATING
  |
VERIFYING
  |
COMPLETED

Terminal exceptions:

FAILED
CANCELLED
REJECTED
POLICY_BLOCKED
BUDGET_EXCEEDED
COMPENSATION_FAILED

14. AI Planning Layer

Planner converts:

"Onboard Priya into engineering and request production read access."

into a structured plan:

{
  "goal": "employee onboarding",
  "steps": [
    {
      "type": "tool",
      "tool": "identity.create_account"
    },
    {
      "type": "tool",
      "tool": "github.add_team_member"
    },
    {
      "type": "approval",
      "reason": "production access"
    },
    {
      "type": "tool",
      "tool": "prod_access.request_read_role"
    }
  ]
}

This plan is a proposal, not authorization.


15. Plan Representation

A plan should include:

step id
action type
tool capability
inputs
dependencies
risk
expected result
verification
compensation candidate

Avoid executable arbitrary code as the plan representation.


16. Plan Validation

Validate:

  • schema;
  • allowed tools;
  • dependency DAG;
  • maximum steps;
  • loops;
  • risk;
  • missing approval;
  • unsupported compensation;
  • tenant scope.

Invalid plan is rejected before execution.


17. Deterministic Policy Boundary

Planner
   |
proposes tool call
   |
Policy Engine
   |
ALLOW / DENY / REQUIRE_APPROVAL

Policy inputs:

tenant
principal
workflow
tool
arguments
resource
environment
risk

18. Workflow Orchestrator

The orchestrator controls:

  • state transitions;
  • timers;
  • retries;
  • activity scheduling;
  • signals;
  • compensation stack;
  • cancellation;
  • budgets.

It must remain deterministic under replay.


19. Workflow vs Activity Separation

Workflow code

deterministic coordination

Activity code

network calls
LLM calls
database side effects
enterprise APIs

Example:

workflow:
result = execute_activity("create_ticket")

activity:
POST /tickets

20. Determinism Requirements

Workflow replay expects the same decisions for the same recorded history.

Avoid directly inside workflow code:

random()
current wall clock
HTTP calls
LLM calls
database queries

Use workflow-engine abstractions/activities.


21. Activity Architecture

Activity contract:

input
idempotency context
deadline
heartbeat context
output
typed errors

Activities should classify errors:

transient
permanent
policy
validation
business rejection

22. Tool Execution Layer

Activity Worker
     |
Tool Gateway
     |
schema validation
policy
credential brokerage
rate limit
audit
     |
Enterprise API

The tool gateway centralizes governance.


23. MCP Tool Plane

Representative capabilities:

crm.get_customer
crm.create_ticket
identity.create_user
identity.assign_group
ops.restart_service
finance.create_invoice

Prefer narrow business capabilities over:

execute_sql
run_shell
call_any_url

24. Enterprise API Connectors

Java/Spring side can implement typed connectors for:

CRM
ITSM
ERP
HRIS
Git
Cloud
Messaging

Connector responsibilities:

  • API contract;
  • auth;
  • idempotency;
  • error mapping;
  • observability.

25. Human-in-the-Loop

Human decisions can occur hours/days later.

The workflow must:

persist state
release worker
wait durably
resume after signal

Never keep a process/thread sleeping for approval.


26. Signals

Signals represent asynchronous external events:

approve
reject
cancel
provide_more_information

Signal handling must validate:

identity
workflow
current state
authorization

27. Queries

Queries inspect workflow state without mutating it.

Examples:

current step
pending approval
completed actions
last error

28. Updates / External Commands

Where supported, an update-like operation can:

validate request
mutate workflow state
return a result

Use it when stronger synchronous acknowledgement semantics are needed than a fire-and-forget signal.


29. Approval Architecture

Workflow
  |
ActionRequest
  |
Approval Service
  |
Authorized Human
  |
Approve/Reject
  |
Authenticated signal/update
  |
Workflow resumes

30. Exact Action Binding

Approval binds to:

workflow_id
step_id
tenant
requester
tool
canonical arguments hash
resource
environment
policy version
expiry
nonce

If arguments change, approval is invalid.


31. Separation of Duties

For critical actions:

requester != approver

Potentially require:

2-person approval

Policy determines this, not the LLM.


32. Timers and Waiting

Durable timer:

wait 72 hours

should not consume a worker for 72 hours.

Use cases:

  • approval expiry;
  • follow-up reminder;
  • delayed execution;
  • SLA timeout.

33. Retry Architecture

Retry only appropriate failures.

Example:

network timeout -> retry
429 -> retry with backoff
400 validation -> no retry
403 policy -> no retry
business rejection -> workflow decision

Use exponential backoff + jitter where appropriate.


34. Timeout Architecture

Different timeouts:

schedule-to-start
start-to-close
schedule-to-close
heartbeat
workflow-level deadline

Set according to activity characteristics.


35. Heartbeats

Long-running activity:

process 1M records

periodically heartbeats:

processed offset = 480000

Benefits:

  • liveness detection;
  • cancellation;
  • progress;
  • resume hints.

36. Cancellation

Cancellation propagates:

API
 -> workflow
 -> child workflows
 -> activities

Activities must cooperate.

External side effects already committed may require compensation rather than cancellation.


37. Idempotency

Mutation key:

workflow_id + step_id + attempt-independent operation id

External service should return same logical result for repeated key.

Do not use retry attempt number as the idempotency identity.


38. Exactly-Once Illusion

Distributed side effects cannot generally be guaranteed exactly once merely by a workflow engine.

Correct mental model:

at-least-once execution
+
idempotency
+
reconciliation
=
effectively-once business behavior

39. Ambiguous Failure Handling

Example:

create_ticket()
server commits
response lost

Next attempt:

  1. query by idempotency key;
  2. if found, return existing ticket;
  3. otherwise retry creation.

Never assume timeout means failure.


40. Compensation and Sagas

Workflow:

reserve inventory
charge payment
create shipment

If shipment creation fails:

refund payment
release inventory

Compensation is business logic, not database rollback.


41. Compensation Ordering

Maintain compensation stack:

A completed -> push compensate_A
B completed -> push compensate_B
C fails

run:
compensate_B
compensate_A

Usually reverse order.


42. Irreversible Actions

Some actions cannot be perfectly compensated:

email sent
physical shipment departed
external notification
legal filing

Architecture must represent:

irreversible=true

and require stronger preconditions/approval.


43. Checkpointing

Durable workflow history is the primary checkpoint.

For large external artifacts, persist references:

document id
batch offset
result object URI

Do not place huge payloads in workflow history.


44. Workflow History

History may include:

workflow started
activity scheduled
activity completed
timer fired
signal received
child started
workflow completed

History enables replay and debugging.


45. Replay

On worker restart/deployment:

history
 -> workflow code
 -> reconstruct state

Workflow code changes must preserve replay compatibility.


46. Workflow Versioning

Long-running workflows may span deployments.

Never make incompatible workflow changes casually.

Use:

  • version gates;
  • worker versioning;
  • new workflow type/version;
  • migration strategy.

47. Worker Versioning

Route workflows to compatible workers.

Example:

workflow started with v1
 -> v1-compatible worker

new workflows
 -> v2

This enables gradual deployment.


48. Continue-As-New

Long histories grow expensive.

Pattern:

workflow runs 10k iterations
 -> Continue-As-New
 -> new history with carried state

Useful for:

  • perpetual monitors;
  • polling;
  • long batch workflows.

49. Child Workflows

Large process:

EmployeeOnboarding
 |
 +-- AccountProvisioning
 +-- DeviceProvisioning
 +-- AccessProvisioning

Child workflows provide independent lifecycle and visibility.


50. Parent-Child Policies

Define behavior if parent:

completes
fails
cancels
terminates

Do not leave child lifecycle implicit.


51. Search Attributes

Index operational metadata:

tenant
workflow type
business key
risk
status
approver

Supports operational search without scanning full history.

Do not put secrets in searchable metadata.


52. Event-Driven Triggers

Kafka/Event Bus
    |
Trigger Service
    |
deduplication
    |
Start workflow

Use stable event ID as workflow/idempotency identity.


53. Scheduled Workflows

Examples:

daily reconciliation
monthly billing
weekly compliance report

Schedule layer starts durable workflow instances.

Handle overlapping runs explicitly.


54. Webhook Triggers

Webhook path:

verify signature
deduplicate event
authorize source
normalize payload
start/signal workflow

Never trust webhook payload solely because endpoint is obscure.


55. Kafka / Event Bus Integration

For event-driven scale:

Producer
 -> Kafka
 -> Trigger Consumer
 -> Workflow Start

Persist/derive:

event id
partition
offset
business key

Deduplicate before side effects.


56. Data Model

Core entities:

WorkflowDefinition
WorkflowRun
Plan
PlanStep
ActivityRun
ToolInvocation
ApprovalRequest
CompensationRecord
Artifact
AuditEvent
PromptVersion
PolicyVersion
EvaluationRun

57. API Design

Representative:

POST /v1/workflows
GET  /v1/workflows/{id}
POST /v1/workflows/{id}/cancel
POST /v1/workflows/{id}/signals
POST /v1/approvals/{id}/decision
GET  /v1/workflows/{id}/history

Start request:

{
  "workflow_type": "employee_onboarding",
  "input": {
    "employee_id": "emp-42"
  }
}

58. Event Model

Business/platform events:

WorkflowStarted
PlanCreated
PlanValidated
StepStarted
ToolExecuted
ApprovalRequested
ApprovalGranted
StepCompleted
CompensationStarted
WorkflowCompleted
WorkflowFailed

59. Multi-Tenant Architecture

Tenant isolation applies to:

workflow namespace
data
search
tools
credentials
approvals
rate limits
audit

Large/regulatory tenants may use dedicated namespaces/clusters.


60. Authorization

Authorization checks:

start workflow
read workflow
signal workflow
approve action
cancel workflow
administer definition

Never derive tenant from model-generated arguments.


61. Credential Brokerage

Activity
  |
Tool Gateway
  |
Policy
  |
Credential Broker
  |
short-lived service credential
  |
Enterprise System

Credential remains outside model context and workflow history.


62. Secret Management

Use:

  • secret manager;
  • workload identity;
  • short TTL;
  • scoped credentials;
  • log redaction.

Avoid static credentials in environment where possible.


63. Data Privacy

Classify workflow payloads.

Do not automatically send all workflow history to the LLM.

Construct minimum necessary AI context.

Trace payloads may require:

redaction
hashing
sampling
zero-data-retention provider settings

64. Threat Model

Threat Example Control
Prompt injection ticket asks model to bypass approval deterministic policy
Confused deputy agent acts on another tenant trusted identity context
Approval replay reuse approval exact binding + one-use
Credential leak secret in prompt broker outside model
Duplicate mutation retry creates twice idempotency/reconciliation
SSRF arbitrary URL tool typed tools/egress policy
Tool poisoning malicious connector registry/trust controls
Runaway loop agent repeats budgets
Cross-tenant signal wrong workflow authorization
History leakage sensitive payload minimization/redaction

65. Prompt Injection

Untrusted content:

email
ticket
document
tool output
webhook text

can contain instructions.

The model must treat these as data.

But real enforcement comes from:

tool allowlist
policy
approval
credentials
network boundaries

66. Confused Deputy Prevention

Trusted context:

caller identity
tenant
roles
resource ownership

must be attached by infrastructure.

The model cannot claim:

tenant=other_customer

to gain authority.


67. Tool Governance

Registry metadata:

tool
version
owner
risk
mutation
required scopes
approval policy
idempotency support
timeout
compensation

Unknown/unregistered tools are denied.


68. Rate and Cost Budgets

Per workflow:

max model calls
max tokens
max tool calls
max retries
max wall time
max cost

Budget breach becomes explicit workflow state.


69. Reliability Architecture

Dependencies:

workflow service
database
queue
model provider
tool gateway
enterprise APIs
approval service
secrets

Each dependency needs timeout, retry and failure semantics.


70. Dependency Isolation

One slow connector must not consume all activity workers.

Use:

separate task queues
worker pools
concurrency limits

71. Circuit Breakers

At connector/gateway layer:

closed
 -> failures
 -> open
 -> cooldown
 -> half-open

Workflow history should record business-relevant failure without exploding with low-level noise.


72. Bulkheads

Queues:

AI activities
CRM
finance
ops
long batch
critical workflow

Independent pools reduce blast radius.


73. Backpressure

Controls:

queue depth
tenant quota
connector concurrency
rate limit
worker autoscaling
admission control

Do not start unlimited workflows when downstream systems are saturated.


74. Failure-Mode Matrix

Failure Safe behavior
AI planner timeout retry/fallback
invalid plan reject/replan
worker crash replay/reschedule
activity timeout retry per policy
mutation response lost reconcile
approval timeout expire/escalate
policy unavailable fail closed
secret unavailable wait/fail
downstream 429 backoff
downstream permanent 4xx no retry
compensation fails explicit manual-recovery state
history too large Continue-As-New
incompatible deployment worker/version routing

75. Recovery Semantics

Every step declares:

retryable?
idempotent?
reconcilable?
compensatable?
irreversible?
manual recovery?

This should be visible in architecture/tool metadata.


76. Observability

Trace:

workflow.run
 |
 +-- ai.plan
 +-- plan.validate
 +-- step.1
 |    +-- policy.evaluate
 |    +-- tool.execute
 |    `-- verify
 +-- approval.wait
 +-- step.2
 `-- workflow.complete

77. Distributed Tracing

Attributes:

workflow.id
workflow.type
tenant.ref
step.id
activity.type
tool.name
tool.version
policy.version
model
prompt.version
retry.attempt
approval.required
compensation

Avoid secrets/raw sensitive inputs.


78. Metrics and Dashboards

Workflow

  • started/completed/failed;
  • duration;
  • waiting approvals;
  • cancellations;
  • compensations.

Activities

  • latency;
  • retries;
  • timeouts;
  • heartbeat failures.

AI

  • model calls;
  • tokens;
  • invalid plans;
  • replans;
  • cost.

Tools

  • calls;
  • failures;
  • 429s;
  • idempotency reconciliations.

79. SLOs and SLIs

Example:

SLI Target
Workflow start availability 99.9%
Durable state loss 0
Unauthorized action 0
Duplicate business mutation near-zero / invariant-driven
Audit coverage for mutations 100%
Approval integrity 100%
Activity dispatch latency workload-specific
Recovery after worker failure bounded

80. Audit Architecture

Audit semantic events:

who requested
what workflow
AI plan version
policy decision
approval
tool action
business result
compensation
final state

Workflow engine history is operational execution history.

Compliance audit may require a separate immutable representation.


81. Evaluation Architecture

Versioned Workflow Scenarios
      |
candidate model/prompt/workflow
      |
simulated tools
      |
trajectory capture
      |
graders
      |
regression gate

82. Planner Evaluation

Measure:

  • valid schema;
  • correct tools;
  • correct dependencies;
  • missing steps;
  • unnecessary steps;
  • risk classification;
  • approval placement.

83. Tool-Trajectory Evaluation

Expected:

lookup_customer
 -> create_ticket
 -> request_approval
 -> grant_access

Evaluate sequence, arguments, and forbidden calls.

Final answer quality alone is insufficient.


84. Approval Evaluation

Adversarial tests:

  • changed args after approval;
  • expired approval;
  • wrong tenant;
  • wrong approver;
  • replay;
  • requester self-approval when prohibited.

Expected: deny.


85. Reliability Evaluation

Inject:

worker crash
activity timeout
lost response
duplicate event
late signal
downstream 429
compensation failure

Verify correct recovery semantics.


86. Security Evaluation

Test:

  • prompt injection;
  • cross-tenant action;
  • secret exfiltration;
  • SSRF;
  • unauthorized tool;
  • approval bypass;
  • runaway loop.

87. Testing Strategy

unit
 -> workflow replay
 -> activity contract
 -> connector integration
 -> end-to-end
 -> adversarial
 -> load
 -> chaos

Replay tests are especially important for workflow code changes.


88. Chaos Engineering

Kill:

  • workers;
  • activity processes;
  • connector service;
  • Redis;
  • model provider route.

Inject:

  • latency;
  • 429;
  • duplicate events;
  • ambiguous responses.

Verify no unauthorized/duplicate side effects.


89. Capacity Planning

Assume:

1,000,000 workflow starts/day
average 8 activities

Activity schedules/day:

8,000,000

Average:

~92.6 activities/s

At 10x peak:

~926 activities/s

But long-running workflows primarily consume persisted state, not active workers while waiting.


90. Latency Modeling

Workflow wall time:

T =
planning
+ sum(activity latency)
+ approval waits
+ timers
+ retries
+ verification

User-perceived latency and business completion time are different SLIs.


91. Cost Modeling

Per workflow:

C =
model planning
+ model verification
+ tool/API cost
+ worker compute
+ persistence/history
+ observability

Human wait time affects duration but not necessarily compute cost.


92. Worker Pool Architecture

workflow workers
AI activity workers
CRM activity workers
finance workers
ops workers
batch workers

Autoscale by task queue depth and latency.


93. Kubernetes Deployment

                   API Gateway
                        |
                  Workflow API
                        |
               Durable Workflow Cluster
                 /       |       \
                /        |        \
       Workflow W.   AI Workers  Tool Workers
                        |           |
                   Model APIs   Tool Gateway
                                    |
                              Enterprise APIs

Policy Service
Approval Service
Secrets Broker
PostgreSQL
Redis
OTel Collector
Prometheus

94. Multi-Region Architecture

Options:

Region-local workflow ownership

tenant -> home region

Benefits:

  • residency;
  • simpler consistency.

Active/standby

Fail over workflow control plane according to platform support and recovery strategy.

Do not casually run the same logical workflow actively in two regions without fencing/idempotency.


95. Disaster Recovery

Define RPO/RTO for:

workflow history
definitions
policy
audit
approvals
artifacts

External system state must be reconciled after recovery.


96. CI/CD

PR
 |
unit tests
 |
workflow replay tests
 |
activity/connector tests
 |
AI evals
 |
security tests
 |
container/SBOM
 |
staging
 |
canary workers
 |
production

Workflow compatibility is a deployment gate.


97. Model and Prompt Lifecycle

Version:

planner model
planner prompt
verifier model
verifier prompt
structured schemas

Store versions in workflow metadata/audit.

Model upgrade:

offline eval
 -> shadow
 -> canary
 -> production

98. Tool and Workflow Schema Versioning

Tool:

crm.create_ticket.v1
crm.create_ticket.v2

Avoid silently changing semantics beneath running workflows.

Workflow definitions also need compatibility strategy.


99. Architecture Decision Records

ADR-001 — Durable orchestration

Long-running enterprise automation cannot depend on process memory.

ADR-002 — AI calls are activities

LLM calls are nondeterministic external operations.

ADR-003 — Policy outside model

Authorization must remain deterministic.

ADR-004 — Exact approval binding

Approval must apply to a specific action, not a vague workflow.

ADR-005 — Idempotency + reconciliation

Timeout does not prove side-effect failure.

ADR-006 — Compensation over rollback

Distributed enterprise systems do not share one transaction.

ADR-007 — Continue-As-New for perpetual workflows

Bound history growth.


100. Key Trade-Offs

AI planner vs static workflow

AI:

  • flexible intent understanding.
  • nondeterminism/cost.

Static:

  • predictable.
  • less flexible.

Hybrid is often best.

Fine-grained activities

  • precise retries/visibility.
  • history/complexity.

Coarse activities

  • simple.
  • poor recovery granularity.

Central tool gateway

  • governance.
  • extra hop/control-plane dependency.

Compensation

  • automated recovery.
  • complex business semantics.

101. Production Hardening Roadmap

Phase 1

  • basic durable workflows;
  • AI planner;
  • Java tool API;
  • retries.

Phase 2

  • idempotency;
  • signals;
  • human approval;
  • typed errors.

Phase 3

  • policy gateway;
  • exact approval binding;
  • secrets broker;
  • audit.

Phase 4

  • compensation;
  • heartbeats;
  • cancellation;
  • child workflows.

Phase 5

  • worker versioning;
  • Continue-As-New;
  • event/Kafka triggers;
  • multi-tenant quotas.

Phase 6

  • multi-region;
  • chaos;
  • full evaluation platform;
  • enterprise governance.

102. Operational Runbooks

Workflow stuck waiting approval

  1. inspect approval state;
  2. verify approver routing;
  3. inspect expiry;
  4. do not manually skip policy;
  5. signal only through authenticated path.

Duplicate mutation suspected

  1. stop retries;
  2. query external system using idempotency/business key;
  3. reconcile workflow state;
  4. compensate duplicate if safe;
  5. audit incident.

Bad workflow deployment

  1. route old histories to compatible worker;
  2. stop new rollout;
  3. run replay tests;
  4. roll back.

Compensation failure

  1. mark manual recovery;
  2. preserve completed/compensated step list;
  3. alert operator;
  4. avoid repeatedly applying unsafe compensation.

  1. What does durable execution actually guarantee?
  2. Why is exactly-once side effect execution generally an illusion?
  3. How do you reconcile an ambiguous API timeout?
  4. How should idempotency keys be generated?
  5. When should compensation be automatic?
  6. How do you model irreversible actions?
  7. How do you safely wait a month for approval?
  8. What belongs in workflow history?
  9. When should you Continue-As-New?
  10. How do you version a year-long workflow?
  11. How do you deploy incompatible worker code?
  12. How do child workflow cancellation policies work?
  13. When should AI planning happen once vs incrementally?
  14. How do you prevent prompt injection from authorizing tools?
  15. How do you keep credentials out of LLM context?
  16. How do you evaluate an agent trajectory?
  17. How do you handle duplicate Kafka events?
  18. How do you prevent two regions from executing the same action?
  19. How do you implement separation of duties?
  20. What happens when compensation itself fails?
  21. How do you define SLOs for workflows waiting on humans?
  22. How do you isolate noisy tenants?
  23. How do you search millions of active workflows?
  24. What should happen if the policy service is unavailable?
  25. When should a workflow be deterministic with no AI at all?

105. Portfolio Positioning

Durable AI Workflow Automation Engine — Architected a multi-tenant automation control plane separating probabilistic AI planning from deterministic durable execution. Designed Temporal-style workflow/activity boundaries, structured plans, governed MCP/API tools, authenticated signals and exact action approvals, retry/timeout/heartbeat semantics, idempotency and ambiguous-write reconciliation, Saga compensation, child workflows, Continue-As-New, worker versioning, event/Kafka triggers, credential brokerage, observability, adversarial evaluation, capacity controls and multi-region evolution across Python and Java services.


106. Repository Guide

durable-ai-workflow-automation-engine/
|
+-- python-orchestrator/
|   +-- app/
|   |   +-- activities.py
|   |   +-- config.py
|   |   +-- main.py
|   |   +-- schemas.py
|   |   +-- worker.py
|   |   `-- workflows.py
|   +-- tests/
|   +-- Dockerfile
|   `-- requirements.txt
|
+-- java-tools/
|   +-- src/main/
|   +-- src/test/
|   +-- Dockerfile
|   `-- pom.xml
|
+-- docs/
+-- evals/
+-- infra/
+-- docker-compose.yml
+-- Makefile
`-- README.md

107. Local Development

Typical:

cp .env.example .env
docker compose up --build

Start workflow:

curl -X POST localhost:8000/v1/workflows \
  -H 'Content-Type: application/json' \
  -d '{
    "workflow_type":"support_escalation",
    "input":{
      "customer_id":"cust-42",
      "issue":"Production outage"
    }
  }'

Run tests:

make python-test
make java-test

A local demo approval endpoint is not a production authorization system. Production must authenticate users, bind approvals to exact actions and keep tool credentials outside model context.


108. Final Architecture Summary

A production Durable AI Workflow Automation Engine should obey:

1. AI REASONS; WORKFLOW INFRASTRUCTURE EXECUTES DURABLY.
2. NONDETERMINISTIC OPERATIONS BELONG IN ACTIVITIES.
3. POLICY, IDENTITY AND APPROVAL ARE OUTSIDE THE MODEL.
4. HUMAN WAITING IS DURABLE STATE, NOT A SLEEPING PROCESS.
5. RETRIES REQUIRE ERROR CLASSIFICATION.
6. MUTATIONS REQUIRE IDEMPOTENCY AND RECONCILIATION.
7. TIMEOUT DOES NOT MEAN THE SIDE EFFECT FAILED.
8. DISTRIBUTED ROLLBACK IS BUSINESS COMPENSATION.
9. IRREVERSIBLE ACTIONS REQUIRE STRONGER PRECONDITIONS.
10. LONG HISTORIES REQUIRE VERSIONING AND CONTINUE-AS-NEW.
11. RUNNING WORKFLOWS MUST SURVIVE SOFTWARE DEPLOYMENTS.
12. EVALUATE PLANS, TRAJECTORIES, SECURITY AND RECOVERY — NOT ONLY FINAL TEXT.

The defining principle is:

Use AI for judgment; use deterministic durable infrastructure for execution semantics.

Microsoft / Azure engineering — repository-specific visual gallery

Azure durable workflow semantics for autonomous agents. Reuse documented durable execution, workflow/task state, leases, retries, checkpoints, approval and compensation design. Evaluate Azure Durable Functions as a separate orchestration adapter rather than claim compatibility.

Independent proposed adaptations; no claim of live Microsoft integration, internal architecture, certification or measured results.

01. Durable workflow control plane

Durable-AI-Workflow-Automation-Engine: Durable workflow control plane

Concept and step-by-step workflow: Separate probabilistic task planning from deterministic durable state. Persist workflow version before dispatch, commit typed result, then advance dependency state.

Diagram reading guide: Workflow request → Persist definition and run; Persist definition and run → Schedule task; Schedule task → Commit result; Commit result → Advance workflow. Arrows describe proposed processing/dependencies, with branching semantics explained above.

How to adapt the current repository: Use existing workflow/run/task contracts as source of truth; compare proposed Durable Functions or AKS worker implementation without duplicating orchestration authority.

Expected outputs, failure handling and validation: Crash after scheduling or result commit must not skip or repeat committed effect.

02. Long-running approval state

Durable-AI-Workflow-Automation-Engine: Long-running approval state

Concept and step-by-step workflow: Persist exact proposal and deadline, wait without holding worker, validate reviewer decision and current authority, resume only approved unchanged action.

Diagram reading guide: Task proposal → Bind exact digest; Bind exact digest → Persist waiting state; Persist waiting state → Human decision event; Human decision event → Resume or cancel. Arrows describe proposed processing/dependencies, with branching semantics explained above.

How to adapt the current repository: Reuse documented approval and checkpoint contracts; map external events to a durable orchestration adapter only with replay-safe handling.

Expected outputs, failure handling and validation: Test late decision, cancellation and restart; stale decision denied.

03. Worker lease and fencing

Durable-AI-Workflow-Automation-Engine: Worker lease and fencing

Concept and step-by-step workflow: Claim task under lease, pass fencing token to commit boundary and reject stale worker completion after lease transfer. External effects require separate idempotency.

Diagram reading guide: Ready task → Lease acquisition; Lease acquisition → Fencing token; Fencing token → Worker attempt; Worker attempt → Conditional commit. Arrows describe proposed processing/dependencies, with branching semantics explained above.

How to adapt the current repository: Reuse documented worker coordination and task state; evaluate Azure SQL/PostgreSQL lease implementation or Service Bus worker adapter under explicit semantics.

Expected outputs, failure handling and validation: Test expired lease and concurrent workers; only current owner may commit result.

04. Compensation decision workflow

Durable-AI-Workflow-Automation-Engine: Compensation decision workflow

Concept and step-by-step workflow: Identify actual committed effects, select supported compensation, validate current state and permission, approve and verify. Compensation is new effect, not rollback of time.

Diagram reading guide: Failed dependent step → Inspect committed effects; Inspect committed effects → Propose compensation; Propose compensation → Independent approval; Independent approval → Verify result. Arrows describe proposed processing/dependencies, with branching semantics explained above.

How to adapt the current repository: Reuse documented Saga/compensation design; add Microsoft connector-specific inverse operations only where supported and safe.

Expected outputs, failure handling and validation: Do not compensate unknown effect automatically; test partial completion and rejected compensation.

05. Queue backpressure and retry budget

Durable-AI-Workflow-Automation-Engine: Queue backpressure and retry budget

Concept and step-by-step workflow: Bound queue and concurrency, allocate deadline/retry budget, defer or reject excess work and classify safe retry versus uncertain effect.

Diagram reading guide: Queued runs → Admission limit; Admission limit → Worker capacity; Worker capacity → Deadline-aware retry; Deadline-aware retry → Terminal or delayed. Arrows describe proposed processing/dependencies, with branching semantics explained above.

How to adapt the current repository: Use existing scheduling/reliability design; evaluate Azure Service Bus queue integration with stable message/task IDs and dead-letter policy.

Expected outputs, failure handling and validation: Test overload, duplicate delivery and retry exhaustion; no claimed queue exactly-once guarantee.

06. Durability fault-injection plan

Durable-AI-Workflow-Automation-Engine: Durability fault-injection plan

Concept and step-by-step workflow: Inject faults at durable state and external effect boundaries, verify resume, idempotency and audit. Compare current scaffold and proposed hosting separately.

Diagram reading guide: Synthetic workflow → Crash before commit; Synthetic workflow → Crash after effect; Synthetic workflow → Approval interruption; Crash before commit → Invariant report; Crash after effect → Invariant report; Approval interruption → Invariant report. Arrows describe proposed processing/dependencies, with branching semantics explained above.

How to adapt the current repository: Extend repository's documented test plan with fake Microsoft provider and local fault injection, then staging deployment tests.

Expected outputs, failure handling and validation: No production Azure SLA claim; require durable state/effect invariants on tested fixtures.

References: Azure architecture center · Microsoft Graph · Foundry Agent Service.

Netflix engineering — repository-specific visual gallery

Durable media processing and editorial workflows. Reuse documented workflow/activity separation, deterministic orchestration, approvals, signals, retries, compensation and MCP action plane. Separate probabilistic planning from media-job state.

Independent proposed adaptations inspired by public engineering writing; no private Netflix access, deployed integration, certification or measured results. Examples use fictional or appropriately licensed data.

01. Media workflow compilation and execution

Durable-AI-Workflow-Automation-Engine: Media workflow compilation and execution

Concept and step-by-step architecture: Validate asset version and typed dependencies before dispatch. Schedule activities independently of model reasoning and advance only from durable outcomes.

Diagram reading guide: Asset manifest → Validated workflow definition; Validated workflow definition → Schedule typed activities; Schedule typed activities → Commit activity outcomes; Commit activity outcomes → Delivery state. Arrows represent proposed processing dependencies; conditions and joins follow the workflow above.

How to adapt the current repository: Reuse documented workflow/activity and plan validation architecture; add media processing task types and artifact references, implement missing adapters separately.

Expected outputs, failure handling and validation: Crash after dispatch must not imply completion; test durable replay.

02. Parallel encoding job barrier

Durable-AI-Workflow-Automation-Engine: Parallel encoding job barrier

Concept and step-by-step architecture: Dispatch independent activities on pinned master, wait for required outputs and verify codecs, time alignment and manifest before packaging.

Diagram reading guide: Master digest → Video rendition activity; Master digest → Audio activity; Master digest → Subtitle activity; Video rendition activity → Package validation; Audio activity → Package validation; Subtitle activity → Package validation. Arrows represent proposed processing dependencies; conditions and joins follow the workflow above.

How to adapt the current repository: Extend activity schema with rendition, audio and subtitle contracts; retain existing join semantics and provider-neutral tool plane.

Expected outputs, failure handling and validation: Missing rendition blocks package; no actual encoder or Netflix pipeline assumed.

03. Editorial approval as durable signal

Durable-AI-Workflow-Automation-Engine: Editorial approval as durable signal

Concept and step-by-step architecture: Persist approval state without occupying worker, validate reviewer and unchanged manifest upon signal, then resume only eligible activity.

Diagram reading guide: Reviewable package → Exact manifest digest; Exact manifest digest → Persist waiting state; Persist waiting state → Reviewer signal; Reviewer signal → Resume or reject. Arrows represent proposed processing dependencies; conditions and joins follow the workflow above.

How to adapt the current repository: Reuse documented HITL signals and checkpoint design; add media version, approval expiry and source rights recheck.

Expected outputs, failure handling and validation: Late approval and changed package denied; no duplicate release.

04. Media job lease and backpressure

Durable-AI-Workflow-Automation-Engine: Media job lease and backpressure

Concept and step-by-step architecture: Limit concurrent resource-heavy jobs, claim task with lease, enforce deadline and classify transient failure versus uncertain external effect.

Diagram reading guide: Queued asset tasks → Admission budget; Admission budget → Worker lease; Worker lease → Bounded execution; Bounded execution → Commit or retry. Arrows represent proposed processing dependencies; conditions and joins follow the workflow above.

How to adapt the current repository: Reuse documented retries and task coordination; add resource-class quotas and fenced result commit if not already present.

Expected outputs, failure handling and validation: Test overload and worker expiry; no unbounded retry or measured capacity claim.

05. Failed package compensation

Durable-AI-Workflow-Automation-Engine: Failed package compensation

Concept and step-by-step architecture: Inspect actual artifact state, identify unreferenced or invalid derived objects, request separate cleanup approval and verify outcome. Do not delete original masters.

Diagram reading guide: Failed validation → Inspect committed artifacts; Inspect committed artifacts → Propose cleanup; Propose cleanup → Authorize cleanup; Authorize cleanup → Verify disposition. Arrows represent proposed processing dependencies; conditions and joins follow the workflow above.

How to adapt the current repository: Reuse compensation contracts and action policy; add safe derivative-only cleanup tools for a test environment.

Expected outputs, failure handling and validation: Unknown reference status blocks cleanup; no automatic deletion of user media.

06. Media workflow fault regression

Durable-AI-Workflow-Automation-Engine: Media workflow fault regression

Concept and step-by-step architecture: Replay synthetic assets and injected failures, inspect task state, artifact digest and side-effect ledger across restarts.

Diagram reading guide: Synthetic manifest → Crash at activity boundary; Synthetic manifest → Approval interruption; Synthetic manifest → Duplicate completion; Crash at activity boundary → Durability report; Approval interruption → Durability report; Duplicate completion → Durability report. Arrows represent proposed processing dependencies; conditions and joins follow the workflow above.

How to adapt the current repository: Extend documented test plan with mocked encoding and storage tools, deterministic signals and dependency fixtures.

Expected outputs, failure handling and validation: No actual Netflix deployment, throughput or recovery SLA.

Public inspiration: Netflix Technology Blog. The diagrams are independent application proposals, not a reproduction of Netflix's architecture.