Basic Concepts Flashcards
(27 cards)
Workflow Definition
A Workflow Definition is the code that defines your Workflow.
The Workflow Type is the name that maps to a Workflow Definition. It’s an identifier that makes it possible to distinguish one type of Workflow (such as order processing) from another (such as customer onboarding).
A Workflow Execution is a running Workflow
Workflow Definition can have
1- Long running processes
2 - Conditional Logic
3-Cycles (that refer to previous steps)
Temporal Worflows
Temporal Workflows are resilient. They can run—and keeping running—for years, even if the underlying infrastructure fails. If the application itself crashes, Temporal will automatically recreate its pre-failure state so it can continue right where it left off.
Workflows must follow deterministic constraints to ensure consistent replay behavior.
The given statement is foundational to how Temporal works
Deterministic means - The same code, when replayed with the same inputs, must produce the same outputs and behavior.
Non-Deterministic Operations to avoid
System.currentTimeMillis() - returns different value each time
UUID.randomUUID() - Produces a new value every time
Random.nextInt() - Non-repeatable unless seeded
External API calls - State may change or fail unexpectedly
Reading environment/system state - Results vary on each run
Invoking Activity still makes workflow deterministic
This is safe and deterministic, because:
The activity result is stored in the event history
On replay, the workflow uses the stored result, not a fresh activity call
Activities can be non-deterministic
An Activity is a method that encapsulates business logic prone to failure
Unlike workflows, activities are not replayed. They are:
Executed once
Their results (success/failure/exception) are recorded in workflow history
Most Importantly - On replay, the result is replayed, not the activity itself
Activity
An Activity is a normal function or method that executes a single, well-defined action (either short or long running), such as calling another service, transcoding a media file, or sending an email message. Activity code can be non-deterministic. We recommend that it be idempotent.
Activity should be indempotent
What - Activity produces same result even if repeated
Why - Temporal may retry activities automatically
How - Use unique IDs, track state, design safe retries
Not Indempotent
public void chargeCreditCard(String userId, double amount) {
paymentService.charge(userId, amount); // May charge twice if retried
}
Indempotent
public void chargeCreditCard(String userId, double amount, String transactionId) {
if (!paymentService.hasCharged(transactionId)) {
paymentService.charge(userId, amount, transactionId);
}
}
Here, the payment is only processed once — even if retried — thanks to the transactionId.
How to have indempotency in Activities
Use a unique business key (idempotency key) e.g. payment ID, request ID
Store state before acting Mark email as “sent” before sending
Use external service with idempotent API Payment API with idempotency token
Log side effects in a DB So you can skip repeated execution
Activity Failure
If an Activity Function Execution fails, any future execution starts from initial state
Activity Results
Activity Functions are executed by Worker Processes. When the Activity Function returns, the Worker sends the results back to the Temporal Service as part of the ActivityTaskCompleted Event. The Event is added to the Workflow Execution’s Event History.
Temporal CLI
Temporal provides a command-line interface (CLI), temporal, which allows you to interact with a cluster, start a development server, and more.
Temporal CLI Commands
activity Complete or fail an Activity
batch Manage running batch jobs
completion Generate the autocompletion script for the specified shell
env Manage environments
help Help about any command
operator Manage Temporal deployments
schedule Perform operations on Schedules
server Run Temporal Server
task-queue Manage Task Queues
workflow Start, list, and operate on Workflows
Temporal Namespace
Isolation
Workflows in one namespace cannot interact with workflows in another namespace.
Scoped Configuration
Workflow retention period (how long completed workflow histories are kept)
Input Params and Outputs
Temporal recommends that your Workflow Definition takes a single input parameter, a custom object, rather than multiple input parameters. Changing which fields are part of the object doesn’t change the type of the object itself, so this provides a backwards-compatible way to evolve your code.
Workflow Versioning
Since Workflow Executions in Temporal can run for long periods — sometimes months or even years — it’s common to need major changes to a Workflow Definition, even while a particular Workflow Execution is in progress. For example, imagine that your Workflow currently notifies a customer when an order is shipped with an e-mail notification. Later, you decide to change the Workflow so that it sends both an email and a text message instead. Versioning is a feature in Temporal that helps manage these code changes safely.
Activity
The Java interface must be annotated with @ActivityInterface
Registering the activity
worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class);
worker.registerActivitiesImplementations(new GreetingActivitiesImpl()); factory.start();
Sync/Async Activities
Temporal Activities can be executed either synchronously or asynchronously, depending on your use case.
Start-to-Close timeout
ActivityOptions options = ActivityOptions.newBuilder()
.setStartToCloseTimeout(Duration.ofSeconds(5))
.build();
Its value should be longer than the maximum amount of time you think the execution of the Activity should take. This allows the Temporal Cluster to detect a Worker that crashed, in which case it will consider that attempt failed and will create another task that a different Worker could pick up.
Executing Activitiy
private final GreetingActivities activities =
Workflow.newActivityStub(GreetingActivities.class, options);
Get the activity inside the workflow
String spanishGreeting = activities.greetInSpanish(name);
String spanishFarewell = activities.farewellInSpanish(name);
If the activity is synchronous then ctivities.greetInSpanish will block
Async Execution of Activity
To execute the Activity asynchronously you will use Temporal’s Async and Promise implementations. We pass in the Activity Method from the stubbed instance of our implementation. his will begin execution of the Activity and not wait for the Activity to complete before continuing execution. Promise<String> hello = Async.function(activities::greetInSpanish, name);
Promise<String> bye = Async.function(activities::farewellInSpanish, name);
To access the value from this Promise, you must first define a variable of the type corresponding to the value. Next, you will call the get function on the variable used to store the Promise. Be sure to check for an error before attempting to use the result, as this variable will not be assigned the value if the Activity Execution failed.</String></String>
Activity Scheduling
The Workflow does not execute the Activity. That is, it does not invoke the Activity Function. Instead, it makes a request to the Temporal Cluster, asking it to schedule execution of the Activity.
Handling Exceptions
Activity method signatures should not include checked exceptions. If your Activity implementation calls code that throws a checked exception, we recommend using the Activity.wrap method to re-throw it. This converts it to a Temporal-specific unchecked exception and the original exception can be retrieved (if needed) by calling its getCause() method.
try {
data = readData(dataFilePath);
} catch (IOException e) {
throw Activity.wrap(e);
}