Skip to main content

DBOS Methods & Variables

Workflow Communication Methods​

getEvent​

<T> Optional<T> getEvent(String workflowId, String key, Duration timeout)

Retrieve the latest value of an event published by the workflow identified by workflowId to the key key. If the event does not yet exist, wait for it to be published, returning empty if the wait times out. If the calling workflow is cancelled while waiting, throws DBOSWorkflowCancelledException.

Parameters:

  • workflowId: The identifier of the workflow whose events to retrieve.
  • key: The key of the event to retrieve.
  • timeout: A timeout duration. If the wait times out, an empty Optional is returned.

setEvent​

void setEvent(String key, Object value)
void setEvent(String key, Object value, SerializationStrategy serialization)

Create and associate with this workflow an event with key key and value value. If the event already exists, update its value. setEvent can only be called from within a workflow.

Parameters:

  • key: The key of the event.
  • value: The value of the event. Must be serializable.
  • serialization: The serialization strategy to use for this event. Defaults to SerializationStrategy.DEFAULT, which uses the serialization format recorded for the calling workflow.

getAllEvents​

Map<String, Object> getAllEvents(String workflowId)

Retrieve all events published by the workflow identified by workflowId, returned as a map of event key to deserialized value.

Parameters:

  • workflowId: The identifier of the workflow whose events to retrieve.

send​

void send(String destinationId, Object message, String topic)
void send(String destinationId, Object message, String topic, String idempotencyKey)
void send(String destinationId, Object message, String topic, String idempotencyKey, SerializationStrategy serialization)

Send a message to the workflow identified by destinationID. Messages can optionally be associated with a topic.

Parameters:

  • destinationId: The workflow to which to send the message.
  • message: The message to send. Must be serializable.
  • topic: A topic with which to associate the message. Messages are enqueued per-topic on the receiver.
  • idempotencyKey: If dbos.send is called from outside a workflow and an idempotency key is set, the message will only be sent once no matter how many times dbos.send is called with this key.
  • serialization: The serialization strategy to use for this message. Defaults to SerializationStrategy.DEFAULT, which inside a workflow uses the serialization format recorded for the sending workflow (for example, a workflow started with portable serialization sends portable messages), and outside a workflow uses the application's configured serializer.

sendBulk​

void sendBulk(List<SendMessage> messages)
void sendBulk(List<SendMessage> messages, boolean sendToForks)
void sendBulk(List<SendMessage> messages, boolean sendToForks, SerializationStrategy serialization)

Send multiple messages to workflows in a single batch. Each message is delivered to its destination workflow independently; messages need not share the same destination.

Parameters:

  • messages: A list of SendMessage records describing each message to send.
  • sendToForks: If true, also deliver each message to any forked copies of the destination workflow. Defaults to false.
  • serialization: The serialization strategy to use for all messages in the batch. Defaults to SerializationStrategy.DEFAULT, which behaves as described for send.

SendMessage​

new SendMessage(String destinationId, Object message)
new SendMessage(String destinationId, Object message, String topic)
new SendMessage(String destinationId, Object message, String topic, String idempotencyKey)

A record describing a single message in a sendBulk batch.

Parameters:

  • destinationId: The workflow to which to send the message.
  • message: The message to send. Must be serializable.
  • topic: A topic with which to associate the message.
  • idempotencyKey: Idempotency key for exactly-once delivery; a message with a given key is sent only once.

recv​

<T> Optional<T> recv(String topic, Duration timeout)

Receive and return a message sent to this workflow. Can only be called from within a workflow. Messages are dequeued first-in, first-out from a queue associated with the topic. Calls to recv wait for the next message in the queue, returning null if the wait times out. If the workflow is cancelled while waiting, recv throws DBOSWorkflowCancelledException.

Parameters:

  • topic: A topic queue on which to wait.
  • timeout: A timeout duration. If the wait times out, return an empty Optional.

sleep​

void sleep(Duration sleepduration)

Sleep for the given duration. If called from within a workflow, this sleep is durable—it records its intended wake-up time in the database so if it is interrupted and recovers, it still wakes up at the intended time. If called from outside a workflow, or from within a step, it behaves like a regular Thread.sleep.

Parameters:

  • duration: The duration to sleep.

writeStream​

void writeStream(String key, Object value)
void writeStream(String key, Object value, SerializationStrategy serialization)

Append a value to a named stream owned by the current workflow. Must be called from within a workflow or step. Consumers read the stream in order via readStream.

