This is the detailed repository reference for the first-party PHP client and worker SDK. Start with the root README or the PHP developer portal for the shortest runnable path.
- Laravel adoption: start with the ownership-first transition
guide when moving a
Laravel Workflow v1 application to v2 embedded or service mode, or when
moving embedded v2 to service mode. The current bridge supports PHP
^8.2and patched Laravel^12.72.0|^13.41.0; Laravel 13 needs PHP 8.3 or newer. Embedded-to-service transitions require the installed Workflow package to publish that same support contract. The bare SDK retains PHP^8.1. Existing applications must apply Laravel security updates while upgrading. Stable-v1 authority is unchanged. - Plain PHP service mode: follow the quickstart below when a framework-neutral application and remote worker connect to Durable Workflow Cloud or a self-hosted Server.
- Symfony service mode: use the Symfony bridge from this SDK for autowired remote handlers and a managed console worker.
- Embedded Laravel workflows: use
durable-workflow/workflowwhen the Laravel application itself should own durable state and execute through Laravel queues. That is a different deployment model, not a prerequisite for this SDK.
Supply a PayloadProtection configuration to each PHP client and Worker that
handles protected payloads. Use a compatible Native Server and PHP with
ext-sodium. The SDK encrypts Avro values before sending them to the Server or
an external payload store and authenticates them using the namespace and the
logical payload boundary. Clients and workers receive keys from the
application's secret store. Each key is 32 raw bytes.
use DurableWorkflow\Client;
use DurableWorkflow\PayloadProtection;
use DurableWorkflow\PreparedPayloadCommand;
$protection = new PayloadProtection(
['orders-v1' => $oldKey, 'orders-v2' => $currentKey],
activeKeyId: 'orders-v2',
);
$client = new Client(
$serverUri,
namespace: 'orders',
token: $serverToken,
payloadProtection: $protection,
);
// Store this record durably before sending if the process may need to retry.
$record = $client->prepareUpdate(
'order-42',
'approve',
[9223372036854775807, null, 'λ'],
runId: $runId,
)->toArray();
// A fresh process with the same namespace can restore and send the record.
$receipt = $client->sendPreparedCommand(PreparedPayloadCommand::fromArray($record));Configure the Worker's client with the same namespace and keyring. During
rotation, distribute the new read key to all participants before choosing it
as the active writer key. Retain the older read keys for as long as existing
history can replay and existing results can be read. A client with no active
key can read results and resend a saved command. It cannot seal a new command.
Use prepareSignal() for the same retry pattern with signals.
Protection covers workflow and remote activity arguments and results, standalone
signal arguments, update and query arguments and results, and recorded side
effect results. The Server must support the corresponding protected operations.
The SDK refuses protected local activities, heartbeat payloads, streams, and
service operations. Protected signal-with-start requires explicit nonempty
signal arguments. Workflow IDs, namespaces, queue and handler names, memo,
searchable attributes, and application-supplied error text remain visible.
Keep sensitive values out of those fields. Missing or incorrect keys, modified
ciphertext, and wrong namespaces or boundaries cause explicit errors. Strict
reads are the default. allowPlaintext: true allows applications to read old
plaintext Avro history during a planned migration.
Use an operator credential to read dashboard aggregates for the client's
namespace. boundedOperatorDashboard() leaves fleet-wide history audits
unevaluated. workflowTypeOperatorDashboard(['orders.import']) also limits
workflow totals, trends and alerts to the explicit types. An empty list matches
no workflows. Worker, queue and storage metrics retain the namespace scope.
The selected types are returned in dashboard.workflow_scope, with concrete
time windows in dashboard.time_windows. The type-filtered operation uses an
additive Server route. Older Servers return their original HTTP 404 without an
unfiltered fallback. The SDK rejects malformed selections and encoded query
values larger than 4096 bytes before sending them.
With an operator credential and a Server that advertises
task_queue_activity_dispatch_pause (native 3.8.0 and later), you can pause
activity dispatch on one task queue of the client's namespace and resume it:
if ($client->clusterInfo()->supportsTaskQueueActivityDispatchPause()) {
$paused = $client->pauseTaskQueueActivityDispatch('payments', 'payments vendor outage');
// $paused['outcome'] is 'paused', or 'already_paused' with the original pause.
$state = $client->describeTaskQueueActivityDispatch('payments');
// $state['activity_dispatch']['state'] is 'paused' or 'active'.
$resumed = $client->resumeTaskQueueActivityDispatch('payments');
// $resumed['outcome'] is 'resumed', or 'not_paused' when nothing changed.
}Each call returns the Server's answer: namespace, task_queue,
activity_dispatch (state, paused, reason, paused_at, paused_by,
resumed_at, resumed_by) and, for pause and resume, outcome. While a queue
is paused, no activity task on it is leased. Activities already leased keep
running, workflow tasks are still delivered, and activity deadlines keep
running. The reason is optional and at most 1000 characters. The Server records
the credential's principal as the one who paused. Queue names are exact:
pausing Orders does not pause orders.
Pause and resume are sent once and never retried, so a lost answer never
repeats a pause. Read the state with describeTaskQueueActivityDispatch()
instead. A worker credential, or a tenant credential for another namespace,
gets a ServerException with status 403. An invalid reason or queue name gets
status 422 with Laravel validation errors in details. A Server without the
routes (published PHP Server 2.x, older native) answers 404, which the SDK raises
as DurableWorkflow\Exception\ServerCapabilityUnavailable: a
ServerException with status 501, reason backend_capability_unavailable and
capability task_queue_activity_dispatch_pause. Nothing was changed.
With an operator credential, workflowObservation('order-1', 'run-1') reads
scalar run metadata, current waits, related run statuses and recent failure
references. Omit the run ID to observe the instance's stored current pointer.
Related runs have their own statuses. Unknown or pruned evidence stays explicit.
This read does not establish authority to issue commands.
Application context is opt in. Pass up to 20 distinct search attribute keys as
the third argument. The response preserves their metadata without interpreting
it as a payload reference. The observation includes 200 history events by
default. historyPageSize selects up to 1000. Pass history.next_page_token as
historyPageToken to continue inside the original sequence boundary. Supporting
failure references also provide a cursor for direct inspection. These cursors
belong to this observation route. Application values and external payload
references in the history stay encoded.
This additive Server route requires a runtime that supports bounded observations.
An older runtime's refusal is returned directly. Use workflowDiagnostics()
explicitly when full diagnostics are needed.
Create an empty Composer project and install the current published package:
mkdir durable-php-quickstart
cd durable-php-quickstart
composer init --name=acme/durable-php-quickstart --no-interaction
composer require durable-workflow/sdkThe package declares its supported Server baseline in Composer metadata.
Contributors testing the current source branch can install it directly:
composer config repositories.durable-workflow-sdk vcs https://github.com/durable-workflow/sdk-php
composer require durable-workflow/sdk:dev-mainThe SDK uses the official apache/avro
package for schema parsing and binary payload encoding. Guzzle is included as
the default PSR-18 transport; any PSR-18 client and PSR-17 factories can be
injected instead.
Set one runtime URI exactly as provisioned:
# Self-hosted Server: pass the bare origin. The SDK appends one /api segment.
export DURABLE_WORKFLOW_RUNTIME_URL='http://localhost:8080'
export DURABLE_WORKFLOW_NAMESPACE='default'
# Durable Workflow Cloud: instead use both values returned by provisioning.
# export DURABLE_WORKFLOW_RUNTIME_URL='https://cloud.example/api/runtime/v1/namespaces/<runtime-id>'
# export DURABLE_WORKFLOW_NAMESPACE='<provisioned-namespace>'
export DURABLE_WORKFLOW_TASK_QUEUE="php-quickstart-$(php -r 'echo bin2hex(random_bytes(8));')"The Cloud URL already contains /api/runtime/v1/namespaces/...; do not trim
that prefix or replace it with the Cloud control-plane URL. Keep the separately
provisioned Cloud namespace value unchanged as well. The SDK appends its
endpoint /api after the namespace runtime URI. For Server, pass an origin such
as http://localhost:8080, not http://localhost:8080/api, so the request path
contains one /api segment rather than two.
Inject credentials through the process environment or a secret manager. Client operations and worker polling are separate roles, so keep their variables separate even when a development Server is configured with one shared token:
read -rsp 'Client credential: ' DURABLE_WORKFLOW_CLIENT_TOKEN; echo
export DURABLE_WORKFLOW_CLIENT_TOKEN
read -rsp 'Worker credential: ' DURABLE_WORKFLOW_WORKER_TOKEN; echo
export DURABLE_WORKFLOW_WORKER_TOKENThe prompts do not echo values. Do not put these exports in source files,
commit an .env file, or print either value in diagnostics.
bootstrap.php resolves Composer consistently when the example is in a clean
project, this SDK checkout, an installed SDK package, or a Sample App
playground/container that copies the files beside its own vendor/ directory.
<?php
declare(strict_types=1);
(static function (): void {
$candidates = array_unique([
__DIR__.'/vendor/autoload.php',
dirname(__DIR__).'/vendor/autoload.php',
dirname(__DIR__, 2).'/vendor/autoload.php',
dirname(__DIR__, 3).'/autoload.php',
getcwd().'/vendor/autoload.php',
]);
foreach ($candidates as $candidate) {
if (is_file($candidate)) {
require $candidate;
return;
}
}
throw new RuntimeException(
'Composer autoload.php was not found. Run the example from a Composer project or copy all three example files beside vendor/.',
);
})();
function quickstartEnvironment(string $name): string
{
$value = getenv($name);
if (!is_string($value) || trim($value) === '') {
throw new RuntimeException("Set the {$name} environment variable before running this example.");
}
return trim($value);
}worker.php keeps #[Workflow], #[Activity], and the register() call in one
visible path. The attributes provide the public type names that Server admits.
<?php
declare(strict_types=1);
require __DIR__.'/bootstrap.php';
use DurableWorkflow\Attribute\Activity;
use DurableWorkflow\Attribute\Workflow;
use DurableWorkflow\Client;
use DurableWorkflow\Worker;
use DurableWorkflow\Worker\ActivityContext;
use DurableWorkflow\Worker\WorkflowContext;
final class GreeterWorkflow
{
#[Workflow('quickstart.php.greeter')]
public function run(WorkflowContext $context, string $name): array
{
$greeting = $context->activity('quickstart.php.greet', [$name]);
return ['greeting' => $greeting];
}
}
final class GreetingActivities
{
#[Activity('quickstart.php.greet')]
public function greet(ActivityContext $context, string $name): string
{
return "hello, {$name}";
}
}
$client = new Client(
quickstartEnvironment('DURABLE_WORKFLOW_RUNTIME_URL'),
namespace: quickstartEnvironment('DURABLE_WORKFLOW_NAMESPACE'),
workerToken: quickstartEnvironment('DURABLE_WORKFLOW_WORKER_TOKEN'),
);
Worker::create($client, quickstartEnvironment('DURABLE_WORKFLOW_TASK_QUEUE'))
->register(GreeterWorkflow::class, GreetingActivities::class)
->run();client.php starts a unique workflow and waits for its completed result.
<?php
declare(strict_types=1);
require __DIR__.'/bootstrap.php';
use DurableWorkflow\Client;
$client = new Client(
quickstartEnvironment('DURABLE_WORKFLOW_RUNTIME_URL'),
namespace: quickstartEnvironment('DURABLE_WORKFLOW_NAMESPACE'),
controlToken: quickstartEnvironment('DURABLE_WORKFLOW_CLIENT_TOKEN'),
);
$workflowId = 'php-quickstart-'.bin2hex(random_bytes(16));
$handle = $client->startWorkflow(
workflowType: 'quickstart.php.greeter',
workflowId: $workflowId,
taskQueue: quickstartEnvironment('DURABLE_WORKFLOW_TASK_QUEUE'),
input: ['PHP'],
);
$result = $handle->result(timeoutSeconds: 90, pollIntervalSeconds: 1);
echo json_encode(
['workflow_id' => $workflowId, 'result' => $result],
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES,
).PHP_EOL;The files above ship under examples/. Copy all three into the
new project if you prefer not to create them from the visible blocks.
Run the worker in the first terminal with only its role credential:
env -u DURABLE_WORKFLOW_CLIENT_TOKEN php worker.phpIn a second terminal with the same runtime, namespace, and task queue, start the workflow and read the result with only the client credential:
env -u DURABLE_WORKFLOW_WORKER_TOKEN php client.phpThe output contains a new workflow ID and this result shape:
{"workflow_id":"php-quickstart-…","result":{"greeting":"hello, PHP"}}Stop the worker with Ctrl+C after the client completes.
register() is the preferred class-oriented API: it discovers every attributed
handler in the supplied classes before polling. For generated handlers or other
callable-first code, the direct alternative is explicit and does not use
attributes:
$worker = Worker::create($client, $taskQueue)
->registerWorkflow('quickstart.php.greeter', $workflowHandler)
->registerActivity('quickstart.php.greet', $activityHandler);Both callables receive the same WorkflowContext and ActivityContext values
shown in the class-oriented example. Do not call register() with un-attributed
classes; use one complete registration style or the other.
The machine-readable quickstart contract records the supported runtime URL forms, role-specific environment variables, package-owned source files, and expected result. Documentation builds verify that the visible examples still match those runnable files.
ActivityContext::activityExecutionId is the nullable logical
execution identity supplied by an activity claim. workflowId and runId
identify its owning workflow/run; activityAttemptId remains attempt-specific.
Use a caller-owned business key when logical identity is unavailable. The SDK
preserves received ID spelling and never manufactures an execution ID from a
task, attempt or session ID. Prepared local callbacks expose the validated
Server execution ID; inline local/Server-free callbacks without one report
null. Session callbacks use the actual claim field when present. The same
accessor is used in ordinary and cooperative remote execution.
A retried activity attempt can read the checkpoint that an earlier attempt of
the same activity execution recorded with heartbeat(). The worker registers
activity_heartbeat_resume, and a Server that supports version 1 of the
contract adds the last acknowledged details to each retry claim.
use DurableWorkflow\Exception\ActivityHeartbeatResumeUnavailable;
use DurableWorkflow\Worker\ActivityContext;
$worker->registerActivity('batch.import', function (ActivityContext $context, array $items): int {
try {
$next = $context->lastHeartbeatDetails()['next_item'] ?? 0;
} catch (ActivityHeartbeatResumeUnavailable) {
$next = 0; // Older Server: start over, relying on idempotent item writes.
}
for ($index = $next; $index < count($items); ++$index) {
importItem($items[$index], idempotencyKey: $context->activityExecutionId.':'.$index);
$context->heartbeat(['next_item' => $index + 1]);
}
return count($items);
});lastHeartbeatCheckpoint() returns an ActivityHeartbeatCheckpoint, or null
when the supported claim has no checkpoint, such as a first attempt or a retry
whose earlier attempts recorded none. It throws
ActivityHeartbeatResumeUnavailable when the Server or claim does not carry
the contract, and for local activities and Server-free tests. Unavailable is
never reported as an empty checkpoint.
The checkpoint's details() returns a fresh copy of the acknowledged
details. acknowledgedAt is the original RFC 3339 acknowledgement time and
acknowledgedAtTime() is the same instant in UTC with microsecond precision.
contractVersion and heartbeatResumeVersion() name the negotiated protocol
version. Version 1 has no per-checkpoint write sequence.
The received checkpoint does not change while the attempt runs. A heartbeat from this attempt never updates it, whether the Server acknowledges or refuses the write, or its response is lost. A later attempt receives whatever the Server retained, so a write whose response was lost may still be resumed. An acknowledged heartbeat does not commit an external business effect. Keep using stable idempotency keys and provider reconciliation for effects that can repeat. Retry policy and timeouts are those of the original activity.
A run started by a schedule can read the fire that started it with
$context->scheduleOrigin(). It returns a ScheduleOrigin with the
scheduleId, the occurrenceTime the scheduler evaluated and the
triggerNumber. A run that no schedule started gets null. The value comes
from the run's ScheduleTriggered history event, so it is available on the
first workflow task and identical on replay.
Use occurrenceTime to pick the window a scheduled workflow processes. For a
tick it is the jittered fire time. For a backfill it is the enumerated past
occurrence. It is not the run's actual start time, so it does not drift with
scheduler delay:
$origin = $context->scheduleOrigin();
$windowEnd = $origin?->occurrenceTime ?? throw new LogicException('Start this workflow from a schedule.');
$report = $context->activity('reports.build', [$windowEnd->modify('-1 day')->format(DATE_ATOM), $windowEnd->format(DATE_ATOM)]);occurrenceTime is null for a fire recorded without an occurrence. Whether
continue-as-new successors and retried runs carry the origin depends on the
Server writing ScheduleTriggered into those runs.
WorkflowHandle distinguishes the stable workflow instance from a selected
run. Its ordinary operations follow whichever run is current after a
continue-as-new transition. The *SelectedRun() methods retain the original
run guard and fail rather than silently targeting a successor.
signalWorkflow(), updateWorkflow(), updateWorkflowReceipt() and the
matching handle methods send a request_id with every call. Pass requestId
to choose it, or the SDK generates one per call. The receipt and any
SignalFailed or UpdateFailed carry the key that was sent, so a caller that
lost a response can retry with the same key. The SDK never resends a signal or
update by itself.
On a Server that advertises command_request_keys (native 3.9.0 and later,
$client->clusterInfo()->supportsCommandRequestKeys()), the key is a durable
command key on the workflow instance:
- A retry with the same name, arguments and run target returns the original
receipt and writes nothing. A signal receipt then carries
retained: trueandintent_verified: true. - The same key with a different name, arguments or run target is refused with
409
request_id_conflict. Nothing is written. The exception'sisRequestIdConflict()is true,conflict()lists the parts that differ (name,argumentsortarget_or_arguments) andretainedCommandId()names the original command. Don't retry it unchanged: send the original input to recover the receipt, or use a new key for new input. - A key retained before the Server recorded command intent (a legacy receipt)
reads back the original receipt with
retained: trueandintent_verified: false. The Server can't prove the retry matches it, so it neither admits a new command nor reports equality; check the receipt's identities before treating it as your command. - A key that matches an ambiguous legacy identity (a raw legacy key and a
hashed key, or keys differing only by case on a case-insensitive database) is
refused with 409
request_id_ambiguousandisRequestIdAmbiguous()is true. Nothing is written and no receipt is selected; inspect the original command before sending the input under a new key.
use DurableWorkflow\Exception\SignalFailed;
try {
$handle->signal('approve', ['Grace'], 'approve-order-1');
} catch (SignalFailed $failed) {
if (!$failed->isRequestIdConflict()) {
throw $failed;
}
// $failed->conflict() is ['arguments']; $failed->retainedCommandId() is the original signal.
}Older Servers (PHP Server 2.x and native up to 3.8) don't compare input under a key: a repeated signal key records a second signal, and an update retried with changed arguments returns the original receipt. Keep business-event handling idempotent there.
$handle->update() and Client::updateWorkflow() wait for the update to
complete by default (waitFor: 'completed') and return its decoded result.
If the wait ends first, for example after waitTimeoutSeconds, they throw
UpdateStillPending instead of returning a value. The exception carries
updateId, requestId, workflowId, runId and updateStatus. To keep
waiting, call the same update again with that requestId. The Server returns
the retained update instead of admitting a second one:
use DurableWorkflow\Exception\UpdateStillPending;
try {
$name = $handle->update('rename', ['Grace'], waitTimeoutSeconds: 5);
} catch (UpdateStillPending $pending) {
$name = $handle->update('rename', ['Grace'], requestId: $pending->requestId);
}waitFor: 'accepted' returns the acceptance receipt as before.
updateWorkflowReceipt() always returns the raw receipt.
On a Server that advertises update_outcome_reads (native 3.6.0 and later),
Client::updateOutcome($workflowId, $pending->updateId) reads the same
update's outcome by its id instead, without submitting it again. It waits for
completion by default and returns the decoded result, throws
UpdateStillPending while the update is still running, and throws
UpdateFailed for a failed update or update_not_found. On a Server without
the capability it throws a LogicException rather than resubmitting.
updateOutcomeReceipt() returns the raw receipt.
A pending outcome read preserves the stable updateId and points callers to
updateOutcome() again. The producer may omit the original request key on
this GET path; UpdateStillPending::requestId is then an empty string for
unknown. Continue reading by update id in that case. The original caller key
is retained by the admission-time pending exception; an empty, cached or
internal hashed token cannot stand in for that key.
listWorkflows() and workflowHistory() each read one page. The
iterator API follows the Server's continuation tokens lazily:
foreach ($client->iterateWorkflows(status: 'running', pageSize: 100) as $execution) {
echo $execution->workflowId, "\n";
}
foreach ($client->iterateWorkflowHistory($workflowId, $runId, pageSize: 100) as $event) {
echo $event['sequence'], ': ', $event['event_type'], "\n";
}The list yields WorkflowExecution values; history yields the original event
maps. Both retain one page and fetch the next only when needed. Breaking out
does not prefetch. History stays on the selected run through continue-as-new;
listing follows the Server's ordering and consistency, not a global snapshot.
Missing or invalid page metadata and repeated/cyclic tokens throw
PaginationException with a typed reason. An HTTP error propagates unchanged
and closes the generator. Earlier items may already have been yielded, so
consumers must handle a partial export on failure.
Client::withNamespace() returns an immutable namespace selection that keeps
the configured authentication and transport. Workflow payload encoding remains
Apache Avro. Workflow
visibility results and the newly covered administrative surfaces use SDK model
types while retaining the complete server payload in each model's raw
property.
use DurableWorkflow\Model\ServiceOperationOptions;
$orders = $client->withNamespace('orders-prod');
$page = $orders->listWorkflows(
workflowType: 'orders.process',
status: 'running',
query: 'CustomerId = "42"',
pageSize: 25,
);
$schedulePage = $orders->listSchedules(
status: 'paused',
workflowType: 'reports.rollup',
query: 'Region = "eu-west"',
pageSize: 25,
);
$attributes = $orders->listSearchAttributes();
$orders->createSearchAttribute('OrderTotal', 'double');
$orders->deleteSearchAttribute('TemporaryField');
$orders->setNamespaceExternalStorage(
'orders-prod',
's3',
thresholdBytes: 2 * 1024 * 1024,
config: ['bucket' => 'workflow-payloads'],
);
$operation = $orders->startServiceOperation(
'payments',
'Cards',
'authorize',
['amount' => 4200, 'currency' => 'USD'],
new ServiceOperationOptions(idempotencyKey: 'order-42-authorization'),
);
$call = $operation->describe();
$operation->cancel('customer request');
$cluster = $orders->clusterInfo();listSchedules() returns a typed page with schedules, nextPageToken, and
the original response in raw. It supports server-side status, workflow
type, visibility-query, page-size, and continuation-token filtering. Pass a
non-null nextPageToken back unchanged with the same namespace and filters to
read the next page. See the protocol guide for the paging and error contract.
listWorkers() reads one page of worker registrations. Native Server 3.13.0
and later return at most 100 registrations per page in worker id order with a
next_page_token; older Servers return every registration in one response
without a token. listAllWorkers() follows the tokens with the same filters
for at most Client::LIST_ALL_WORKERS_MAX_PAGES (50) requests by default and
returns the last page with workers holding every registration read.
next_page_token is null when the list is complete and is the unread token
when the page bound stopped the read:
$workers = $client->listAllWorkers(taskQueue: 'orders', status: 'stale');
if ($workers['next_page_token'] ?? null) {
// More registrations remain beyond the page bound.
}startServiceOperation() explicitly starts an asynchronous call and returns a
ServiceOperationHandle. executeServiceOperation() honors the catalog mode,
waits for completion by default, and returns a ServiceOperationDescription.
Arguments use the official Apache Avro payload codec.
ServiceOperationOptions::targetNamespace selects the target of a durable
WorkflowContext::serviceOperation() call. Direct client calls select their
target through $client->withNamespace('billing'). They refuse that workflow
option because Server would otherwise ignore the body field and use the
client's namespace.
The preferred service-mode API discovers handler contracts from ordinary PHP
classes. Attributes name the server contract while method signatures describe
its arguments. Calls on WorkflowContext suspend the workflow's Fiber at each
durable step. Replay resumes that call with its recorded value, or throws its
recorded failure there, without repeating external work.
<?php
declare(strict_types=1);
require __DIR__.'/vendor/autoload.php';
use DurableWorkflow\Attribute\Activity;
use DurableWorkflow\Attribute\Query;
use DurableWorkflow\Attribute\Signal;
use DurableWorkflow\Attribute\Update;
use DurableWorkflow\Attribute\Workflow;
use DurableWorkflow\Client;
use DurableWorkflow\Worker;
use DurableWorkflow\Worker\ActivityContext;
use DurableWorkflow\Worker\QueryContext;
use DurableWorkflow\Worker\WorkflowContext;
final class GreeterWorkflow
{
#[Workflow('greeter')]
public function run(WorkflowContext $context, string $name): array
{
$greeting = $context->activity('greet', [$name]);
return ['greeting' => $greeting];
}
#[Query]
public function status(QueryContext $context): array
{
return ['events' => count($context->history)];
}
#[Signal('set-language')]
public function setLanguage(string $language): void
{
// This declaration is reflected for admission; run() consumes signals.
}
#[Update]
public function rename(QueryContext $context, string $name): string
{
return $name;
}
}
final class GreetingActivities
{
#[Activity]
public function greet(ActivityContext $context, string $name): string
{
return "hello, {$name}";
}
}
$client = new Client('http://server:8080', token: 'dev-token-123');
Worker::create($client, 'php-workers')
->register(GreeterWorkflow::class, GreetingActivities::class)
->run();register() resolves class names and validates every attributed method
before registration or polling. With no container, concrete classes with no
required constructor arguments are instantiated automatically. Pass any PSR-11
ContainerInterface as the third argument to Worker::create() when handlers
have application dependencies.
Attributed workflow classes have a replay-scoped lifecycle. Each workflow task replay, query, and update constructs a new handler. Constructor-created nested state belongs to that invocation, including mutable objects held by readonly properties. Constructors and container factories must be free of external side effects because construction repeats during replay. Perform side effects in activities.
With a PSR-11 container, workflow bindings must return a new instance on every resolution. Dependencies such as API clients, loggers, and configuration may remain shared. Laravel's bridge resolves workflows for each invocation. The Symfony bridge makes attributed workflow services non-shared while retaining their dependencies' configured lifetimes.
Use WorkflowFactory for custom construction or a container that exposes only
singleton workflow services:
use DurableWorkflow\Worker\WorkflowFactory;
$sharedClient = $container->get(ApplicationApiClient::class);
$worker->register(new WorkflowFactory(
static fn (): OrderWorkflow => new OrderWorkflow($sharedClient),
));Create execution-local state inside the workflow constructor or factory. Do not capture a mutable workflow-state object outside the factory and share it among the new handlers. Injected services retain their identity and must not hold execution-local state.
Registration migration: replace register($workflowObject) with class
registration or register(new WorkflowFactory(fn () => new YourWorkflow($dependencies))).
The SDK cannot infer a configured object's construction recipe or distinguish
its nested state from shared services. Reused factory results and singleton
workflow bindings fail validation before polling. A factory that becomes invalid
after startup produces a recoverable workflow_instance_factory_invalid replay
error instead of a terminal workflow completion or failure. Workflow classes no
longer need to be cloneable.
Activity services have worker-scoped lifetimes instead: their resolved instance
is reused for activity tasks, so they can retain clients and other service
resources. The explicit registerWorkflow(), registerQuery(), and
registerUpdate() low-level methods also invoke the supplied callable as-is;
state captured by such a callable remains owned by the application. Neither
registration style makes shared mutable objects safe workflow-local storage.
Pass a PSR-3 LoggerInterface with the named logger argument; lifecycle,
retry, shutdown, and handler failures then use the application's normal logging
pipeline. The optional diagnosticListener receives the same event names and
structured context.
The worker.stopped context includes sticky_cache counters for hit, miss,
eviction and forced_cold_replay over that worker process's lifetime. Clearing
retained history during shutdown preserves these counters. Laravel and Symfony
forward the same context through WorkerDiagnosticEvent. A cache hit still
replays the workflow; these counters do not measure retained live execution.
Signal methods are signature declarations for server admission and are not
invoked. The workflow reads their committed values with
$context->signals('set-language') during replay. Query and update methods are
executed with immutable QueryContext state.
Declare an update validator to refuse a bad request before the update is accepted. Without one, an update that breaks a business rule is accepted first and then fails, and the caller can't tell the bad request from a failed operation.
use DurableWorkflow\Attribute\Update;
use DurableWorkflow\Attribute\UpdateValidator;
use DurableWorkflow\Worker\QueryContext;
final class OrderWorkflow
{
#[Update('approve')]
public function approve(QueryContext $context, int $amount): int
{
return $amount;
}
#[UpdateValidator('approve')]
public function validateApprove(QueryContext $context, int $amount): void
{
if ($amount <= 0) {
throw new \DomainException('The amount must be positive.');
}
}
}#[UpdateValidator] names an #[Update] declared on the same class. The
validator takes a QueryContext followed by the update's arguments. Use
registerUpdateValidator($workflowType, $updateName, $callable) with the
low-level API, after registerUpdate() for the same name.
The worker registers the update in its update_validators contract and
advertises update_validation_tasks. Registration is refused with
update_validation_tasks_unavailable when the Server does not advertise
synchronous update validation. The worker then polls workflow and update
validation tasks together. For each validation task, it runs only the
validator against the run's committed history:
- Returning normally approves the update, and the Server accepts it.
- Throwing, or returning
false, rejects it withupdate_validator_rejected, the exception message and class, and any field errors that anerrors()method on the exception returns. The update is never accepted, its handler never runs and the workflow isn't woken. The Server records the rejection only as anUpdateRejectedaudit event, as it does for other refusals. - A validator that tries to schedule durable work is refused with
UpdateValidatorCommandRefused, which rejects the update. Validators readQueryContextstate and never emit commands.
Validators aren't recorded in history and never run during replay, so they don't affect determinism. The same committed history gives the same decision.
Each validation sees only the history committed before its own task. Two
validations running at the same time therefore can't see each other's
updates, and both can pass a check that only one of them should. The
validator runs in its own Fiber, so a library that suspends Fibers can't be
used inside it. Worker interceptors wrap each validation task through
executeUpdateValidation(), which observes but can't change the decision
(see Worker interceptors). A validator worker doesn't
use carried or prefetched workflow polls, so validation tasks keep their turn.
updateWorkflow() throws UpdateFailed for a rejected update.
rejectedByValidator() is true for a validator rejection, and
validationErrors() returns its field errors. validationFailed() is true
when the Server couldn't get a decision, for example because no capable worker
answered in time; nothing was accepted, so retry with the same request ID.
The worker replays a workflow from its history on every workflow task, so an
ordinary logger call in workflow code repeats once per completed step. A
workflow with 50 steps logs its opening line 50 times. Use
$context->logger() instead:
use DurableWorkflow\Worker\WorkflowContext;
function approve(WorkflowContext $context, string $orderId): string
{
$context->logger()->info('Approval started', ['order_id' => $orderId]);
$decision = $context->activity('review', [$orderId]);
$context->logger()->info('Review finished', ['decision' => $decision]);
return $decision;
}logger() returns a PSR-3 LoggerInterface. It writes through the logger you
pass to the Worker (the named logger argument) only when the code runs past
the run's committed history, that is, for the first time. Each line gets
namespace, workflow_type, workflow_id and workflow_run_id in its
context. Without a Worker logger, and in offline Replayer runs, it writes
nothing.
$context->replayState() returns a WorkflowReplayState: Replaying while
code re-runs over committed history, Executing past it, and Unavailable
outside the workflow's own Fiber. isReplaying() is the boolean form. Use them
for diagnostics only; never choose workflow commands from them.
Lines are written after the worker submits the workflow task that ran the code. A replay that is superseded, speculative and declined, or refused writes nothing, and code that parks on a pending child or operation handle without recording a step logs once, in the task that moves past it. If the worker dies between the Server accepting a task and the write, those lines are lost; the logger is not an outbox for business effects. Keep log handlers fast and non-blocking, because a handler that waits on the network stalls the worker. Logger failures are caught and never change the workflow's commands.
When replay finds a mismatch at a suspended workflow call,
NonDeterministicWorkflow::workflowSource() reports the authored function or
method, source filename, and line. A blocked worker task includes the same
location in its failure message.
To inspect a captured history offline, pass its events, the original workflow arguments, and the current workflow callable to the replayer.
use DurableWorkflow\Codec\AvroPayloadCodec;
use DurableWorkflow\Exception\NonDeterministicWorkflow;
use DurableWorkflow\Worker\Replayer;
try {
(new Replayer(new AvroPayloadCodec()))->replay(
[$workflow, 'handle'],
$historyEvents,
$input,
'approvals',
);
} catch (NonDeterministicWorkflow $failure) {
$location = $failure->workflowSource();
if ($location !== null) {
printf("%s (%s:%d)\n", $location['function'], $location['file'], $location['line']);
}
}For example, ApproveOrder::reserve (ApproveOrder.php:42) points to the
call to review alongside the workflow sequence and expected shape. The
filename omits its directory. A mismatch without a suspended authored call
may have no source location.
signals() returns only signals the Server has applied to the run, plus the
signal the current workflow task delivers, in the order the Server received
them. The Server applies signals in message order with updates, so an update
sent before a signal is applied first. A signal that has been received but not
yet applied is not returned, and one the Server rejects (for example because
the run closed first) never is.
Earlier SDK releases returned every received signal, so the applied-only view
is versioned with the marker durable-workflow.sdk-php.signals-applied-only.
The worker records it the first time hiding an unapplied signal changes what
signals() returns to a live decision: a call at the end of the recorded
history, or the predicate of a condition wait whose outcome is not recorded.
A history without the marker replays with every received signal visible. With
the marker, live decisions and calls replayed at or after the marker's sequence
use the applied-only view, and calls replayed before it keep the earlier view.
A run that never meets an unapplied signal records no marker.
Workflow code signals another workflow with
$context->signalExternalWorkflow($workflowId, $signalName, $arguments, runId: null),
or $child->signal() on a started child's handle. It is a durable
signal_external_workflow command: the runtime records and delivers it and
records the outcome, and the call returns an ExternalSignalResult whose
outcome is delivered, target_not_found, target_closed or rejected
with a reason. A failed outcome is a returned value, not an exception. Replay
returns the recorded result without sending the signal again, and a changed
target, run, name or arguments fails replay with external_signal_mismatch.
The worker refuses the command with signal_external_workflow_unavailable
before submitting it when the runtime does not advertise
signal_external_workflow; native Server 3.15.0 and later advertise it.
Client::signalWithStart() likewise needs native Server 3.15.0 or later,
which advertises signal_with_start, and throws ServerCapabilityUnavailable
before sending anything on an older Server.
The PHP SDK does not expose update-validator authoring. Worker registration
therefore declares an empty update_validators list for every workflow type;
capability discovery and Server admission must not infer validator parity from
the presence of ordinary update handlers.
The callable registration methods remain the intentional low-level escape hatch. For example, replay-consumed signals can be declared directly:
$worker->declareSignal(
'counter',
'increment',
static fn (int $amount): mixed => null,
);Call $context->heartbeat($details) from a long-running activity. It throws
ActivityCancelled when the server requests cancellation. Worker::run()
installs SIGINT/SIGTERM handlers when pcntl is available, stops accepting new
tasks, and lets the active synchronous task settle before returning. The
managed worker also returns when any task poll reports a server stop or drain
(draining or stopped); empty and timeout polls remain idle. If the Server
reports stale_worker_registration, for example after a host pause or network
partition longer than the registration-freshness window, run() drops the
fenced claims, registers again and keeps polling. It logs worker.reregistered
with short fingerprints of the old and new incarnation and increments the
durable_workflow_worker_reregistrations counter. Construct the worker with
stopOnStaleRegistration: true to keep the earlier stop behavior. Registration also negotiates the worker heartbeat cadence.
Managed long polls are bounded by that cadence and heartbeat checks run between
workflow, activity, and query polls, so an idle polling cycle cannot silently
consume the server's registration freshness window. Invalid advertised cadence
values leave the worker's configured safe fallback in effect.
Low-level worker integrations can call pollWorkflowTaskResponse(),
pollActivityTaskResponse(), and pollQueryTaskResponse() to receive the
complete server envelope, including poll_status, reason, protocol metadata,
and any future fields. The existing task-only poll methods delegate to these
response methods and still return the leased task or null. Use
DurableWorkflow\Worker\PollResponse::isTerminal() to apply the same typed
terminal-outcome classification as the managed worker.
When a poll fails with a complete worker-protocol envelope explicitly marked as
transient, the managed worker retries that same poll with capped backoff while
keeping heartbeats and graceful shutdown responsive. Pass a
transientPollRetryObserver callback to the Worker constructor to record the
task kind, consecutive attempt, selected delay, and typed server exception.
Authentication failures, malformed responses, and other definitive refusals
remain fatal.
run() keeps running through a Server restart or a database failover. The
managed worker treats these answers as an outage, not a refusal:
- a connection that can't be made, is reset or times out;
- HTTP 500, 502, 503 or 504 whose body names no reason or only the generic
server_errorreason, whatever else the body holds (an HTML or JSON error page from a load balancer, or native Server'sserver_errorwhile it can't read its database during a failover); - 503
storage_unavailableorbackend_unavailable.
Workflow, activity and query polls, worker, workflow-task and activity
heartbeats, completions, failure reports and query answers are repeated through
an outage with the same identity: the same poll request ID, or the same task,
attempt and lease. The Server's lease fence then decides a request it may
already have recorded. A repeated activity completion is answered by its
committed receipt. A repeated failure report or query answer that the Server
refuses with a 409 for the same task is settled: the Server already owns the
outcome, and the worker logs worker.outcome_already_settled. Handlers never
run again because of an outage. With enableCooperativeCancellation, a
supervised activity's heartbeat() is repeated the same way, and its reply
must still match the original task, attempt and lease and allow the activity to
continue.
Retries wait on a jittered exponential schedule: up to 0.25 s, doubling to a
4 s ceiling. A wait is never shorter than the Server's Retry-After (header in
delta-seconds or HTTP-date form, or a retry_after_seconds body field), capped
at 60 s. A completion, failure report or heartbeat inside a claim stops
retrying when its lease grant ends, or after eight retries without lease
maintenance. The task is then left to the Server, which delivers it again when
the lease expires, and the worker keeps polling. worker.retrying is logged at
warning level for each retry, and worker.outage_persisting at error level
once an outage lasts 60 s, then every 5 minutes.
These still stop the worker: an explicit retryable: false, authentication and
authorization failures, other 4xx refusals, 501 and other 5xx statuses, and
typed refusals that fail their own protocol checks (such as backend_lock_pressure
without a valid retry_after_seconds). Task-offer 409 refusals, storage
admission refusals and the completion size and history limits keep their
documented handling.
WorkflowContext::replayNow() returns a replay-safe UTC DateTimeImmutable
that advances with consumed history. Every replay of the same history returns
the same values, so workflow code can use it for deadlines and elapsed time.
- At workflow entry, before any durable step, it returns the run's start
from the workflow task's
replay_clockcarrier (WorkerReplayClockv1, sent by Server 3.6.0 and later). A redrive successor whose history proves the original start uses that start. - After a supported durable step (an activity, a plain timer, a child workflow, a condition wait, including one satisfied by signals, or a validated all-group of those) it returns that step's recorded time.
- Repeated reads between two durable steps return the same value.
A deadline loop around a durable timer therefore terminates, and the difference between two reads taken after two durable steps is their recorded elapsed time:
$deadline = $context->replayNow()->modify('+1 hour');
while ($context->replayNow() < $deadline) {
if ($context->activity('orders.poll', [$orderId])) {
return 'ready';
}
$context->sleep(60);
}
return 'timed out';Where the SDK cannot prove a time, replayNow() throws
DurableWorkflow\Exception\ReplayClockUnavailable instead of using wall time or
any other value. An unhandled ReplayClockUnavailable fails the workflow. The
clock is unavailable:
- at entry when the task carries no valid
replay_clock(Servers older than 3.6.0, or a run whose start the Server cannot prove); - after inline and local operations:
sideEffect(), version markers (getVersion()), local activities, memo or search-attribute upserts and any other command that is not a supported durable step (for example thestartChildWorkflow()handle). These stay unavailable until the platform defines a persisted time for those steps; - inside
waitCondition()predicates andparallel()/all()builder closures; - after group modes other than the validated all-groups;
- inside query, update and update-validator handlers;
- once cancellation is requested, and inside a cancellation scope.
Queries, updates and update validators read history snapshots and never re-run the workflow body, so a body that reads the clock at entry cannot diverge from what its workflow task computed.
Do not use timestamps to order emitted events. Order them by stream offset, outbox sequence or a workflow-local counter.
Upgrading: earlier releases reported replayNow() as unavailable at
entry. A running workflow whose code branches on that, for example by
catching ReplayClockUnavailable at entry and taking another path, takes the
other branch when it replays on the new SDK. The same happens during a rolling
deploy that mixes SDK versions, or when the Server is upgraded to 3.6.0 or
later. Version such code or drain those runs before you upgrade.
SDK 3.10.0 can request the next task on a task completion when the runtime
advertises the matching capability: workflow_task_completion_activity_poll,
activity_completion_workflow_poll, or workflow_task_completion_workflow_poll.
The Worker reserves a free slot for that task kind. Workflow carriers request
only workflow tasks; when both carriers are sent, activity dispatch has priority.
An embedded lease uses the ordinary payload, history and lease-supervision path without sending or recording another poll. A lease reported without its answer uses an ordinary follow-up with the original carried request ID. An omitted result in a successful completion releases the reservation unless an earlier attempt has an uncertain outcome. It does not mark the queue empty. Lost completion acknowledgements retain the original request ID for recovery. Grant freshness includes the original completion transit and time spent waiting to dispatch. Shutdown finishes a known delivered lease before returning. Runtimes without the capability keep the ordinary polling path.
Each command's arguments must fit the Server's per-payload limit
(DW_MAX_PAYLOAD_BYTES, 2 MiB by default). Server 3.6.0 also bounds a whole
workflow-task completion that carries commands at 16 payload limits, 32 MiB by
default, so a large fan-out of small commands completes. A larger completion is
refused with 413 payload_too_large and limit_kind: workflow_task_completion_bytes before the Server reads it.
The PHP Worker raises WorkflowTaskCompletionTooLarge, a ServerException
with limitBytes (the Server's limit) and sizeBytes (the encoded size of
the completion it sent). Replaying the task would produce the same commands, so
the Worker never sends that completion again. It completes the same task once
with a fail_workflow command whose message starts Structural limit exceeded: workflow_task_completion_bytes: and names both sizes, and logs
worker.workflow_task_completion_too_large. The run fails with
failure_category: structural_limit; it is not retried and not recorded as a
replay block. If that small completion is refused too, the error surfaces as
any other completion error.
To stay within the limit, split the fan-out into smaller batches across
workflow tasks, move work into child workflows, or continue as new, and offload
large payloads with external payload storage. An activity continuation that is
refused the same way falls back to an ordinary activity completion; the run's
own workflow task then reports the limit. Other 413 responses and 5xx errors
keep their existing ServerException behavior.
The Server records a completion in one history transaction, bounded by its
history_transaction_size (events), history_transaction_bytes and
history_transaction_rows structural limits. ActivityScheduled events repeat
their arguments, so a fan-out that fits the completion size limit can still
exceed a lowered DW_V2_LIMIT_HISTORY_TRANSACTION_BYTES. Native Server 3.13.0
defaults that budget to four times the completion size limit, and refuses a
completion over it with 409 history_transaction_limit_exceeded, naming
limit_kind, the measured current_value and the configured_limit. The
transaction rolls back, so nothing is recorded.
The PHP Worker raises WorkflowTaskHistoryLimitExceeded, a ServerException
with limitKind, currentValue and configuredLimit (null when the Server
does not report them; limitKind is then the refusal reason, which may also be
completion_budget_exceeded). It handles the refusal like the oversized
completion above: it never resends the completion, completes the same task once
with a non-retryable fail_workflow command whose message starts Structural limit exceeded: <limit kind>:, and logs
worker.workflow_task_history_limit_exceeded. The run fails with
failure_category: structural_limit. Replaying that history reproduces the
refused commands; it is not a replay block. A refused activity continuation
falls back to an ordinary activity completion. Other 409 responses keep their
existing behavior.
Pass ordered interceptors to Worker::create() (or the Worker
constructor) to add audit logging, metric tags, tenant context or tracing
around every task once, instead of in each handler. Each interceptor
implements DurableWorkflow\Worker\Interceptor\WorkerInterceptor; extend
PassthroughWorkerInterceptor to implement only the hooks you need. The first
interceptor is the outermost wrapper, and each hook calls $next($context) to
continue the chain.
use DurableWorkflow\Worker;
use DurableWorkflow\Worker\Interceptor\ActivityInterceptorContext;
use DurableWorkflow\Worker\Interceptor\PassthroughWorkerInterceptor;
use DurableWorkflow\Worker\Interceptor\WorkflowTaskInterceptorContext;
use DurableWorkflow\Worker\Interceptor\WorkflowTaskOutcome;
use Psr\Log\LoggerInterface;
final class AuditInterceptor extends PassthroughWorkerInterceptor
{
public function __construct(private readonly LoggerInterface $audit)
{
}
public function executeWorkflowTask(WorkflowTaskInterceptorContext $context, callable $next): WorkflowTaskOutcome
{
$outcome = $next($context);
$this->audit->info('workflow task', [
'workflow_id' => $context->workflowId,
'workflow_type' => $context->workflowType,
'attempt' => $context->workflowTaskAttempt,
'replayed_history' => $context->replaying,
'commands' => $outcome->commandTypes(),
]);
return $outcome;
}
public function executeActivity(ActivityInterceptorContext $context, callable $next): mixed
{
$this->audit->info('activity started', [
'activity_type' => $context->activityType,
'attempt' => $context->attemptNumber,
'workflow_id' => $context->workflowId,
]);
try {
return $next($context);
} finally {
$this->audit->info('activity finished', ['activity_type' => $context->activityType]);
}
}
}
$worker = Worker::create($client, 'orders', container: $container,
interceptors: [AuditInterceptor::class]);Pass instances or class names. Class names are resolved from the PSR-11 container passed to the worker, the same way attributed handlers are; without a container a class name must have no required constructor arguments.
| Hook | Context | $next returns |
|---|---|---|
executeWorkflowTask($context, $next) |
workerId, taskQueue, namespace, task, taskId, workflowType, workflowId, runId, workflowTaskAttempt, historyLength, replaying (also replayState()), updateId, observabilitySupported |
WorkflowTaskOutcome with a copy of the commands |
executeActivity($context, $next) |
workerId, taskQueue, namespace, task, activityType, arguments, attemptNumber, taskId, activityAttemptId, workflowId, runId, local, activityContext, observabilitySupported |
the activity result |
executeQueryTask($context, $next) |
workerId, taskQueue, namespace, task, taskId, workflowType, queryName, workflowId, runId, arguments, queryContext, observabilitySupported |
the query result |
Workflow-task interceptors cannot break determinism:
executeWorkflowTaskwraps the run of workflow code that produces one workflow task's commands, once per task attempt.replayingistruewhen the delivered history already holds commands recorded by earlier workflow tasks, so the workflow code re-ran that committed prefix before reaching new code.replayState()reports the same thing as theWorkflowReplayStatethatWorkflowContext::replayState()uses:ReplayingorExecuting. The outcome holds only the commands this task adds; replayed commands are never resubmitted. A retried attempt (workflowTaskAttempt > 1) can repeat an outcome whose task failed, so make external audit writes idempotent.- Update tasks (
updateIdset) run the update handler against committed state without re-running the workflow body; for themreplayingonly reports that earlier commands exist. - The worker submits exactly the commands the workflow code produced. The
outcome is a copy; returning a different outcome, or passing a different
context to
$next, changes nothing. - A failure from the workflow code reaches the worker unchanged, even if an interceptor catches it and returns normally.
- An exception thrown by an interceptor fails the workflow task. Nothing is
recorded and the Server retries the task. Skipping
$next, or calling it more than once, fails the task withWorkflowTaskInterceptorViolation.
Update-validation interceptors (executeUpdateValidation()) wrap the run of
an update's validator before the Server accepts the update. They see the
task in UpdateValidationInterceptorContext and the decision as a read-only
UpdateValidationOutcome (approved, reason, message, failureType,
validationErrors). They cannot change the decision, the update's arguments
or the history the validator reads: the validator always runs read-only in
its own Fiber with the Worker's copy of the task, and the Worker answers with
the validator's own decision. An exception from the interceptor, or skipping
or repeating $next (UpdateValidationInterceptorViolation), answers the
task with update_validation_worker_failed, so the update is not accepted and
the caller can retry.
Activity and query interceptors may change arguments with
$context->withArguments(...) and may change the returned value, because
activity results are recorded once and queries record nothing. Activity
exceptions pass through every interceptor unless one handles them. Activity
interceptors wrap remote and local activities (local tells them apart). With
cooperative cancellation, remote, cooperative local and prepared local activity
callbacks and their interceptors run in the activity's child process, so memory
changes there do not reach the worker process. When interceptors are
configured, enableActivityContinuation keeps the ordinary activity completion,
so every workflow task still runs through executeWorkflowTask. When tracing is configured, the built-in worker spans stay
outermost, so interceptors run inside the active task span.
In Laravel and Symfony service mode, list interceptor classes under
worker.interceptors; they are resolved from the framework container in that
order:
// config/durable-workflow.php
'worker' => [
'interceptors' => [App\Durable\AuditInterceptor::class],
],# config/packages/durable_workflow.yaml
durable_workflow:
worker:
interceptors:
- App\Durable\AuditInterceptorWorker::create($client, $taskQueue, enableCompletionPipelining: true) allows
managed run() to overlap a completion response with useful work on one
already-leased workflow. The option defaults to false in both create() and
the constructor. Public tick() remains synchronous.
After successful local activity work, the Worker first makes an ordinary zero-timeout workflow poll. If it leases a task, the owned default cURL transport may suspend the current completion after sending its full request body. The Worker runs the leased task, then joins the original response before publishing the next task's completion or failure. It retains the original lease owner, attempt, grant deadline and poll transit time. A held or uncertain workflow slot prevents another completion-carried workflow poll.
Activity-scheduling, cancellation, retained local failures, telemetry and metrics keep their synchronous behavior. Cooperative cancellation mode, injected HTTP clients, streamed requests, progress callbacks and an earlier discovery or payload request also keep completion I/O synchronous. The transport arm belongs to one Fiber and is consumed by its first request; retries cannot suspend it again.
Opting in changes when a completion refusal becomes visible: useful work on the next leased task may have run before the refusal arrives. Worker registration or authentication refusal prevents that task's publication. An identity-bound lost claim is released as usual; other deferred failures remain errors. Shutdown settles a known leased task and creates no further prefetch. No throughput improvement or default change is claimed.
The managed Worker starts a separate PHP CLI maintenance process when the
runtime registration advertises activity_lease_renewal. It renews only the
original activity attempt and reports the Worker slots as busy. Ordinary
activity code still runs in the original Worker process, including captured
memory, dependency-injected services and application-owned connections.
Maintenance carries the original namespace, queue, task, run, execution,
attempt and owner. It cannot extend recorded activity/workflow deadlines,
change an attempt or reset the original TTL of a required worker session.
Actual application heartbeats can advance only their recorded progress
interval. Runtime pings do not record progress or add heartbeat history events.
A renewal that reports no progress yet never extends the claim's heartbeat
deadline. A heartbeat reply without heartbeat_deadline_at advances it by the
original heartbeat_timeout only.
An activity with a heartbeat timeout must still call $context->heartbeat().
Slow or failed renewal. The claim is first held under the poll's own grant, measured conservatively from when the poll started. If a renewal does not reach a definite answer (timeout, connection failure, 5xx or 429), the Worker keeps working under that grant and retries. Every SDK uses the same retry schedule: 0.25 s, doubling to a 4 s cap, with full random jitter (each delay is uniform between zero and the cap), and never more than a third of the remaining grant. Once only a reserve of min(10 s, a fifth of the grant) is left, maintenance gives the claim up. A refusal from the Server (a 4xx, such as a cancelled run or activity) is the Server's decision: the Worker stops publishing for that attempt and sends nothing.
Releasing a claim. A claim that maintenance gave up is released through
POST /fail as a retryable failure with type worker_lost, the reason code
every SDK uses, and class DurableWorkflow\Worker\ActivityWorkerLost. It is
released only after the activity's execution has confirmed stopped (the inline
callback returned, or never started), and only before the grant ends. If
execution cannot be confirmed stopped in time, nothing is sent and the Server's
lease expiry records lease_expired, so two executions never overlap.
ActivityFailed::leaseLossReason() returns worker_lost, lease_expired or
worker_deregistered.
The helper exits when its owning process dies or its private input closes. Server recovery then uses the last acknowledged lease and recorded retry policy. Ordinary inline PHP callbacks cannot be forcibly stopped safely by this helper. If authority is lost, the managed Worker and its captured Client reject late completion/failure publication even when application code catches an earlier refusal. External side effects still need application idempotency.
PHP CLI must permit proc_open. The default HTTP transport and static worker
credentials need no extra setup. Custom PSR-18 clients, middleware, TLS/CA
configuration or dynamic authentication require a trusted bootstrap file that
returns a fresh Client for the same runtime URI, namespace and protocol:
// lease-client.php: recreate the same HTTP/auth settings used by the Worker.
return new DurableWorkflow\Client(
getenv('DURABLE_WORKFLOW_SERVER'),
namespace: 'orders',
workerToken: getenv('DURABLE_WORKFLOW_WORKER_TOKEN'),
transport: new DurableWorkflow\Transport\Psr18Transport(
new GuzzleHttp\Client(['verify' => getenv('COMPANY_CA_BUNDLE')]),
),
);Configure the original Client before constructing the Worker:
$client = $client->withActivityLeaseBootstrap(__DIR__.'/lease-client.php');The file runs in the helper, so create new transport/authentication objects there. Do not return inherited database or HTTP handles. Worker credentials and claim metadata travel over the private input pipe, not command arguments. The SDK refuses custom configurations without this bootstrap rather than silently replacing their TLS, proxy or authentication behavior. Runtimes that do not advertise the capability retain their existing lease behavior.
Inbound Message Streams deliver repeated, ordered application input to a stable
workflow instance. The application appends a stable message identity through
WorkflowHandle::appendMessage(), while workflow code consumes one message or
a bounded ordered batch through messageStream(). Runtime-owned cursors survive
replay, worker replacement, server restart, and continue-as-new.
See the task-oriented Message Streams guide and the shipped client and worker examples.
Patched Laravel ^12.72.0|^13.41.0 applications auto-discover the provider from
the SDK package. The bridge requires PHP ^8.2, with PHP 8.3 or newer for
Laravel 13. The provider refuses unsupported or unknown installed framework/PHP
versions before registering config, clients or workers. Upgrade PHP and Laravel
before adopting this bridge. The bare SDK's PHP ^8.1 support remains independent.
Publish the environment-backed configuration, add attributed handler services,
and start the supervised Artisan command. The worker process needs ext-pcntl;
the command refuses to start without it so SIGINT and SIGTERM always drain
cleanly. Composer only suggests the extension, and the official php:*-cli
images do not include it:
composer require durable-workflow/sdk
php artisan vendor:publish --tag=durable-workflow-config
php artisan config:cache
php artisan durable-workflow:workerSet DURABLE_WORKFLOW_RUNTIME_URL to a self-hosted Server origin or the complete
Cloud runtime base URI. Set DURABLE_WORKFLOW_NAMESPACE and
DURABLE_WORKFLOW_TASK_QUEUE, then choose shared-token or scoped authentication.
For scoped Cloud authentication, inject credentials at the process boundary:
| Laravel process | Inject | Do not inject |
|---|---|---|
| Web, queue, or other application process | DURABLE_WORKFLOW_CLIENT_TOKEN |
DURABLE_WORKFLOW_WORKER_TOKEN |
php artisan durable-workflow:worker |
DURABLE_WORKFLOW_WORKER_TOKEN |
DURABLE_WORKFLOW_CLIENT_TOKEN |
The service provider gives the injectable application interfaces only the client
credential and creates a separate worker client only for the worker factory.
For a self-hosted deployment that uses one credential for both roles, inject
DURABLE_WORKFLOW_TOKEN instead. Supply secret values through the deployment
platform's process environment or secret store, not a generated configuration
file or a committed .env file.
The published configuration deliberately has no credential entries. Build and
deploy one cached configuration without any Durable Workflow credential in the
cache-building environment, then inject only the required role credential when
each application or worker process starts. Resolving either documented client
interface is credential-lazy; the provider resolves the client credential when
the interface performs its first application-client operation, after Laravel has
loaded the cache. Resolving Client directly is the explicit eager low-level
path and validates the application credential immediately.
Applications upgrading an older published configuration should republish it or
remove its credentials block before rebuilding the cache. List handler classes
in config/durable-workflow.php:
'handlers' => [
App\Workflows\GreeterWorkflow::class,
App\Activities\GreetingActivities::class,
],Laravel resolves every handler through its container, so ordinary constructor
injection works. Inject LaravelWorkflowClientInterface to start an attributed
workflow service class on the configured default queue; explicit IDs and
WorkflowStartOptions remain available. Inject WorkflowClientInterface for
low-level cross-language string contracts; like the Laravel-shaped interface,
it is safe to constructor-inject into services that may be discovered by a
worker-only Artisan process. Inject Client directly only when eager application
credential validation and its broader concrete API are intentional.
Worker diagnostics use Laravel's PSR logger and dispatch
WorkerDiagnosticEvent through Laravel events. The event name is available in
its name property and includes lifecycle, retry, handler-failure, and shutdown
events. After server registration, Artisan prints a registered-and-polling line
with the runtime host, namespace, queue, workflow and activity types, and
credential role; it never includes credential values.
In a Laravel test, DurableWorkflow::fake() replaces the class-shaped Laravel
client and its low-level transport. It returns LaravelWorkflowClientFake for
result setup and service-class interaction assertions:
$workflows = DurableWorkflow::fake()
->setWorkflowResult('greeting-1', ['greeting' => 'hello, Ada']);
// Exercise application code, then use the framework-independent assertions.
$workflows->assertWorkflowStarted(GreeterWorkflow::class, ['Ada']);Symfony 6.4, 7, and 8 applications register the Bundle from the SDK package in
config/bundles.php:
return [
// ...
DurableWorkflow\Bridge\Symfony\DurableWorkflowBundle::class => ['all' => true],
];Configure Server or Cloud through environment processors. Attributed services
under Symfony's normal autoconfigured imports are registered as handlers. The
optional handlers list also registers classes outside those imports as
autowired services:
# config/packages/durable_workflow.yaml
durable_workflow:
endpoint: '%env(DURABLE_WORKFLOW_RUNTIME_URL)%'
namespace: '%env(DURABLE_WORKFLOW_NAMESPACE)%'
task_queue: '%env(DURABLE_WORKFLOW_TASK_QUEUE)%'
credentials:
control_token: '%env(default::DURABLE_WORKFLOW_CLIENT_TOKEN)%'
worker_token: '%env(default::DURABLE_WORKFLOW_WORKER_TOKEN)%'
handlers:
- App\Workflow\GreeterWorkflow
- App\Activity\GreetingActivitiesInject DURABLE_WORKFLOW_CLIENT_TOKEN only into web and other application
processes. Inject DURABLE_WORKFLOW_WORKER_TOKEN only into the process running
php bin/console durable-workflow:worker; the default:: processors leave the
opposite scoped credential unset. The Bundle binds the public autowired client
to the client credential and gives its private worker client only the worker
credential. Self-hosted deployments can instead set credentials.token from
DURABLE_WORKFLOW_TOKEN and inject that shared credential into both
processes. Keep values in the deployment platform's environment or secret store,
not YAML, generated container files, or committed environment files.
Run php bin/console durable-workflow:worker. Client and
WorkflowClientInterface are public autowired services. Handler services retain
normal Symfony autowiring, worker messages use the standard PSR logger when it
is installed, and WorkerDiagnosticEvent is dispatched through Symfony's event
dispatcher under the diagnostic name. A KernelTestCase can use
InteractsWithDurableWorkflow::fakeDurableWorkflow() to replace the autowired
interface with the same assertion-capable fake used by plain PHP and Laravel.
Both console commands accept --queue and --poll-timeout. They require
ext-pcntl so SIGINT and SIGTERM always request a graceful worker shutdown.
Configuration errors, an unreachable endpoint, rejected credentials, and
worker-protocol or contract mismatches are reported with remediation specific
to the failing boundary. Neither bridge stores workflow state or installs the
embedded Laravel workflow engine.
The testing namespace has no PHPUnit dependency. Its assertions throw
DurableWorkflow\Testing\AssertionFailed, so they work with PHPUnit, Pest, or
plain PHP. Application services can type their dependency as
WorkflowClientInterface; both the network Client and WorkflowClientFake
implement that interface and return handles with the same interaction methods.
use DurableWorkflow\Testing\WorkerTestHarness;
use DurableWorkflow\Testing\WorkflowClientFake;
$worker = Worker::create($client, 'php-workers')
->register(GreeterWorkflow::class, GreetingActivities::class);
$handlers = new WorkerTestHarness($worker);
$handlers->assertWorkflowEmits('greeter', 'schedule_activity', ['Ada']);
$handlers->assertActivityResult('greet', 'hello, Ada', ['Ada']);
$handlers->assertQueryResult('greeter', 'status', ['events' => 0]);
$handlers->assertUpdateResult('greeter', 'rename', 'Grace', ['Grace']);
$handlers->assertRegistered('signal', 'set-language', 'greeter');
$workflows = (new WorkflowClientFake())
->setQueryResult('greeting-1', 'status', 'running')
->setUpdateResult('greeting-1', 'rename', 'accepted')
->setWorkflowResult('greeting-1', ['greeting' => 'hello, Ada']);
$handle = $workflows->startWorkflow('greeter', 'greeting-1', 'php-workers', ['Ada']);
$handle->signal('set-language', ['en']);
$handle->query('status');
$handle->update('rename', ['Grace']);
$handle->result();
$workflows->assertWorkflowStarted('greeter', ['Ada']);
$workflows->assertSignalSent('greeting-1', 'set-language', ['en']);
$workflows->assertQueryRequested('greeting-1', 'status');
$workflows->assertUpdateRequested('greeting-1', 'rename', ['Grace']);
$workflows->assertResultRequested('greeting-1');Workflow tasks require a fresh, identity-bound runtime grant or an acknowledged lease renewal before user code runs. Typed transient renewal pressure is retried with the original task ID, attempt, and lease owner; shutdown or a terminal/lost lease prevents task execution and completion.
See examples/, the authored
PHP developer portal, the generated
API reference, and
docs/protocol.md for the complete client, schedule,
namespace, visibility, search-attribute, service-operation, discovery,
authentication, worker, query, and update surfaces.
composer install
composer validate --strict
composer test
composer analyse
composer docsThe dependency-boundary check rejects Laravel, Illuminate, the embedded workflow package, and the standalone server package in both declared and resolved production dependencies.