Del
10/30/2025, 8:56 PMMarvin
10/30/2025, 8:57 PMMarvin
10/30/2025, 9:00 PMcache_key computed from its cache policy. You can retrieve it a few ways:
- Inside the task while it’s running
from prefect import task, get_run_context, get_run_logger
@task
def my_task(x):
ctx = get_run_context() # TaskRunContext
logger = get_run_logger()
<http://logger.info|logger.info>(f"cache_key={ctx.task_run.cache_key}")
return x * 2
- From the API using the Python client (given a task run ID)
import asyncio
from prefect import get_client
async def get_cache_key(task_run_id):
async with get_client() as client:
tr = await client.read_task_run(task_run_id)
return tr.cache_key
# asyncio.run(get_cache_key(UUID("...")))
- From a PrefectFuture (to get the task run ID first)
from prefect import flow
@flow
def parent():
fut = my_task.submit(1)
print(f"task_run_id={fut.task_run_id}")
Then pass that task_run_id to the client snippet above.
- Via REST API directly
Make a GET request to /task_runs/{id} and read the cache_key field:
Task run by id
Notes
- The Prefect UI does not currently surface cache_key directly; use the API or log it from within the task.
- For how keys are computed and how to customize them, see Caching concepts.
If you’re on Prefect 2.x, the pattern is similar (the cache_key is still on the Task Run), but let me know and I can tailor the examples. Do you want to fetch the key for an in-flight run, a past run, or compute what it would be ahead of time?