Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions .github/scripts/start-fake-gcs.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/env bash
# Start the CI Google Cloud Storage emulator (fake-gcs-server) on http://localhost:4443 as
# container `fake-gcs`, storing objects in memory. Point a client at it with
# STORAGE_EMULATOR_HOST=http://localhost:4443.
# The image is pinned by digest, so the registry only carries the bytes: the
# daemon verifies them against the digest wherever they come from. Each
# registry's anonymous quota is per source IP and hosted runners share IPs, so
# the pull walks FAKE_GCS_REPOS in order, twice, and uses the first that serves it.
#
# CI: bash .github/scripts/start-fake-gcs.sh
# Local: bash .github/scripts/start-fake-gcs.sh (needs docker and a free port 4443)
# Test: put a stub `docker` first on PATH; FAKE_GCS_DIGEST / FAKE_GCS_REPOS override the pin.
set -u

# fsouza/fake-gcs-server 1.56.1 multi-arch index, resolved 2026-11-27.
# Every registry listed serves this digest. Renovate does not bump it.
FAKE_GCS_DIGEST=${FAKE_GCS_DIGEST:-sha256:797ce226d62f947c009dc40246b30cfb456b8473d8241407f9d6f2c04e4d69ef}
FAKE_GCS_REPOS=${FAKE_GCS_REPOS:-mirror.gcr.io/fsouza/fake-gcs-server docker.io/fsouza/fake-gcs-server}

image=
for round in 1 2; do
for repo in $FAKE_GCS_REPOS; do
if timeout 120 docker pull "$repo@$FAKE_GCS_DIGEST"; then image=$repo@$FAKE_GCS_DIGEST; break 2; fi
done
[ "$round" = 1 ] && sleep 15
done
[ -n "$image" ] || { echo "::error::no registry served fake-gcs-server@${FAKE_GCS_DIGEST} (tried: ${FAKE_GCS_REPOS})"; exit 1; }

docker run -d --name fake-gcs -p 4443:4443 "$image" \
-scheme http -port 4443 -backend memory -public-host localhost:4443 || exit 1

# Ready when the server lists buckets on the published port. The 30s deadline
# covers the probes too, so a server that never comes up, or accepts but never
# answers, fails this step instead of hanging the job.
deadline=$((SECONDS + 30))
while [ "$SECONDS" -lt "$deadline" ]; do
if curl --silent --fail --max-time 2 --output /dev/null http://127.0.0.1:4443/storage/v1/b; then
exit 0
fi
sleep 1
done
echo "::error::fake-gcs-server did not answer on 127.0.0.1:4443 within 30s"
docker logs fake-gcs
exit 1
10 changes: 10 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,12 @@ jobs:
if: github.event_name == 'push'
run: bash .github/scripts/start-memcached.sh

# Push runs only: tests/integration/test_gcs_integration.py skips its whole module when
# nothing answers on localhost:4443.
- name: Start the GCS emulator
if: github.event_name == 'push'
run: bash .github/scripts/start-fake-gcs.sh

- name: Run full test suite (main)
if: github.event_name == 'push'
env:
Expand All @@ -186,6 +192,10 @@ jobs:
if: github.event_name == 'push'
run: python3 .github/scripts/assert-junit-ran.py junit.xml tests.integration.test_memcached_integration

- name: Check the GCS integration tests ran
if: github.event_name == 'push'
run: python3 .github/scripts/assert-junit-ran.py junit.xml tests.integration.test_gcs_integration

# Executable docs are tests: docstring examples, tests/docs/ and the docs/
# markdown blocks. None of them sit under tests/unit or tests/critical, so
# the runs above never collect them.
Expand Down
32 changes: 30 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ backend that fits your infrastructure — they're peers behind the same `@cache`
| Redis | Self-hosted, full control | `REDIS_URL` / `CACHEKIT_REDIS_URL` |
| CacheKit Cloud | Managed, zero-ops (closed beta) | `CACHEKIT_API_KEY` |
| Memcached | High-throughput, existing infra | `CACHEKIT_MEMCACHED_SERVERS` |
| Google Cloud Storage | Durable results on Cloud Run and jobs, no server | `CACHEKIT_GCS_BUCKET` |
| File / L1-only | Local dev, tests, no external deps | `CACHEKIT_FILE_CACHE_DIR` / nothing (or `backend=None`) |

