Skip to content

Caches

Sharing data between tasks is crucial for workflows, especially in satellite imagery processing, where large datasets are the norm. Tilebox Workflows offers a straightforward API for storing and retrieving data from a shared cache.

Caches are configured on the Runner definition. Because runners can be deployed across multiple locations, caches must be accessible from all runners contributing to a workflow.

By default, cache is None (no cache is configured). For multi-runner production deployments, pass a cloud-backed cache such as GoogleStorageCache or AmazonS3Cache. For quick prototyping and local development, use LocalFileSystemCache or InMemoryCache.

If needed, you can create your own cache backend by implementing the JobCache interface.

Configuring a Cache

Pass a cache instance to the cache parameter of Runner. Because the cache belongs to the reusable Runner definition, the same configuration works for both release runners (loaded via tilebox.workflow.toml) and direct runners (started with runner.connect_to(client)).

To use an in-memory cache for local development and quick testing, pass tilebox.workflows.cache.InMemoryCache. For shared backends, see the supported cache backends.

Python
from tilebox.workflows import Client, Runner
from tilebox.workflows.cache import InMemoryCache

runner = Runner(
    tasks=[...],
    cache=InMemoryCache(),
)

# For direct execution:
if __name__ == "__main__":
    runner.connect_to(Client()).run_forever()

By configuring a cache on Runner, the context object passed to each task’s execute method gains access to a job_cache attribute that can be used to store and retrieve data from the cache.

Cache Backends

Tilebox Workflows comes with four cache implementations out of the box, each backed by a different storage system.

Google Storage Cache

A cache implementation backed by a Google Cloud Storage bucket to store and retrieve data. It’s a reliable method for sharing data across tasks, suitable for production environments. You will need access to a GCP project and a bucket.

GoogleStorageCache authenticates with Google Application Default Credentials (google.auth). To set up authentication, refer to the Google Cloud ADC documentation.

GoogleStorageCache

Python
from tilebox.workflows import Runner
from tilebox.workflows.cache import GoogleStorageCache

runner = Runner(
    tasks=[...],
    cache=GoogleStorageCache("cache-bucket", prefix="jobs"),
)

Amazon S3 Cache

A cache implementation backed by an Amazon S3 bucket to store and retrieve data. Like the Google Cloud Storage option, it’s reliable and scalable for production use.

Tilebox utilizes the boto3 library to communicate with Amazon S3. For the necessary authentication setup, refer to its documentation.

Python
from tilebox.workflows import Runner
from tilebox.workflows.cache import AmazonS3Cache

runner = Runner(
    tasks=[...],
    cache=AmazonS3Cache("my-bucket-name", prefix="jobs"),
)

Local File System Cache

A cache implementation backed by a local file system. It’s suitable for quick prototyping and local development, assuming all runners share the same machine or access the same file system.

Python
from tilebox.workflows import Runner
from tilebox.workflows.cache import LocalFileSystemCache

runner = Runner(
    tasks=[...],
    cache=LocalFileSystemCache("/path/to/cache/directory"),
)

In-Memory Cache

A simple in-memory cache useful for quick prototyping and development. The data is not shared between runners and is lost upon runner restarts. Use this cache only for workflows executed on a single runner.

Python
from tilebox.workflows import Runner
from tilebox.workflows.cache import InMemoryCache

runner = Runner(
    tasks=[...],
    cache=InMemoryCache(),
)

Data Isolation

Caches are isolated per job, meaning that each job’s cache data is only accessible to tasks within that job. This setup prevents key conflicts between different job executions. Currently, accessing cache data of other jobs is not supported.

Storing and Retrieving Data

The job cache can be accessed via the ExecutionContext passed to a task’s execute function. This job_cache object provides methods to handle data storage and retrieval from the cache. The specifics of data storage depend on the chosen cache backend.

The cache API is designed to be simple and can handle all types of data, supporting binary data in the form of bytes, identified by str cache keys. This allows for storing many different data types, such as pickled Python objects, serialized JSON, UTF-8, or binary data.

