External Storage - Python SDK
External Storage is in Pre-Release. APIs and configuration may change before the stable release. Join the #large-payloads Slack channel to provide feedback or ask for help.
The Temporal Service enforces a 2 MB per-payload limit by default. This limit is configurable on self-hosted deployments. When your Workflows or Activities handle data larger than the limit, you can offload payloads to external storage, such as Amazon S3, and pass a small reference token through the Event History instead. This page shows you how to set up External Storage with Amazon S3 and how to implement a custom storage driver.
For a conceptual overview of External Storage and its use cases, see External Storage.
Store and retrieve large payloads with Amazon S3
The Python SDK includes an S3 storage driver. Follow these steps to set it up:
Prerequisites
- An Amazon S3 bucket that you have read and write access to. Refer to lifecycle management to ensure that your payloads remain available for the entire lifetime of the Workflow.
- Install the
aioboto3extra:python -m pip install "temporalio[aioboto3]"
Procedure
-
Create an S3 client using
aioboto3and pass it to theS3StorageDriver. The driver uses your standard AWS credentials from the environment (environment variables, IAM role, or AWS config file):import aioboto3
from temporalio.contrib.aws.s3driver import S3StorageDriver
from temporalio.contrib.aws.s3driver.aioboto3 import new_aioboto3_client
session = aioboto3.Session(profile_name=AWS_PROFILE, region_name=AWS_REGION)
async with session.client("s3") as s3_client:
driver = S3StorageDriver(
client=new_aioboto3_client(s3_client),
bucket="my-temporal-payloads",
) -
Configure the driver on your
DataConverterand pass the converter to your Client and Worker:import dataclasses
from temporalio.client import Client, ClientConfig
from temporalio.converter import DataConverter, ExternalStorage
from temporalio.worker import Worker
data_converter = dataclasses.replace(
DataConverter.default,
external_storage=ExternalStorage(drivers=[driver]),
)
client_config = ClientConfig.load_client_connect_config()
client = await Client.connect(**client_config, data_converter=data_converter)
worker = Worker(
client,
task_queue="my-task-queue",
workflows=[MyWorkflow],
activities=[my_activity],
)By default, payloads larger than 256 KiB are offloaded to external storage. You can adjust this with the
payload_size_thresholdparameter, even setting it to 0 to externalize all payloads regardless of size. Refer to Configure payload size threshold for more information.All Workflows and Activities running on the Worker use the storage driver automatically without changes to your business logic. The driver uploads and downloads payloads concurrently and validates payload integrity on retrieve.
Implement a custom storage driver
If you need a storage backend other than what the built-in drivers allow, you can implement your own storage driver. Store payloads durably so that they survive process crashes and remain available for debugging and auditing after the Workflow completes. Refer to lifecycle management for retention requirements.
The following example shows a custom driver that uses local disk as the backing store. This example is for local development and testing only. In production, use a durable storage system that is accessible to all Workers:
import os
import uuid
from collections.abc import Sequence
from temporalio.api.common.v1 import Payload
from temporalio.converter import (
StorageDriver,
StorageDriverClaim,
StorageDriverStoreContext,
StorageDriverRetrieveContext,
StorageDriverWorkflowInfo,
)
class LocalDiskStorageDriver(StorageDriver):
def __init__(self, store_dir: str = "/tmp/temporal-payload-store") -> None:
self._store_dir = store_dir
def name(self) -> str:
return "local-disk"
async def store(
self,
context: StorageDriverStoreContext,
payloads: Sequence[Payload],
) -> list[StorageDriverClaim]:
os.makedirs(self._store_dir, exist_ok=True)
prefix = self._store_dir
target = context.target
if isinstance(target, StorageDriverWorkflowInfo) and target.id:
prefix = os.path.join(self._store_dir, target.namespace, target.id)
os.makedirs(prefix, exist_ok=True)
claims = []
for payload in payloads:
key = f"{uuid.uuid4()}.bin"
file_path = os.path.join(prefix, key)
with open(file_path, "wb") as f:
f.write(payload.SerializeToString())
claims.append(StorageDriverClaim(data={"path": file_path}))
return claims
async def retrieve(
self,
context: StorageDriverRetrieveContext,
claims: Sequence[StorageDriverClaim],
) -> list[Payload]:
payloads = []
for claim in claims:
file_path = claim.data["path"]
with open(file_path, "rb") as f:
raw = f.read()
payload = Payload()
payload.ParseFromString(raw)
payloads.append(payload)
return payloads
The following sections walk through the key parts of the driver implementation.
1. Extend the StorageDriver class
A custom driver extends the StorageDriver abstract class and implements three methods:
name()returns a unique string that identifies the driver. The SDK stores this name in the claim check reference so it can route retrieval requests to the correct driver. Changing the name after payloads have been stored breaks retrieval.store()receives a list of payloads and returns oneStorageDriverClaimper payload. A claim is a set of string key-value pairs that the driver uses to locate the payload later.retrieve()receives the claims thatstore()produced and returns the original payloads.
2. Store payloads
In store(), convert each Payload protobuf message to bytes with payload.SerializeToString() and write the bytes to
your storage system. The application data has already been serialized by the Payload Converter
and Payload Codec before it reaches the driver.
See the data conversion pipeline for more details.
Return a StorageDriverClaim for each payload with enough information to retrieve it later. The context.target
provides identity information (namespace, Workflow ID, or Activity ID) depending on the operation. Consider structuring
your storage keys to include this information so that you can identify which Workflow owns each payload. Within that
scope, content-addressable keys (such as a SHA-256 hash of the payload bytes) can help deduplicate identical payloads.
3. Retrieve payloads
In retrieve(), download the bytes using the claim data, then reconstruct the Payload protobuf message with
payload.ParseFromString(data). The Payload Converter handles deserializing the application data after the driver
returns the payload.
4. Configure the Data Converter
Pass an ExternalStorage instance to your DataConverter and use the converter when creating your Client and Worker.
You can also package your driver as a plugin for easier reuse across services:
import dataclasses
from temporalio.converter import DataConverter, ExternalStorage
data_converter = dataclasses.replace(
DataConverter.default,
external_storage=ExternalStorage(
drivers=[LocalDiskStorageDriver()],
),
)
Configure payload size threshold
You can configure the payload size threshold that triggers external storage. By default, payloads larger than 256 KiB
are offloaded to external storage. You can adjust this with the payload_size_threshold parameter, or set it to 0 to
externalize all payloads regardless of size.
import dataclasses
from temporalio.converter import DataConverter, ExternalStorage
data_converter = dataclasses.replace(
DataConverter.default,
external_storage=ExternalStorage(
drivers=[driver],
payload_size_threshold=0,
),
)
Use multiple storage drivers
When you register multiple drivers, you must provide a driver_selector function that chooses which driver stores each
payload. Any driver in the list that is not selected for storing is still available for retrieval, which is useful when
migrating between storage backends. Return None from the selector to keep a specific payload inline in Event History.
Multiple drivers are useful in scenarios such as:
- Driver migration. Your Worker needs to retrieve payloads created by clients that use a different driver than the one you prefer. Register both drivers and use the selector to always pick your preferred driver for new payloads. The old driver remains available for retrieving existing claims.
- Latency vs. durability tradeoffs. Some Workflow types may benefit from a faster storage backend at the cost of durability, while others require a durable backend like S3. Use the selector to route based on Workflow context.
The following example registers two drivers but always selects preferred_driver for new payloads. The legacy_driver
is only registered so the Worker can retrieve payloads that were previously stored with it:
from temporalio.converter import ExternalStorage
preferred_driver = S3StorageDriver(client=s3_client, bucket="my-bucket")
legacy_driver = LegacyStorageDriver()
ExternalStorage(
drivers=[preferred_driver, legacy_driver],
driver_selector=lambda context, payload: preferred_driver,
)