---
title: "Caches"
description: "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."
image: "https://tilebox.com/images/tilebox-docs-social-preview.png"
---

> Documentation Index
> Fetch the complete documentation index at: https://tilebox.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Caches

:::warning
  The cache API is currently experimental and may undergo changes in the future. Many more features and new [backends](#cache-backends) are on the roadmap. There might be breaking changes to the Cache API in the future.
:::

Caches are configured on the [`Runner`](/docs/api-reference/python/tilebox.workflows/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](/docs/workflows/concepts/runners#release-runners) (loaded via `tilebox.workflow.toml`) and [direct runners](/docs/workflows/concepts/runners#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](#cache-backends).

```python title="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](#storing-and-retrieving-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 Cloud Storage](#google-storage-cache)

- [Amazon S3](#amazon-s3-cache)

- [Local File System](#local-file-system-cache)

- [In-Memory](#in-memory-cache)

### 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 <a href="https://cloud.google.com/docs/authentication/application-default-credentials" target="_blank">Google Cloud ADC documentation</a>.

**GoogleStorageCache**

```python title="Python"
from tilebox.workflows import Runner
from tilebox.workflows.cache import GoogleStorageCache

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

:::tip
    The `prefix` parameter is optional and sets a common prefix for all cache keys, which helps organize objects within a bucket reused for other purposes. When defining a [release runner](/docs/workflows/concepts/runners#release-runners), `tilebox workflow build-release` imports `runner.py` locally—guard cloud cache creation behind an environment variable (for example `os.environ.get("CACHE_BUCKET")`) if build machines do not have cloud credentials configured.
:::

### 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](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html#configuration).

```python title="Python"
from tilebox.workflows import Runner
from tilebox.workflows.cache import AmazonS3Cache

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

:::tip
    The `prefix` parameter is optional and can be used to set a common prefix for all cache keys, which helps organize objects within a bucket when re-using the same bucket for other purposes.
:::

### 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 title="Python"
from tilebox.workflows import Runner
from tilebox.workflows.cache import LocalFileSystemCache

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

:::tip
    Local file system caches can also be used in conjunction with network attached storage or similar tools, making it a viable option also for distributed setups.
:::

### 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 title="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.

:::note
    The capability to share data across jobs is planned for future updates. This feature will be beneficial for real-time processing workflows or workflows requiring auxiliary data from external sources.
:::

## Storing and Retrieving Data

The job cache can be accessed via the `ExecutionContext` passed to a task's `execute` function. This [`job_cache`](/docs/api-reference/python/tilebox.workflows/ExecutionContext.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 title="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 title="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()
```

```plaintext title="Logs"
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 title="Python" {39,44-45}
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 title="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()
```

```plaintext title="Logs"
Computed sum of all numbers total=284
```

Source: https://tilebox.com/docs/workflows/authoring/caches/index.mdx
