Microservice Orchestration
View as MarkdownOne Flow calls up to four APIs. API 2 and API 3 run in parallel. The branch for API 3 waits for a callback or a 24-hour timeout before it makes its call.
SDKs: Python · Go · TypeScript · Java · Rust
Shows: Static Parallel Steps and Decision with Deadline.
The graph and the names in this description come from the Python example. The Rust example uses other names; see Rust example.
Product requirements
The process starts with a data value. It must:
- Call API 1 and store the value.
- Then call API 2 and API 3 in parallel.
- Before API 3, wait until another service reports that it is ready, for at most 24 hours.
- If 24 hours pass first, call API 4 after API 3.
- While the process runs, let a caller swap the value: store a new one and get the previous one back, in one operation.
API 2, API 3, and API 4 use the value that is current when they run.
Flow design
CallAPI1 stores the value in the data Attribute and starts CallAPI2 and CallAPI3 as parallel Steps. Each API call is its own Step. So a retry of API 3 does not repeat API 1 or API 2.
CallAPI2 returns DeadEnd, which ends its branch. The other branch completes the Flow.
CallAPI3 waits with AnyOf for one Ready Channel message or a 24-hour Timer. Its Execute calls API 3, then checks whether the Timer fired. If it did, the Flow goes on to CallAPI4.
The Swap RPC locks data, writes the new value, and returns the old one. Each branch reads data when it runs. So a swap between the two reads gives CallAPI2 and CallAPI3 different values.
A real API call needs an idempotency key, because a Step that was cut off can run again. The example passes none: it calls local stubs.
Core implementation
Each tab shows the Flow with the Swap RPC, then CallAPI1 and CallAPI3.
class OrchestrationFlow(Flow[str]):
data = Attribute("data", str)
ready = Channel[None]("Ready", type(None))
def __init__(self, service: MyDependencyService) -> None:
self.service = service
self.call_api4 = CallAPI4(service, self.data)
self.call_api3 = CallAPI3(service, self.data, self.ready, self.call_api4)
self.call_api2 = CallAPI2(service, self.data)
self.call_api1 = CallAPI1(service, self.data, self.call_api2, self.call_api3)
def get_steps(self) -> StepList[str]:
return StepList.start_step(self.call_api1).other_steps(
self.call_api2,
self.call_api3,
self.call_api4,
)
def get_persistence_schema(self) -> PersistenceSchema:
return PersistenceSchema.of(self.data, self.ready)
@rpc(lock_attributes=(data.lock(),))
def swap(self, context: Context, new_data: str) -> RPCResult[str]:
old_data = self.data.get(context)
# CallAPI1 would overwrite a value written before it stores data.
if old_data is None:
raise RuntimeError("data is not ready yet")
self.data.set(context, new_data)
return RPCResult(old_data)
class CallAPI1(Step[str]):
def execute(self, context: Context, input: str) -> StepDecision:
self.service.call_api1(input)
self.data.set(context, input)
return go_to_many(
StepMovement.of(CallAPI2, None),
StepMovement.of(CallAPI3, None),
)
class CallAPI3(Step[None]):
def wait_for(self, context: Context, input: None) -> Wait:
return Wait.any_of(
Timer.by_duration(timedelta(hours=24)),
self.ready.for_one(),
)
def execute(self, context: Context, input: None) -> StepDecision:
value = self.data.get(context)
self.service.call_api3(value)
if context.has_timer_fired():
return go_to(CallAPI4, None)
return graceful_complete(value)
Example: examples/python/dex_examples/products/microservices/orchestration_flow.py
type OrchestrationFlow struct {
dex.FlowDefaults
service service.MyService
}
func NewOrchestrationFlow(applicationService service.MyService) *OrchestrationFlow {
return &OrchestrationFlow{service: applicationService}
}
func (flow *OrchestrationFlow) GetSteps() []dex.StepDef {
return []dex.StepDef{
dex.DefineStartStep(callAPI1{service: flow.service}),
dex.DefineStep(callAPI2{service: flow.service}),
dex.DefineStep(callAPI3{service: flow.service}),
dex.DefineStep(callAPI4{service: flow.service}),
}
}
func (flow *OrchestrationFlow) GetRPCs() []dex.RPCDef {
return []dex.RPCDef{
dex.DefineRPC(flow.Swap, &dex.RPCOptions{
LockAttributes: []dex.AttributeLock{dex.LockAttribute(Data)},
}),
dex.DefineRPC(flow.SignalReady, nil),
dex.DefineRPC(flow.GetData, nil),
}
}
func (*OrchestrationFlow) GetPersistenceSchema() dex.PersistenceSchema {
return dex.PersistenceSchema{
Attributes: []dex.AttributeDef{Data},
Channels: []dex.ChannelDef{Ready},
}
}
func (*OrchestrationFlow) Swap(
ctx dex.Context,
newData string,
) (*dex.RPCResult[string], error) {
oldData, err := Data.Get(ctx)
if err != nil {
return nil, err
}
if err := Data.Set(ctx, newData); err != nil {
return nil, err
}
return &dex.RPCResult[string]{Output: oldData}, nil
}
func (step callAPI1) Execute(
ctx dex.Context,
input string,
) (*dex.StepDecision, error) {
step.service.CallAPI1(input)
if err := Data.Set(ctx, input); err != nil {
return nil, err
}
return dex.GoToMany(
dex.MovementOf(callAPI2{}, nil),
dex.MovementOf(callAPI3{}, nil),
), nil
}
func (callAPI3) WaitFor(
dex.Context,
dex.None,
) (*dex.Wait, error) {
return dex.AnyOf(
dex.Timer(24*time.Hour),
Ready.ForOne(),
), nil
}
func (step callAPI3) Execute(
ctx dex.Context,
_ dex.None,
) (*dex.StepDecision, error) {
data, err := Data.Get(ctx)
if err != nil {
return nil, err
}
step.service.CallAPI3(data)
if ctx.HasTimerFired() {
return dex.GoTo(callAPI4{}, nil), nil
}
return dex.GracefulComplete(data), nil
}
@Component
public class OrchestrationFlow implements Flow<String> {
public final Attribute<String> data = Attribute.define("data", String.class);
public final Channel<Void> ready = Channel.define("Ready", Void.class);
private final MyDependencyService service;
private final CallAPI1 callAPI1 = new CallAPI1();
private final CallAPI2 callAPI2 = new CallAPI2();
private final CallAPI3 callAPI3 = new CallAPI3();
private final CallAPI4 callAPI4 = new CallAPI4();
public OrchestrationFlow(final MyDependencyService service) {
this.service = service;
}
@Override
public StepList<String> getSteps() {
return StepList.startStep(callAPI1).otherSteps(callAPI2, callAPI3, callAPI4);
}
@Override
public PersistenceSchema getPersistenceSchema() {
return PersistenceSchema.of(data, ready);
}
@RPC(lockAttributes = {"data"})
public RPCResult<String> swap(final Context context, final String newData) {
final String oldData = data.get(context);
// CallAPI1 would overwrite a value written before it stores data.
if (oldData == null) {
throw new IllegalStateException("data is not ready yet");
}
data.set(context, newData);
return RPCResult.of(oldData);
}
final class CallAPI1 implements Step<String> {
@Override
public StepDecision execute(final Context context, final String input) {
service.callAPI1(input);
data.set(context, input);
return StepDecision.goToMany(
StepMovement.of(CallAPI2.class, null),
StepMovement.of(CallAPI3.class, null));
}
}
final class CallAPI3 implements Step<Void> {
@Override
public Wait waitFor(final Context context, final Void input) {
return Wait.anyOf(Timer.byDuration(Duration.ofHours(24)), ready.forOne());
}
@Override
public StepDecision execute(final Context context, final Void input) {
final String value = data.get(context);
service.callAPI3(value);
if (context.hasTimerFired()) {
return StepDecision.goTo(CallAPI4.class, null);
}
return StepDecision.gracefulComplete(value);
}
}
Example: examples/java/src/main/java/io/superdurable/dex/products/microservices/OrchestrationFlow.java
const data = new Attribute("data", stringCodec);
export class OrchestrationFlow implements Flow<string> {
public readonly data = data;
public readonly callAPI1 = new CallAPI1(this);
public readonly callAPI2 = new CallAPI2(this);
public readonly callAPI3 = new CallAPI3(this);
public readonly callAPI4 = new CallAPI4(this);
public constructor(public readonly service: MyDependencyService = myDependencyService) {}
public getFlowType(): string {
return "OrchestrationFlow";
}
public getSteps() {
return StepList.startStep(this.callAPI1).otherSteps(
this.callAPI2,
this.callAPI3,
this.callAPI4,
);
}
public getPersistenceSchema(): PersistenceSchema {
return {
attributes: [this.data],
channels: [ready],
};
}
@rpc({ inputCodec: stringCodec, outputCodec: stringCodec, lockAttributes: [data.lock()] })
public swap(context: Context, newData: string): RPCResult<string> {
const oldData = this.data.get(context);
// CallAPI1 would overwrite a value written before it stores data.
if (oldData === undefined) {
throw new Error("data is not ready yet");
}
this.data.set(context, newData);
return { output: oldData };
}
class CallAPI1 implements Step<string> {
public execute(context: Context, input: string): StepDecision {
this.flow.service.callAPI1(input);
this.flow.data.set(context, input);
return goToMany(
StepMovement.of(CallAPI2, undefined),
StepMovement.of(CallAPI3, undefined),
);
}
}
class CallAPI3 implements Step<void> {
public waitFor(_context: Context, _input: void): Wait {
return Wait.anyOf(Timer.byDuration(DAY_MS), ready.forOne());
}
public execute(context: Context, _input: void): StepDecision {
const value = this.flow.data.get(context);
this.flow.service.callAPI3(value);
if (context.hasTimerFired()) {
return goTo(CallAPI4, undefined);
}
return gracefulComplete(value);
}
}
Example: examples/typescript/src/products/microservices/orchestration-flow.ts
pub const SWAP_ORCHESTRATION_DATA: Rpc<String, String> = Rpc::new("SwapOrchestrationData");
pub const SIGNAL_ORCHESTRATION_READY: Rpc<(), ()> = Rpc::new("SignalOrchestrationReady");
pub static DATA: LazyLock<Attribute<String>> =
LazyLock::new(|| Attribute::new("orchestration-data"));
pub static READY: LazyLock<Channel<()>> = LazyLock::new(|| Channel::new("orchestration-ready"));
#[derive(Default)]
pub struct OrchestrationFlow {
call_api_one: CallApiOne,
call_api_two: CallApiTwo,
call_api_three: CallApiThree,
call_api_four: CallApiFour,
}
impl Flow for OrchestrationFlow {
type StartInput = String;
fn steps(&self) -> StepList<'_, Self::StartInput> {
StepList::start(&self.call_api_one)
.and(&self.call_api_two)
.and(&self.call_api_three)
.and(&self.call_api_four)
}
fn persistence(&self) -> PersistenceSchema {
PersistenceSchema::new().attribute(&DATA).channel(&READY)
}
fn rpcs(&self) -> RpcList<Self> {
RpcList::new()
.function(SWAP_ORCHESTRATION_DATA.lock(DATA.lock()), Self::swap)
.procedure_without_input(SIGNAL_ORCHESTRATION_READY, Self::signal_ready)
}
}
impl Step for CallApiOne {
type Input = String;
fn execute(&self, context: &mut Context, input: Self::Input) -> HandlerResult<StepDecision> {
context.record_event("api-one", input.clone())?;
DATA.set(context, input)?;
Ok(StepDecision::go_to_many([
StepMovement::to(&CallApiTwo, ()),
StepMovement::to(&CallApiThree, ()),
]))
}
}
impl Step for CallApiThree {
type Input = ();
fn wait_for(&self, _context: &mut Context, _input: Self::Input) -> HandlerResult<Wait> {
Ok(Wait::any_of([
READY.for_one(),
Timer::by_duration(Duration::from_secs(24 * 60 * 60)),
]))
}
fn execute(&self, context: &mut Context, _input: Self::Input) -> HandlerResult<StepDecision> {
let data = DATA.get(context)?.unwrap_or_default();
context.record_event("api-three", data.clone())?;
if context.has_timer_fired(0) {
return Ok(StepDecision::go_to(&CallApiFour, ()));
}
Ok(StepDecision::graceful_complete(data))
}
}
Rust example
The Rust example runs the same Flow under other names. Its Attribute is orchestration-data, its Channel is orchestration-ready, and its Steps are CallApiOne to CallApiFour. Each Step records an event in place of an API call. The calls in Run it work the same way.
Run it
Start the examples of one language as in Run an example from the playground. In the examples playground, choose Microservices. Call Start, then Swap data (RPC), then Signal ready, all with the same Flow ID. Swap fails until CallAPI1 has stored the value; call it again.
The screenshots below come from a run with its own values. It started with initial-data, and Swap replaced it with updated-data. The playground starts with test initial data and swaps in the value of its data field. Ready arrived before the Timer fired, so CallAPI4 did not run.
In Dex Web, open Events. Timeline shows the Swap RPC and the Ready message. Graph shows which Steps ran.