Parameters:

  • key: The stream name within this workflow. A workflow may have multiple independent streams identified by different keys.
  • value: A serializable value to write.
  • serialization: The serialization strategy to use. Defaults to SerializationStrategy.DEFAULT, which uses the serialization format recorded for the calling workflow. Use SerializationStrategy.PORTABLE for cross-language consumers.

closeStream​

void closeStream(String key)

Close a stream, signalling to consumers that no more values will be written. Must be called from within a workflow (not a step). After closing, readStream iterators will drain any remaining values and then stop.

Parameters:

  • key: The stream key to close.

readStream​

Iterator<Object> readStream(String workflowId, String key)

Read all values written to a stream by the specified workflow. Returns a blocking iterator that stops when the stream is closed or the workflow terminates. Can be called from outside the workflow — typically from a separate thread or external process. If no workflow with the given ID exists, iterating throws DBOSNonExistentWorkflowException.

On PostgreSQL, the iterator wakes up immediately when a new value is written (via LISTEN/NOTIFY). On CockroachDB, it falls back to polling once per second.

Parameters:

  • workflowId: The ID of the workflow that owns the stream.
  • key: The stream key to read.

retrieveWorkflow​

<T, E extends Exception> WorkflowHandle<T, E> retrieveWorkflow(String workflowId)

Retrieve the handle of a workflow.

Parameters:

  • workflowId: The ID of the workflow whose handle to retrieve.

getResult​

<T, E extends Exception> T getResult(String workflowId) throws E

Wait for the workflow to complete and return its result, or rethrow the exception it threw. This is a convenience alternative to retrieveWorkflow(workflowId).getResult().

Parameters:

  • workflowId: The ID of the workflow whose result to retrieve.

patch​

boolean patch(String patchName)

Insert a patch marker at the current point in workflow history. Returns true if it was successfully inserted or false if there is already a checkpoint present at this point in history. Used to safely upgrade workflow code, see the patching tutorial for more detail.

deprecatePatch​

boolean deprecatePatch(String patchName)

Safely bypass a patch marker at the current point in workflow history if present. Always returns true. Used to safely deprecate patches, see the patching tutorial for more detail.

Enqueueing Workflows by Name​

enqueueWorkflow​

<T, E extends Exception> WorkflowHandle<T, E> enqueueWorkflow(
EnqueueOptions options, Object[] args)
<T, E extends Exception> WorkflowHandle<T, E> enqueueWorkflow(
EnqueueOptions options, Object[] positionalArgs, Map<String, Object> namedArgs)

Enqueue a workflow by name, without a reference to its function, and return a handle to it. This takes the same EnqueueOptions as DBOSClient.enqueueWorkflow and writes the same database record, so the enqueued workflow may be implemented by another process, another application sharing this system database, or an application written in another language.

Unlike startWorkflow, the options are not validated against this process's registered workflows and queues. If no application version is set, the workflow is only dequeued by an executor running the owning application's latest version. The enqueued workflow is owned by this application unless EnqueueOptions.withApplicationName names another one; see Sharing a System Database.

enqueueWorkflow may be called from inside a workflow, where the enqueued workflow is recorded as a child: if the calling workflow is recovered, it gets a handle to the original child rather than enqueueing a second one. It may not be called from inside a step; doing so throws IllegalStateException. Inside a workflow, the enqueued workflow's timeout is resolved as for startWorkflow: unless EnqueueOptions sets one, it inherits the calling workflow's timeout; withNoTimeout() declines it.

Parameters:

  • options: The workflow name, queue, and other options; see EnqueueOptions.
  • args / positionalArgs: The workflow's positional arguments.
  • namedArgs: The workflow's named arguments, for targets that take them (for example, a Python workflow with keyword arguments). Only portable serialization carries named arguments, so passing any requires withSerialization(SerializationStrategy.PORTABLE) on the options; otherwise the call throws IllegalArgumentException.

Example Syntax:

var options = new EnqueueOptions("processOrder", "com.example.OrderServiceImpl", QueueName.of("orders"))
.withApplicationName("order-service");
WorkflowHandle<Object, Exception> handle =
dbos.enqueueWorkflow(options, new Object[] {"order-123"});

Workflow Management Methods​

WorkflowStatus​

Some workflow introspection and management methods return a WorkflowStatus. This object has the following definition:

