The following features are currently supported:
Orchestrators are implemented using ordinary Python functions that take an OrchestrationContext as
their first parameter. The OrchestrationContext provides APIs for starting child orchestrations,
scheduling activities, and waiting for external events, among other things. Orchestrations are
fault-tolerant and durable, meaning that they can automatically recover from failures and rebuild
their local execution state. Orchestrator functions must be deterministic, meaning that they must
always produce the same output given the same input.
Orchestrations may be assigned a version when they are first created. If an orchestration is given a version, it will continually be checked during its lifecycle to ensure that it remains compatible with the underlying orchestrator code. If the orchestrator code is updated while an orchestration is running, rules can be set that will define the behavior - whether the orchestration should fail, abandon for reprocessing at a later time, or attempt to run anyway. For more information, see The provided examples. For more information about versioning in the context of Durable Functions, see Orchestration versioning in Durable Functions (Note that concepts specific to Azure Functions, such as host.json settings, do not apply to this SDK).
Both the Durable worker and durable client have versioning configuration available. Because
versioning checks are handled by the worker, the only information the client needs is a
default_version, taken in its constructor, to use as the version for new orchestrations unless
otherwise specified. The worker takes a VersioningOptions object with a default_version for new
sub-orchestrations, a version used by the worker for orchestration version comparisons, and two
more options giving control over versioning behavior in case of match failures, a
VersionMatchStrategy and VersionFailureStrategy.
VersionMatchStrategy.NONE: Do not compare orchestration versions.VersionMatchStrategy.STRICT: Only allow orchestrations with the same version as the worker.VersionMatchStrategy.CURRENT_OR_OLDER: Allow orchestrations with the same or older version as the worker.
VersionFailureStrategy.REJECT: Abandon execution of the orchestrator, but allow it to be reprocessed later.VersionFailureStrategy.FAIL: Fail the orchestration.
Scenario 1: You are implementing versioning for the first time in your worker. You want to have a default version for new orchestrations, but do not care about comparing versions with currently running ones. Choose VersionMatchStrategy.NONE, and VersionFailureStrategy does not matter.
Scenario 2: You are updating an orchestrator's code, and you do not want old orchestrations to continue to be processed on the new code. Bump the default version and the worker version, set VersionMatchStrategy.STRICT and VersionFailureStrategy.FAIL.
Scenario 3: You are updating an orchestrator's code, and you have ensured the code is version-aware so that it remains backward-compatible with existing orchestrations. Bump the default version and the worker version, and set VersionMatchStrategy.CURRENT_OR_OLDER and VersionFailureStrategy.FAIL.
Scenario 4: You are performing a high-availability deployment, and your orchestrator code contains breaking changes making it not backward-compatible. Bump the default version and the worker version, and set VersionFailureStrategy.REJECT and VersionMatchStrategy.STRICT. Ensure that at least a few of the previous version of workers remain available to continue processing the older orchestrations - eventually, all older orchestrations should land on the correct workers for processing. Once all remaining old orchestrations have been processed, shut down the remaining old workers.
Activities are implemented using ordinary Python functions that take an ActivityContext as their
first parameter. Activity functions are scheduled by orchestrations and have at-least-once execution
guarantees, meaning that they will be executed at least once but may be executed multiple times in
the event of a transient failure. Activity functions are where the real "work" of any orchestration
is done.
Orchestrations can schedule durable timers using the create_timer API. These timers are durable,
meaning that they will survive orchestrator restarts and will fire even if the orchestrator is not
actively in memory. Durable timers can be of any duration, from milliseconds to months.
Orchestrations can start child orchestrations using the call_sub_orchestrator API. Child
orchestrations are useful for encapsulating complex logic and for breaking up large orchestrations
into smaller, more manageable pieces. Sub-orchestrations can also be versioned in a similar manner
to their parent orchestrations, however, they do not inherit the parent orchestrator's version.
Instead, they will use the default_version defined in the current worker's VersioningOptions unless
otherwise specified during call_sub_orchestrator.
Durable Entities provide a way to model small, stateful objects within your orchestration workflows. Each entity has a unique identity and maintains its own state, which is persisted durably. Entities can be interacted with by sending them operations (messages) that mutate or query their state. These operations are processed sequentially, ensuring consistency. Examples of uses for durable entities include counters, accumulators, or any other operation which requires state to persist across orchestrations.
Entities can be invoked from durable clients directly, or from durable orchestrators. They support features like automatic state persistence, concurrency control, and can be locked for exclusive access during critical operations.
Entities are accessed by a unique ID, implemented here as EntityInstanceId. This ID is comprised of two parts, an entity name referring to the function or class that defines the behavior of the entity, and a key which is any string defined in your code. Each entity instance, represented by a distinct EntityInstanceId, has its own state.
Entities can be defined using either function-based or class-based syntax.
# Funtion-based entity
def counter(ctx: entities.EntityContext, input: int):
state = ctx.get_state(int, 0)
if ctx.operation == "add":
state += input
ctx.set_state(state)
elif operation == "get":
return state
# Class-based entity
class Counter(entities.DurableEntity):
def __init__(self):
self.set_state(0)
def add(self, amount: int):
self.set_state(self.get_state(int, 0) + amount)
def get(self):
return self.get_state(int, 0)Note that the object properties of class-based entities may not be preserved across invocations. Use the derived get_state and set_state methods to access the persisted entity data.
Entities are invoked using the signal_entity or call_entity APIs. The Durable Client only allows
signal_entity:
c = DurableTaskSchedulerClient(host_address=endpoint, secure_channel=True,
taskhub=taskhub_name, token_credential=None)
entity_id = entities.EntityInstanceId("my_entity_function", "myEntityId")
c.signal_entity(entity_id, "do_nothing")Whereas orchestrators can choose to use signal_entity or call_entity:
# Signal an entity (fire-and-forget)
entity_id = entities.EntityInstanceId("my_entity_function", "myEntityId")
ctx.signal_entity(entity_id, operation_name="add", input=5)
# Call an entity (wait for result)
entity_id = entities.EntityInstanceId("my_entity_function", "myEntityId")
result = yield ctx.call_entity(entity_id, operation_name="get")Entities can perform actions such signaling other entities or starting new orchestrations
ctx.signal_entity(entity_id, operation, input)ctx.schedule_new_orchestration(orchestrator_name, input)
Because entities can be accessed from multiple running orchestrations at the same time, entities may also be locked by a single orchestrator ensuring exclusive access during the duration of the lock (also known as a critical section). Think semaphores:
with (yield ctx.lock_entities([entity_id_1, entity_id_2]):
# Perform entity call operations that require exclusive access
...Note that locked entities may not be signalled, and every call to a locked entity must return a result before another call to the same entity may be made from within the critical section. For more details and advanced usage, see the examples and API documentation.
Entities are represented as orchestration instances in your Task Hub, and their state is persisted in the Task Hub as well. When using the Durable Task Scheduler as your durability provider, the backend will automatically clean up entities when their state is empty, this is effectively the "delete" operation to save space in the Task Hub. In the DTS Dashboard, "delete entity" simply signals the entity with the "delete" operation. In this SDK, we provide a default implementation for the "delete" operation to clear the state when using class-based entities, which end users are free to override as needed. Users must implement "delete" manually for function-based entities.
Orchestrations can wait for external events using the wait_for_external_event API. External events
are useful for implementing human interaction patterns, such as waiting for a user to approve an
order before continuing.
Orchestrations can be continued as new using the continue_as_new API. This API allows an
orchestration to restart itself from scratch, optionally with a new input.
Orchestrations can be suspended using the suspend_orchestration client API and will remain
suspended until resumed using the resume_orchestration client API. A suspended orchestration will
stop processing new events, but will continue to buffer any that happen to arrive until resumed,
ensuring that no data is lost. An orchestration can also be terminated using the
terminate_orchestration client API. Terminated orchestrations will stop processing new events and
will discard any buffered events.
Orchestrations can specify retry policies for activities and sub-orchestrations. These policies control how many times and how frequently an activity or sub-orchestration will be retried in the event of a transient error.
Orchestrator functions replay their history each time they are resumed,
which can cause duplicate log messages. The create_replay_safe_logger
method on OrchestrationContext returns a ReplaySafeLogger that wraps
a standard logging.Logger and automatically suppresses output while
the orchestrator is replaying. ReplaySafeLogger extends Python's
logging.LoggerAdapter, which is the idiomatic way to add context or
modify behavior on an existing logger.
import logging
from durabletask import task
logger = logging.getLogger("my_orchestrator")
def my_orchestrator(ctx: task.OrchestrationContext, payload):
replay_logger = ctx.create_replay_safe_logger(logger)
replay_logger.info("Starting orchestration %s", ctx.instance_id)
result = yield ctx.call_activity(my_activity, input=payload)
replay_logger.info("Activity returned: %s", result)
return resultNote
Unlike the .NET SDK, where CreateReplaySafeLogger accepts a
category name string and internally creates the logger via
ILoggerFactory, the Python SDK requires you to pass an existing
logging.Logger instance. This is because Python's
logging.getLogger(name) already serves as the global factory and
is the standard way to obtain loggers.
The replay-safe logger supports all standard log levels: debug,
info, warning, error, critical, and exception, as well as
the generic log(level, msg) method. It also exposes isEnabledFor
which returns False during replay so callers can skip expensive
message formatting.
Tip
Create the replay-safe logger once at the start of your orchestrator and reuse it throughout the function.
TaskHubGrpcClient, AsyncTaskHubGrpcClient, and TaskHubGrpcWorker
accept a configured logging.Logger through their logger parameter. The
SDK uses a supplied logger unchanged: it does not add handlers or modify its
formatter, level, filters, or propagation setting. The Durable Task Scheduler
client and worker accept the same parameter.
Use one shared logger when client and worker records should use the same destination, format, and correlation filters:
import logging
from durabletask.client import TaskHubGrpcClient
from durabletask.worker import TaskHubGrpcWorker
sdk_logger = logging.getLogger("myapp.durabletask")
sdk_logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
"%(asctime)s %(name)s %(levelname)s %(message)s"))
sdk_logger.addHandler(handler)
sdk_logger.propagate = False
worker = TaskHubGrpcWorker(logger=sdk_logger)
client = TaskHubGrpcClient(logger=sdk_logger)Because logging.getLogger() returns the same logger for a given name,
configure a shared logger once during application startup. Do not add a new
handler every time a client or worker is constructed, or every record will be
emitted once by each handler.
Alternatively, configure handlers on the root logger and allow propagation:
import logging
logging.basicConfig(level=logging.INFO)
sdk_logger = logging.getLogger("myapp.durabletask")
worker = TaskHubGrpcWorker(logger=sdk_logger)
client = TaskHubGrpcClient(logger=sdk_logger)Warning
Use either handlers attached directly to sdk_logger with
sdk_logger.propagate = False, or root handlers with propagation enabled.
Combining both emits each Durable Task record twice.
Pass separate named loggers when clients and workers need independently configured levels, destinations, or filters:
worker = TaskHubGrpcWorker(
logger=logging.getLogger("myapp.durabletask.worker"))
client = TaskHubGrpcClient(
logger=logging.getLogger("myapp.durabletask.client"))The older log_handler and log_formatter parameters are deprecated. They
will be removed in a future major release. Passing either one together with
logger raises ValueError; none of the supplied logging options are ignored.
Note
SDK clients and workers emit detailed DEBUG logs that can help diagnose
orchestration behavior. Enable that level on the logger you pass to the SDK
when reproducing an issue.
Orchestration inputs, outputs, and event data are transmitted through gRPC messages. When these payloads become very large they can exceed gRPC message size limits or degrade performance. Large payload externalization solves this by transparently offloading oversized payloads to an external store (such as Azure Blob Storage) and replacing them with compact reference tokens in the gRPC messages.
This feature is opt-in and requires installing an optional dependency:
pip install durabletask[azure-blob-payloads]- When the worker or client sends a payload that exceeds the configured threshold (default 256 KiB), the payload is compressed (GZip, enabled by default) and uploaded to the external store.
- The original payload in the gRPC message is replaced with a
compact token (e.g.
blob:v2:https://<account>.blob.core.windows.net/<container>/<blobName>). - When the worker or client receives a message containing a token, it downloads and decompresses the original payload automatically.
This process is fully transparent to orchestrator and activity code — no changes are needed in your workflow logic.
The built-in BlobPayloadStore uses Azure Blob Storage. Create a store instance and pass it to both
the worker and client:
from durabletask.extensions.azure_blob_payloads import BlobPayloadStore, BlobPayloadStoreOptions
store = BlobPayloadStore(BlobPayloadStoreOptions(
connection_string="DefaultEndpointsProtocol=https;...",
container_name="durabletask-payloads", # default
threshold_bytes=262_144, # default (256 KiB)
max_stored_payload_bytes=10_485_760, # default (10 MB)
enable_compression=True, # default
))Then pass the store to the worker and client:
with DurableTaskSchedulerWorker(
host_address=endpoint,
secure_channel=secure_channel,
taskhub=taskhub_name,
token_credential=credential,
payload_store=store,
) as w:
# ... register orchestrators and activities ...
w.start()
c = DurableTaskSchedulerClient(
host_address=endpoint,
secure_channel=secure_channel,
taskhub=taskhub_name,
token_credential=credential,
payload_store=store,
)You can also authenticate using account_url and a TokenCredential instead of a connection
string:
from azure.identity import DefaultAzureCredential
store = BlobPayloadStore(BlobPayloadStoreOptions(
account_url="https://<account>.blob.core.windows.net",
credential=DefaultAzureCredential(),
))| Option | Default | Description |
|---|---|---|
threshold_bytes |
262,144 (256 KiB) | Payloads larger than this are externalized |
max_stored_payload_bytes |
10,485,760 (10 MB) | Maximum size for externalized payloads |
enable_compression |
True |
GZip-compress payloads before uploading |
container_name |
"durabletask-payloads" |
Azure Blob container name |
connection_string |
None |
Azure Storage connection string |
account_url |
None |
Azure Storage account URL (use with credential) |
credential |
None |
Storage credential; see supported modes below |
allow_all_containers_in_configured_account |
False |
Read all primary-account containers |
additional_account_urls |
[] |
Additional exact account endpoints for reads |
By default, BlobPayloadStore reads only from the configured account endpoint and configured
container, even if its credentials have broader Storage permissions. Token recognition identifies a
reference's format; knowing a Blob URL does not authorize its destination.
Two independent options can broaden reads:
allow_all_containers_in_configured_account=Truepermits all containers in the configured account, without allowing other account endpoints.additional_account_urlspermits all containers within each explicitly listed additional account endpoint. It does not broaden access to the primary account's other containers.
Both options affect downloads only. Uploads still use account_url (or the connection string)
and container_name. Account endpoints are compared by scheme, case-insensitive hostname,
effective port (443 for HTTPS, 80 for HTTP), and the complete case-sensitive account path for
path-style endpoints. These are exact endpoint scopes, not hostname-only allowlists. Listing
https://account.blob.core.windows.net does not permit HTTP, another port, or another account.
For Azurite, /devstoreaccount1 and /anotheraccount are different account paths on the same host.
IP-address and localhost account endpoints must include one account-path segment recognized
by the Azure Blob SDK. Arbitrary custom-host path prefixes and container/blob endpoint URLs
are not account endpoints. Paths that the SDK rewrites or does not recognize are rejected;
this includes IPv6 path-style endpoints not recognized by the current Python Azure Blob SDK.
URL paths are decoded once and blob names are re-escaped through the configured Azure Blob client.
Dot path segments are rejected, and HTTP redirects are not followed.
When response externalization encounters an invalid Blob upload path or exceeds the stored-payload size limit, core and Azure Managed workers report non-retriable failures for orchestrations, activities, and entity operations. Orchestration failures release acquired entity locks. Entity batches discard their new state and outgoing actions, retain the original state (including an existing payload reference), and fail the previously successful operations; existing operation failures are preserved. This completes the work item without redelivering those operations. Transient Storage errors and incoming-reference resolution failures retain the existing retry behavior.
For example, to read references from all containers in one additional account while retaining the default container restriction in the primary account:
store = BlobPayloadStore(BlobPayloadStoreOptions(
account_url="https://primary.blob.core.windows.net",
container_name="durabletask-payloads",
credential=DefaultAzureCredential(),
additional_account_urls=["https://archive.blob.core.windows.net"],
))Set allow_all_containers_in_configured_account=True separately only when all containers in the
primary account should be readable. Do not list the primary account as an additional endpoint;
construction rejects that configuration. Additional endpoints must be complete HTTPS account
service URLs without credentials, query parameters, or fragments. Equivalent entries are deduplicated.
| Authentication | Default container and account-wide primary reads | Additional-account reads |
|---|---|---|
account_url with TokenCredential |
Supported | Supported with an explicit endpoint list |
| Connection string / account key | Supported within the configured account | Not supported |
| SAS (URL, connection string, or credential) | Original SAS permissions only | Not supported |
| Anonymous | Supported for publicly readable blobs | Not supported |
Additional-account scope requires account_url and a token credential; unsupported combinations
raise ValueError during store construction, before credential acquisition or HTTP requests.
The same configured identity is used for every allowed account, and Azure Storage permissions still
apply. A container-scoped SAS is not upgraded to account-wide permissions by the account-wide
option. Storage authentication and permission errors propagate; the store never switches to
another identity, a different authentication mode, or anonymous access. Use a credential compatible
with the operations being called: synchronous token credentials work with both SDK call styles;
async-only credentials require asynchronous operations.
Scopes are captured at store construction. Create a new store after changing scope configuration.
Removing an allowed account or disabling account-wide access makes affected references fail with
ValueError before Storage access; their tokens are not rewritten or treated as successful reads.
For v2 references retained across an account migration, list the old endpoint explicitly and ensure
the configured token identity can still read it. For a container change within the same account,
account-wide access can retain reads of the old container. Legacy v1 references do not record an
account: they always use the currently configured account, so an additional-account list cannot
recover their original account automatically. Keep the original account configuration when reading
those references, or migrate them separately. Retain the original compression settings as well.
Warning
Review retained references before upgrading. Existing histories with references outside the
configured access scopes, or blob names containing . or .. path segments, now fail during
replay and retrieval. Aligning current clients and workers does not rewrite persisted tokens.
Explicit broader scopes can retain reads of authorized older locations, but do not permit
dot-segment paths; migrate affected references separately or finish affected instances on the
previous SDK before switching.
The policy is shared by core clients and workers, history retrieval, Azure Managed clients and
workers, and Functions payload handling (including JSON-quoted references and entity envelopes).
Custom PayloadStore implementations define their own policy. This repository implements no
external-payload Blob deletion or purge cleanup; orchestration purge submits a backend RPC and
does not delete payload blobs here. It also implements no dashboard Blob-read service. Dashboard
reads performed elsewhere with the signed-in user's delegated Storage identity remain independent;
this SDK does not provide fallback to worker or service credentials.
New uploads use the .NET-compatible blob:v2:<fullBlobUrl> format. Each reference records the
Storage endpoint, container, and URL-escaped blob name. DNS-style Azure endpoints and path-style
Azurite endpoints are supported. SAS query parameters are not included in emitted references;
downloads use the store's configured credentials, not credentials supplied in a reference.
Downloads also accept existing blob:v1:<container>:<blobName> references, using the configured
Storage account. Both formats follow the configured access scopes:
the default is the configured endpoint and container only. References outside those scopes raise
ValueError before accessing storage, even if the configured credentials could read them.
Repointing the store does not automatically allow the old account or container. V2 URLs must not
contain userinfo. For compatibility, query parameters and fragments in older v2 references are
discarded before selecting a destination or creating a client. Token SAS credentials, snapshots,
and version selectors are never used; configured credentials (including a configured SAS) still apply.
Blob names and instance ID folders must not contain . or .. path segments, which HTTP transports
can normalize. Escaped separators cannot change the selected account or container.
Warning
Older Python SDK versions cannot resolve v2 references. Upgrade all payload-reading clients and workers before enabling new writers, and avoid mixing older workers with v2 writers on the same task hub. Existing v1 references remain readable when their original Storage endpoint, container, and compression settings are retained.
Python and .NET workers can exchange references when configured for the same payload location.
New compressed uploads set the Blob's Content-Encoding: gzip property, as the .NET and Go stores
do. Python downloads disable transport decompression and explicitly decompress marked GZIP blobs,
including when enable_compression=False. This avoids decoding the same body twice. Invalid GZIP
raises an error rather than falling back to plain data.
Headerless blobs retain Python's previous behavior: enable_compression=True expects GZIP bytes,
and False expects uncompressed bytes. Keep the original setting when reading those blobs.
Existing Python-compressed blobs without the encoding property are not automatically
interoperable with .NET or Go; those readers rely on the header. Uncompressed v2 payloads with
compression disabled on the Python reader can be exchanged without that limitation.
Warning
Upgrade all Python payload readers before enabling new writers. Older Python readers may transparently decode header-marked GZIP and then attempt a second decompression, even if they understand the token format. Existing headerless blobs are not rewritten; retaining their original compression setting remains necessary.
Message serialization strategies may still differ for complex objects and custom types.
You can implement a custom payload store by subclassing PayloadStore from durabletask.payload
and implementing the upload, upload_async, download, download_async, and is_known_token
methods:
from typing import Optional
from durabletask.payload import PayloadStore, LargePayloadStorageOptions
class MyPayloadStore(PayloadStore):
def __init__(self, options: LargePayloadStorageOptions):
self._options = options
@property
def options(self) -> LargePayloadStorageOptions:
return self._options
def upload(self, data: bytes, *, instance_id: Optional[str] = None) -> str:
# Store data and return a unique token string
...
async def upload_async(
self,
data: bytes,
*,
instance_id: Optional[str] = None,
) -> str:
...
def download(self, token: str) -> bytes:
# Retrieve data by token
...
async def download_async(self, token: str) -> bytes:
...
def is_known_token(self, value: str) -> bool:
# Return True if the value looks like a token from this store
...See the large payload example for a complete working sample.
The optional durabletask.extensions.history_export package provides a workflow for exporting the
full event history of terminal orchestrations to an external destination (for example Azure Blob
Storage). It is modeled after the .NET SDK's ExportHistory package.
An export job scans a time window of terminal instances, fetches each instance's history through
the standard client API, serializes it, and writes it through a pluggable HistoryWriter. Job
state is owned by a durable entity so progress survives worker restarts.
The core extension has no extra dependencies beyond the SDK. The bundled Azure Blob writer requires an optional dependency:
pip install durabletask[history-export-azure]from datetime import datetime, timedelta, timezone
from durabletask import client, worker
from durabletask.extensions.history_export import (
ExportDestination,
ExportFormat,
ExportFormatKind,
ExportHistoryClient,
ExportJobCreationOptions,
ExportMode,
)
from durabletask.extensions.history_export.azure_blob import (
AzureBlobHistoryExportWriter,
AzureBlobHistoryExportWriterOptions,
)
writer = AzureBlobHistoryExportWriter(
AzureBlobHistoryExportWriterOptions(
container_name="orchestration-history",
connection_string="DefaultEndpointsProtocol=https;...",
)
)
dt_client = client.TaskHubGrpcClient(host_address="localhost:4001")
export_client = ExportHistoryClient(dt_client, writer)
with worker.TaskHubGrpcWorker(host_address="localhost:4001") as w:
export_client.register_worker(w)
w.start()
now = datetime.now(timezone.utc)
desc = export_client.create_job(ExportJobCreationOptions(
mode=ExportMode.BATCH,
completed_time_from=now - timedelta(days=1),
completed_time_to=now,
destination=ExportDestination(container="orchestration-history", prefix="2026-05"),
format=ExportFormat(kind=ExportFormatKind.JSONL_GZIP),
max_instances_per_batch=100,
))
final = export_client.wait_for_job(desc.job_id, timeout=600)
print(final.status, final.exported_instances, final.failed_instances)ExportFormatKind |
Per-instance blob extension | Content-Type | Content-Encoding |
|---|---|---|---|
JSON |
.json |
application/json |
(none) |
JSONL_GZIP |
.jsonl.gz |
application/x-ndjson |
gzip |
The JSONL format prepends a metadata line and writes one event per line, which streams well for large histories.
Two ExportMode values are supported:
BATCHexports a fixed time window (completed_time_from..completed_time_to) and then marks the jobCompleted. This is the default and is appropriate for one-off backfills.CONTINUOUStails terminal instances indefinitely, sleeping between empty pages. The job has no natural completion; stop it by callingexport_client.delete_job(job_id)(or signallingmark_failed). The orchestrator re-reads entity state at the top of each page loop, so the next iteration after the delete observes the missing entity and exits cleanly.
Use list_jobs(ExportJobQuery(...)) to enumerate existing jobs, optionally filtered by status
or last-modified window:
from durabletask.extensions.history_export import ExportJobQuery, ExportJobStatus
for desc in export_client.list_jobs(
ExportJobQuery(status=[ExportJobStatus.FAILED])
):
print(desc.job_id, desc.last_error)Use get_job_client(job_id) for a per-job convenience wrapper that exposes describe(),
wait(timeout=...), and delete() directly:
job_client = export_client.get_job_client(desc.job_id)
final = job_client.wait(timeout=600)
print(final.status.value, final.exported_instances)
job_client.delete()The Azure Blob writer is one implementation of the
HistoryWriter extension point. Implement the protocol (no
inheritance required — it's a typing.Protocol) to send exports to
any destination (S3, GCS, SFTP, local filesystem, a database, etc.):
from durabletask.extensions.history_export import HistoryWriter
class LocalFileSystemHistoryWriter:
def __init__(self, root_dir: str) -> None:
self._root = root_dir
def write(
self,
*,
instance_id: str,
container: str,
blob_name: str,
payload: bytes,
content_type: str,
content_encoding: str | None,
) -> None:
import os
# ``container`` is the destination's logical container name
# (an ExportDestination.container). Per-job routing writers
# combine it with ``blob_name``; writers that pin to a fixed
# location at construction time may ignore it.
path = os.path.join(self._root, container, blob_name)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "wb") as fp:
fp.write(payload)
export_client = ExportHistoryClient(
dt_client, LocalFileSystemHistoryWriter("/var/exports")
)Tip
The bundled AzureBlobHistoryExportWriter lives in the optional
durabletask.extensions.history_export.azure_blob submodule and
requires pip install durabletask[history-export-azure]. The
core history-export package has no third-party runtime
dependencies — only the bundled destination does. Future
first-party destinations (S3, GCS, etc.) will be packaged as
additional optional extras using the same pattern.
By default a worker receives all work items from the backend, regardless of which orchestrations, activities, or entities are registered. Work item filtering lets you explicitly tell the backend which work items a worker can handle so that only matching items are dispatched. This is useful when running multiple specialized workers against the same task hub.
Work item filtering is opt-in. Call use_work_item_filters() on the worker before starting it.
Calling use_work_item_filters() with no arguments builds filters automatically from the worker's
registry at start time:
with DurableTaskSchedulerWorker(...) as w:
w.add_orchestrator(my_orchestrator)
w.add_activity(my_activity)
w.use_work_item_filters() # auto-generate from registry
w.start()When versioning is configured with VersionMatchStrategy.STRICT, the worker's version is included
in every filter so the backend only dispatches work items that match that exact version.
Pass a WorkItemFilters instance for fine-grained control:
from durabletask.worker import (
WorkItemFilters,
OrchestrationWorkItemFilter,
ActivityWorkItemFilter,
EntityWorkItemFilter,
)
w.use_work_item_filters(WorkItemFilters(
orchestrations=[
OrchestrationWorkItemFilter(name="my_orch", versions=["2.0.0"]),
],
activities=[
ActivityWorkItemFilter(name="my_activity"),
],
entities=[
EntityWorkItemFilter(name="my_entity"),
],
))Pass None to clear any previously configured filters and return to the default behaviour of
processing all work items:
w.use_work_item_filters(None)See the full work item filtering sample.