The following snippet illustrates storing and retrieving data from the cache.

Python
from tilebox.workflows import Task, ExecutionContext

class ProducerTask(Task):
    def execute(self, context: ExecutionContext) -> None:
        # store data in the cache
        context.job_cache["data"] = b"my_binary_data_to_store"
        context.submit_subtask(ConsumerTask())

class ConsumerTask(Task):
    def execute(self, context: ExecutionContext) -> None:
        data = context.job_cache["data"]
        context.logger.info("Read data from cache", data=data.decode())

In this example, data stored under the key "data" can be any size that fits the cache backend constraints. Ensure the key remains unique within the job’s scope to avoid conflicts.

To test the workflow locally, define a Runner with LocalFileSystemCache, submit a job to execute ProducerTask, and inspect the logs emitted by ConsumerTask.

Python
from tilebox.workflows import Client, Runner
from tilebox.workflows.cache import LocalFileSystemCache

client = Client()

# submit a job to test our workflow
job_client = client.jobs()
job_client.submit("testing-cache-access", ProducerTask())

# start a runner to execute it
runner = Runner(
    tasks=[ProducerTask, ConsumerTask],
    cache=LocalFileSystemCache("/path/to/cache/directory"),
)
runner.connect_to(client).run_forever()
Logs plaintext
Read data from cache data=my_binary_data_to_store

Groups and Hierarchical Keys

The cache API supports groups and hierarchical keys, analogous to directories and files in a file system. Groups help organize cache keys hierarchically, preventing key conflicts and allowing data to be structured better. Additionally, groups are iterable, enabling retrieval of all keys within the group. This feature is useful when multiple tasks create cache data, and a later task needs to list all produced data by earlier tasks.

The following code shows an example of how cache groups can be used.

Python
from tilebox.workflows import Task, ExecutionContext
import random

class CacheGroupDemo(Task):
    n: int

    def execute(self, context: ExecutionContext):
        # define a cache group key for subtasks
        group_key = "random_numbers"
        produce_numbers = context.submit_subtask(
            ProduceRandomNumbers(self.n, group_key)
        )
        sum_task = context.submit_subtask(
            PrintSum(group_key),
            depends_on=[produce_numbers],
        )

class ProduceRandomNumbers(Task):
    n: int
    group_key: str

    def execute(self, context: ExecutionContext):
        for i in range(self.n):
            context.submit_subtask(ProduceRandomNumber(i, self.group_key))

class ProduceRandomNumber(Task):
    index: int
    group_key: str

    def execute(self, context: ExecutionContext) -> None:
        number = random.randint(0, 100)
        group = context.job_cache.group(self.group_key)
        group[f"key_{self.index}"] = str(number).encode()

class PrintSum(Task):
    group_key: str

    def execute(self, context: ExecutionContext) -> None:
        group = context.job_cache.group(self.group_key)

        # PrintSum doesn't know how many numbers were produced,
        # instead it iterates over all keys in the cache group
        numbers = []
        for key in group:  # iterate over all stored numbers
            number = group[key]  # read data from cache
            numbers.append(int(number.decode()))  # convert bytes back to int

        context.logger.info("Computed sum of all numbers", total=sum(numbers))

Submitting a job of the CacheGroupDemo and running it with a runner can be done as follows:

Python
from tilebox.workflows import Client, Runner
from tilebox.workflows.cache import LocalFileSystemCache

client = Client()

# submit a job to test our workflow
job_client = client.jobs()
job_client.submit("cache-groups", CacheGroupDemo(5))

# start a runner to execute it
runner = Runner(
    tasks=[CacheGroupDemo, ProduceRandomNumbers, ProduceRandomNumber, PrintSum],
    cache=LocalFileSystemCache("/path/to/cache/directory"),
)
runner.connect_to(client).run_forever()
Logs plaintext
Computed sum of all numbers total=284

Type to search…