public record WorkflowStatus(
// The workflow ID
String workflowId,
// The workflow status: ENQUEUED, PENDING, DELAYED, SUCCESS, ERROR, CANCELLED, or MAX_RECOVERY_ATTEMPTS_EXCEEDED
WorkflowState status,
// The name of the workflow function
String workflowName,
// The class of the workflow function
String className,
// The name given to the class instance, if any
String instanceName,
// The authenticated user who initiated the workflow, if any
String authenticatedUser,
// The assumed role for the workflow execution, if any
String assumedRole,
// Roles authenticated for the workflow
List<String> authenticatedRoles,
// The deserialized workflow input
Object[] input,
// The workflow's output, if any
Object output,
// The error the workflow threw, if any
ErrorResult error,
// The ID of the executor (process) that most recently executed this workflow
String executorId,
// When the workflow was created
Instant createdAt,
// The last time the workflow status was updated
Instant updatedAt,
// The application version on which this workflow was started
String appVersion,
// The application identifier
String appId,
// The number of times this workflow has been started
Integer recoveryAttempts,
// If this workflow was enqueued, on which queue
String queueName,
// The workflow timeout duration, if any
Duration timeout,
// The absolute deadline for the workflow, if any
Instant deadline,
// When the workflow started executing (after being dequeued), if applicable
Instant startedAt,
// The deduplication ID assigned to this workflow, if any
String deduplicationId,
// The priority assigned to this workflow in its queue, if any
Integer priority,
// The queue partition key, if any
String queuePartitionKey,
// The ID of the workflow this was forked from, if any
String forkedFrom,
// The parent workflow ID if this is a child workflow, if any
String parentWorkflowId,
// Whether another workflow has been forked from this one
Boolean wasForkedFrom,
// Time until which the workflow is delayed before starting
Instant delayUntil,
// When the workflow completed (terminal states only)
Instant completedAt,
// The serialization format used for the workflow's inputs/outputs
String serialization,
// Custom key-value metadata attached to the workflow
Map<String, Object> attributes,
// The name of the schedule that started this workflow, if any
String scheduleName,
// The application that owns this workflow, or null if no application owns it
String applicationName
)

See Sharing a System Database for how applications own workflows.

listWorkflows​

List<WorkflowStatus> listWorkflows(ListWorkflowsInput input)

Retrieve a list of WorkflowStatus of all workflows matching specified criteria.

ListWorkflowsInput​

ListWorkflowsInput is a with-based configuration record for filtering and customizing workflow queries. All fields are optional.

with Methods:

Many filters accept either a single value or a list. Single-value overloads are provided for convenience.

withWorkflowIds​

ListWorkflowsInput withWorkflowIds(String workflowId)
ListWorkflowsInput withWorkflowIds(List<String> workflowIds)

Filter by one or more workflow IDs.

withClassName​

ListWorkflowsInput withClassName(String className)

Filter workflows by the class name containing the workflow function.

withInstanceName​

ListWorkflowsInput withInstanceName(String instanceName)

Filter workflows by the instance name of the class.

withWorkflowName​

ListWorkflowsInput withWorkflowName(String workflowName)
ListWorkflowsInput withWorkflowName(List<String> workflowNames)

Filter workflows by the workflow function name.

withAuthenticatedUser​

ListWorkflowsInput withAuthenticatedUser(String authenticatedUser)
ListWorkflowsInput withAuthenticatedUser(List<String> authenticatedUsers)

Filter workflows run by this authenticated user.

withStartTime​

ListWorkflowsInput withStartTime(Instant startTime)

Retrieve workflows created after this timestamp.

withEndTime​

ListWorkflowsInput withEndTime(Instant endTime)

Retrieve workflows created before this timestamp.

withStatus​

ListWorkflowsInput withStatus(WorkflowState... statuses)
ListWorkflowsInput withStatus(List<WorkflowState> statuses)

Filter workflows by status. Status must be one of: ENQUEUED, PENDING, DELAYED, SUCCESS, ERROR, CANCELLED, or MAX_RECOVERY_ATTEMPTS_EXCEEDED.

withApplicationVersion​

ListWorkflowsInput withApplicationVersion(String applicationVersion)
ListWorkflowsInput withApplicationVersion(List<String> applicationVersions)

Retrieve workflows tagged with this application version.

withLimit​

ListWorkflowsInput withLimit(Integer limit)

Retrieve up to this many workflows.

withOffset​

ListWorkflowsInput withOffset(Integer offset)

Skip this many workflows from the results returned (for pagination).

withSortDesc​

ListWorkflowsInput withSortDesc(Boolean sortDesc)

Sort the results in descending (true) or ascending (false) order by workflow creation time.

withExecutorIds​

ListWorkflowsInput withExecutorIds(String executorId)
ListWorkflowsInput withExecutorIds(List<String> executorIds)

Retrieve workflows that ran on these executor processes.

withQueueName​

