Skip to content
Development preview · 2.0.0-SNAPSHOT

Durable architecture

Durable runs processes that wait for external events or need to continue after an application restart. It stores their progress in a database and uses background workers to advance them. Use DurableProcessEngine to start and manage these executions. Each execution is a Run. ProcessEngine handles ordinary in-process execution and is a separate engine.

This page follows an order through execution and recovery, then explains the storage, scheduling, and data rules behind it. See Durable process for integration code and the operations runbook for troubleshooting.

To answer a specific question:

Consider a process with three business steps: calculate the order total, wait for a payment notification, and ask a warehouse to create a shipment. Calculating the total uses only process inputs. Creating a shipment changes another system.

A successful execution proceeds as follows:

  1. The application assigns a Run ID and calls start(...). The engine validates the process and its input, then saves the definition and initial state for this execution. Returning from start(...) does not mean the process has finished.
  2. A Worker claims the Run and calculates the total. At the wait node, it saves the total, the position from which execution will continue, and the wait record in one transaction. That batch of work ends, so the Worker does not hold a thread while waiting for payment.
  3. Integration code receives the wait notification and its WaitToken. When the payment message arrives, it calls completeWait(...) to save the payment result. That call records the result; a Worker advances the process afterwards.
  4. The process reaches the Action that creates a shipment. Because this Action declares execution=effect, the engine saves a request first. A Worker dedicated to external operations then calls the warehouse.
  5. When the warehouse returns a shipment ID, the Worker saves that result. The Run Worker reads it, continues the process, and eventually saves the Run’s output.

Advancing a process and calling an external system are separate jobs. Committed database records connect them:

Process or architecture diagram

The Store is Durable’s storage interface, implemented by a database Provider. The application and both kinds of Worker can run in one application process. Multiple workers can also share a Store. The application supplies business Actions and declared Java types. Workbench reads these same committed records through the APIs.

Each time a Worker claims a Run, it reads the saved state, executes process steps, and commits the result. This batch of work is a Turn. Creating a new Wait, Timer, or Effect request ends that Turn: the Worker commits the request together with the current progress. A Turn also commits when the process finishes or reaches its step limit.

A waiting path does not prevent other parallel paths from running. If another path is runnable when the Turn commits, the Run remains runnable. The next Turn continues that path without waiting for the new Wait, Timer, or Effect result.

A claim supplies an ordered prefix of resolved, unconsumed Wait, Timer, and Effect results: at most 256 results and 64 MiB of complete stored envelopes. PostgreSQL and MySQL select the prefix by stored byte lengths before reading the payloads. An omitted result may already be resolved; the Worker acknowledges only results offered to it. If resolved results remain unconsumed when a waiting Turn commits, the Run remains runnable.

One Turn may advance several parallel paths and enter or return from child processes. They share the Turn’s step budget and follow the configured active-iteration limit. Their state is saved together. Calling a child process does not create another Run.

To continue later, the Worker saves the following data, called a continuation in the code:

Saved data Purpose in the order process
Execution position Know whether the process is still waiting for payment or can create a shipment
Variables encoded with their declared types Restore the saved order total and other values
Parallel paths and loop progress Track unfinished paths and the current iteration
Child-process frames and exact call targets Return to the right caller when a child finishes

A Turn commits the next continuation, consumed results, and new Wait, Timer, or Effect records in one transaction. For example, the database cannot record that the payment result was consumed while omitting the next state committed with it.

If the process crashes before that transaction commits, the previous continuation remains in the database. Computation that has not committed may run again. An Action marked execution=replayable must therefore be safe to run again with the same inputs.

Sequential multi-instance and while loops explicitly record the position before entering the loop body in both compiled and interpreted modes. Yielding at the Turn limit does not itself repeat or skip an iteration.

The step limit bounds how many nodes a Turn processes. The active-iteration limit bounds how many parallel foreach iterations are active at once; completing an iteration can make room for another. Neither limit bounds the duration of an individual application callback.

The Store grants the Worker a time-limited lease and a token. The Worker renews the lease while running, and the Store checks the token again when it commits. This check is called fencing.

Suppose Worker A pauses long enough for its lease to expire and Worker B takes over. If A later resumes, it cannot use the old token to commit progress over B’s state. An Effect invocation that already began under a recorded attempt may still save its late result against that attempt, but doing so does not restore permission to start new work.

The Store also checks termination requests at commit time. A requested termination takes precedence. Thus, commitTurn returning true means a state transition committed under the lease; it may have committed termination rather than the business result proposed by the Worker.

To recover, a Worker reads the Run’s saved continuation, exact definition, pending requests, and Wait, Timer, and Effect records. It obtains or rebuilds a runtime for that definition, then continues from the saved position.

