- Executive Summary
- Problem Statement
- Why AI Automation Needs Durable Execution
- Product Scope
- Goals and Non-Goals
- Architecture Principles
- Functional Requirements
- Non-Functional Requirements
- C4 Level 1 — System Context
- C4 Level 2 — Container Architecture
- Control Plane vs Execution Plane
- End-to-End Workflow Lifecycle
- Workflow State Machine
- AI Planning Layer
- Plan Representation
- Plan Validation
- Deterministic Policy Boundary
- Workflow Orchestrator
- Workflow vs Activity Separation
- Determinism Requirements
- Activity Architecture
- Tool Execution Layer
- MCP Tool Plane
- Enterprise API Connectors
- Human-in-the-Loop
- Signals
- Queries
- Updates / External Commands
- Approval Architecture
- Exact Action Binding
- Separation of Duties
- Timers and Waiting
- Retry Architecture
- Timeout Architecture
- Heartbeats
- Cancellation
- Idempotency
- Exactly-Once Illusion
- Ambiguous Failure Handling
- Compensation and Sagas
- Compensation Ordering
- Irreversible Actions
- Checkpointing
- Workflow History
- Replay
- Workflow Versioning
- Worker Versioning
- Continue-As-New
- Child Workflows
- Parent-Child Policies
- Search Attributes
- Event-Driven Triggers
- Scheduled Workflows
- Webhook Triggers
- Kafka / Event Bus Integration
- Data Model
- API Design
- Event Model
- Multi-Tenant Architecture
- Authorization
- Credential Brokerage
- Secret Management
- Data Privacy
- Threat Model
- Prompt Injection
- Confused Deputy Prevention
- Tool Governance
- Rate and Cost Budgets
- Reliability Architecture
- Dependency Isolation
- Circuit Breakers
- Bulkheads
- Backpressure
- Failure-Mode Matrix
- Recovery Semantics
- Observability
- Distributed Tracing
- Metrics and Dashboards
- SLOs and SLIs
- Audit Architecture
- Evaluation Architecture
- Planner Evaluation
- Tool-Trajectory Evaluation
- Approval Evaluation
- Reliability Evaluation
- Security Evaluation
- Testing Strategy
- Chaos Engineering
- Capacity Planning
- Latency Modeling
- Cost Modeling
- Worker Pool Architecture
- Kubernetes Deployment
- Multi-Region Architecture
- Disaster Recovery
- CI/CD
- Model and Prompt Lifecycle
- Tool and Workflow Schema Versioning
- Architecture Decision Records
- Key Trade-Offs
- Production Hardening Roadmap
- Operational Runbooks
- Principal Engineer Interview Walkthrough
- Distinguished-Level Discussion Questions
- Resume Positioning
- Repository Guide
- Local Development
- Final Architecture 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.
Enterprise automations can last:
milliseconds
minutes
hours
days
weeks
A workflow might:
- understand an employee request;
- query multiple systems;
- create a ticket;
- wait three days for approval;
- provision access;
- verify provisioning;
- send a notification;
- 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.
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
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
- Durable long-running execution.
- Structured AI planning.
- Governed tool execution.
- Human approval.
- Safe retries.
- Idempotent external mutations.
- Compensation.
- Workflow versioning.
- Multi-tenant isolation.
- Full auditability.
- Horizontal scalability.
- Evaluation of both AI and workflow behavior.
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.
Workflow controls:
WHEN and WHETHER execution happens.
AI decides:
WHAT semantic action may best satisfy the goal.
Workflow code should not directly perform network calls.
One of:
idempotency
reconciliation
compensation
manual recovery
Approval cannot exist only in chat context.
The LLM may request an action.
It cannot authorize itself.
Execution must be reconstructable.
| 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 |
| 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 |
+----------------------+
| 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
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
Owns:
workflow definitions
policy
identity
approval
routing
versions
budgets
Owns:
workflow tasks
activities
tool calls
sandboxes/connectors
Separate them so business execution load cannot destabilize administration/configuration.
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
CREATED
|
PLANNING
|
PLAN_VALIDATED
|
RUNNING
|
+--> WAITING_APPROVAL
|
+--> WAITING_TIMER
|
+--> RETRYING
|
+--> COMPENSATING
|
VERIFYING
|
COMPLETED
Terminal exceptions:
FAILED
CANCELLED
REJECTED
POLICY_BLOCKED
BUDGET_EXCEEDED
COMPENSATION_FAILED
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.
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.
Validate:
- schema;
- allowed tools;
- dependency DAG;
- maximum steps;
- loops;
- risk;
- missing approval;
- unsupported compensation;
- tenant scope.
Invalid plan is rejected before execution.
Planner
|
proposes tool call
|
Policy Engine
|
ALLOW / DENY / REQUIRE_APPROVAL
Policy inputs:
tenant
principal
workflow
tool
arguments
resource
environment
risk
The orchestrator controls:
- state transitions;
- timers;
- retries;
- activity scheduling;
- signals;
- compensation stack;
- cancellation;
- budgets.
It must remain deterministic under replay.
deterministic coordination
network calls
LLM calls
database side effects
enterprise APIs
Example:
workflow:
result = execute_activity("create_ticket")
activity:
POST /tickets
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.
Activity contract:
input
idempotency context
deadline
heartbeat context
output
typed errors
Activities should classify errors:
transient
permanent
policy
validation
business rejection
Activity Worker
|
Tool Gateway
|
schema validation
policy
credential brokerage
rate limit
audit
|
Enterprise API
The tool gateway centralizes governance.
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
Java/Spring side can implement typed connectors for:
CRM
ITSM
ERP
HRIS
Git
Cloud
Messaging
Connector responsibilities:
- API contract;
- auth;
- idempotency;
- error mapping;
- observability.
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.
Signals represent asynchronous external events:
approve
reject
cancel
provide_more_information
Signal handling must validate:
identity
workflow
current state
authorization
Queries inspect workflow state without mutating it.
Examples:
current step
pending approval
completed actions
last error
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.
Workflow
|
ActionRequest
|
Approval Service
|
Authorized Human
|
Approve/Reject
|
Authenticated signal/update
|
Workflow resumes
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.
For critical actions:
requester != approver
Potentially require:
2-person approval
Policy determines this, not the LLM.
Durable timer:
wait 72 hours
should not consume a worker for 72 hours.
Use cases:
- approval expiry;
- follow-up reminder;
- delayed execution;
- SLA timeout.
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.
Different timeouts:
schedule-to-start
start-to-close
schedule-to-close
heartbeat
workflow-level deadline
Set according to activity characteristics.
Long-running activity:
process 1M records
periodically heartbeats:
processed offset = 480000
Benefits:
- liveness detection;
- cancellation;
- progress;
- resume hints.
Cancellation propagates:
API
-> workflow
-> child workflows
-> activities
Activities must cooperate.
External side effects already committed may require compensation rather than cancellation.
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.
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
Example:
create_ticket()
server commits
response lost
Next attempt:
- query by idempotency key;
- if found, return existing ticket;
- otherwise retry creation.
Never assume timeout means failure.
Workflow:
reserve inventory
charge payment
create shipment
If shipment creation fails:
refund payment
release inventory
Compensation is business logic, not database rollback.
Maintain compensation stack:
A completed -> push compensate_A
B completed -> push compensate_B
C fails
run:
compensate_B
compensate_A
Usually reverse order.
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.
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.
History may include:
workflow started
activity scheduled
activity completed
timer fired
signal received
child started
workflow completed
History enables replay and debugging.
On worker restart/deployment:
history
-> workflow code
-> reconstruct state
Workflow code changes must preserve replay compatibility.
Long-running workflows may span deployments.
Never make incompatible workflow changes casually.
Use:
- version gates;
- worker versioning;
- new workflow type/version;
- migration strategy.
Route workflows to compatible workers.
Example:
workflow started with v1
-> v1-compatible worker
new workflows
-> v2
This enables gradual deployment.
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.
Large process:
EmployeeOnboarding
|
+-- AccountProvisioning
+-- DeviceProvisioning
+-- AccessProvisioning
Child workflows provide independent lifecycle and visibility.
Define behavior if parent:
completes
fails
cancels
terminates
Do not leave child lifecycle implicit.
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.
Kafka/Event Bus
|
Trigger Service
|
deduplication
|
Start workflow
Use stable event ID as workflow/idempotency identity.
Examples:
daily reconciliation
monthly billing
weekly compliance report
Schedule layer starts durable workflow instances.
Handle overlapping runs explicitly.
Webhook path:
verify signature
deduplicate event
authorize source
normalize payload
start/signal workflow
Never trust webhook payload solely because endpoint is obscure.
For event-driven scale:
Producer
-> Kafka
-> Trigger Consumer
-> Workflow Start
Persist/derive:
event id
partition
offset
business key
Deduplicate before side effects.
Core entities:
WorkflowDefinition
WorkflowRun
Plan
PlanStep
ActivityRun
ToolInvocation
ApprovalRequest
CompensationRecord
Artifact
AuditEvent
PromptVersion
PolicyVersion
EvaluationRun
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"
}
}Business/platform events:
WorkflowStarted
PlanCreated
PlanValidated
StepStarted
ToolExecuted
ApprovalRequested
ApprovalGranted
StepCompleted
CompensationStarted
WorkflowCompleted
WorkflowFailed
Tenant isolation applies to:
workflow namespace
data
search
tools
credentials
approvals
rate limits
audit
Large/regulatory tenants may use dedicated namespaces/clusters.
Authorization checks:
start workflow
read workflow
signal workflow
approve action
cancel workflow
administer definition
Never derive tenant from model-generated arguments.
Activity
|
Tool Gateway
|
Policy
|
Credential Broker
|
short-lived service credential
|
Enterprise System
Credential remains outside model context and workflow history.
Use:
- secret manager;
- workload identity;
- short TTL;
- scoped credentials;
- log redaction.
Avoid static credentials in environment where possible.
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
| 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 |
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
Trusted context:
caller identity
tenant
roles
resource ownership
must be attached by infrastructure.
The model cannot claim:
tenant=other_customer
to gain authority.
Registry metadata:
tool
version
owner
risk
mutation
required scopes
approval policy
idempotency support
timeout
compensation
Unknown/unregistered tools are denied.
Per workflow:
max model calls
max tokens
max tool calls
max retries
max wall time
max cost
Budget breach becomes explicit workflow state.
Dependencies:
workflow service
database
queue
model provider
tool gateway
enterprise APIs
approval service
secrets
Each dependency needs timeout, retry and failure semantics.
One slow connector must not consume all activity workers.
Use:
separate task queues
worker pools
concurrency limits
At connector/gateway layer:
closed
-> failures
-> open
-> cooldown
-> half-open
Workflow history should record business-relevant failure without exploding with low-level noise.
Queues:
AI activities
CRM
finance
ops
long batch
critical workflow
Independent pools reduce blast radius.
Controls:
queue depth
tenant quota
connector concurrency
rate limit
worker autoscaling
admission control
Do not start unlimited workflows when downstream systems are saturated.
| 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 |
Every step declares:
retryable?
idempotent?
reconcilable?
compensatable?
irreversible?
manual recovery?
This should be visible in architecture/tool metadata.
Trace:
workflow.run
|
+-- ai.plan
+-- plan.validate
+-- step.1
| +-- policy.evaluate
| +-- tool.execute
| `-- verify
+-- approval.wait
+-- step.2
`-- workflow.complete
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.
- started/completed/failed;
- duration;
- waiting approvals;
- cancellations;
- compensations.
- latency;
- retries;
- timeouts;
- heartbeat failures.
- model calls;
- tokens;
- invalid plans;
- replans;
- cost.
- calls;
- failures;
- 429s;
- idempotency reconciliations.
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 |
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.
Versioned Workflow Scenarios
|
candidate model/prompt/workflow
|
simulated tools
|
trajectory capture
|
graders
|
regression gate
Measure:
- valid schema;
- correct tools;
- correct dependencies;
- missing steps;
- unnecessary steps;
- risk classification;
- approval placement.
Expected:
lookup_customer
-> create_ticket
-> request_approval
-> grant_access
Evaluate sequence, arguments, and forbidden calls.
Final answer quality alone is insufficient.
Adversarial tests:
- changed args after approval;
- expired approval;
- wrong tenant;
- wrong approver;
- replay;
- requester self-approval when prohibited.
Expected: deny.
Inject:
worker crash
activity timeout
lost response
duplicate event
late signal
downstream 429
compensation failure
Verify correct recovery semantics.
Test:
- prompt injection;
- cross-tenant action;
- secret exfiltration;
- SSRF;
- unauthorized tool;
- approval bypass;
- runaway loop.
unit
-> workflow replay
-> activity contract
-> connector integration
-> end-to-end
-> adversarial
-> load
-> chaos
Replay tests are especially important for workflow code changes.
Kill:
- workers;
- activity processes;
- connector service;
- Redis;
- model provider route.
Inject:
- latency;
- 429;
- duplicate events;
- ambiguous responses.
Verify no unauthorized/duplicate side effects.
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.
Workflow wall time:
T =
planning
+ sum(activity latency)
+ approval waits
+ timers
+ retries
+ verification
User-perceived latency and business completion time are different SLIs.
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.
workflow workers
AI activity workers
CRM activity workers
finance workers
ops workers
batch workers
Autoscale by task queue depth and latency.
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
Options:
tenant -> home region
Benefits:
- residency;
- simpler consistency.
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.
Define RPO/RTO for:
workflow history
definitions
policy
audit
approvals
artifacts
External system state must be reconciled after recovery.
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.
Version:
planner model
planner prompt
verifier model
verifier prompt
structured schemas
Store versions in workflow metadata/audit.
Model upgrade:
offline eval
-> shadow
-> canary
-> production
Tool:
crm.create_ticket.v1
crm.create_ticket.v2
Avoid silently changing semantics beneath running workflows.
Workflow definitions also need compatibility strategy.
Long-running enterprise automation cannot depend on process memory.
LLM calls are nondeterministic external operations.
Authorization must remain deterministic.
Approval must apply to a specific action, not a vague workflow.
Timeout does not prove side-effect failure.
Distributed enterprise systems do not share one transaction.
Bound history growth.
AI:
- flexible intent understanding.
- nondeterminism/cost.
Static:
- predictable.
- less flexible.
Hybrid is often best.
- precise retries/visibility.
- history/complexity.
- simple.
- poor recovery granularity.
- governance.
- extra hop/control-plane dependency.
- automated recovery.
- complex business semantics.
- basic durable workflows;
- AI planner;
- Java tool API;
- retries.
- idempotency;
- signals;
- human approval;
- typed errors.
- policy gateway;
- exact approval binding;
- secrets broker;
- audit.
- compensation;
- heartbeats;
- cancellation;
- child workflows.
- worker versioning;
- Continue-As-New;
- event/Kafka triggers;
- multi-tenant quotas.
- multi-region;
- chaos;
- full evaluation platform;
- enterprise governance.
- inspect approval state;
- verify approver routing;
- inspect expiry;
- do not manually skip policy;
- signal only through authenticated path.
- stop retries;
- query external system using idempotency/business key;
- reconcile workflow state;
- compensate duplicate if safe;
- audit incident.
- route old histories to compatible worker;
- stop new rollout;
- run replay tests;
- roll back.
- mark manual recovery;
- preserve completed/compensated step list;
- alert operator;
- avoid repeatedly applying unsafe compensation.
- What does durable execution actually guarantee?
- Why is exactly-once side effect execution generally an illusion?
- How do you reconcile an ambiguous API timeout?
- How should idempotency keys be generated?
- When should compensation be automatic?
- How do you model irreversible actions?
- How do you safely wait a month for approval?
- What belongs in workflow history?
- When should you Continue-As-New?
- How do you version a year-long workflow?
- How do you deploy incompatible worker code?
- How do child workflow cancellation policies work?
- When should AI planning happen once vs incrementally?
- How do you prevent prompt injection from authorizing tools?
- How do you keep credentials out of LLM context?
- How do you evaluate an agent trajectory?
- How do you handle duplicate Kafka events?
- How do you prevent two regions from executing the same action?
- How do you implement separation of duties?
- What happens when compensation itself fails?
- How do you define SLOs for workflows waiting on humans?
- How do you isolate noisy tenants?
- How do you search millions of active workflows?
- What should happen if the policy service is unavailable?
- When should a workflow be deterministic with no AI at all?
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.
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
Typical:
cp .env.example .env
docker compose up --buildStart 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-testA 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.