```bash
Expand Down Expand Up @@ -157,6 +158,28 @@ def expensive_api_call(user_id: int):

</details>

<details>
<summary><strong>Google Cloud Storage — Optional</strong></summary>

```python notest
from cachekit import cache
from cachekit.backends.gcs import GCSBackend, GCSBackendConfig

# pip install cachekit[gcs]

backend = GCSBackend(GCSBackendConfig(bucket="my-cache-bucket")) # Application Default Credentials

@cache(backend=backend, ttl=3600)
def expensive_api_call(user_id: int):
return fetch_user_data(user_id)
```

One object per entry, in the file backend's format. See [Google Cloud Storage Backend](docs/backends/gcs.md) for IAM and the bucket lifecycle rule.

*Requires: `pip install cachekit[gcs]` or `uv add cachekit[gcs]`*

</details>

---

> **CacheKit Cloud (Closed Beta)**
Expand Down Expand Up @@ -294,7 +317,7 @@ Hosted runners come with other CPU models too: in a run of an earlier commit, an
- Connection pooling with thread affinity
- The CacheKit Cloud backend keeps idle connections pooled until the server closes them, with TCP keepalive probes, so a request after a pause skips a new TLS handshake
- Distributed locking guards against cache stampedes across pods, best effort (async functions, on a backend that supports it)
- Pluggable backend abstraction (Redis, CacheKit Cloud, File, Memcached, custom)
- Pluggable backend abstraction (Redis, CacheKit Cloud, File, Memcached, Google Cloud Storage, custom)
- Untrusted-decode bounds: nesting depth and header-declared allocation are capped on every cache read (a forged entry is a bounded cache miss), verified against the protocol's shared [`decode-bounds.json`](https://github.com/cachekit-io/protocol/blob/42ea601f3c1656df0a06904afa2406604f43f57d/test-vectors/decode-bounds.json) vectors

> [!NOTE]
Expand Down Expand Up @@ -520,7 +543,7 @@ info = expensive_func.cache_info()

```bash
# Backend selection: set exactly ONE of CACHEKIT_REDIS_URL, CACHEKIT_API_KEY,
# CACHEKIT_MEMCACHED_SERVERS, CACHEKIT_FILE_CACHE_DIR. Two or more is a ConfigurationError at
# CACHEKIT_MEMCACHED_SERVERS, CACHEKIT_FILE_CACHE_DIR, CACHEKIT_GCS_BUCKET. Two or more is a ConfigurationError at
# first call, and decorators relying on env auto-detection run uncached (docs/backends/README.md).
# REDIS_URL is only a fallback and never conflicts. With none of them set, decorators cache
# L1-only, in process (encrypted decorators still use localhost Redis; interop decorators refuse
Expand All @@ -541,6 +564,11 @@ CACHEKIT_MEMCACHED_CONNECT_TIMEOUT=2.0 # Default: 2.0 seconds
CACHEKIT_MEMCACHED_TIMEOUT=1.0 # Default: 1.0 seconds
CACHEKIT_MEMCACHED_KEY_PREFIX="myapp:" # Default: "" (none)

# Google Cloud Storage Backend (optional: pip install cachekit[gcs]; Application Default Credentials)
# CACHEKIT_GCS_BUCKET="my-cache-bucket" # Required to select it
CACHEKIT_GCS_PREFIX="cachekit/" # Default: "" (bucket root)
CACHEKIT_GCS_TIMEOUT=10.0 # Default: 10.0 seconds

