Versions used. Temporal Java SDK 1.41.1 (temporal-sdk,temporal-testingandtemporal-spring-boot-starterall at 1.41.1, the release versions in Maven Central metadata on 29 November 2026) · Spring Boot 4.2.0 · Temurin JDK 25.0.5.1 · JUnit 6.1.3 (managed by the Boot BOM). Most output comes fromTestWorkflowEnvironment, the in-memory Temporal server that ships intemporal-testing: no Docker and no server install. The crash-recovery run uses a real Temporal dev server (Temporal CLI 1.10.1, server 1.32.2). Every console block below is quoted from a file in the companion repository, and 11 tests assert the same facts.
What you hand-roll today, and what Temporal takes over
The earlier post on this blog, Saga Pattern in Spring Boot: Orchestration vs Choreography with Kafka, built the same order, payment and inventory saga on a real broker. It works, and it also shows the cost: the orchestrator class is only part of the solution. The retries, the idempotent consumers, the record of “which step are we on” and the compensation triggers are all code you own and test. A workflow engine moves exactly that part out of your code. You still write the steps and the compensations, because only you know that a refund undoes a charge. What you stop writing is the part that remembers where the saga is. This post uses the same domain on purpose, so the two can be compared line for line in the section after the saga.The mental model: a function whose progress is written down
Three words carry the whole model. A workflow is a method that describes the order of steps. An activity is one step that does real work: a database write, an HTTP call, a payment. A worker is your application process, which runs both and polls the Temporal service for things to do. The rule that makes it work: workflow code must be deterministic, and activities are where everything else lives. Every time the workflow method calls an activity, the call does not run it directly. It asks the Temporal service to schedule an activity task, and when the result comes back the service records it in the workflow’s event history. If the worker dies, a new worker re-runs the workflow method from the top, and each activity call returns its recorded result instead of running again, until the method reaches the first step that has no result yet. That re-run is called replay.Going deeper: what “deterministic” rules out
The workflow method is replayed, so it must make the same decisions given the same history. Things that break that:System.currentTimeMillis(), new Random() or UUID.randomUUID() (use Workflow.currentTimeMillis(), Workflow.newRandom() or Workflow.randomUUID()), Thread.sleep (use Workflow.sleep), starting your own threads, reading mutable static state, and calling a database or HTTP client directly. All of those belong in an activity. Workflow.currentTimeMillis, Workflow.newRandom, Workflow.randomUUID, Workflow.sleep and Workflow.await all exist in the 1.41.1 jar (checked with javap). The rules are documented in Temporal: Workflows and Temporal: Activities.
The smallest workflow that runs, with no server
Start with one workflow that calls one activity. The workflow interface is annotated, the implementation calls the activity through a stub, and the stub is what turns a method call into a scheduled task.The dependencies are the SDK starter, the test module and Boot’s web starter, in pom.xml:
<dependency>
<groupId>io.temporal</groupId>
<artifactId>temporal-spring-boot-starter</artifactId>
<version>${temporal.version}</version>
</dependency>
<dependency>
<groupId>io.temporal</groupId>
<artifactId>temporal-testing</artifactId>
<version>${temporal.version}</version>
</dependency>
The workflow, in GreetingWorkflowImpl.java:
public class GreetingWorkflowImpl implements GreetingWorkflow {
// A stub: calling a method on it does not run the code here, it schedules an activity task.
private final GreetingActivities activities = Workflow.newActivityStub(
GreetingActivities.class,
ActivityOptions.newBuilder().setStartToCloseTimeout(Duration.ofSeconds(5)).build());
@Override
public String greet(String name) {
return activities.composeGreeting(name);
}
}
And the test that runs it against the in-memory server, from GreetingWorkflowTest.java:
TestWorkflowEnvironment env = TestWorkflowEnvironment.newInstance();
try {
Worker worker = env.newWorker("hello");
worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class);
worker.registerActivitiesImplementations(new GreetingActivitiesImpl());
env.start();
WorkflowClient client = env.getWorkflowClient();
GreetingWorkflow wf = client.newWorkflowStub(GreetingWorkflow.class,
WorkflowOptions.newBuilder().setTaskQueue("hello").setWorkflowId("hello-1").build());
String result = wf.greet("Ankur");
assertEquals("Hello, Ankur!", result);
The test then fetches the workflow’s event history. This is the whole record Temporal keeps for a one-step workflow (output/01-hello-history.txt):
result: Hello, Ankur!
event history of workflow hello-1:
1 WORKFLOW_EXECUTION_STARTED
2 WORKFLOW_TASK_SCHEDULED
3 WORKFLOW_TASK_STARTED
4 WORKFLOW_TASK_COMPLETED
5 ACTIVITY_TASK_SCHEDULED ComposeGreeting
6 ACTIVITY_TASK_STARTED
7 ACTIVITY_TASK_COMPLETED
8 WORKFLOW_TASK_SCHEDULED
9 WORKFLOW_TASK_STARTED
10 WORKFLOW_TASK_COMPLETED
11 WORKFLOW_EXECUTION_COMPLETED
Read it top to bottom. The activity was scheduled (event 5), started and completed. The three WORKFLOW_TASK triples are the moments your workflow method actually ran on a worker: once to schedule the activity and once more, after the result arrived, to finish. Event numbers matter later, because the versioning error message points at one.
Going deeper: how the test environment works
TestWorkflowEnvironment.newInstance() starts an in-process Temporal test server and gives you a real WorkflowClient and a Worker factory wired to it. Your workflow and activity code run unchanged; only the server is a stand-in. The environment has one special feature: time skipping. While a workflow is blocked on a timer, the test server advances its clock to the next timer instead of waiting. The retry and approval sections below rely on it: a 24-hour wait finishes in well under five seconds of wall time, asserted in the tests.Limits worth knowing: the test server is not the production server, so it can differ on rarely-used server features. The real-server run later in the post is there to cover the gap for the behaviour that matters most. The testing guide is at Temporal: Java testing suite.
Retries are a policy you declare, not a loop you write
Activities fail: a rate service returns 503, a database is briefly locked. In a hand-rolled saga this is the part that grows (retry loops, backoff, a cap, a dead-letter). In Temporal it is a field on the activity options. Here the workflow asks for an initial interval of 1 second, doubling, at most 4 attempts (RateWorkflowImpl.java):
private final RateActivities activities = Workflow.newActivityStub(
RateActivities.class,
ActivityOptions.newBuilder()
.setStartToCloseTimeout(Duration.ofSeconds(5))
.setRetryOptions(RetryOptions.newBuilder()
.setInitialInterval(Duration.ofSeconds(1))
.setBackoffCoefficient(2.0)
.setMaximumAttempts(4)
.build())
.build());
The activity under test fails twice with a plain exception, fails forever in another run, and in a third run throws a non-retryable ApplicationFailure. The result, from output/02-retries.txt:
retry policy: initial 1s, coefficient 2.0, maximum attempts 4
== two transient failures, then success ==
fetchRate(USD/INR) attempt 1
fetchRate(USD/INR) attempt 2
fetchRate(USD/INR) attempt 3
result: USD/INR=83.21
workflow history spans 3 s (1 s + 2 s of backoff); wall clock under 5 s: true
== always failing: attempts exhausted ==
fetchRate(USD/INR) attempt 1
fetchRate(USD/INR) attempt 2
fetchRate(USD/INR) attempt 3
fetchRate(USD/INR) attempt 4
workflow failed: ActivityFailure -> ApplicationFailure: message='503 from rate service', type='java.lang.IllegalStateException', nonRetryable=false
== non-retryable ApplicationFailure ==
fetchRate(USD/INR) attempt 1
workflow failed: type=UnknownPair nonRetryable=true message=unknown currency pair USD/INR
Three behaviours are visible. A transient failure is retried by the server, not by your code, so the attempt counter the activity reads from its execution context goes 1, 2, 3. When attempts run out, the workflow fails with an ActivityFailure whose cause is the last exception. And a failure marked non-retryable stops after one attempt, which is how a business error like an unknown currency pair or a declined card should be reported: retrying it only delays the inevitable.
Activities run at least once, not exactly once. If the worker dies after the activity finished its work but before the result was recorded, the activity runs again. The saga below handles this by making every activity idempotent on the order id, and one test reproduces the case on purpose.If you set no retry options at all, the server applies its default policy. The docs state it as: initial interval 1 second, backoff coefficient 2.0, maximum interval 100 times the initial interval, and unlimited attempts; workflows, unlike activities, have no default retry policy. I read that from the retry policy documentation rather than from code:
RetryOptions.getDefaultInstance() in the SDK prints all fields as unset, because the defaults are applied by the server. Unlimited attempts is a real risk for a payment activity, so set a cap.
setDoNotRetrylists exception types that stop retrying;setStartToCloseTimeoutbounds each attempt whilesetScheduleToCloseTimeoutbounds all attempts together. See Retry policies.- Test source:
RetryTest.java.
The saga: charge, reserve, confirm, and undo in reverse
Now the order saga, with the same three steps as the Kafka post: charge the payment, reserve the stock, confirm the order. The workflow registers a compensation right after each step succeeds. If any later step fails,saga.compensate() runs the registered compensations in reverse order (OrderSagaWorkflowImpl.java):
public class OrderSagaWorkflowImpl implements OrderSagaWorkflow {
private final OrderActivities activities = Workflow.newActivityStub(
OrderActivities.class,
ActivityOptions.newBuilder()
.setStartToCloseTimeout(Duration.ofSeconds(5))
.setRetryOptions(RetryOptions.newBuilder()
.setInitialInterval(Duration.ofSeconds(1))
.setMaximumAttempts(3)
.build())
.build());
@Override
public OrderResult placeOrder(OrderRequest r) {
Saga saga = new Saga(new Saga.Options.Builder().setParallelCompensation(false).build());
try {
activities.chargePayment(r.orderId(), r.amount());
saga.addCompensation(activities::refundPayment, r.orderId());
activities.reserveStock(r.orderId(), r.sku(), r.quantity());
saga.addCompensation(activities::releaseStock, r.orderId());
activities.confirmOrder(r.orderId(), r.shipTo());
return OrderResult.confirmed(r.orderId());
} catch (ActivityFailure failure) {
// Compensations run in reverse order of registration.
saga.compensate();
String type = failure.getCause() instanceof ApplicationFailure af ? af.getType() : "Unknown";
return OrderResult.cancelled(r.orderId(), type);
}
}
}
There is no status column, no state-machine enum and no message handler. The program counter is the state: after chargePayment returns, the workflow is “at” the line that reserves stock, and Temporal can reconstruct that from the history.
Each activity is idempotent. Here is the payment one, which also has a hook that simulates the worst case, the charge going through and the connection dropping before the reply (OrderActivitiesImpl.java):
public void chargePayment(String orderId, long amount) {
int attempt = attempt();
if (amount > 1000) {
ledger.log("chargePayment " + orderId + " attempt " + attempt + ": DECLINED (amount " + amount + ")");
throw ApplicationFailure.newNonRetryableFailure("card declined for " + orderId, "PaymentDeclined");
}
if (ledger.payments.putIfAbsent(orderId, "CHARGED") == null) {
ledger.log("chargePayment " + orderId + " attempt " + attempt + ": charged " + amount);
} else {
ledger.log("chargePayment " + orderId + " attempt " + attempt + ": already charged, skipped");
}
if (attempt == 1 && ledger.crashAfterChargeOnce.contains(orderId)) {
throw new IllegalStateException("connection reset after the charge went through");
}
}
First the happy path (output/03-saga-happy-path.txt), journal lines first and the recorded history after them:
result: OrderResult[orderId=o-1, status=CONFIRMED, reason=null]
chargePayment o-1 attempt 1: charged 500
reserveStock o-1 attempt 1: reserved 2 x BOOK-1
confirmOrder o-1 attempt 1: confirmed, shipping to Mumbai
stock BOOK-1 after: 3
event history (workflow tasks hidden):
1 WORKFLOW_EXECUTION_STARTED
5 ACTIVITY_TASK_SCHEDULED ChargePayment
6 ACTIVITY_TASK_STARTED
7 ACTIVITY_TASK_COMPLETED
11 ACTIVITY_TASK_SCHEDULED ReserveStock
12 ACTIVITY_TASK_STARTED
13 ACTIVITY_TASK_COMPLETED
17 ACTIVITY_TASK_SCHEDULED ConfirmOrder
18 ACTIVITY_TASK_STARTED
19 ACTIVITY_TASK_COMPLETED
23 WORKFLOW_EXECUTION_COMPLETED
Now stock runs out on the second step. The payment is already taken, so the saga refunds it (output/04-saga-out-of-stock.txt):
result: OrderResult[orderId=o-2, status=CANCELLED, reason=OutOfStock]
chargePayment o-2 attempt 1: charged 900
reserveStock o-2 attempt 1: OUT OF STOCK (1 of LAPTOP-9)
refundPayment o-2 attempt 1: refunded
payment state: REFUNDED
Fail the third step instead, and two compensations run, in reverse registration order (output/05-saga-late-failure.txt):
result: OrderResult[orderId=o-3, status=CANCELLED, reason=Unshippable]
chargePayment o-3 attempt 1: charged 100
reserveStock o-3 attempt 1: reserved 1 x BOOK-1
confirmOrder o-3 attempt 1: FAILED (cannot ship to NOWHERE)
releaseStock o-3 attempt 1: released 1
refundPayment o-3 attempt 1: refunded
payment state: REFUNDED
stock BOOK-1 after: 5
REFUNDED.
The idempotency hook produces this (output/06-saga-idempotent-retry.txt): the first charge attempt records the payment and then throws, the server retries, and attempt 2 sees the payment already exists and skips it.
result: OrderResult[orderId=o-4, status=CONFIRMED, reason=null]
chargePayment o-4 attempt 1: charged 100
chargePayment o-4 attempt 2: already charged, skipped
reserveStock o-4 attempt 1: reserved 1 x BOOK-1
confirmOrder o-4 attempt 1: confirmed, shipping to Pune
payments recorded for o-4: CHARGED
Without the idempotency check, attempt 2 would charge the customer twice. Temporal retried correctly; it is the activity’s job to make that safe.
How this compares with the Kafka saga
Same domain, same compensations, different place for the coordination state. The table compares the orchestrated Kafka version from the earlier post with this one.| Concern | Kafka orchestrator (earlier post) | Temporal workflow (this post) |
|---|---|---|
| Where the saga’s position is stored | Your own saga state in your database, advanced by reply messages | The workflow’s event history on the Temporal service |
| Retrying a failed step | You write it (redelivery, retry topics, backoff) | A RetryOptions field on the activity |
| Waiting hours for a human or a timer | You add a scheduler or a sweeper | Workflow.await / Workflow.sleep, a durable timer |
| Reading the saga as a whole | The orchestrator class plus its handlers and topics | One method |
| Infrastructure you run | A Kafka cluster | A Temporal service and its database (or Temporal Cloud) |
| Duplicate-delivery safety | Idempotent consumers | Idempotent activities (same idea) |
| Changing the saga while orders are in flight | Version your messages and states | Replay rules and Workflow.getVersion (see below) |
The last row is the price. Temporal gives you the readable method, and in return in-flight executions are bound to the code that wrote their history.
- Test source:
OrderSagaTest.java; the in-memory ledger:Ledger.java. - Pattern background: microservices.io: Saga.
- The microservice patterns this saga sits next to (retry, idempotency, outbox) are run for real in Top 40 Microservices Interview Questions and Transactional Outbox with the Spring Modulith Event Publication Registry.
Durability: the workflow survives having no worker, and having no JVM
Two experiments make “durable” concrete. First, start a workflow when no worker exists at all. The server accepts it and holds the task (output/07-saga-no-worker-yet.txt):
events recorded while no worker was running: [WORKFLOW_EXECUTION_STARTED, WORKFLOW_TASK_SCHEDULED]
journal while no worker was running: []
after a worker started polling: OrderResult[orderId=o-5, status=CONFIRMED, reason=null]
chargePayment o-5 attempt 1: charged 100
reserveStock o-5 attempt 1: reserved 1 x BOOK-1
confirmOrder o-5 attempt 1: confirmed, shipping to Delhi
Before the worker started, the history had two events and the journal (the activities’ side effects) was empty. Once a worker began polling, the same workflow ran to completion. A deploy window or a crashed pod is the same situation with a shorter gap.
Second, the harder test against a real server. crash-recovery.sh starts the Spring Boot app against a Temporal dev server, starts an approval workflow, runs kill -9 on the JVM, starts a brand-new JVM, queries the workflow, sends the approving signal, and prints the history from the server’s own CLI (output/12-crash-recovery.txt):
== JVM #1: start the approval workflow ==
{"workflowId":"approval-req-29700"}
status query: {"status":"WAITING"}
== kill -9 the JVM (no graceful shutdown) ==
app listening on 8099 after kill: 000
== JVM #2: a brand-new process ==
status query: {"status":"WAITING"}
{"signalled":"approve"}
status query: {"status":"APPROVED by priya"}
== temporal workflow show ==
1 EVENT_TYPE_WORKFLOW_EXECUTION_STARTED
2 EVENT_TYPE_WORKFLOW_TASK_SCHEDULED
3 EVENT_TYPE_WORKFLOW_TASK_STARTED
4 EVENT_TYPE_WORKFLOW_TASK_COMPLETED
5 EVENT_TYPE_TIMER_STARTED
6 EVENT_TYPE_WORKFLOW_EXECUTION_SIGNALED
7 EVENT_TYPE_WORKFLOW_TASK_SCHEDULED
8 EVENT_TYPE_WORKFLOW_TASK_STARTED
9 EVENT_TYPE_WORKFLOW_TASK_COMPLETED
10 EVENT_TYPE_TIMER_CANCELED
11 EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED
After the kill the port answers 000 (connection refused). The new JVM, a different process with an empty heap, answers the query WAITING by replaying the history, accepts the signal, and the workflow completes. The history at the bottom, printed by temporal workflow show, has one timer, one signal and a cancelled timer: nothing in it knows a process died.
Event history is not unbounded. The Temporal docs state that an execution is terminated when its history exceeds 51,200 events (with warnings starting at 10,240), so a loop that runs forever must useWorkflow.continueAsNew, which starts a fresh run carrying state forward. I took these numbers from the event history documentation and did not run a workflow to the limit;continueAsNewexists in the 1.41.1 jar (checked withjavap).
Going deeper: the app and the kill-and-restart script
The approval workflow used by the script is the one in the next section, registered by the Spring Boot starter throughApprovalWorkflowImpl.java and exposed by ApprovalController.java. The script is a plain bash file; it generates a random workflow id per run, which is why that id differs between runs of the transcript. To try it yourself: scripts/dev-server.sh in one shell, then scripts/crash-recovery.sh in another. The Temporal CLI download and docs are at Temporal CLI.
Signals, queries and timers: waiting for people without holding a thread
Sagas often wait: for a manager’s approval, for a webhook, for 24 hours before expiring a reservation. A signal pushes data into a running workflow, a query reads its state without changing it, andWorkflow.await blocks until a condition becomes true or a timeout passes (ApprovalWorkflowImpl.java):
public class ApprovalWorkflowImpl implements ApprovalWorkflow {
private String decision; // set by a signal
private String status = "WAITING";
@Override
public String awaitDecision(String requestId) {
// Blocks for up to 24 hours of *workflow* time. No thread is held and no worker needs to stay up:
// the wait is a durable timer on the server.
boolean decided = Workflow.await(Duration.ofHours(24), () -> decision != null);
if (!decided) {
status = "EXPIRED";
return requestId + ": EXPIRED after 24h";
}
status = decision;
return requestId + ": " + decision;
}
@Override
public void approve(String by) {
decision = "APPROVED by " + by;
}
@Override
public void reject(String by, String reason) {
decision = "REJECTED by " + by + " (" + reason + ")";
}
@Override
public String status() {
return status;
}
}
The test sends a signal after five minutes, lets a second request wait the full 24 hours, and rejects a third with two arguments (output/08-signals-queries-timers.txt):
== signal arrives after 5 minutes ==
query while waiting: WAITING
result: req-1: APPROVED by priya
query after: APPROVED by priya
== nobody answers ==
result: req-2: EXPIRED after 24h
workflow clock advanced about 24 hours; wall clock under 5 s: true
query after: EXPIRED
== rejected with a reason ==
result: req-3: REJECTED by rahul (over budget)
event history of req-3:
1 WORKFLOW_EXECUTION_STARTED
3 WORKFLOW_EXECUTION_SIGNALED reject
6 WORKFLOW_EXECUTION_COMPLETED
The 24-hour timeout ran in a test that asserts under five seconds of wall time, which is the time-skipping from earlier. In production that wait is a server-side timer: no thread is parked in your JVM while it runs. The history of the rejected request shows the signal event, and the timer being cancelled when the condition became true.
- Test source:
ApprovalWorkflowTest.java; the interface with@SignalMethodand@QueryMethod:ApprovalWorkflow.java.
Changing a workflow that is already running
This is the part that surprises people. Because a worker replays history against your code, the code must still produce the same sequence of commands that the history recorded. Say the business adds a fraud check between picking and shipping. The tempting change is to insert one line (FulfilmentNaiveV2.java):
public String fulfil(String orderId) {
String a = act.pick(orderId);
String f = act.fraudCheck(orderId);
String b = act.ship(orderId);
return a + ", " + f + ", " + b;
}
The safe version wraps the new step in Workflow.getVersion, which records a marker in the history the first time a workflow reaches that line (FulfilmentPatchedV2.java):
public String fulfil(String orderId) {
String a = act.pick(orderId);
// DEFAULT_VERSION (-1) is what histories recorded before this line existed will see.
int version = Workflow.getVersion("add-fraud-check", Workflow.DEFAULT_VERSION, 1);
String f = version == 1 ? act.fraudCheck(orderId) : "no fraud check";
String b = act.ship(orderId);
return version == 1 ? a + ", " + f + ", " + b : a + ", " + b;
}
The test runs version 1, captures its history, then replays that history with WorkflowReplayer against each candidate (output/09-versioning-replay.txt):
V1 run: result: picked o-9, shipped o-9
V1 history:
1 WORKFLOW_EXECUTION_STARTED
5 ACTIVITY_TASK_SCHEDULED Pick
6 ACTIVITY_TASK_STARTED
7 ACTIVITY_TASK_COMPLETED
11 ACTIVITY_TASK_SCHEDULED Ship
12 ACTIVITY_TASK_STARTED
13 ACTIVITY_TASK_COMPLETED
17 WORKFLOW_EXECUTION_COMPLETED
== replay the V1 history against V1 code ==
OK
== replay the V1 history against NaiveV2 (new step inserted, no guard) ==
java.lang.RuntimeException: query failure for workflow_id: "ful-1"
run_id: "run_id_in_replay"
, queryType=__replay_only, args=Optional.empty, error=io.temporal.worker.NonDeterministicException: [TMPRL1100] Failure handling event 11 of type 'EVENT_TYPE_ACTIVITY_TASK_SCHEDULED' during replay. [TMPRL1100] Command COMMAND_TYPE_SCHEDULE_ACTIVITY_TASK doesn't match event EVENT_TYPE_ACTIVITY_TASK_SCHEDULED with EventId=11 on check activityType with an expected value 'name: "FraudCheck"
' and an actual value 'name: "Ship"
'. {WorkflowTaskStartedEventId=9223372036854775807, CurrentStartedEventId=9}
== replay the V1 history against PatchedV2 (getVersion guard) ==
OK
Ship, the naive code asks for FraudCheck at that point, and replay stops. The Temporal docs describe the production symptom as failing workflow tasks on executions that were in flight at deploy time rather than an error at startup; I ran only the replay form of this check.
The guarded version passes against the old history, and a new execution records the marker (output/09-versioning-replay.txt, lines 25 onward):
== a NEW execution on PatchedV2 ==
PatchedV2 run: result: picked o-9, fraud-checked o-9, shipped o-9
PatchedV2 history:
1 WORKFLOW_EXECUTION_STARTED
5 ACTIVITY_TASK_SCHEDULED Pick
6 ACTIVITY_TASK_STARTED
7 ACTIVITY_TASK_COMPLETED
11 MARKER_RECORDED Version
12 ACTIVITY_TASK_SCHEDULED FraudCheck
13 ACTIVITY_TASK_STARTED
14 ACTIVITY_TASK_COMPLETED
18 ACTIVITY_TASK_SCHEDULED Ship
19 ACTIVITY_TASK_STARTED
20 ACTIVITY_TASK_COMPLETED
24 WORKFLOW_EXECUTION_COMPLETED
replay of its own history: OK
Event 11 is now a MARKER_RECORDED named Version and the new activity follows it. Old histories have no marker, so getVersion returns DEFAULT_VERSION (-1) for them and they keep the old path.
Make replay a CI check. Save real histories (export them from the server or from a staging run) and replay them against every change in a unit test, exactly as VersioningTest does. It is the only way to find out before deploy that a refactor changed the command sequence. One honest limit of this demo: I replayed a completed history, which exercises the same matching logic a worker applies to an in-flight one, but I did not park a workflow mid-flight across a redeploy.
- Test source:
VersioningTest.java. - Long tail, not run in this repo: when old executions have all closed you can remove the
getVersionbranch; Temporal also offers Worker Versioning for pinning workflows to a build. See Temporal: versioning in Java.
Going deeper: the full replay error
The exception thatWorkflowReplayer raises wraps the real cause, and the real cause is the useful part. Its text, in the transcript above, names the event (11), both activity types (expected FraudCheck, actual Ship) and the error code TMPRL1100.The wrapping RuntimeException comes from the replayer running the history as a query (queryType=__replay_only). Search for the TMPRL1100 code in your logs to find nondeterminism in a running system.
Wiring it into Spring Boot 4.2
Temporal publishes a Spring Boot starter. With it you annotate implementations and the starter registers them on a worker:@WorkflowImpl(taskQueues = "orders") on the workflow class (visible in the saga above) and @ActivityImpl on a Spring bean, so activities can inject other beans such as the ledger. The configuration is small (application.yml):
spring:
application:
name: temporal-demo
temporal:
# In-memory Temporal test server: no Docker, no temporal CLI. Switch to the "server" profile for a real one.
test-server:
enabled: true
workers-auto-discovery:
packages:
- com.ankurm.workflows.temporal.saga
- com.ankurm.workflows.temporal.signal
Setting spring.temporal.test-server.enabled makes the starter use the in-memory server from temporal-testing, so mvn spring-boot:run works with nothing installed. The server profile (application-server.yml) points at 127.0.0.1:7233 for a real one.
The REST layer starts the saga and returns immediately. The workflow id is the order id, and the controller asks the server to reject a second start with the same id (OrderController.java):
@PostMapping("/orders")
public ResponseEntity<Map<String, String>> place(@RequestBody OrderRequest request) {
OrderSagaWorkflow workflow = client.newWorkflowStub(OrderSagaWorkflow.class,
WorkflowOptions.newBuilder()
.setTaskQueue(OrderActivitiesImpl.TASK_QUEUE)
.setWorkflowId("order-" + request.orderId())
// The default policy would allow a second run once the first has closed.
.setWorkflowIdReusePolicy(WorkflowIdReusePolicy.WORKFLOW_ID_REUSE_POLICY_REJECT_DUPLICATE)
.build());
try {
WorkflowClient.start(workflow::placeOrder, request);
} catch (WorkflowExecutionAlreadyStarted e) {
return ResponseEntity.status(HttpStatus.CONFLICT).body(Map.of("error", "order already submitted"));
}
return ResponseEntity.ok(Map.of("workflowId", "order-" + request.orderId()));
}
A Spring test drives it through MockMvc against the starter’s test server (output/10-spring-boot-rest.txt):
POST /orders {"orderId":"api-1","sku":"BOOK-1","quantity":1,"amount":250,"shipTo":"Navi Mumbai"}
-> {"workflowId":"order-api-1"}
GET /orders/api-1 -> {"orderId":"api-1","status":"CONFIRMED","reason":null}
POST /orders {"orderId":"api-2","sku":"BOOK-1","quantity":1,"amount":5000,"shipTo":"Navi Mumbai"}
-> {"workflowId":"order-api-2"}
GET /orders/api-2 -> {"orderId":"api-2","status":"CANCELLED","reason":"PaymentDeclined"}
POST the same order again -> HTTP 409
That 409 exists because of something the first version of this controller got wrong. With the default workflow id reuse policy, a second start under the same id is allowed once the first run has closed, so a retried POST quietly ran the saga a second time. I noticed it because the test printed HTTP 200 where I expected a rejection. The repo now pins the behaviour (output/11-workflow-id-reuse.txt):
default policy (ALLOW_DUPLICATE), second start after the first closed: new run id = true
REJECT_DUPLICATE, synchronous call: no exception, returned OrderResult[orderId=o-6, status=CONFIRMED, reason=null]; attached to the latest run = true
REJECT_DUPLICATE, WorkflowClient.start: WorkflowExecutionAlreadyStarted
The third line is a second surprise: with REJECT_DUPLICATE, a synchronous typed-stub call did not throw, it attached to the existing run and returned its result. Only the asynchronous WorkflowClient.start surfaces WorkflowExecutionAlreadyStarted, which is what the controller catches. Also note that the second run in the default case did not double-charge, only because the activities are idempotent.
Check the starter against your Boot version. The starter’s own POM still declaresspring-boot-dependencies2.7.18 in its dependency management section. Against Spring Boot 4.2.0 everything in this repo worked: auto-discovery of workflows and activities, the test server,WorkflowClientinjection, and a real dev-server run. I did not exercise other starter features (for example Micrometer metrics or Kotlin), so test those before relying on them.
- Starter docs: Temporal: Spring Boot integration.
- Test source:
OrderApiTest.java; controllers:OrderController.javaandApprovalController.java.
Should you use Temporal for this?
Not automatically. Temporal earns its place when a process is long-running, has many steps, needs timers or human input, or must be inspectable per instance. It costs a service to operate (or a Temporal Cloud bill), a database behind it, a determinism discipline in every workflow, and a versioning routine for every change. For a three-step saga that finishes in a second, the Kafka version from the earlier post, or even a database transaction if everything lives in one database, is simpler to run. The practical test: if you are about to build a state table, a retry scheduler and a timeout sweeper, you are building a worse Temporal. If you are not, you probably do not need it.
Further reading
- Companion repository: asmhatre/workflow-engines-demo, module temporal, with every transcript under
output/. - On this blog: Saga Pattern in Spring Boot: Orchestration vs Choreography with Kafka; Transactional Outbox with Spring Modulith; Spring Boot Microservices Project.
- Temporal docs: Workflows, Activities, Retry policies, Event history, Versioning (Java), Testing suite (Java).
- microservices.io: Saga pattern.
No Comments yet!