ListWorkflowsInput withQueueName(String queueName)
ListWorkflowsInput withQueueName(List<String> queueNames)

Retrieve workflows that were enqueued on these queues.

withWorkflowIdPrefix​

ListWorkflowsInput withWorkflowIdPrefix(String workflowIdPrefix)
ListWorkflowsInput withWorkflowIdPrefix(List<String> workflowIdPrefixes)

Filter workflows whose IDs start with the specified prefix.

withQueuesOnly​

ListWorkflowsInput withQueuesOnly(Boolean queuedOnly)

Select only workflows that were enqueued.

withLoadInput​

ListWorkflowsInput withLoadInput(Boolean value)

Controls whether to load workflow input data (default: true).

withLoadOutput​

ListWorkflowsInput withLoadOutput(Boolean value)

Controls whether to load workflow output data (results and errors) (default: true).

withForkedFrom​

ListWorkflowsInput withForkedFrom(String workflowId)
ListWorkflowsInput withForkedFrom(List<String> workflowIds)

Filter to workflows that were forked from the specified workflow(s).

withParentWorkflowId​

ListWorkflowsInput withParentWorkflowId(String parentWorkflowId)
ListWorkflowsInput withParentWorkflowId(List<String> parentWorkflowIds)

Filter to workflows that are children of the specified parent workflow(s).

withWasForkedFrom​

ListWorkflowsInput withWasForkedFrom(Boolean wasForkedFrom)

Filter to workflows from which another workflow was forked.

withHasParent​

ListWorkflowsInput withHasParent(Boolean hasParent)

Filter to workflows that have a parent workflow.

withCompletedAfter​

ListWorkflowsInput withCompletedAfter(Instant completedAfter)

Filter to workflows that completed after this timestamp.

withCompletedBefore​

ListWorkflowsInput withCompletedBefore(Instant completedBefore)

Filter to workflows that completed before this timestamp.

withDequeuedAfter​

ListWorkflowsInput withDequeuedAfter(Instant dequeuedAfter)

Filter to workflows that were dequeued (started execution) after this timestamp.

withDequeuedBefore​

ListWorkflowsInput withDequeuedBefore(Instant dequeuedBefore)

Filter to workflows that were dequeued (started execution) before this timestamp.

withScheduleName​

ListWorkflowsInput withScheduleName(String scheduleName)
ListWorkflowsInput withScheduleName(List<String> scheduleNames)

Retrieve workflows started by these schedules.

withApplicationName​

ListWorkflowsInput withApplicationName(String applicationName)
ListWorkflowsInput withApplicationName(List<String> applicationNames)

Retrieve workflows owned by these applications, plus workflows no application owns. If unset, only this application's workflows (and unowned ones) are listed, unless the query is filtered by workflow ID, which is never narrowed by default; pass an empty list to list every application's workflows. See Sharing a System Database.

withAttributes​

ListWorkflowsInput withAttributes(Map<String, Object> attributes)

Filter to workflows whose custom attributes contain all the specified key-value pairs (PostgreSQL @> containment check using a GIN index). Pass a map with the subset of attributes to match.

listWorkflowSteps​

List<StepInfo> listWorkflowSteps(String workflowId)
List<StepInfo> listWorkflowSteps(String workflowId, Integer limit, Integer offset)

Retrieve the execution steps of a workflow. The limit and offset parameters support pagination over large step lists. This is a list of StepInfo objects, with the following structure:

StepInfo(
// The sequential ID of the step within the workflow
int functionId,
// The name of the step function
String functionName,
// The output returned by the step, if any
Object output,
// The error returned by the step, if any
ErrorResult error,
// If the step starts or retrieves the result of a workflow, its ID
String childWorkflowId,
// When the step started executing
Instant startedAt,
// When the step completed
Instant completedAt,
// The serialization format used for the step's output
String serialization,
// The application that ran this step, or null if no application owns it.
// Usually the owner of the step's workflow, but a workflow resumed or forked
// by another application records its new steps under that application.
String applicationName
)

getWorkflowStatus​

Optional<WorkflowStatus> getWorkflowStatus(String workflowId)

Retrieve the WorkflowStatus of a single workflow by ID.

cancelWorkflow​

void cancelWorkflow(String workflowId)
void cancelWorkflow(String workflowId, boolean cancelChildren)
void cancelWorkflows(List<String> workflowIds)
void cancelWorkflows(List<String> workflowIds, boolean cancelChildren)

Cancel one or more workflows. This sets their status to CANCELLED, removes them from their queue (if enqueued) and preempts execution (interrupting at the beginning of the next step).

