Laravel PHP and Laravel Rust Workflows, Side by Side
Your team is building the new service in Laravel for Rust. The Laravel PHP application is not going away for a year. It owns the invoices, the ledger and the customer tables, and the rules around them took years to get right. Until it is retired, the two applications share business processes.
This post shows how to connect them with Durable Workflow: a PHP workflow that hands heavy work to a Rust activity, a Rust workflow that writes through PHP activities, and what each side gets from the runtime between them. Here is the whole idea in two pairs of files.
At a glance
A PHP workflow in the Laravel app calls an activity that the Laravel for Rust app implements:
// Laravel PHP: app/Workflows/InvoicePdfWorkflow.php
#[Workflow('billing.invoice_pdf')]
public function run(WorkflowContext $context, int $invoiceId): array
{
$document = $context->activity('billing.load_invoice', [$invoiceId]);
$rendered = $context->activity(
'billing.render_invoice_pdf',
[$document],
['queue' => 'rust-workers', 'start_to_close_timeout' => '5 minutes'],
);
$context->activity('billing.attach_invoice_pdf', [$rendered]);
return $rendered;
}
// Laravel for Rust: src/main.rs
worker.register_typed_activity(
"billing.render_invoice_pdf",
|_ctx, doc: InvoiceDocument| async move {
// Lay out and write the PDF.
Ok(RenderedInvoice {
invoice_id: doc.invoice_id,
path: format!("invoices/{}.pdf", doc.invoice_id),
})
},
);
And the reverse: a Rust workflow calls an activity that the PHP app implements with Eloquent:
// Laravel for Rust: src/main.rs
worker.register_typed_workflow(
"billing.close_invoice",
|ctx, invoice: CloseInvoice| async move {
let posted: Posted = ctx
.activity_typed_with_options(
"legacy.ledger.post_invoice",
ActivityOptions::new().task_queue("php-workers"),
LedgerPosting::from(&invoice),
)
.await?;
Ok(posted)
},
);
// Laravel PHP: app/Activities/LedgerActivities.php
#[Activity('legacy.ledger.post_invoice')]
public function postInvoice(ActivityContext $context, array $posting): array
{
$entry = LedgerEntry::createOrFirst(
['operation_key' => $posting['operation_key']],
[
'customer_id' => $posting['customer_id'],
'total_cents' => $posting['total_cents'],
],
);
return ['ledger_entry_id' => $entry->id];
}
Neither application calls the other. Each workflow names an activity and a task queue. The Durable Workflow runtime records the call in the workflow's history, gives the task to a worker in the other application, and records the result. Complete versions of both pairs follow below.
One process, or several applications
Inside one Rust process, async code can already coordinate work: spawn tokio tasks, join them, retry in a loop. That state lives in the process. When the process stops for a deploy or a crash, the tasks stop with it.
Laravel for Rust also has durable workflows of its own. A #[workflow] struct's
handle method records each run.step in a store and resumes from the last
recorded step, advanced by the application's queue jobs. For processes that
live inside one Laravel for Rust application, that is a good fit, and it can
run beside Durable Workflow in the same application. See
Coming from Laravel workflows (Rust)
for how the two map to each other.
Production processes rarely live in one application. Here the invoice data is
in the PHP application's database, the PDF renderer is in the Rust service,
and the result has to go back to PHP. A run.step runs a Rust future inside
the Rust application, so the PHP half of the process would still need its own
integration.
Durable Workflow is the layer between applications. One runtime, a self-hosted Server or a Cloud namespace, keeps the history. Workers in PHP and in Rust connect to it and execute the steps written in their language. A workflow can start in either application, call activities in both, and continue after either application restarts.
Move one job to Rust without writing glue
The safe way to adopt a new language is one job at a time, with the old application still in charge of everything else. Take invoice PDF generation: it is CPU-heavy, it has no business rules of its own, and it is a good first job for Rust.
Moved with ordinary infrastructure, that job usually needs:
- a message queue, a Rust consumer for render requests, and a reply channel, either a callback endpoint in PHP or a second queue and PHP consumer;
- a status column on
invoicesand code that moves it fromrequestedtorenderingtodoneorfailed; - retries with backoff, a dead-letter path, and a scheduled sweep for requests that never got an answer;
- deduplication for redelivered messages, on both sides.
With Durable Workflow, the same move is the three activity calls in the PHP workflow above:
| Concern | Where it lives |
|---|---|
| Request and reply between the apps | $context->activity(...) with 'queue' => 'rust-workers' |
| Progress of each invoice | The workflow's recorded history |
| Retries, backoff and deadlines | Options on the activity call |
| A worker or app that is down | The task waits on its queue for the next worker |
| Duplicate delivery | The Server accepts one result per activity; the write-back is repeatable |
The PHP application keeps loading and saving invoices through Eloquent. The
Rust service sees only a typed struct and returns another. When the next job
moves, it is another activity on rust-workers.
Set up both applications
Install the PHP SDK and its Laravel bridge in the Laravel application. The bridge runs on PHP 8.2 or later with Laravel 12.72 or later, or on PHP 8.3 or later with Laravel 13.41 or later; see the PHP SDK requirements. It is Durable Workflow's service mode, in which workers in any language connect to the runtime over its worker protocol. Laravel still builds your workflow and activity classes through its container, and the SDK installs beside the code you already have. The Laravel adoption guide covers moving existing workflows.
composer require durable-workflow/sdk
php artisan vendor:publish --tag=durable-workflow-config
The Laravel for Rust application's package is named app, which is how
Laravel for Rust finds the console commands that the integration adds:
cargo new app
cd app
cargo add durable-workflow-laravel
cargo add durable-workflow --no-default-features
cargo add laravel-rust@=0.1.4 --rename laravel
cargo add serde --features derive
Both integrations read the same environment variables. Give the two applications the same runtime URL and namespace, and each its own task queue:
# Laravel PHP .env
DURABLE_WORKFLOW_RUNTIME_URL=http://127.0.0.1:8080
DURABLE_WORKFLOW_NAMESPACE=billing
DURABLE_WORKFLOW_TASK_QUEUE=php-workers
# Laravel for Rust .env
DURABLE_WORKFLOW_RUNTIME_URL=http://127.0.0.1:8080
DURABLE_WORKFLOW_NAMESPACE=billing
DURABLE_WORKFLOW_TASK_QUEUE=rust-workers
Web processes get DURABLE_WORKFLOW_CLIENT_TOKEN, and worker processes get
DURABLE_WORKFLOW_WORKER_TOKEN. Run the workers with
php artisan durable-workflow:worker and cargo run -- durable-workflow:work.
The invoice PDF, end to end
The workflow starts in the PHP application, loads the invoice with Eloquent, hands rendering to Rust, and writes the result back through Eloquent.
<?php
namespace App\Workflows;
use DurableWorkflow\Attribute\Workflow;
use DurableWorkflow\Exception\ActivityFailed;
use DurableWorkflow\Worker\WorkflowContext;
final class InvoicePdfWorkflow
{
#[Workflow('billing.invoice_pdf')]
public function run(WorkflowContext $context, int $invoiceId): array
{
$local = [
'start_to_close_timeout' => '30 seconds',
'retry_policy' => ['max_attempts' => 5, 'backoff_seconds' => [5, 30]],
];
$document = $context->activity('billing.load_invoice', [$invoiceId], $local);
try {
$rendered = $context->activity('billing.render_invoice_pdf', [$document], [
'queue' => 'rust-workers',
'start_to_close_timeout' => '5 minutes',
'heartbeat_timeout' => '30 seconds',
'schedule_to_close_timeout' => '2 hours',
'retry_policy' => ['max_attempts' => 5, 'backoff_seconds' => [10, 60, 300]],
]);
} catch (ActivityFailed $failure) {
$context->activity('billing.flag_invoice_pdf', [[
'invoice_id' => $invoiceId,
'reason' => $failure->failure['timeout_kind'] ?? $failure->failureType,
]], $local);
return ['invoice_id' => $invoiceId, 'status' => 'needs_attention'];
}
$context->activity('billing.attach_invoice_pdf', [$rendered], $local);
return ['invoice_id' => $invoiceId, 'status' => 'attached', 'path' => $rendered['path']];
}
}
The PHP activities are ordinary Eloquent code. Each one can run again safely: loading reads, and attaching writes the same values a second time.
<?php
namespace App\Activities;
use App\Models\Invoice;
use DurableWorkflow\Attribute\Activity;
use DurableWorkflow\Worker\ActivityContext;
final class InvoiceActivities
{
#[Activity('billing.load_invoice')]
public function load(ActivityContext $context, int $invoiceId): array
{
$invoice = Invoice::with('customer', 'lines')->findOrFail($invoiceId);
return [
'invoice_id' => $invoice->id,
'customer_name' => $invoice->customer->name,
'lines' => $invoice->lines->map(fn ($line): array => [
'description' => $line->description,
'quantity' => (int) $line->quantity,
'unit_price_cents' => (int) $line->unit_price_cents,
])->values()->all(),
];
}
#[Activity('billing.attach_invoice_pdf')]
public function attach(ActivityContext $context, array $rendered): array
{
Invoice::whereKey($rendered['invoice_id'])->update(['pdf_path' => $rendered['path']]);
return ['invoice_id' => $rendered['invoice_id']];
}
#[Activity('billing.flag_invoice_pdf')]
public function flag(ActivityContext $context, array $flag): array
{
Invoice::whereKey($flag['invoice_id'])->update(['pdf_error' => $flag['reason']]);
return $flag;
}
}
List both classes under handlers in config/durable-workflow.php, and start
the workflow through the injected
DurableWorkflow\Bridge\Laravel\LaravelWorkflowClientInterface. A run times
out after ten minutes unless its start sets longer timeouts, so give this one
more than the render's two-hour limit:
use DurableWorkflow\Bridge\Laravel\WorkflowStartOptions;
$workflows->start(
InvoicePdfWorkflow::class,
[$invoice->id],
workflowId: "invoice-pdf-{$invoice->id}",
options: new WorkflowStartOptions(executionTimeoutSeconds: 3 * 3600, runTimeoutSeconds: 3 * 3600),
);
The Rust application registers the renderer. It reports progress with a typed heartbeat, so a renderer that stops responding is retried after 30 seconds instead of after the full five minutes:
use durable_workflow_laravel::DurableWorkflowServiceProvider;
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct InvoiceDocument {
invoice_id: i64,
customer_name: String,
lines: Vec<InvoiceLine>,
}
#[derive(Deserialize)]
struct InvoiceLine {
description: String,
quantity: i64,
unit_price_cents: i64,
}
#[derive(Serialize)]
struct RenderProgress {
lines_done: i64,
}
#[derive(Serialize)]
struct RenderedInvoice {
invoice_id: i64,
path: String,
}
fn main() -> std::process::ExitCode {
laravel::Application::configure()
.with_providers(|providers| {
providers.add(DurableWorkflowServiceProvider::new().worker(|mut worker, _app| {
worker.register_typed_activity(
"billing.render_invoice_pdf",
|ctx, doc: InvoiceDocument| async move {
let mut lines_done = 0;
for _line in &doc.lines {
// Lay out one line of the invoice for doc.customer_name.
lines_done += 1;
ctx.heartbeat(RenderProgress { lines_done }).await?;
}
// Write the PDF to storage that the PHP app can read.
Ok(RenderedInvoice {
invoice_id: doc.invoice_id,
path: format!("invoices/{}.pdf", doc.invoice_id),
})
},
);
Ok(worker)
}));
})
.run()
}
An activity that needs a Laravel service runs its body in app.scope(...);
the crate's
example application
shows the pattern.
A Rust workflow that writes through PHP
The Rust service now owns month-end billing. To close an invoice it posts the amount to the PHP ledger, then charges the customer from Rust. If the charge fails, a PHP activity reverses the ledger entry.
use std::time::Duration;
use durable_workflow::{ActivityOptions, ActivityRetryPolicy};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, laravel::validation::Validate)]
struct CloseInvoice {
invoice_id: i64,
customer_id: i64,
total_cents: i64,
}
#[derive(Serialize)]
struct LedgerPosting {
operation_key: String,
customer_id: i64,
total_cents: i64,
}
impl From<&CloseInvoice> for LedgerPosting {
fn from(invoice: &CloseInvoice) -> Self {
Self {
// Derived from workflow input, so every replay and retry uses the same key.
operation_key: format!("invoice-{}", invoice.invoice_id),
customer_id: invoice.customer_id,
total_cents: invoice.total_cents,
}
}
}
#[derive(Serialize, Deserialize)]
struct Posted {
ledger_entry_id: i64,
}
#[derive(Serialize, Deserialize)]
struct Charged {
idempotency_key: String,
}
fn php_ledger() -> ActivityOptions {
ActivityOptions::new()
.task_queue("php-workers")
.start_to_close_timeout(Duration::from_secs(30))
.retry_policy(
ActivityRetryPolicy::new(5)
.backoff_intervals([Duration::from_secs(5), Duration::from_secs(30)]),
)
}
// Inside the provider's `worker(|mut worker, _app| { ... })` callback:
worker.register_typed_workflow("billing.close_invoice", |ctx, invoice: CloseInvoice| async move {
let mut saga = ctx.saga();
let outcome = async {
let posted: Posted = ctx
.activity_typed_with_options(
"legacy.ledger.post_invoice",
php_ledger(),
LedgerPosting::from(&invoice),
)
.await?;
saga.add_compensation_with_options("legacy.ledger.reverse_entry", php_ledger(), &posted)?;
let charged: Charged = ctx
.activity_typed_with_options(
"payments.charge",
ActivityOptions::new()
.task_queue("rust-workers")
.start_to_close_timeout(Duration::from_secs(30))
.retry_policy(ActivityRetryPolicy::new(3).non_retryable_error_type("CardDeclined")),
&invoice,
)
.await?;
Ok(charged)
}
.await;
saga.finish(outcome).await
});
worker.register_typed_activity("payments.charge", |ctx, invoice: CloseInvoice| async move {
let key = match ctx.activity_execution_id() {
Some(id) => format!("billing:charge:{id}"),
None => format!("billing:charge:invoice-{}", invoice.invoice_id),
};
// Call the payment provider with `key` as its idempotency key.
Ok(Charged { idempotency_key: key })
});
Start it from a Laravel for Rust route handler:
use durable_workflow_laravel::{DurableWorkflow, StartOptions};
use laravel::prelude::*;
async fn close_invoice(
workflows: Inject<DurableWorkflow>,
Json(invoice): Json<CloseInvoice>,
) -> laravel::Result<String> {
let id = format!("close-invoice-{}", invoice.invoice_id);
let workflow = workflows
.start_with("billing.close_invoice", invoice, StartOptions::new().id(id))
.await?;
Ok(workflow.id().to_owned())
}
On the PHP side, the ledger is an Eloquent model whose operation_key column
has a unique index. That index is what makes the posting idempotent:
// database/migrations/..._create_ledger_entries_table.php
Schema::create('ledger_entries', function (Blueprint $table) {
$table->id();
$table->string('operation_key')->unique();
$table->unsignedBigInteger('customer_id');
$table->bigInteger('total_cents');
$table->timestamp('reversed_at')->nullable();
$table->timestamps();
});
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
final class LedgerEntry extends Model
{
protected $fillable = ['operation_key', 'customer_id', 'total_cents', 'reversed_at'];
}
<?php
namespace App\Activities;
use App\Models\LedgerEntry;
use DurableWorkflow\Attribute\Activity;
use DurableWorkflow\Worker\ActivityContext;
final class LedgerActivities
{
#[Activity('legacy.ledger.post_invoice')]
public function postInvoice(ActivityContext $context, array $posting): array
{
$entry = LedgerEntry::createOrFirst(
['operation_key' => $posting['operation_key']],
[
'customer_id' => $posting['customer_id'],
'total_cents' => $posting['total_cents'],
],
);
return ['ledger_entry_id' => $entry->id];
}
#[Activity('legacy.ledger.reverse_entry')]
public function reverseEntry(ActivityContext $context, array $posted): array
{
LedgerEntry::whereKey($posted['ledger_entry_id'])
->whereNull('reversed_at')
->update(['reversed_at' => now()]);
return ['reversed_entry_id' => $posted['ledger_entry_id']];
}
}
Both directions follow the cross-language paths that the
sample app's polyglot stack
runs in CI against the published Server and SDKs, with a
PHP worker
and a Rust worker.
The two Laravel integrations run the same SDK Worker types.
What usually goes wrong between two apps, and how this handles it
One app crashes or deploys in the middle of a process
Scheduling an activity writes a task to the runtime, not a request to the
other application. If the Rust service is deploying when the PHP workflow
reaches billing.render_invoice_pdf, the task waits on rust-workers. When a
Rust worker that registered that type starts, it claims the task, and the PHP
workflow continues from the same line. The same holds in the other direction
for the ledger activities on php-workers.
The workflow's own application can restart too. Its next worker replays the
recorded history, receives the recorded results of completed activities
without running them again, and continues. A worker that dies during an
attempt is covered by the attempt's deadline (start_to_close_timeout, or
heartbeat_timeout for a long render), after which the retry runs on a live
worker with the same arguments. When a process should not wait forever,
schedule_to_close_timeout bounds it, and the workflow handles the result as
an ActivityFailed whose failure['timeout_kind'] names the deadline, as the
PDF workflow does.
The sample app tests these cases with the published packages. Its activity suites cover all nine PHP, Python and Rust directions. In one, workflows wait with an activity that no running worker handles; new workers start, run each activity once, and complete the original workflows. In another, an activity worker is killed with SIGKILL during an attempt, and the retry completes the original run.
A failure halfway through leaves two databases inconsistent
The ledger entry is in PHP's database and the charge failed in Rust. The close
workflow uses a saga: each compensation is registered after its forward step
succeeds, and saga.finish(outcome) runs the registered compensations in
reverse order on failure, then returns the original failure. A compensation is
an ordinary activity, so a Rust workflow can compensate through a PHP activity.
The PHP SDK has the same feature through $context->saga()->run(...) and
$saga->addCompensation(...). Compensation progress is recorded in history, so
a restart during compensation continues with the next step. See the
PHP SDK saga guide
and the Rust Saga reference.
A retry writes twice
Each activity call states its own retry policy: attempts, delays between them,
and failure types that end retries immediately, such as CardDeclined. The
Server refuses a result from an attempt that has already been replaced, so the
history records one outcome per activity. For the external write, each
activity has a stable identity to deduplicate on:
- an operation key derived from workflow input, as
LedgerPostingdoes, with a unique index andcreateOrFirst(); - the activity execution ID, which stays the same across retries of one
activity:
$context->activityExecutionIdin PHP andctx.activity_execution_id()in Rust. The documented pattern falls back to a business key when it is not available, aspayments.chargedoes.
The sample app's external-effects suite runs this in every PHP, Python and Rust direction: an activity commits an effect under an operation key, its worker is killed, and the retry produces exactly one business effect. See logical activity identity and its Rust equivalent.
The two apps disagree about the payload format
Durable Workflow uses one Avro value schema for every workflow input, activity argument, result, signal and failure detail, in every SDK. You do not write or register schemas between your applications. The Rust struct and the PHP array are two views of the same value:
#[derive(Serialize)]
struct LedgerPosting {
operation_key: String, // PHP string
customer_id: i64, // PHP int
total_cents: i64, // PHP int
}
['operation_key' => 'invoice-42', 'customer_id' => 7, 'total_cents' => 1999]
The schema keeps integers and doubles, text and bytes, and lists and maps
distinct, so 7 stays an integer and a list stays a list in both languages.
Send money as integer cents, dates as ISO-8601 UTC strings and enums as their
->value, and pass one struct or one associative array per activity call,
because a Rust typed handler takes one request value. A value the schema
cannot carry, such as a PHP object or a map with integer keys, is refused at
the sender with a named error such as unsupported_value_type or
invalid_map_key, rather than converted. Rust field names match the struct as
written; Serde's rename_all maps them if the PHP side uses another style.
A process waits for days
Approvals and settlements take days. A workflow waits without holding a worker: the Server keeps the wait and its timer. In PHP, a workflow declares a signal and waits for it with a timeout:
#[Signal('approve')]
public function approve(string $approvedBy): void
{
}
// In the workflow method:
$approved = $context->waitCondition(
static fn (): bool => $context->signals('approve') !== [],
key: 'invoice-approved',
timeout: '3 days',
);
The back office resumes it with
$workflows->handle(InvoicePdfWorkflow::class, $id)->signal('approve', [$email]).
In Rust, ctx.next_signal("approve").timeout(...) returns None when the
deadline passes, and ctx.sleep(...) is a durable timer. The Rust integration
can also build a signed link that sends one signal to one run, such as an
"Approve" button in an email; see
Coming from Laravel workflows (Rust).
Both SDKs end a run after ten minutes and an execution after an hour by
default, so start a workflow that waits for days with longer timeouts:
WorkflowStartOptions in PHP, or StartOptions::run_timeout_seconds and
execution_timeout_seconds in Rust.
The two apps deploy on different days while processes are in flight
The runtime records each activity's arguments when it is scheduled and its result when it completes, and a deploy changes neither. The versioning guide gives one rollout order for both languages: deploy the reader of a value before the writer.
- To add an input field, make the activity accept it as optional (a Rust
Optionor#[serde(default)], or$posting['currency'] ?? 'USD'in PHP), deploy that worker, then deploy the workflow that sends it. - To add a result field, make the workflow accept results with and without it, then deploy the activity that returns it.
- To change what a call does, register a new activity type and choose it with
patched(). In-flight runs keep the old path and new runs take the new one:
$type = $context->patched('ledger-v2') ? 'legacy.ledger.post_invoice_v2' : 'legacy.ledger.post_invoice';
let activity = if ctx.patched("ledger-v2")? { "legacy.ledger.post_invoice_v2" } else { "legacy.ledger.post_invoice" };
Replay checks itself. If deployed Rust workflow code would schedule a different
activity type, queue or retry policy than the history records, the SDK stops
that workflow task with a named replay error such as
activity_task_queue_mismatch. The PHP SDK raises NonDeterministicWorkflow
when recorded operations change. Neither continues on a diverged path. See
failures and recovery.
Nobody can tell where a cross-app process is stuck
One run has one history, whichever language ran each step. The PDF workflow's history holds the PHP load, the Rust render with its heartbeats and attempts, and the PHP write-back, in order. Cloud includes Managed Waterline for browsing runs, and a self-hosted Server can have Waterline deployed beside it, as the sample app's polyglot stack does. For a run that is waiting, the Server's debug view names the reason:
curl -fsS "$DW_SERVER_URL/api/workflows/$WORKFLOW_ID/runs/$RUN_ID/debug" \
-H "Authorization: Bearer $DW_OPERATOR_TOKEN" \
-H "X-Durable-Workflow-Control-Plane-Version: 2" \
-H "X-Namespace: $DW_NAMESPACE"
A pending activity with no worker on its queue is reported as
pending_activity_queue_without_active_pollers. A queue whose workers do not
register that activity type is reported as pending_activity_type_unsupported,
with each active worker's ID, runtime (php or rust) and registered types.
The PHP worker also prints its queue and registered types when it starts, and
the Rust worker prints its queue. See
recorded queue diagnostics.
Run both apps against one local Server
Start a Server with Docker. The quickstart has the current image pin:
export DW_AUTH_TOKEN=dev-token
docker run -d --name durable-workflow-server \
-p 127.0.0.1:8080:8080 \
-v durable-workflow-dev:/app/database \
-e DW_AUTH_TOKEN="$DW_AUTH_TOKEN" \
durableworkflow/server:3.33.2
until curl -sf http://localhost:8080/api/ready >/dev/null; do sleep 1; done
The Server creates the default namespace on first start, so use
DURABLE_WORKFLOW_NAMESPACE=default locally. Run one worker from each
application in its own terminal. Locally, DURABLE_WORKFLOW_TOKEN serves as
both the client and the worker credential:
# Laravel PHP application
DURABLE_WORKFLOW_NAMESPACE=default DURABLE_WORKFLOW_TOKEN=dev-token \
php artisan durable-workflow:worker
# Laravel for Rust application
DURABLE_WORKFLOW_NAMESPACE=default DURABLE_WORKFLOW_TOKEN=dev-token \
cargo run -- durable-workflow:work
Stop either worker while a PDF workflow is running and start it again: the run continues where it was. For a fuller reference, the sample app's polyglot Compose file runs the native Server on MySQL with PHP, Python and Rust workers on their own queues and a Waterline service.
