title: Enqueue Workflows from External Applications impact: HIGH impactDescription: Enables decoupled architecture with separate API and worker services tags: client, enqueue, workflow, external
Enqueue Workflows from External Applications
Use client.enqueue() to submit workflows from outside the DBOS application. Must specify workflow and queue names explicitly.
Incorrect (missing required options):
from dbos import DBOSClient
client = DBOSClient(system_database_url=db_url)
# Missing workflow_name and queue_name!
handle = client.enqueue({}, task_data)
Correct (with required options):
from dbos import DBOSClient, EnqueueOptions
client = DBOSClient(system_database_url=db_url)
# Optionally register the queue from the client (persists to system database)
client.register_queue("task_queue", global_concurrency=10)
options: EnqueueOptions = {
"workflow_name": "process_task", # Required
"queue_name": "task_queue", # Required
}
handle = client.enqueue(options, task_data)
result = handle.get_result()
client.destroy()
The queue does not need to exist when enqueue is called. If no queue with the given name has been registered, the workflow is still durably recorded as ENQUEUED and starts running once the queue is registered and a worker becomes available.
workflow_name is the workflow’s registered name: the name passed to @DBOS.workflow, or by default the function’s __qualname__ (no module prefix, e.g. process_task or URLFetcher.fetch_workflow).
Optional parameters:
options: EnqueueOptions = {
"workflow_name": "process_task",
"queue_name": "task_queue",
"workflow_id": "custom-id-123",
"workflow_id_reuse_policy": "reject", # or "return-existing" (default)
"workflow_timeout": 300,
"deduplication_id": "user-123", # not supported on partitioned queues
"duplication_policy": "return-existing", # singleton: attach to the existing workflow
"priority": 1,
"delay_seconds": 60, # Delay before becoming eligible
# "queue_partition_key": "user-123", # required on partitioned queues (use instead of deduplication_id)
"app_version": "1.0.0", # unset = dequeued by the latest version
"authenticated_user": "alice",
"authenticated_roles": ["admin"],
"attributes": {"customer": "acme"}, # searchable via list_workflows(attributes=...) (Postgres only)
"application_name": "order-service", # owning app, if the system DB is shared
}
workflow_id_reuse_policy="reject"raisesDBOSWorkflowIDInUseErrorif the ID exists.duplication_policy="return-existing"requiresdeduplication_id; the colliding caller’s arguments are discarded and the handle resolves with the original workflow’s result. Otherwise a collision raisesDBOSQueueDeduplicatedError.- Also available:
serialization_type(see advanced-serialization) andotel_context(propagate an OpenTelemetry trace context). max_recovery_attemptsis not an enqueue option; set it on@DBOS.workflow(max_recovery_attempts=...).
Enqueueing Class Methods
To enqueue a @classmethod workflow, set class_name; for a method on a configured instance, set both class_name and instance_name (the instance’s config_name). The class and instance must be registered in the application that dequeues the workflow. Static methods need neither.
options: EnqueueOptions = {
"queue_name": "example_queue",
"workflow_name": "URLFetcher.fetch_workflow",
"class_name": "URLFetcher",
"instance_name": "https://example.com",
}
handle = client.enqueue(options)Enqueue or Send Inside Your Own Transaction
Three client methods write inside a caller-owned SQLAlchemy transaction, so they commit or roll back atomically with your own writes:
client.enqueue_in_transaction(conn_or_session, options: EnqueueOptions, *args, **kwargs) -> WorkflowHandle
client.send_in_transaction(conn_or_session, destination_id, message, topic=None, idempotency_key=None,
*, serialization_type=..., send_to_forks=False) -> None
client.send_bulk_in_transaction(conn_or_session, messages: List[SendMessage],
*, serialization_type=..., send_to_forks=False) -> None
Incorrect (separate transactions: a crash between them loses or orphans work):
with engine.begin() as conn:
conn.execute(text("INSERT INTO orders (id) VALUES (:id)"), {"id": order_id})
client.enqueue(options, order_id) # not atomic with the insert
Correct (one transaction):
import os
import sqlalchemy as sa
from sqlalchemy import text
from dbos import DBOSClient, EnqueueOptions, SendMessage
client = DBOSClient(system_database_url=os.environ["DBOS_SYSTEM_DATABASE_URL"])
# Must target the DBOS **system** database. For Postgres, use the psycopg (v3) driver
# DBOS installs; a plain postgresql:// URL makes SQLAlchemy look for psycopg2.
engine = sa.create_engine(
sa.make_url(os.environ["DBOS_SYSTEM_DATABASE_URL"]).set(drivername="postgresql+psycopg")
)
options: EnqueueOptions = {"queue_name": "orders", "workflow_name": "process_order"}
order_id = "order-123"
payment_workflow_id = "payment-order-123" # IDs of workflows waiting on recv
wf_a, wf_b = "listener-a", "listener-b"
# The orders table in this example lives in the system database, since conn is connected to it
with engine.begin() as conn:
conn.execute(text("INSERT INTO orders (id) VALUES (:id)"), {"id": order_id})
handle = client.enqueue_in_transaction(conn, options, order_id)
client.send_in_transaction(conn, payment_workflow_id, "paid", "payment_status",
idempotency_key=f"paid-{order_id}")
client.send_bulk_in_transaction(conn, [
SendMessage(wf_a, "order-created", "events"),
SendMessage(wf_b, "order-created", "events"),
])
# Nothing is enqueued or sent until the transaction commits
result = handle.get_result() # Only after commit
- Pass a SQLAlchemy
Connectionor ORMSessionon the system database; the write can’t atomically span a separate app database. - You own the transaction: these methods don’t begin, commit, roll back, or retry on DB errors.
enqueue_in_transactiontakes the same options asenqueue, exceptduplication_policy="return-existing"(raisesDBOSException). Its handle exists immediately, but don’t callget_result()before commit.- Messages are not visible to the destination workflow until commit.
- No async variants; from async code, bridge with
await conn.run_sync(lambda sync_conn: client.send_in_transaction(sync_conn, dest, msg))on anAsyncConnectioninsideasync with conn.begin().
Reference: DBOSClient.enqueue