Parameters:

  • cancelChildren: If true, recursively cancel all descendant workflows spawned by the cancelled workflow(s). Defaults to false.

resumeWorkflow​

<T, E extends Exception> WorkflowHandle<T, E> resumeWorkflow(String workflowId)
<T, E extends Exception> WorkflowHandle<T, E> resumeWorkflow(String workflowId, String queueName)
List<WorkflowHandle<Object, Exception>> resumeWorkflows(List<String> workflowIds)
List<WorkflowHandle<Object, Exception>> resumeWorkflows(List<String> workflowIds, String queueName)

Resume one or more workflows from their last completed step. You can use this to resume workflows that are cancelled or have exceeded their maximum recovery attempts.

Resuming a workflow sets it back to ENQUEUED, on queueName if given and otherwise on the DBOS internal queue, which has no flow control, so the workflow starts as soon as an executor dequeues it. This works on a workflow that is already ENQUEUED, so you can also use it to start an enqueued workflow without waiting on its queue, or to move a workflow stranded on a deleted or newly partitioned queue. A resumed workflow keeps its application version, so it runs only on an executor of that version. Workflows that already completed with SUCCESS or ERROR are left unchanged.

Parameters:

  • queueName: The queue to enqueue the resumed workflow on. If omitted or null, it is enqueued on the DBOS internal queue.

deleteWorkflow​

void deleteWorkflow(String workflowId)
void deleteWorkflow(String workflowId, boolean deleteChildren)
void deleteWorkflows(List<String> workflowIds)
void deleteWorkflows(List<String> workflowIds, boolean deleteChildren)

Permanently delete one or more workflows and their recorded steps from the database.

Parameters:

  • deleteChildren: If true, also delete all child workflows spawned by the deleted workflow(s). Defaults to false.

forkWorkflow​

<T, E extends Exception> WorkflowHandle<T, E> forkWorkflow(String workflowId, int startStep)
<T, E extends Exception> WorkflowHandle<T, E> forkWorkflow(String workflowId, int startStep, ForkOptions options)
public record ForkOptions(
String forkedWorkflowId,
String applicationVersion,
Duration timeout, // null means no timeout
String queueName,
String queuePartitionKey
) {
ForkOptions withForkedWorkflowId(String forkedWorkflowId);
ForkOptions withApplicationVersion(String applicationVersion);
ForkOptions withTimeout(Duration timeout);
ForkOptions withTimeout(long value, TimeUnit unit);
ForkOptions withQueue(QueueName queue);
ForkOptions withQueue(String queueName);
ForkOptions withQueue(Queue queue); // deprecated since 1.1
ForkOptions withQueuePartitionKey(String queuePartitionKey);
}

Start a new execution of a workflow from a specific step. The input step ID (startStep) must match the step number of the step returned by workflow introspection. The specified startStep is the step from which the new workflow will start, so any steps whose ID is less than startStep will not be re-executed.

Parameters:

  • workflowId: The ID of the workflow to fork
  • startStep: The step from which to fork the workflow
  • options:
    • forkedWorkflowId: The workflow ID for the newly forked workflow (if not provided, generate a UUID)
    • applicationVersion: The application version for the forked workflow (inherited from the original if not provided)
    • timeout: A Duration timeout for the forked workflow. Pass null for no timeout.
    • queueName: Enqueue the forked workflow on this queue instead of starting it immediately. Set it with withQueue(QueueName) or withQueue(String); withQueue(Queue) is (deprecated since 1.1).
    • queuePartitionKey: Partition key for the queue (only for partitioned queues).

updateWorkflowAttributes​

void updateWorkflowAttributes(String workflowId, Map<String, Object> attributes)

Replace the custom attributes attached to a workflow. Pass null or an empty map to clear all attributes.

Safe to call from within a workflow — the update is recorded as a step so it executes exactly once even if the workflow is recovered.

Parameters:

  • workflowId: The ID of the workflow whose attributes to update.
  • attributes: The new JSON-serializable key-value attributes, or null/empty map to clear.

setWorkflowDelay​

void setWorkflowDelay(String workflowId, Duration delay)
void setWorkflowDelay(String workflowId, Instant delayUntil)

Pause an enqueued or pending workflow so it will not be dequeued until after the specified duration or absolute time. The workflow's status changes to DELAYED while waiting.

Parameters:

  • workflowId: The ID of the workflow to delay.
  • delay: How long from now to delay the workflow.
  • delayUntil: The absolute time until which to delay the workflow.

listApplicationVersions​

List<VersionInfo> listApplicationVersions()

Return all registered application versions, ordered by timestamp descending.

