Best way to create an async child workflow

Currently, it is not straightforward. We have plans to improve the experience (relevant issue), but in the meantime, the following should be done.

Java SDK

  1. Set ChildWorkflowOptions.ParentClosePolicy to ABANDON when creating a child workflow stub.
  2. Start child workflow asynchronously using Async.function or Async.procedure.
  3. Call Workflow.getWorkflowExecution(…) on the child stub
  4. Wait for the Promise returned by getWorkflowExecution to complete. This indicates that the child successfully started (or start failed).
  5. Complete parent workflow.

Steps 3 and 4 are needed to ensure that child workflow starts before the parent closes. If the parent initiates child workflow and immediately completes the child would never start. Here is the code that demonstrates the steps:

   public void parentWorklfow() {
       ChildWorkflowOptions options =
          ChildWorkflowOptions.newBuilder()
              .setParentClosePolicy(ParentClosePolicy.PARENT_CLOSE_POLICY_ABANDON)
              .build();
       MyChildWorkflow child = Workflow.newChildWorkflowStub(MyChildWorkflow.class, options);
       Async.procedure(child::<workflowMethod>, <args>...);
       Promise<WorkflowExecution> childExecution = Workflow.getWorkflowExecution(child);
       // Wait for child to start
       childExecution.get()
  }

Go SDK

  1. Set ChildWorkflowOptions.ParentClosePolicy to ABANDON when creating a child workflow stub.
  2. Start child workflow using ExecuteChildWorkflow
  3. Call GetChildWorkflowExecution on the ChildWorkflowFuture returned by the ExecuteChildWorkflow
  4. Wait on the WorkflowExecution Future. This indicates that the child successfully started (or start failed).
  5. Complete parent workflow

Steps 3 and 4 are needed to ensure that child workflow starts before the parent closes. If the parent initiates child workflow and immediately completes the child would never start. Here is the code that demonstrates the steps (error handling omitted for brevity):

func ParentWorkflow(ctx workflow.Context) error {
    childWorkflow := workflow.ExecuteChildWorkflow(ctx, MyChildWorkflow)
    // Wait for child to start
    _ = childWorkflow.GetChildWorkflowExecution().Get(ctx, nil)
    return nil
}
5 Likes