Basic Concepts Flashcards

(36 cards)

1
Q

Workflow Definition

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Temporal Worflows

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Workflows must follow deterministic constraints to ensure consistent replay behavior.

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Non-Deterministic Operations to avoid

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Invoking Activity still makes workflow deterministic

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Activities can be non-deterministic

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Activity

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Activity should be indempotent

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to have indempotency in Activities

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Activity Failure

A

If an Activity Function Execution fails, any future execution starts from initial state

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Activity Results

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Temporal CLI

A

Temporal provides a command-line interface (CLI), temporal, which allows you to interact with a cluster, start a development server, and more.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Temporal CLI Commands

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Temporal Namespace

A

Isolation
Workflows in one namespace cannot interact with workflows in another namespace.
Scoped Configuration
Workflow retention period (how long completed workflow histories are kept)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Input Params and Outputs

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Workflow Versioning

A

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.

17
Q

Activity

A

The Java interface must be annotated with @ActivityInterface

18
Q

Registering the activity

A

worker.registerWorkflowImplementationTypes(GreetingWorkflowImpl.class);

    worker.registerActivitiesImplementations(new GreetingActivitiesImpl());

    factory.start();
19
Q

Sync/Async Activities

A

Temporal Activities can be executed either synchronously or asynchronously, depending on your use case.

20
Q

Start-to-Close timeout

A

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.

21
Q

Executing Activitiy

A

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

22
Q

Async Execution of Activity

A

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>

23
Q

Activity Scheduling

A

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.

24
Q

Handling Exceptions

A

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);
}

25
Default Behaviour
Temporal's default behavior is to automatically retry an Activity, with a short delay between each attempt, until it either succeeds or is canceled. That means that intermittent failures require no action on your part. However, that behavior may not always be desirable, so Temporal allows you to customize it through a custom Retry Policy.
26
Changing Timing and Number of Retry Attempts
InitialInterval, BackoffCoefficient, MaximumInterval, MaximumAttempts
27
Client & Worker & Workflow & Task and Activity & Queue relationship
Create a Worker and register the workflow Worker process registers workflows and activities The Worker is started after registering the Workflow class and Task Queue with the Worker. Worker continuously polls the Task queue for Workflow and Activity Tasks The Client triggers the Workflow execution by providing a WorkflowId, The Task Queue Name, The Workflow Class Name, Parameters required for the Workflow. When the client triggers the Workflow a Workflow task is placed on the task queue. Worker receives the Workflow task from the Task Queue and executes the code of the Workflow. When the Worker sees an activity call inside the workflow it creates and activity task and puts it on the Task queue. The worker then pulls the Activity Task from the Task queue and executes it. This cycle continues till the end
28
Determinism vs Indempotence
Think of your deterministic workflow as a car going from Kadavanthra to Kakkanad every day. If the car chooses to travel based on traffic conditions then it's route each day is un predictable. However if it is based on driver memory, he will choose same route each time. Similarly if there are 5 toll booths on the path the driver takes. An indepotent approach would not charge the driver again if he has passed that route once already on its way to Kakkanad
29
Terminology
Better to refer to Temporal like technologies like Durable Execution Workflows
30
When to use workflows
You need to synchronize state across microservices You want fault tolerant, perfectly replayable logic You want a low cost scalability abstraction without wasting hardware resources.
31
When to use worflows
Any setting where no significant action needs to feel synchronous Interaction lifespans are from minutes to days i.e 1 interaction completes in 1 min but other may take 2 hours Coordination cannot be easily handled by a client
32
2 types of workflow
1. Each workflow run is very similar to the other runs 2. Each workflow run can be different from the previous run , i.e highly individualized
33
Human in Loop
Advantage of workflows is that it allows human in the loop possibility
34
When to use Temporal
Long running processes Business transactions Infrastructure provisioning and operations
35
Value provided by Temporal
Temporal shields you from unreliability - unreliabiliyt == infra going down, network going down. Temporal provides and abstraction which elevates developers from these issues.
36
Temporal in Business Process Applications
https://www.youtube.com/watch?v=eMf1fk9RmhY Business Process Applications- Involves people and system. Between seconds to days is the time spent between steps of the workflow. Any application which relies on a person or application which is outside of its control., simple features get complicated Only some states are valid in Business Process Application. Managing states of the Business Process Application is hard. You need to be constantly be aware of which state you are in and what are the possible actions that you can take when you are in that state. For example you may have a feature to be able to review a person's compensation but it is also possible that needs to be available only when that person is up for a performance review. So you cant write a simple CRUD function to update a person's compensation, that CRUD function is contingent on being aware of what state that process is at that given moment of time. This leads to engineering teams ending up building state machines. So you have to have one feature to have an update to the state and a whole lot of other features to make sure that you are making the right update. This is a whole lot more harder than just making the update in state in the first place. And it is usually the case that these other features are distributed in different layers of the application and not just in one. 3rd reason why writing business process application using classical approach is hard is because of scheduling. Most times scheduling is externalized to a CRON or 3rd party system