public record VersionInfo(
// The generated version ID
String versionId,
// The human-readable version name (e.g., "v1.2.3")
String versionName,
// When this version was promoted
Instant versionTimestamp,
// When this version record was created
Instant createdAt,
// The application that registered this version, or null if no application owns it
String applicationName
)

getLatestApplicationVersion​

VersionInfo getLatestApplicationVersion()

Return the most recently promoted application version.

setLatestApplicationVersion​

void setLatestApplicationVersion(String versionName)

Promote a version by name to be the latest application version. Used during blue-green deployments to control which version new workflows are assigned to. See upgrading workflows for more detail.

Schedule Management Methods​

These methods manage WorkflowSchedule records that periodically invoke workflows on a cron schedule. All schedule methods require DBOS to be launched first.

WorkflowSchedule​

public record WorkflowSchedule(
String id, // Generated schedule ID (read-only; null on creation)
String scheduleName, // Unique name for this schedule
String workflowName, // Name of the workflow function to invoke
String className, // Class containing the workflow (use @WorkflowClassName for a portable name)
String cron, // Cron expression (Spring 5.3+ format)
ScheduleStatus status, // ACTIVE or PAUSED
Object context, // Optional context object passed to the workflow
Instant lastFiredAt, // When the schedule last fired (read-only)
boolean automaticBackfill,// If true, missed firings are retroactively started on launch
ZoneId cronTimezone, // Timezone for interpreting the cron expression (defaults to UTC)
String queueName, // Queue to enqueue scheduled workflows on
String applicationName // Application that owns the schedule and runs its workflows
)

Constructors:

new WorkflowSchedule(String scheduleName, String workflowName, String className, String cron)

Creates an ACTIVE schedule with no backfill, UTC timezone, and no queue override.

with Methods:

  • withScheduleName(String name) — Change the schedule's unique name.
  • withWorkflowName(String name) — Change the target workflow function name.
  • withClassName(String name) — Change the target class name.
  • withCron(String cron) — Change the cron expression.
  • withStatus(ScheduleStatus status) — Set ACTIVE or PAUSED.
  • withContext(Object context) — Attach a context object, serialized and passed to the workflow as its third argument.
  • withAutomaticBackfill(boolean value) — If true, any firings missed while the app was down are retroactively started when the app launches.
  • withCronTimezone(ZoneId timezone) — Interpret the cron expression in this timezone instead of UTC.
  • withQueueName(String queueName) — Enqueue scheduled executions on this queue.
  • withApplicationName(String applicationName) — The application that owns the schedule and runs its workflows. Defaults to the creating application. Schedule names are unique across all applications sharing a system database: creating or applying a schedule whose name a different application owns throws DBOSApplicationNameConflictException. See Sharing a System Database.
public enum ScheduleStatus { ACTIVE, PAUSED }

applySchedules​

void applySchedules(WorkflowSchedule... schedules)
void applySchedules(List<WorkflowSchedule> schedules)

Atomically create or update a set of schedules in one transaction. Existing schedules are upserted by name: all definition fields are replaced with the new declaration's values (so any optional setting left unset is cleared, e.g. an omitted queue name reverts the schedule to the default scheduler queue), while the schedule's status and last-fired time are preserved. This is the recommended way to declare schedules at application startup — call it once after dbos.launch() and it will always reflect your current schedule definitions.

createSchedule​

void createSchedule(WorkflowSchedule schedule)

Create a single schedule. Throws if a schedule with the same scheduleName already exists.

getSchedule​

Optional<WorkflowSchedule> getSchedule(String name)

Retrieve a schedule by name. Returns empty if not found.

listSchedules​

List<WorkflowSchedule> listSchedules(List<ScheduleStatus> status, List<String> workflowName, List<String> namePrefix)
List<WorkflowSchedule> listSchedules(List<ScheduleStatus> status, List<String> workflowName, List<String> namePrefix, List<String> applicationName)

List schedules with optional filters. Pass null for any filter to skip it.

Parameters:

  • status: Filter by ScheduleStatus.ACTIVE or ScheduleStatus.PAUSED.
  • workflowName: Filter by workflow function name.
  • namePrefix: Filter by schedule name prefix.
  • applicationName: List schedules owned by these applications, plus schedules no application owns. If null (or omitted), lists this application's schedules; pass an empty list to list every application's schedules.

pauseSchedule​

void pauseSchedule(String name)

Pause a schedule. A paused schedule does not fire until resumed.

resumeSchedule​

void resumeSchedule(String name)

Resume a paused schedule.

deleteSchedule​

void deleteSchedule(String name)