# Optional Configuration
CACHEKIT_MAX_VALUE_SIZE=104857600
CACHEKIT_ARROW_COMPRESSION=zstd
Expand Down
2 changes: 2 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ Choose your storage backend:
| [Redis](backends/redis.md) | Self-hosted, production-grade, connection pooling |
| [File](backends/file.md) | Local filesystem, zero dependencies |
| [Memcached](backends/memcached.md) | High-throughput, consistent hashing |
| [Google Cloud Storage](backends/gcs.md) | Durable, one object per entry, no server |
| [CacheKit Cloud](backends/cachekitio.md) | Managed, zero infrastructure |
| [L1-Only (None)](backends/none.md) | In-memory only, no external services |
| [Custom](backends/custom.md) | Implement your own backend |
Expand Down Expand Up @@ -88,6 +89,7 @@ docs/
│ ├── README.md # Backend overview (auto-rendered)
│ ├── redis.md, file.md # Built-in backends
│ ├── memcached.md, cachekitio.md # Optional backends
│ ├── gcs.md # Google Cloud Storage (optional)
│ ├── none.md # L1-only mode
│ └── custom.md # Custom backend guide
│
Expand Down
2 changes: 1 addition & 1 deletion docs/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -711,7 +711,7 @@ For error examples and handling patterns, see [Troubleshooting Guide](troublesho

## Backend Abstraction

cachekit uses a protocol-based backend abstraction (PEP 544) that allows pluggable storage backends for L2 cache. Built-in backends include Redis, CacheKit Cloud, File, and Memcached. You can also implement custom backends for any key-value store.
cachekit uses a protocol-based backend abstraction (PEP 544) that allows pluggable storage backends for L2 cache. Built-in backends include Redis, CacheKit Cloud, File, Memcached, and Google Cloud Storage. You can also implement custom backends for any key-value store.

For comprehensive backend guide with examples and implementation patterns, see **[Backend Guide](backends/README.md)**.

Expand Down
17 changes: 14 additions & 3 deletions docs/backends/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

# Backend Guide

Pluggable L2 cache storage for cachekit. Four backends are included out of the box — Redis, File (local), Memcached, and CacheKit Cloud (managed). With no backend configured, a plaintext decorator runs in [L1-only mode](none.md), as `backend=None` does; encrypted and interop decorators still need a backend ([Nothing Configured](#4-nothing-configured-l1-only)). You can also implement custom backends for any key-value store.
Pluggable L2 cache storage for cachekit. Five backends are included out of the box — Redis, File (local), Memcached, Google Cloud Storage, and CacheKit Cloud (managed). With no backend configured, a plaintext decorator runs in [L1-only mode](none.md), as `backend=None` does; encrypted and interop decorators still need a backend ([Nothing Configured](#4-nothing-configured-l1-only)). You can also implement custom backends for any key-value store.

## Overview

Expand Down Expand Up @@ -98,6 +98,7 @@ class BaseBackend(Protocol):
| **[File](file.md)** | set = fsync + a scan of every entry, so slow on a large cache; get waits on a concurrent set ([cost model](file.md#performance-characteristics)) | Yes (disk) | Format shared; one writer process | Yes | File locks |
| **[Redis](redis.md)** | One network round trip per operation ([not measured here](../performance.md#not-measured-here)) | Yes (RDB/AOF) | Yes | Yes | Yes |
| **[Memcached](memcached.md)** | One network round trip per operation ([not measured here](../performance.md#not-measured-here)) | No | Yes | Yes (max 30d) | No |
| **[Google Cloud Storage](gcs.md)** | One HTTPS request to GCS per ordinary operation ([request counts](gcs.md#requests-per-operation); [not measured here](../performance.md#not-measured-here)) | Yes | Yes | Yes (checked on read) | No |
| **[CacheKit Cloud](cachekitio.md)** | 42–45ms p50 hit, measured from MEL ([varies by vantage](cachekitio.md#characteristics)) | Yes | Yes | Yes | Yes |
| **[HTTP (custom)](custom.md)** | One HTTP request per operation ([not measured here](../performance.md#not-measured-here)) | Varies | Yes | Varies | Varies |
| **[DynamoDB (custom)](custom.md)** | One DynamoDB API request per operation ([not measured here](../performance.md#not-measured-here)) | Yes | Yes | Yes | No |
Expand All @@ -106,6 +107,8 @@ class BaseBackend(Protocol):
`TTLInspectableBackend` protocol): supported by **File**, **Redis**, and **CacheKit Cloud**.
**Memcached** supports `refresh_ttl` (via `touch`) directly but not `get_ttl`, so
`refresh_ttl_on_get` does not apply to it (see [Memcached](memcached.md#ttl-inspection--refresh)).
**Google Cloud Storage** supports neither: an object cannot be edited in place
(see [Google Cloud Storage](gcs.md#limitations)).

**Cross-process whole-function invalidation** (a server-side key registry, via the
`KeyTrackableBackend` protocol): supported only by the tenant-scoped **Redis** backend that env
Expand Down Expand Up @@ -134,6 +137,11 @@ calling process knows (see [Whole-Function Invalidation](../features/l1-invalida
- Existing Memcached infrastructure you want to reuse
- Read-heavy workloads where a network round trip on each L1 miss is acceptable ([not measured here](../performance.md#not-measured-here))

**Use [GCSBackend](gcs.md) when**:
- The workload runs on Cloud Run, Cloud Functions or batch jobs, with no Redis and no disk that survives a run
- The cached call is expensive and its result is worth keeping for hours or days
- A round trip to GCS on each L1 miss is acceptable ([not measured here](../performance.md#not-measured-here))

**Use [CacheKit Cloud](cachekitio.md) (`CachekitIOBackend`) when** *(closed beta: sign-up is by waitlist at [dash.cachekit.io](https://dash.cachekit.io))*:
- You want managed, zero-ops distributed caching
- Multi-region caching without operating Redis
Expand Down Expand Up @@ -220,7 +228,7 @@ it builds its own `CachekitIOBackend` and never consults `set_default_backend()`

If no explicit backend and no module-level default, `DefaultBackendProvider`
picks a backend at the function's first call from the one environment selector that is
set. The four prefixed selectors are mutually exclusive, with no precedence between them:
set. The five prefixed selectors are mutually exclusive, with no precedence between them:
set exactly one.

| Environment variable | Backend |
Expand All @@ -229,6 +237,7 @@ set exactly one.
| `CACHEKIT_REDIS_URL` | Redis (tenant-scoped, keys prefixed `t:{tenant}:`) |
| `CACHEKIT_MEMCACHED_SERVERS`| `MemcachedBackend` |
| `CACHEKIT_FILE_CACHE_DIR` | `FileBackend` |
| `CACHEKIT_GCS_BUCKET` | `GCSBackend` |
| none of the above: `REDIS_URL` | Redis, as above |
| nothing set at all | plaintext, non-interop decorators: [L1-only](#4-nothing-configured-l1-only), no backend; secure and `encryption=True` decorators: Redis at `redis://localhost:6379`, tenant-scoped as above; `interop=` decorators: the same Redis, which interop refuses (see below) |

Expand All @@ -237,7 +246,7 @@ set exactly one.
`backend=RedisBackend()` instead ([Interop Mode](../features/interop-mode.md)). A
`CachekitIOBackend` from `CACHEKIT_API_KEY` prefixes nothing and serves interop as resolved.

Setting more than one of the four `CACHEKIT_*` selectors is ambiguous and raises
Setting more than one of the five `CACHEKIT_*` selectors is ambiguous and raises
`ConfigurationError` at first call. The decorator catches it, logs a WARNING on
the `cachekit.decorators.orchestrator` logger, and runs the function uncached:

Expand Down Expand Up @@ -415,6 +424,7 @@ first call (and runs uncached if nothing listens there): give it `backend=RedisB
| **HTTP API** | One HTTP request per operation ([not measured here](../performance.md#not-measured-here)) | Custom cloud services | Network dependent |
| **DynamoDB** | One DynamoDB API request per operation ([not measured here](../performance.md#not-measured-here)) | Serverless, low-traffic | High availability |
| **Memcached** | One network round trip per operation ([not measured here](../performance.md#not-measured-here)) | Alternative to Redis | No persistence |
| **Google Cloud Storage** | One HTTPS request to GCS per ordinary operation ([request counts](gcs.md#requests-per-operation); [not measured here](../performance.md#not-measured-here)) | Expensive results kept across runs, no server | No locking; expiry checked on read |

---

Expand All @@ -423,6 +433,7 @@ first call (and runs uncached if nothing listens there): give it `backend=RedisB
- [Redis Backend](redis.md) — Production-grade, shared cache
- [File Backend](file.md) — Local disk, single-process, no infrastructure
- [Memcached Backend](memcached.md) — High-throughput, volatile, multi-process
- [Google Cloud Storage Backend](gcs.md) — Durable, one object per entry, no server
- [CacheKit Cloud Backend](cachekitio.md) — Managed, zero-ops, zero-knowledge
- [Custom Backends](custom.md) — HTTP, DynamoDB, and your own implementations

Expand Down
Loading
Loading