Stop paying twice for the same API call
A Python script keeps the answer of a slow, paid API call under a key, so later runs and teammates read it back in about a second instead of paying again.
The problem
Your script calls something slow that you pay for: an enrichment API, a model, a scraper. It asked the same question an hour ago, and so did a teammate’s script and last night’s job. Each of them waited and each of them paid, because the answer lived only in the process that fetched it.
At the end of this guide you have one Python file, cache.py, that stores the answer under a key on Artefaktum, a file store with an API. Any later run, on any machine, reads it back by that key, and an answer that is too old is fetched again. The output shown is from our own run against production on 16 November 2026, with the artifact ids shortened.
What you need
Python 3.11 or newer, an Artefaktum API key from the console, and the SDK:
pip install artefaktum==0.3.0
export ARTEFAKTUM_API_KEY=ak_...
Paste the blocks below into cache.py in the order they appear; together they are the complete program. It starts with the imports and its constants:
import argparse
import json
import sys
import tempfile
import time
from datetime import UTC, datetime
import httpx # installed with the SDK, which sends its requests through it
from artefaktum import Artefaktum, ArtefaktumError, Conflict, MissingApiKey, NotFound
KEY_PREFIX = "blog-guide/cache-an-api-call/"
TAGS = ["blog-guide", "cache-an-api-call"]
PROVIDER_SECONDS = 3 # how long the stand-in provider takes to answer
PROVIDER_PRICE = "$0.02" # what we pretend one call costs
NOT_READY_TRIES = 5 # how often to look again while another run is still uploading
MISS = 3 # exit status of --read-only when there is no stored answer
The call you pay for
The paid call in this guide is a stand-in. fetch_report calls nobody: it sleeps for three seconds and prints a price we made up, so you can run everything without a second account. It stamps its answer with the time, which is how you will tell a stored answer from a new one. Put your own call in its place.
def fetch_report(city):
"""A stand-in for the call you pay for: an enrichment API, a model, a scraper.
It calls nobody. It sleeps, to be slow, and stamps the answer with the time,
so you can tell a stored answer from a new one.
"""
print(f"calling the provider: {PROVIDER_SECONDS} seconds, {PROVIDER_PRICE} (a stand-in)")
time.sleep(PROVIDER_SECONDS)
return {
"city": city,
"fetched_at": datetime.now(UTC).isoformat(timespec="seconds"),
"summary": f"A report about {city} that was slow and cost money to make.",
}
One key per question
An external key is a name of your own choosing that is unique within a project. The cache rests on one rule: the same question always produces the same key.
def key_for(city):
"""The same question must always give the same key: that is what makes it a cache."""
return KEY_PREFIX + "report/" + city.strip().lower().replace(" ", "-")
Read first, call only on a miss
pull_by_key finds the artifact (a stored file with a title and tags) that holds the key, downloads it and checks its sha256. When no artifact holds the key, or the one that does is older than max_age seconds, it raises NotFound. That exception is the cache miss.
A key is taken from the moment an upload under it starts, and until that upload is finished pull_by_key raises Conflict with the code artifact_not_ready. Every first upload under a key passes through that state, so read_cached looks again once a second, up to five times, before it calls the answer missing.
def read_cached(client, key, max_age):
"""The stored answer under the key, or None when there is none younger than max_age."""
with tempfile.TemporaryDirectory() as folder:
for _ in range(NOT_READY_TRIES):
try:
# Finds the artifact by key, downloads the file and checks its sha256.
path = client.artifacts.pull_by_key(key, folder, max_age=max_age)
except NotFound as miss:
print(f"miss: {miss.message}")
return None
except Conflict as busy:
if busy.code != "artifact_not_ready":
raise
# Another run holds the key and its upload is not finished. Look again.
print("not ready: another run is storing this answer, looking again in a second")
time.sleep(1)
else:
print("hit: read the stored answer")
return json.loads(path.read_text())
print(f"miss: the upload under the key did not finish in {NOT_READY_TRIES} seconds")
return None
On a miss you make the call and store the answer with push. With if_exists="reuse", a push that finds a young enough artifact under the key uploads nothing and returns that artifact with reused set to true. Without it, a second push under the same key is an error.
def store(client, key, city, report, max_age):
"""Store the answer under the key, unless another run got there first."""
artifact = client.artifacts.push(
json.dumps(report, indent=2).encode(),
filename="report.json",
title=f"Report for {city}",
description="The stored answer of fetch_report, kept so that the call is not repeated.",
tags=TAGS,
external_key=key,
# "reuse": when a young enough artifact already holds the key, upload nothing.
if_exists="reuse",
max_age=max_age,
)
version = artifact.latest_version.version_number
if artifact.reused:
print(f"another run stored it first: artifact {artifact.id}, version {version}")
else:
print(f"stored: artifact {artifact.id}, version {version}")
return artifact
push needs the bytes, so by itself it cannot spare you the call. Reading first does that; reuse covers the moment when two runs miss together, shown further down.
def get_report(client, city, max_age):
"""The report for a city: the stored one when it is young enough, else a new one."""
key = key_for(city)
report = read_cached(client, key, max_age)
if report is not None:
return report
report = fetch_report(city)
artifact = store(client, key, city, report, max_age)
if artifact.reused:
# Two runs missed at the same moment and both paid. Everyone uses the stored answer.
return read_cached(client, key, max_age) or report
return report
Miss, then hit
The two remaining blocks are further down. With them pasted, run the program twice:
$ python cache.py Vilnius
key: blog-guide/cache-an-api-call/report/vilnius
miss: Artifact not found
calling the provider: 3 seconds, $0.02 (a stand-in)
stored: artifact 01a1e3c1-39e0-…, version 1
{
"city": "Vilnius",
"fetched_at": "2026-11-16T09:47:33+00:00",
"summary": "A report about Vilnius that was slow and cost money to make."
}
took 5.4 seconds
$ python cache.py Vilnius
key: blog-guide/cache-an-api-call/report/vilnius
hit: read the stored answer
{
"city": "Vilnius",
"fetched_at": "2026-11-16T09:47:33+00:00",
"summary": "A report about Vilnius that was slow and cost money to make."
}
took 0.7 seconds
The second run is a separate process. It did not call the provider, and fetched_at shows it got the first run’s answer. Be clear about the cost: the first run took 5.4 seconds for a 3-second call, because storing takes time too, and a hit took between 0.6 and 2.5 seconds over our seven runs. A cache like this pays when the call is slower or dearer than about a second of lookup.
Decide how old is too old
max_age is in whole seconds, at least 1. We waited six seconds, by which time the stored answer was ten seconds old, and asked for one no older than five:
$ python cache.py Vilnius --max-age 5
key: blog-guide/cache-an-api-call/report/vilnius
miss: artifact under key 'blog-guide/cache-an-api-call/report/vilnius' is 10s old, older than max_age_seconds=5
calling the provider: 3 seconds, $0.02 (a stand-in)
stored: artifact 01a1e3c1-39e0-…, version 2
{
"city": "Vilnius",
"fetched_at": "2026-11-16T09:47:47+00:00",
"summary": "A report about Vilnius that was slow and cost money to make."
}
took 5.3 seconds
The stale answer counted as missing, in the read and in the push. The new answer became version 2 of the same artifact, so the key never points at two things. Each caller picks its own max_age: a dashboard may accept a day, a billing job an hour.
A reader that never pays
A teammate’s script may only want the answer if someone already has it. --read-only does the read and nothing else. On a miss it exits with status 3, so a caller can tell a miss from a failure, which is status 1. Run just before the refresh above, it printed:
$ python cache.py Vilnius --read-only --max-age 5
key: blog-guide/cache-an-api-call/report/vilnius
miss: artifact under key 'blog-guide/cache-an-api-call/report/vilnius' is 9s old, older than max_age_seconds=5
Two runs at the same moment
We started two runs for a new city together. This is the one that lost:
key: blog-guide/cache-an-api-call/report/kaunas
miss: Artifact not found
calling the provider: 3 seconds, $0.02 (a stand-in)
another run stored it first: artifact 01a1e3c1-8dd6-…, version 1
hit: read the stored answer
Both runs missed, so both called the provider and both paid. The cache does not prevent that. For a new key, reuse left one stored answer: the losing push waited for the winner’s upload, uploaded nothing and came back with reused true. It took 9.1 seconds against the winner’s 4.8.
Two runs that miss together on a stale answer behave differently. When we tried it, each stored its own answer, neither was reused, and the artifact went from version 1 to version 3. It was still one artifact under one key.
If the other upload never finishes, because that run died, push waits for its timeout (30 seconds by default) and raises ProcessingTimeout. We saw exactly that after reserving a key and walking away; deleting the unfinished artifact, which --cleanup does, freed the key. According to the server’s source, the dead upload’s hold also lapses on its own: once its upload window closes, 60 minutes by default, the next push with reuse takes the key over. We did not wait for it.
Clean up
In real use you delete nothing: keys stay stable and max_age does the refreshing. To remove what the demo stored, --cleanup deletes by tag. It names the statuses it wants, unfinished uploads included, which leaves out an artifact that is already being deleted. Deleting is asynchronous: the call returns at once and the key stays taken for a few seconds (about three in our runs) while the file is removed. So the function waits until each key is free.
def cleanup(client):
"""Delete every artifact this program stored, and wait until their keys are free again."""
statuses = ["pending_upload", "processing", "ready", "failed"]
stored = [
artifact
for artifact in client.artifacts.iter_all(tag="cache-an-api-call", status=statuses)
if (artifact.external_key or "").startswith(KEY_PREFIX)
]
for artifact in stored:
client.artifacts.delete(artifact.id)
print(f"deleted: {artifact.external_key} (artifact {artifact.id})")
# Deleting is asynchronous: for a few seconds the key still leads to the old artifact.
for artifact in stored:
for _ in range(30):
try:
client.artifacts.get_by_external_key(artifact.external_key)
except NotFound:
break
time.sleep(1)
else:
raise RuntimeError(f"{artifact.external_key} is still taken after 30 seconds")
print(f"nothing left: {len(stored)} deleted")
$ python cache.py --cleanup
deleted: blog-guide/cache-an-api-call/report/kaunas (artifact 01a1e3c1-8dd6-…)
deleted: blog-guide/cache-an-api-call/report/vilnius (artifact 01a1e3c1-39e0-…)
nothing left: 2 deleted
The last block parses the arguments and starts the program. It comes last because main uses every function above it. A failure, of the API or of the network, ends the run with one line that starts with failed: and status 1.
def arguments():
parser = argparse.ArgumentParser(description="Cache the answer of a slow, paid call.")
parser.add_argument("city", nargs="?", default="Vilnius")
parser.add_argument(
"--max-age",
type=int,
default=3600,
metavar="SECONDS",
help="an older stored answer counts as missing (whole seconds, at least 1)",
)
parser.add_argument("--read-only", action="store_true", help="never call the provider")
parser.add_argument("--cleanup", action="store_true", help="delete what this program stored")
return parser.parse_args()
def main():
args = arguments()
try:
client = Artefaktum() # reads ARTEFAKTUM_API_KEY; the project is "default"
except MissingApiKey:
print("usage: ARTEFAKTUM_API_KEY=ak_... python cache.py [city]", file=sys.stderr)
sys.exit(2)
with client:
if args.cleanup:
cleanup(client)
return
started = time.perf_counter()
print(f"key: {key_for(args.city)}")
if args.read_only:
report = read_cached(client, key_for(args.city), args.max_age)
if report is None:
sys.exit(MISS)
else:
report = get_report(client, args.city, args.max_age)
print(json.dumps(report, indent=2))
print(f"took {time.perf_counter() - started:.1f} seconds")
if __name__ == "__main__":
try:
main()
except (ArtefaktumError, RuntimeError, httpx.TransportError) as error:
# The SDK does not wrap a network failure: httpx's own error reaches the caller.
sys.exit(f"failed: {error}")
Where next
- The Python SDK reference covers
push,pull_by_key,get_by_external_key(the lookup without the download) and the errors. - In TypeScript the same calls are
pushwithif_exists: "reuse"andmax_age_seconds, andpullByKey: see the TypeScript SDK. - The same idea without code is an n8n template of the same name.
- No account at all: pay per request from Python.
This page as Markdown: /blog/stop-paying-twice-for-the-same-api-call.md