Best way to kill and restart a workflow

I have a use case where if a workflow with the given id is open then i want to kill it and start a new one. This is what i am doing right now:

try {
} catch (final WorkflowAlreadyStartedException ex) {
    workflowHandler.terminateWorkflow(workflowId, "restart required");

workflowHandler is my wrapper class that does newWorkflowStub() and terminate() respectively

Problem is that when i terminate and immediately try to start a workflow with the same id i am getting WorkflowAlreadyStartedException. I assumed that terminate api call is strongly consistent but it doesn’t seem to be. Is this expected?

Also, Is this the best way to do it if i need kill and immediately start a new workflow with the same id? another option i see is to reset the open workflow (ResetWorkflowExecutionRequest) but i am guessing this adds on to the existing workflow history which i want to avoid.

I personally wouldn’t use terminate for this. I would use signalWithStart to start workflow if it is not running or signal an already running workflow. Upon receiving such a signal the running workflow would call continue as new to start the new one.

I believe the terminate workflow is fully consistent. But I still think that your solution has potential race conditions if the code in your sample is executed by two processes at the same time.

Ah nice, I didnt realize i could do continueAsNew inside the signal method. However as i understand continueAsNew starts a new workflow and continues from the existing workflow state right? is it possible to make it start from the beginning of the workflow

continueAsNew continues current workflow exec as a new run, so its alway a new execution. You can pass the current execution workflow state as parameters to the next execution if needed