Delete a schedule by name. No-op if the schedule does not exist.

backfillSchedule​

List<WorkflowHandle<Object, Exception>> backfillSchedule(String scheduleName, Instant start, Instant end)

Manually enqueue all executions of a schedule that would have fired between start (exclusive) and end (exclusive). Uses the same deterministic workflow IDs as the live scheduler, so already-executed times are skipped. Useful for recovering from outages when automatic backfill is not enabled.

triggerSchedule​

<T, E extends Exception> WorkflowHandle<T, E> triggerSchedule(String scheduleName)

Immediately fire a scheduled workflow outside its normal cron cadence. Returns a handle to the enqueued execution.

Debouncing​

You can create a Debouncer to debounce your workflows. Debouncing delays workflow execution until some time has passed since the workflow was last called. This is useful for preventing wasted work when a workflow may be triggered multiple times in quick succession. For example, if a user is editing an input field, you can debounce their changes to execute a processing workflow only after they haven't edited the field for some time.

Debouncer​

Obtain a Debouncer via dbos.debouncer():

<R> Debouncer<R> debouncer()

Debouncer<R> is an immutable builder. Configure it with the following methods before calling debounce:

  • withDebounceTimeout(Duration debounceTimeout): Set an absolute cap on how long the debouncer may keep absorbing calls for a single key. After this duration elapses from the first call, the user workflow starts regardless of further incoming calls.
  • withQueue(QueueName queue) / withQueue(String queueName): Enqueue the user workflow on the specified queue when the debounce period elapses instead of starting it directly. withQueue(Queue queue) is (deprecated since 1.1).
  • withAppVersion(String appVersion): Target a specific application version for the user workflow.
  • withPriority(Integer priority): Set the priority for the user workflow. A priority requires a queue: if a priority is set without withQueue, debounce throws IllegalArgumentException.
  • withDeduplicationId(String deduplicationId) (deprecated since 1.1): Set a deduplication ID forwarded to the user workflow. This will be ignored from the next release, where the debouncer sets the deduplication ID itself, and removed in 2.0.

debouncer.debounce​

<E extends Exception> WorkflowHandle<Void, E> debounce(
String debounceKey, Duration debouncePeriod, ThrowingRunnable<E> wfLambda)

<E extends Exception> WorkflowHandle<R, E> debounce(
String debounceKey, Duration debouncePeriod, ThrowingSupplier<R, E> wfLambda)

Submit a workflow for execution but delay it by debouncePeriod. Returns a handle to the workflow. The workflow may be debounced again, which further delays its execution (up to debounceTimeout). When the workflow eventually executes, it uses the last set of inputs passed into debounce. After the workflow begins execution, the next call to debounce starts the debouncing process again for a new workflow execution.

Parameters:

  • debounceKey: A key used to group workflow executions that will be debounced together. For example, if the debounce key is set to customer ID, each customer's workflows are debounced separately.
  • debouncePeriod: Inactivity window before the user workflow runs; each call resets it. Must be positive.
  • wfLambda: A lambda calling exactly one @Workflow method on a registered proxy.

Example Syntax:

var dbos = new DBOS(config);
MyService svc = dbos.registerProxy(MyService.class, new MyServiceImpl());
dbos.launch();

var debouncer = dbos.<String>debouncer()
.withDebounceTimeout(Duration.ofMinutes(5));

// Each time a user submits input, debounce the processInput workflow.
// The workflow will run 60 seconds after the user stops submitting.
WorkflowHandle<String, Exception> handle = debouncer.debounce(
userId,
Duration.ofSeconds(60),
() -> svc.processInput(userInput));
String result = handle.getResult();

DBOS Context Variables​

workflowId​

static String workflowId()

Retrieve the ID of the current workflow. Returns null if not called from a workflow or step.

stepId​

static Integer stepId()

Returns the unique ID of the current step within its workflow. Returns null if not called from a step.

inWorkflow​

static boolean inWorkflow();

Return true if the current calling context is executing a workflow, or false otherwise.

inStep​

static boolean inStep();

Return true if the current calling context is executing a workflow step, or false otherwise.

authenticatedUser​

static @Nullable String authenticatedUser()

Return the authenticated user associated with the current workflow, or null if none was set. Must be called from within a workflow or step.

assumedRole​

static @Nullable String assumedRole()

Return the assumed role for the current workflow execution, or null if none was set. Must be called from within a workflow or step.

authenticatedRoles​

static @Nullable List<String> authenticatedRoles()

Return the list of authenticated roles for the current workflow, or null if none were set. Must be called from within a workflow or step.