The next action depends on what had committed before the order process stopped:

Committed before the interruption What happens next
Initial state only; the total has not been committed Recalculate from the last saved position
Total and payment wait record Continue waiting for the same payment notification
Payment result saved; the next Turn has not committed Read and consume the stored payment result
Shipment request saved; external outcome uncertain Follow the Effect’s saved recovery policy; a timeout alone does not prove the warehouse created no shipment
Shipment result and next continuation saved Use the stored result and continue with the later steps

The persisted data consists of definitions and execution state. The Kernel does not save generated Java source, classes, bytecode, live objects, executor state, or in-memory routes. A lost runtime cache can be rebuilt. Values in a saved continuation are read using their declared types.

If an application class, component, script executor, or serializer is missing, restore it in the deployment. Do not rewrite the saved definition to compensate for a missing application implementation. Failed runtime preparation does not advance the process. The Worker releases the claim and retries after backoff.

Recalculating an order total normally has no external effect. Creating a shipment twice could send two packages. An Action declares execution=replayable|effect to distinguish these execution modes.

The Effect request commits before the warehouse call and has a stable occurrence ID identifying this external operation. The application can pass that ID as the warehouse’s idempotency key, but the warehouse or integration code must implement the deduplication.

If the warehouse creates a shipment and the Worker exits before saving the result, the database may know only that the call started. The outcome is UNKNOWN. The stored effectPolicy determines whether to retry, investigate the external result, or require operator review. An exception, timeout, or interruption does not prove that the operation never happened, and the Kernel cannot undo it.

Effect dispatch and reconciliation confirm the lease after binding the actual Action and immediately before calling application code. Confirmation and background renewal use the same Store token checks. A task known to have lost its lease does not start a new Effect call. A JVM pause or lease transfer can still occur after confirmation, allowing external calls to overlap. Token checks prevent an expired lease from authorizing a new invocation or Turn commit. A late result from an invocation that already began can still be recorded under its original attempt. The application remains responsible for remote deduplication or reconciliation.

Process termination and external outcome confirmation are separate facts. A late result that passes the existing identity and competing-evidence checks can settle its Effect after the Run ends; terminal status alone does not prevent confirmation. The Run’s terminal status, completion time, unresolved-at-seal record, and final publication position stay unchanged, and execution does not resume. Competing results and non-execution evidence continue through the existing conflict and operator-resolution rules.

Durable uses effectPolicy to recover external operations. The synchronous retry and timeout settings of ProcessEngine do not apply here; Durable rejects non-default invocationPolicy values.

Internally, all UNKNOWN Effect recovery uses the RECONCILE claim operation. The saved policy still determines what happens:

Policy Work performed in the recovery slot
MANUAL Decide and arrange operator review
RETRY Check the attempt budget and recovery deadline before allowing another dispatch
RECONCILE Call the application’s reconciler to investigate whether the external operation completed

Only the RECONCILE policy increments reconcileAttempts; MANUAL and RETRY leave it at zero. Decisions about review, exhausted attempts, and expired deadlines need only the stored policy. Actual dispatch and reconciliation also require a prepared Action and a valid lease.

If the required application implementation is unavailable, releasing the claim removes the attempt count added by that claim. Preparation failures must not use up the allowed business attempts.

Operator decisions include review_revision so an old decision cannot affect a later dispatch. This revision is managed separately from Worker lease tokens and attempt counts:

  • Granting a new DISPATCH lease increments review_revision in the same transaction. Changes to the review state can increment it too.
  • RECONCILE investigates a previously started operation without starting the business call again, so claiming it does not increment the revision.
  • Releasing a claim because an implementation is unavailable does not decrease the revision.
  • An operator decision may be retried for the same revision but cannot resolve a later dispatch.

PENDING and RUNNING describe whether work is queued or running. They do not establish whether an external operation happened. For example, an UNKNOWN Effect queued again under RETRY keeps its unknown_since value.

Run termination revokes queued Effects only when no earlier dispatch outcome remains unresolved.

When ending a Run under the BOUNDED_DRAIN stop policy, the Store can also cancel a RUNNING DISPATCH claim if it has a matching current attempt record that proves invocation has not begun and there is no earlier unresolved outcome. Missing attempt evidence does not satisfy this check.

Begun invocations and earlier UNKNOWN outcomes remain unresolved. A queued retry with an uncertain earlier outcome goes to operator review and produces a notification.

Conversely, confirming that an operation did not execute clears unknown_since, even if no dispatch attempts remain. The Effect stays PENDING with automatic dispatch blocked for review; cancellation can settle it.

