---
title: "Microservice Orchestration"
description: "One 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."
canonical_url: "https://docs.superdurable.io/examples/microservice-orchestration/"
source: "docs/content/use-cases/microservice-orchestration.mdx"
locale: "en"
language: "python"
---

> Index of every page for AI agents: https://docs.superdurable.io/llms.txt

# Microservice Orchestration

Code on this page is in Python. Other languages: [Go](https://docs.superdurable.io/examples/microservice-orchestration.go.md) · [Java](https://docs.superdurable.io/examples/microservice-orchestration.java.md) · [TypeScript](https://docs.superdurable.io/examples/microservice-orchestration.typescript.md) · [Rust](https://docs.superdurable.io/examples/microservice-orchestration.rust.md)

One 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](https://docs.superdurable.io/design-patterns/parallel/static-parallel-steps.md) and [Decision with Deadline](https://docs.superdurable.io/design-patterns/external-interaction/decision-with-deadline.md).

**Flow graph: OrchestrationFlow**

**Steps**

1. `CallAPI1` (start Step): Call API 1, store its data, and call APIs 2 and 3 in parallel. Next: `CallAPI2`, or `CallAPI3`. Writes `data`.
2. `CallAPI2`: Call API 2 with the stored data. Next: this branch ends. Reads `data`.
3. `CallAPI3`: Wait for the ready signal or 24 hours, then call API 3. Next: `CallAPI4`, or the Flow completes. Reads `data`.
4. `CallAPI4`: Call API 4 when the ready signal did not arrive in time. Next: the Flow completes. Reads `data`.

**RPCs**

- `get_data`: Reads `data`.
- `signal_ready`: Publishes to `Ready`.
- `swap`: Reads `data`; locks `data`; writes `data`.

Example: [examples/python/dex_examples/products/microservices/orchestration_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/microservices/orchestration_flow.py)

The graph and the names in this description come from the Python example. The Rust example uses other names; see [Rust example](https://docs.superdurable.io/examples/microservice-orchestration.md#rust-example).

## Product requirements

The process starts with a data value. It must:

1. Call API 1 and store the value.
2. Then call API 2 and API 3 in parallel.
3. Before API 3, wait until another service reports that it is ready, for at most 24 hours.
4. If 24 hours pass first, call API 4 after API 3.
5. 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](https://docs.superdurable.io/concepts/step.md#idempotency-keys), 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`.

**Python**

```python
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)
```

```python
class CallAPI1(Step[str]):
    def __init__(
        self,
        service: MyDependencyService,
        data: Attribute[str],
        call_api2: CallAPI2,
        call_api3: CallAPI3,
    ) -> None:
        self.service = service
        self.data = data
        self.call_api2 = call_api2
        self.call_api3 = call_api3

    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),
        )
```

```python
class CallAPI3(Step[None]):
    def __init__(
        self,
        service: MyDependencyService,
        data: Attribute[str],
        ready: Channel[None],
        call_api4: CallAPI4,
    ) -> None:
        self.service = service
        self.data = data
        self.ready = ready
        self.call_api4 = call_api4

    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](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/microservices/orchestration_flow.py)

<a id="rust-example"></a>

## 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](https://docs.superdurable.io/examples/microservice-orchestration.md#run-it) work the same way.

## Run it

<a id="demo"></a>

Start the examples of one language as in [Run an example from the playground](https://docs.superdurable.io/install.md#run-an-example-from-the-playground). In the [examples playground](https://github.com/superdurable/dex/tree/main/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.

[![Dex Web Timeline showing the Swap and Signal Ready calls in the orchestration run](https://docs.superdurable.io/img/use-cases/microservice-orchestration-timeline.png)](https://docs.superdurable.io/img/use-cases/microservice-orchestration-timeline.png)

[![Dex Web Graph showing the Swap and Signal Ready calls in the orchestration run](https://docs.superdurable.io/img/use-cases/microservice-orchestration-graph.png)](https://docs.superdurable.io/img/use-cases/microservice-orchestration-graph.png)

## Next

- [Job Posting](https://docs.superdurable.io/examples/job-posting.md)
- [Static Parallel Steps](https://docs.superdurable.io/design-patterns/parallel/static-parallel-steps.md)
- [Decision with Deadline](https://docs.superdurable.io/design-patterns/external-interaction/decision-with-deadline.md)
- [Channels](https://docs.superdurable.io/concepts/primitives/channel.md)
- [Timers](https://docs.superdurable.io/concepts/primitives/timer.md)
- [RPCs](https://docs.superdurable.io/concepts/primitives/rpc.md)
- [Attributes](https://docs.superdurable.io/concepts/primitives/attribute.md)