Timeout​

Timeout is a sealed interface used by StartWorkflowOptions and WorkflowOptions to control how inherited timeouts are handled.

import dev.dbos.transact.workflow.Timeout;

Factory methods:

  • Timeout.of(Duration duration) — Set an explicit timeout of the given duration.
  • Timeout.of(long value, TimeUnit unit) — Set an explicit timeout.
  • Timeout.none() — Opt out of any inherited timeout. The workflow will run without a timeout regardless of what the calling context specifies.
  • Timeout.inherit() — Explicitly inherit the timeout from the calling context (the default behavior when no timeout is set).

Example:

// Detach a child workflow from the parent's timeout
dbos.startWorkflow(() -> proxy.longRunningChild(),
new StartWorkflowOptions().withTimeout(Timeout.none()));

WorkflowState​

WorkflowState is an enum representing the possible states of a workflow. It is used in WorkflowStatus and ListWorkflowsInput.

import dev.dbos.transact.workflow.WorkflowState;
public enum WorkflowState {
PENDING, // Currently executing
ENQUEUED, // Waiting on a queue to be dequeued
DELAYED, // Waiting until a delay expires before being dequeued
SUCCESS, // Completed successfully
ERROR, // Threw an unhandled exception
CANCELLED, // Cancelled by cancelWorkflow()
MAX_RECOVERY_ATTEMPTS_EXCEEDED // Crashed too many times; requires manual intervention
}

WorkflowState.isActive() returns true for PENDING, ENQUEUED, and DELAYED.

Serialization Strategy​

Several DBOS methods accept an optional SerializationStrategy parameter that controls how data is serialized. This is useful for cross-language interoperability—for example, if a TypeScript or Python DBOS application needs to read events or messages set by a Java application.

import dev.dbos.transact.workflow.SerializationStrategy;

The available strategies are:

  • SerializationStrategy.DEFAULT: Uses the serializer configured in DBOSConfig (defaults to Jackson). Inside a workflow, send, sendBulk, setEvent, and writeStream instead use the serialization format recorded for the running workflow, so a workflow started with portable serialization writes portable messages, events, and stream values by default.
  • SerializationStrategy.PORTABLE: Uses a portable JSON format (portable_json) that can be deserialized by DBOS applications in any language.
  • SerializationStrategy.NATIVE: Explicitly uses the native Java Jackson serializer (java_jackson).

Alert Handlers​

Alert handlers let you receive internal DBOS alerts — such as workflow recovery failures or system warnings — and route them to your observability infrastructure (logging, metrics, PagerDuty, etc.).

registerAlertHandler​

void registerAlertHandler(AlertHandler handler)

Register a handler to receive alerts generated by DBOS. Must be called before dbos.launch().

@FunctionalInterface
public interface AlertHandler {
void invoke(String name, String message, Map<String, String> metadata);
}

Parameters:

  • name: A short identifier for the alert type.
  • message: A human-readable description of the alert.
  • metadata: Additional key-value context about the alert.

Example:

DBOS dbos = new DBOS(config);
dbos.registerAlertHandler((name, message, metadata) ->
logger.warn("DBOS alert [{}]: {} {}", name, message, metadata));
dbos.launch();

Exceptions​

DBOSApplicationNameConflictException​

public class DBOSApplicationNameConflictException extends RuntimeException {
String kind(); // "Queue", "Schedule", or "Application version"
String name(); // The name both applications claim
String owner(); // The application that already owns the name
}

Thrown when registering a queue, creating or applying a schedule, or promoting an application version whose name is already owned by a different application sharing the system database. Queue, schedule, and version names are unique across all applications sharing a system database. Either choose a different name or, if the owning application was renamed, transfer its rows first with dbosctl sysdb rename-application or DBOSClient.renameApplication. See Sharing a System Database.

DBOSSystemDatabaseException​

public class DBOSSystemDatabaseException extends RuntimeException {
String sqlState();
Throwable databaseException(); // deprecated since 1.1
}

Thrown when a system database operation fails and DBOS will not retry it any further. This covers two different situations, which sqlState() distinguishes:

  • Connectivity failures are retried first, so one arriving here means the database stayed unreachable across many attempts.
  • Failures that retrying cannot fix, such as a constraint violation or a missing table, are not retried and are thrown immediately.

Methods:

  • sqlState(): The SQLSTATE of the underlying failure, or null if it carried none.
  • getCause(): The underlying SQLException. It is the only level of wrapping, so the database's own exception is always one level down.
  • databaseException() (deprecated since 1.1): Returns the same object as getCause(); use getCause() instead.