This is why reviewRequiredEffects can exceed unknownEffects. The active-work summary counts non-running uncertain retries in unknownEffects and running tasks in runningEffects, without counting one Effect twice.

A call succeeds but its result cannot be saved

Section titled “A call succeeds but its result cannot be saved”

The point of failure matters:

Failure point Handling
Before the Java invocation adapter returns normally The outcome remains UNKNOWN and follows the saved recovery policy. Java return conversions inside the adapter use javac target typing
After the adapter returns, while mapping or encoding its result Request operator review under the current lease. Automatic dispatch is blocked only after that transition commits; if the lease is lost first, the unresolved outcome follows the saved UNKNOWN recovery policy
After encoding, while committing to the Store Retry saving the same encoded bytes against the original begun attempt, without calling the Action or mapping its result again. Lease expiry alone does not invalidate that evidence

Choosing the definition and input at startup

Section titled “Choosing the definition and input at startup”

Starting a Run saves an immutable process definition and records its processId. A direct definition supplies the content; ProcessRef.Version selects a specific version; an Alias is resolved to an exact version when the Run starts.

Aliases belong to the Deploy control plane. Recovery uses the saved definition and does not consult the Alias or require Deploy. Later Alias changes or deletion cannot reroute the Run. Retirement preserves the Alias identity and audit history while disabling its active route. New Starts through a retired Alias fail admission; an identical retry of a retained Start can still return the original Run.

A definition has a content-addressed processId. Its process code, model type, exact source bytes, and digest are immutable. Namespace and optional Version record where a Run was started from; they are not part of this stored semantic identity.

For example, two direct definitions may both use the code order.process but have different processId values because their content differs. They do not need Version identifiers. A published Version’s content remains immutable. Each Run records its exact root processId. It also retains its referenced child definitions.

Semantic and machine fingerprints identify prepared artifacts. Each has one current canonical format and may appear in generated class names or the semantic digest passed to DurableWaitDescriptionProvider. Changing that format does not change the processId of the exact source. Recovery does not use these fingerprints to choose a definition.

Assign a stable, unique Run ID to each new execution. For an ordinary Start, the engine first checks any retained creation record, before resolving an Alias.

While that record is retained, retrying with the same source selector, effective routing options, and typed input returns the original Run. The retry’s input is checked against the first saved definition; the original definition, exact dependencies, and stop policy continue to apply.

A different request, or an existing Run without the creation record used to recognize ordinary Start retries, fails with RUN_ALREADY_EXISTS. Never reuse a Run ID for another execution, even after the original record has been deleted.

Root input may contain only declared param variables and may omit some parameters. The process manages return and inner variables. Undeclared input keys are rejected before business code runs.

See Node support for the supported TBBPM and BPMN nodes and their scope restrictions. tooling().prepare(...) checks whether this application can handle the complete static dependency graph. It makes no Store writes, creates no Run, invokes no Action, and does not warm the recovery cache.

A WaitToken is an opaque credential for completing one persisted Wait. Pass it unchanged with the result; the caller cannot choose a recovery position. Completion does not create another invocation or Run.

The same canonical result may be submitted again while the owning Run and completed Wait record remain queryable. A different result conflicts. Retention cleanup can remove a consumed Wait record even while its Run is active; deleting that record invalidates the token.

The Wait record stores only the token digest. An active Outbox record temporarily holds the raw token for notification delivery, so protect the Outbox as credential storage. Never put raw tokens in logs, URLs, metrics, or operator views. See wait-token security for retention rules.

The application does not need a token table. If an external system returns only its own job ID, integration code may keep a mapping from that ID to the WaitToken.

A wait notification is validated as one complete object, including Kernel fields and application attributes. If encoding the notification exceeds the JSON byte, depth, token, or lexical limits, the Run fails with ENCODING_LIMIT_EXCEEDED: the same transaction consumes the completed occurrences used by this Turn and issues no new Wait or Outbox notification. The same rule applies to newly encoded continuation state, Action preparation values, and terminal results. Provider exceptions and invalid portable description values remain Turn faults and may retry after the application is corrected. Encoding failures after an external Effect has already returned retain the Effect review policy; they never authorize replay of that external action.

The Store reads the output bytes and exact definition of a completed Run in one snapshot. Subsequent cleanup cannot prevent that already-read result from being decoded.

Decoding needs only the declared return types. It does not need input-only classes, Action implementations, script executors, or executable compilation. Full value schemas and result-only decoders each have bounded caches, separate from runtime caches. Invalid stored output is an internal read failure, not invalid caller input.

