What exactly happens when we do terminate and cancel a workflow?

Can someone let me know what exactly happens behind the scene when we do terminate and cancel a workflow?

I know the difference between terminate and cancel.

I am looking to understand cases like let’s say some activity of a workflow is running in the worker in our application code and I terminate the workflow, in that case will the activity will complete in our application code and then the workflow will terminate or activity that is running in our application will be terminated in the middle? If it is the second one how does temporal achieves it?

I was not able to get the inner workings of terminate and cancel from the documentation. If someone can point me to the relevant docs that will also be helpful.

What SDK are you using?

Termination is a hard stop. If the execution is terminated. It is terminated right away on the server, and server does not notify workers about it. Any running workflow/activity tasks on this worker in this case continue to run but are basically canceled. This does mean that they are still using your worker resources which is one main reason termination is not recommended in most cases unless necessary.

Cancelation is an event that is delivered to your workers via workflow task. Worker can react to it as in you have ability to do some cleanup in workflow code before workflow execution is canceled. We have some samples in different sdks that could share if you let us know which Temporal SDK you use.

I am using Java SDK

Here’s a java sample that shows how you can do some cleanup after client makes a cancelation request: samples-java/core/src/main/java/io/temporal/samples/hello/HelloDetachedCancellationScope.java at main · temporalio/samples-java · GitHub

Thanks again @jreynolds23.

Just for my understanding. Let’s say I have a workflow method which is doing something like

Workflow.await(duration);
activity.execute();

When the workflow is awaiting if I do a terminate, in that case will the worker be executing the activity.execute() or the workflow will be terminated and active execution will not be invoked in worker?

For your case the activity would never be invoked. The cached workflow thread that is waiting to unblock workflow.await would never get notification of timer firing, as execution is terminated so timer fired event would never be delivered to your worker, and worker would eventually evict this workflow thread meaning it does not utilize your worker resources.