Skip to main content
Reference vendor/dbos 2 min read

advanced-async


title: Use Async Workflows Correctly impact: LOW impactDescription: Enables non-blocking I/O in workflows tags: async, coroutine, await, asyncio

Use Async Workflows Correctly

Coroutine (async) functions can be DBOS workflows. Use async-specific methods and patterns.

Incorrect (mixing sync and async):

@DBOS.workflow()
async def async_workflow():
    # Don't use sync sleep in async workflow!
    DBOS.sleep(10)

    # Don't use sync start_workflow for async workflows
    handle = DBOS.start_workflow(other_async_workflow)

Correct (async patterns):

import asyncio
import aiohttp

@DBOS.step()
async def fetch_async():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://example.com") as response:
            return await response.text()

@DBOS.workflow()
async def async_workflow():
    # Use async sleep
    await DBOS.sleep_async(10)

    # Await async steps
    result = await fetch_async()

    # Use async start_workflow
    handle = await DBOS.start_workflow_async(other_async_workflow)

    return result

Sync DBOS Methods Raise Inside an Event Loop

Many synchronous DBOS methods (such as DBOS.sleep, DBOS.recv, DBOS.send, DBOS.set_event, DBOS.get_event, and DBOS.register_queue) raise RuntimeError when called while an event loop is running. In async def code (async workflows, async FastAPI handlers), use the _async variants:

# "tasks" is registered at startup, after DBOS.launch()

@DBOS.workflow()
async def other_async_workflow():
    ...

@DBOS.workflow()
async def async_workflow(target_id: str):
    handle = await DBOS.enqueue_workflow_async("tasks", other_async_workflow)
    await DBOS.send_async(target_id, "msg")           # not send
    if await DBOS.patch_async("new-logic"):           # not patch
        ...
    return await handle.get_result()

A workflow enqueued with DBOS.enqueue_workflow_async is started in the event loop in which DBOS.launch() was called (if that loop is still running), otherwise in a background event loop. Calling a coroutine workflow directly or with start_workflow_async runs it in the caller’s loop.

Async steps also support timeout_seconds (cancel and raise DBOSStepTimeoutError) and preemptible=True; see step-basics.

Running Async Steps In Parallel

You can run async steps in parallel if they are started in deterministic order:

Correct (deterministic start order):

@DBOS.workflow()
async def parallel_workflow():
    # Start steps in deterministic order, then await together
    tasks = [
        asyncio.create_task(step1("arg1")),
        asyncio.create_task(step2("arg2")),
        asyncio.create_task(step3("arg3")),
    ]
    # Use return_exceptions=True for proper error handling
    results = await asyncio.gather(*tasks, return_exceptions=True)
    return results

Incorrect (non-deterministic order):

@DBOS.workflow()
async def bad_parallel_workflow():
    async def seq_a():
        await step1("arg1")
        await step2("arg2")  # Order depends on step1 timing

    async def seq_b():
        await step3("arg3")
        await step4("arg4")  # Order depends on step3 timing

    # step2 and step4 may run in either order - non-deterministic!
    await asyncio.gather(seq_a(), seq_b())

Correct (concurrent sequences with reserved step IDs, 3.4+):

Reserve step IDs in a deterministic order with DBOS.reserve_step(), then run each step from its reservation with run_async (or run in a sync workflow), which takes the same arguments as DBOS.run_step_async: step options (or None), a function, and its arguments. Each step is recorded at its reserved position, whenever it actually starts:

def fetch(arg):  # plain function, run as a step through its reservation
    ...

@DBOS.workflow()
async def concurrent_sequences_workflow():
    # Reserve all step IDs before starting any concurrent work
    r1, r2, r3, r4 = [DBOS.reserve_step() for _ in range(4)]

    async def seq_a():
        await r1.run_async({"name": "step1"}, fetch, "arg1")
        await r2.run_async({"name": "step2"}, fetch, "arg2")

    async def seq_b():
        await r3.run_async({"name": "step3"}, fetch, "arg3")
        await r4.run_async({"name": "step4"}, fetch, "arg4")

    return await asyncio.gather(seq_a(), seq_b(), return_exceptions=True)

Call DBOS.reserve_step() from workflow code, outside any step or datasource transaction; it raises DBOSException otherwise. Run each reservation exactly once, from the workflow that reserved it (a second run raises DBOSException); a reservation never run leaves an unused step ID, which is safe. Alternatively, run each sequence in a child workflow.

For database operations in async workflows, use an AsyncSQLAlchemyDatasource, which runs transactions natively in async def. Create it at module scope with asyncio.run, before DBOS.launch(). With SQLite, use a sqlite+aiosqlite:/// URL:

import asyncio
import os
from dbos import AsyncSQLAlchemyDatasource

ads = asyncio.run(AsyncSQLAlchemyDatasource.create(os.environ["APP_DATABASE_URL"]))

@ads.transaction()
async def insert_data(data):
    await ads.sql_session().execute(...)

@DBOS.workflow()
async def async_workflow(data):
    await insert_data(data)

Reference: Async Workflows