Run, timeline, and Outbox queries use exact filters and keyset cursors. A cursor records where the previous page ended so the next page can continue from there. Durable does not offer fuzzy search. Applications may maintain a separate search index, but execution state is determined by Store records. At the Store SPI, timeline queries without includeEvidence select journal metadata only, without loading fact envelopes; the returned fact payloads are null. Raw fact envelopes are reserved for trusted Store callers.

DurableWorkerCoordinator in compileflow-durable-runtime manages polling, execution slots, maintenance, and health without depending on Spring. DurableWorkerLifecycle connects the owning DurableProcessEngine to Spring startup and shutdown. When workers are disabled, neither Worker objects nor their lifecycle adapter are created.

The coordinator reserves an execution slot before claiming work from the Store. Once the claim transaction returns and lease tracking starts, it fills the remaining slots immediately. With a backlog, one slow task does not leave other available slots unused.

Effect dispatch and recovery have separate slots and cannot borrow from each other. The defaults are eight DISPATCH slots and one recovery slot, allowing nine Effect tasks in total. RECONCILE, MANUAL, and RETRY policy handling all use recovery slots.

Reserved recovery slots prevent dispatch from taking all execution capacity, but a blocked reconciler still occupies its recovery slot. Database connections and application locks are not reserved separately; exhaustion of shared resources can delay all tasks. Slots do not guarantee callback deadlines or fair scheduling of arbitrary application code.

Internal notifications only trigger scheduling. They make no Store or business calls and do not put claimed work into another queue. When idle, each work type has one scheduled probe, with backoff between attempts. After stopping or rejecting a submission, the coordinator does not schedule more work to fill additional slots. Tasks already started, including claims still in progress, continue with normal lease renewal and token-checked commits.

A Worker can claim a Run as soon as the Store says work is due, without a local runtime cache entry. It immediately starts lease tracking, then loads the exact process on its execution slot. Concurrent loads of the same process share one loading task.

A bounded LRU cache reduces repeated preparation. A miss or eviction may require compilation when work arrives; idle workers do not precompile the entire process catalog. The current Turn holds references to its root and required child runtimes even if their cache entries are evicted. Maintenance does not compile processes, so slow preparation cannot occupy the capacity used to reclaim expired work and handle Timers.

After loading the root and active invocation runtimes, the Worker confirms its lease against Store time before executing the Turn. Children not yet entered keep exact bindings and load on entry, followed by another lease confirmation. Startup has already validated and saved the complete call graph. Prepared nodes need no per-node database calls.

Method adapters for class and bean actions are cached by Java signature, independently of component names. Script catalogs in one deployment share a bounded cache. Its adapters are released only after the Workers exit.

Unexpected Run faults are counted in metrics and retried with Store-backed backoff. Worker health reflects acquisition, scheduling, and maintenance. A fault in one Run that has been handled according to these rules does not necessarily mean the Worker is unhealthy.

When concurrent branches write to the same process variable, the Turn records CONCURRENT_VARIABLE_WRITE_CONFLICT and the Wait or Effect results consumed in that Turn in the same commit. External work already in progress follows the Run’s stop policy. Retrying the same results cannot resolve the conflict. Corrupt recovery state and other unexpected exceptions follow their own fault handling rules.

Diagnostics include the Run ID, Process ID, processing phase, and a limited set of exception types and stack frames. They exclude exception messages and process payloads. Each Turn Worker emits at most one diagnostic every 30 seconds; the next reports how many were suppressed.

Scheduled tasks release their slots in finally. Nonfatal application Errors are recorded and polling continues with backoff. Nonfatal Store Errors during renewal do not disable later heartbeats. A VirtualMachineError or ThreadDeath in a coordinator task stops acquisition, marks health degraded, and is rethrown for the host to handle. External operations with uncertain outcomes remain uncertain.

Stopping a Worker first prevents new scheduling, then waits within the configured time limit for started work to exit, including claims still in progress. At the limit, the coordinator requests interruption and reports unfinished tasks.

stopWorkersAsync() and completion callbacks finish only when the tasks actually exit. A timeout or an interruption request does not prove that they have stopped. Keep Store, lease-renewal, and runtime resources available until they do. Stopping a Worker does not prove that an external Effect was cancelled. Application APIs and operator APIs remain separate capabilities.

When preparing a runtime, Core compiles two mappings using Java type rules: process variables to Action parameters, and Action results back to process variables.

For example, List<Integer> cannot be assigned to List<String>. This fails before an Effect calls business code. Valid Java assignments and documented explicit DataTypes conversions remain supported. Loop variables keep their lexical types.

