Skip to main content

Entity Flow

View as Markdown

Keep one long-lived Flow for each business entity, such as a customer, an order, or an account. The Flow holds the entity's state for as long as the entity exists. Every change goes through the Flow, so Dex saves it durably.

The runnable example keeps one CustomerAccountFlow per customer account. It stores a display name, an email address, a credit balance, and whether the account is retired. Try its routes in the examples playground.

When to use this pattern

Use an Entity Flow when one business entity needs durable state that several callers change over time. Each change must be validated against the current state. Typical examples are a customer account, a shopping cart, a device, or a subscription record.

To also query the latest state of many entities with SQL, extend this pattern with Entity Flow with Attribute Sync.

How it works

  1. Open the account. The application starts a Flow whose ID comes from the account ID, such as customer-account-42. The start request sets the initial Attributes and an ID reuse policy that rejects every reused ID. A second start with the same account ID fails while Dex keeps the account's Flow, so each account has exactly one Flow.
  2. Change the contact details. UpdateContactDetails checks that the account is open, validates the new name and email address, then writes both Attributes.
  3. Adjust the credit balance. AdjustCreditBalance checks that the account is open, reads the balance, adds the amount, and rejects a result below zero. All three RPCs that change the account declare the same lock. Calls that get the lock run one at a time. A call that finds the lock held fails with a lock conflict, and the caller retries only that error, with backoff.
  4. Read the account. The application reads the Attributes with the Client. No Worker runs for the read.
  5. Retire the account. RetireAccount checks that the balance is zero, marks the account retired, and starts CloseAccountStep. While the Flow still accepts RPCs, a repeated retire changes nothing. CloseAccountStep archives the account once and completes the Flow gracefully.

Between these calls the Flow has no active Step. It keeps running and holds no Worker, so it can live for months or years.

Core implementation

Open one Flow per entity

Derive the Flow ID from the entity ID. Start the Flow with no Flow timeout, and set the initial state as Attributes in the start request. Treat an already-started error as "this account exists".

controller.pyPython
flow_id = customer_account_flow_id(account_id)
options = (
StartFlowOptions(id_reuse_policy=IdReusePolicy.DISALLOW)
.with_attribute(flow.display_name, contact.display_name)
.with_attribute(flow.email, contact.email)
.with_attribute(flow.credit_balance, 0)
.with_attribute(flow.retired, False)
)
run_id = await app_state.client.start_flow(flow, flow_id, None, options)

Example: examples/python/dex_examples/patterns/entity-flow/controller.py

Change state through RPCs

Each RPC checks that the account is open, validates its input against the current state, then writes the Attributes. UpdateContactDetails, AdjustCreditBalance, and RetireAccount declare a lock on the balance Attribute. The lock makes each check and its write one step, so no change slips in after the account is retired and no adjustment overwrites another.

customer_account_flow.pyPython
@rpc(name="UpdateContactDetails", lock_attributes=(credit_balance.lock(),))
def update_contact_details(self, context: Context, input: ContactDetails) -> None:
self.require_open_account(context)
input.validate()
self.display_name.set(context, input.display_name)
self.email.set(context, input.email)

@rpc(name="AdjustCreditBalance", lock_attributes=(credit_balance.lock(),))
def adjust_credit_balance(
self, context: Context, input: CreditAdjustment
) -> RPCResult[int]:
self.require_open_account(context)
if input.amount == 0:
raise ValueError("amount must not be zero")
balance = self.credit_balance.get(context) + input.amount
if balance < 0:
raise ValueError("credit balance cannot go below zero")
self.credit_balance.set(context, balance)
return RPCResult(balance)

Example: examples/python/dex_examples/patterns/entity-flow/customer_account_flow.py

Only calls that get the lock run, and they run one at a time. A locked RPC fails at once with a lock-conflict error when another call holds the lock. Retry only that error, with backoff, and pass any other error to the caller. See RPC lock conflicts.

Read state with the Client

Read stored Attributes with the Client's Attribute read. It returns committed values and runs no Worker. Use a read-only RPC instead when the read needs Flow code, such as authorization or a derived view; see Read-only RPCs.

controller.pyPython
values = await app_state.client.get_attributes(
customer_account_flow_id(account_id),
flow.display_name,
flow.email,
flow.credit_balance,
)

Example: examples/python/dex_examples/patterns/entity-flow/controller.py

Retire the entity

RetireAccount holds the same lock as the other RPCs. It checks the balance, sets the retired Attribute, and starts CloseAccountStep. While the Flow still accepts RPCs, a repeated retire finds the account retired and returns without starting another Step.

CloseAccountStep archives the account and returns GracefulComplete, and the Flow completes. Until the Flow closes, UpdateContactDetails and AdjustCreditBalance see retired under the lock and return the "account is retired" error. When the archive is unavailable, the Step fails and Dex retries it. During those retries the Flow stays running and the account stays retired.

Dex can run the same Step execution more than once, for example when an attempt archives the account but its result is lost. The archive uses the account's Flow ID as a unique key, so a retried attempt finds the record and succeeds without archiving twice. A real archive service does the same with a unique insert or an idempotent upsert.

After the Flow completes, read the retained Attributes with the Client until Dex purges the Flow. Dex rejects locked RPCs to a closing or closed Flow, so a caller that repeats a request then handles that error and reads the retained state.

customer_account_flow.pyPython
def execute(self, context: Context, input: None) -> StepDecision:
self.archive.archive_account(context.flow_id, context.step_execution_id)
return graceful_complete()

@rpc(name="RetireAccount", lock_attributes=(credit_balance.lock(),))
def retire_account(self, context: Context) -> RPCResult[None]:
if self.retired.get(context):
return RPCResult(None)
if self.credit_balance.get(context) != 0:
raise ValueError("spend or refund the credit balance before retiring")
self.retired.set(context, True)
return RPCResult(None, next_steps=(StepMovement.of(CloseAccountStep, None),))

def require_open_account(self, context: Context) -> None:
if self.retired.get(context):
raise ValueError("account is retired")

Example: examples/python/dex_examples/patterns/entity-flow/customer_account_flow.py

An entity Flow can also have a Step that waits on something long, such as a Channel of incoming commands. Add the graceful completion condition to that wait where your SDK and Server provide it; a completion request then wakes the Step. Where they do not, have the retire RPC publish an explicit close message to that Channel, and let the Step end when it reads the message. See Wait for a completion request for the Server support, and the Waits reference of your SDK for its support: Python, Go, Java, TypeScript, or Rust.

Keep the state bounded

Each Attribute holds one value that the Flow rewrites on every change. Keep the entity's current state in plain Attributes. When the entity collects a growing history, such as its orders or audit events, store that history in a Sequentially Chunked AttributeMap.

API endpoints

  • POST /patterns/entity-flow/account: open an account
  • POST /patterns/entity-flow/account/contact: update its contact details
  • POST /patterns/entity-flow/account/credits: adjust its credit balance
  • GET /patterns/entity-flow/account?accountId=...: read the account with the Client
  • POST /patterns/entity-flow/account/retire?accountId=...: retire the account

The examples playground lists these routes with sample request bodies.

Next