Mappings produce parameter values before inputs are detached or persisted. Replayable Actions, Effect dispatch, and confirmed reconciliation use these mappings. An Action with neither variable inputs nor outputs needs no mapping compilation. These checks cover Java assignments. Untyped API payload conversion and JSON continuation validation are separate checks.

Before saving a continuation, Wait result, or Action result, the Kernel applies the same JSON limits used when reading: size, nesting depth, token count, string length, property-name length, and number length.

Finite BigDecimal values may exceed the double range but must fit the encoding length limits. float / double NaN and Infinity are rejected, as is numeric overflow during recovery.

The Kernel also decodes each value and checks that re-encoding produces the same bytes. Stable POJOs and records work. A setter or constructor that loses information fails before persistence. The application must still ensure that accessors are deterministic and have no side effects.

Creation, update, completion, and diagnostic timestamps use the database wall clock. It can move backwards. Use revisions, lease tokens, occurrence IDs, and committed state to establish ordering rather than relying only on timestamps.

Lease validity, Timer deadlines, retry eligibility, and configured recovery or stop durations still follow their specified time comparisons. Timers cannot fire early. Becoming eligible does not mean the Timer has been processed or the Run has resumed; both require subsequent Store and Worker activity.

Absolute AT Timer requests retain their original Instant. PostgreSQL and MySQL round the persisted eligibility threshold upward to whole milliseconds, by less than one millisecond; whole-millisecond values remain unchanged. Timer query and result dueAt fields expose this effective threshold. If the requested instant has just passed, the Timer may still wait until the next millisecond boundary. An effective threshold already in the past is immediately eligible and is never clamped to the database time of the commit.

Run and invocation state, requests, leases, Effects, and Outbox records change through explicit Store operations. A Store Provider must preserve atomicity, lock ordering, compare-and-set behavior, database-time rules, and token fencing.

PostgreSQL and MySQL have separate first-party Providers and migrations. H2 is used only for tests. Providers choose their physical tables but must preserve the same transaction and recovery behavior. The shared testkit checks common requirements. A supported Provider must also demonstrate the transaction, concurrency, crash-recovery, and migration behavior required by Supported surfaces.

An application can have a Run produce records for publication, called emissions. Accepted emissions commit with the continuation under the original Run lease.

PostgreSQL can close publication early in that same transaction. No further emissions are accepted; sealedSequence marks the end of the accepted records and sealedAt records when publication closed. Existing Effects and Waits continue to settle on the original Run.

finalSequence is fixed only when the Run actually terminates and is used for retention acknowledgement. MySQL closes publication at termination and does not support early closing. Closing publication does not create another Run or transfer execution to another component.

Retention must keep every definition referenced by a recoverable or retained Run. This includes child definitions. Keeping only the latest few versions could delete a definition that a long-running process still needs. Generated runtimes can be released earlier. Deleting definitions must also respect backup and rollback windows.

Even after a terminal Run reaches its retention deadline, cleanup waits for these obligations:

  • PENDING or DELIVERING Outbox records;
  • unresolved Effect risks;
  • required emission prefixes not yet acknowledged: published records for which downstream acknowledgement is required.

When those obligations are settled, the Store first saves a deletion seal. Public queries and operator commands then treat the Run as absent. Physical deletion follows in batches.

Each cleanup transaction may delete up to the configured total row limit, shared across Journal, Outbox, Wait, Effect, attempt evidence, Emission, recovery references, and the Run itself. Interrupted cleanup continues from the saved seal. Definitions remain referenced until their dependent rows are gone.

Cleanup of consumed Waits and Effects chooses the oldest eligible record across both categories, so one category cannot indefinitely delay the other. An active Run’s Journal and settled Outbox records remain until terminal cleanup. Include that accumulation when sizing storage for long-running processes.

Both DELIVERED and ABANDONED settle an Outbox retention obligation. With the default no-publication profile, cleanup does not require a receipt proving that a downstream consumer received the complete Run result. Required emissions and application references have their own retention conditions.

Terminal events contain no output payload. If the application needs a durable copy of the result, read and save it before acknowledging delivery, and set a retention policy that keeps it available until then.

Cleaning up a consumed Wait removes the record used to recognize duplicate completion requests. Cleaning up a Run removes its creation record and the Store’s enforcement of ID uniqueness. Callers must still never reuse IDs. An empty query result means only that the Run is not currently visible, not that the ID has never been used.

Operator audit records retain the target type and ID, the revision used to check the decision, the decision, actor, reason, and optional context even after the occurrence row is deleted. Run status views and metrics expose only the specified state and outcomes, not payload variables, credentials, routing keys, or lease tokens. Reading the saved definition or the application result is a separate operation; the host must authorize access to that data separately.