Skip to main content

storage: improve the performance of cache key encoding

ID
80aad94
date
2026-11-11 07:12:07+00:00
author
Alex Chan <alex@alexwlchan.net>
parent
6f32f85
message
storage: improve the performance of cache key encoding

Profiling revealed that we spend a lot of time inside the JSON encoder,
so make some changes to improve performance.

* Don't run the JSON compatibility step (casting all keys to strings)
  unless a TypeError proves that it's necessary.
* For Pydantic models and dataclasses, cache a TypeAdapter rather than
  dumping to string.
* Pre-hash large strings as a direct argument, or as a value inside
  a dict argument.

This patch includes a benchmark for measuring the performance of key encoding
in different scenarios:

== before ==

0.00000171	str
0.00000173	int
0.00000310	pydantic
0.00000224	dataclass
0.00001221	long_str
0.00000207	nested_path_key

== after ==

0.00000141	str
0.00000138	int
0.00000274	pydantic
0.00000195	dataclass
0.00001160	long_str
0.00000398	nested_path_key
changed files
6 files, 138 additions, 21 deletions

Changed files

CHANGELOG.md (54 → 171)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 55c0d38..7b6f050 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,9 @@
 # CHANGELOG
 
+## v1.0.1 - 2026-11-11
+
+Tweak how function arguments are encoded as strings to improve performance in common cases.
+
 ## v1.0.0 - 2026-11-07
 
 Initial release.

pyproject.toml (1479 → 1520)

diff --git a/pyproject.toml b/pyproject.toml
index 0a7e2d6..b0d32bb 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -41,6 +41,7 @@ branch = true
 source = ["funkycache", "tests"]
 omit = [
     "tests/bench_sqlite_storage.py",
+    "tests/bench_key_encode_as_json.py",
 ]
 
 [tool.coverage.report]

src/funkycache/storage.py (10262 → 11057)

diff --git a/src/funkycache/storage.py b/src/funkycache/storage.py
index bb44bef..5bc224d 100644
--- a/src/funkycache/storage.py
+++ b/src/funkycache/storage.py
@@ -6,7 +6,7 @@ a collection of arguments to the return value.
 """
 
 from abc import ABC, abstractmethod
-from collections.abc import Mapping
+import dataclasses
 from datetime import datetime, timezone
 from functools import cache
 import json
@@ -15,7 +15,7 @@ import sqlite3
 from types import TracebackType
 from typing import Any, cast, Self
 
-from pydantic import TypeAdapter
+from pydantic import BaseModel, TypeAdapter
 import xxhash
 
 from .version import __version__
@@ -34,7 +34,7 @@ class CannotOverwriteValueException(ValueError):
     cached function, and cannot be fixed by retrying.
     """
 
-    def __init__(self, key: Mapping[str, Any]) -> None:
+    def __init__(self, key: dict[str, Any]) -> None:
         super().__init__(f"Key already exists: {key!r}")
 
 
@@ -45,7 +45,7 @@ class CacheStorage[V](ABC):
     """
 
     @abstractmethod
-    def set(self, key: Mapping[str, Any], value: V) -> None:
+    def set(self, key: dict[str, Any], value: V) -> None:
         """
         Save a key-value pair in the cache.
 
@@ -54,7 +54,7 @@ class CacheStorage[V](ABC):
         """
 
     @abstractmethod
-    def get(self, key: Mapping[str, Any]) -> V:
+    def get(self, key: dict[str, Any]) -> V:
         """
         Look up the value of a key in the cache.
 
@@ -73,7 +73,7 @@ class MemoryCacheStorage[V](CacheStorage[V]):
     def __init__(self):
         self._underlying: dict[str, V] = {}
 
-    def set(self, key: Mapping[str, Any], value: V) -> None:
+    def set(self, key: dict[str, Any], value: V) -> None:
         """
         Save a key-value pair in the cache.
         """
@@ -85,7 +85,7 @@ class MemoryCacheStorage[V](CacheStorage[V]):
         except KeyError:
             self._underlying[enc_key] = value
 
-    def get(self, key: Mapping[str, Any]) -> V:
+    def get(self, key: dict[str, Any]) -> V:
         """
         Look up the value of a key in the cache.
         """
@@ -105,7 +105,7 @@ class TypedCacheStorage[V](CacheStorage[V]):
         self.adapter = TypeAdapter(data_type)
 
     @abstractmethod
-    def _set_str(self, key: Mapping[str, Any], value: str) -> None:
+    def _set_str(self, key: dict[str, Any], value: str) -> None:
         """
         Save a key-value pair in the cache, where the value is a string.
 
@@ -113,7 +113,7 @@ class TypedCacheStorage[V](CacheStorage[V]):
         a different value.
         """
 
-    def set(self, key: Mapping[str, Any], value: V) -> None:
+    def set(self, key: dict[str, Any], value: V) -> None:
         """
         Save a key-value pair in the cache.
 
@@ -124,14 +124,14 @@ class TypedCacheStorage[V](CacheStorage[V]):
         self._set_str(key, json_str)
 
     @abstractmethod
-    def _get_str(self, key: Mapping[str, Any]) -> str:
+    def _get_str(self, key: dict[str, Any]) -> str:
         """
         Look up the string value of a key in the cache.
 
         Throws a KeyError if you look up a key which isn't in the cache.
         """
 
-    def get(self, key: Mapping[str, Any]) -> V:
+    def get(self, key: dict[str, Any]) -> V:
         """
         Look up the value of a key in the cache.
 
@@ -245,7 +245,7 @@ class SQLiteCacheStorage[V](TypedCacheStorage[V]):
         """
         self.close()
 
-    def _encode_key(self, key: Mapping[str, Any]) -> str:
+    def _encode_key(self, key: dict[str, Any]) -> str:
         """
         Encode a mapping as a string key.
 
@@ -256,7 +256,7 @@ class SQLiteCacheStorage[V](TypedCacheStorage[V]):
         json_key = _encode_key_as_json(key)
         return _hash(json_key)
 
-    def _set_str(self, key: Mapping[str, Any], value: str) -> None:
+    def _set_str(self, key: dict[str, Any], value: str) -> None:
         """
         Save a key-value pair in the cache, where the value is a string.
 
@@ -280,7 +280,7 @@ class SQLiteCacheStorage[V](TypedCacheStorage[V]):
             else:
                 raise
 
-    def _get_str(self, key: Mapping[str, Any]) -> str:
+    def _get_str(self, key: dict[str, Any]) -> str:
         """
         Look up the string value of a key in the cache.
 
@@ -311,7 +311,18 @@ def _make_json_compatible(value: Any) -> Any:
         return value
 
 
-def _encode_key_as_json(key: Mapping[str, Any]) -> str:
+@cache
+def _get_type_adapter(target_type: Any) -> TypeAdapter:
+    """
+    Return a TypeAdapter for the given Pydantic type.
+
+    The type adapter is cached, so schema generation only runs once
+    per unique type.
+    """
+    return TypeAdapter(target_type)
+
+
+def _encode_key_as_json(key: dict[str, Any]) -> str:
     """
     Encode a set of arguments to a Python function as a JSON string.
 
@@ -319,8 +330,24 @@ def _encode_key_as_json(key: Mapping[str, Any]) -> str:
     serialisation as JSON. It is possible for values of different types
     to collide.
     """
-    clean_key = _make_json_compatible(key)
-    return json.dumps(clean_key, sort_keys=True, default=str)
+    for name, val in key.items():
+        if isinstance(val, str) and len(val) > 2048:
+            key[name] = _hash(val)
+
+        elif isinstance(val, dict):
+            for k, v in val.items():
+                if isinstance(v, str) and len(v) > 2048:
+                    val[k] = _hash(v)
+
+        elif isinstance(val, BaseModel) or dataclasses.is_dataclass(val):
+            adapter = _get_type_adapter(type(val))
+            key[name] = adapter.dump_python(val, mode="json")
+
+    try:
+        return json.dumps(key, sort_keys=True, default=str)
+    except TypeError:
+        clean_key = _make_json_compatible(key)
+        return json.dumps(clean_key, sort_keys=True, default=str)
 
 
 @cache

src/funkycache/version.py (55 → 55)

diff --git a/src/funkycache/version.py b/src/funkycache/version.py
index bed9a72..76c0cbc 100644
--- a/src/funkycache/version.py
+++ b/src/funkycache/version.py
@@ -2,4 +2,4 @@
 The FunkyCache version.
 """
 
-__version__ = "1.0.0"
+__version__ = "1.0.1"

tests/bench_key_encode_as_json.py (0 → 634)

diff --git a/tests/bench_key_encode_as_json.py b/tests/bench_key_encode_as_json.py
new file mode 100644
index 0000000..eb39668
--- /dev/null
+++ b/tests/bench_key_encode_as_json.py
@@ -0,0 +1,24 @@
+"""
+Benchmarks for encoding cache keys as JSON.
+"""
+
+from collections import defaultdict
+import statistics
+import time
+
+from funkycache.storage import _encode_key_as_json
+from test_storage import KEY_ENCODING_TEST_CASES
+
+
+if __name__ == "__main__":
+    results = defaultdict(list)
+
+    for _ in range(5000):
+        for tc in KEY_ENCODING_TEST_CASES:
+            t0 = time.perf_counter()
+            _encode_key_as_json(tc.values[0])  # type: ignore
+            elapsed = time.perf_counter() - t0
+            results[tc.id].append(elapsed)
+
+    for name, data in results.items():
+        print(f"{statistics.mean(data):.8f}\t{name}")

tests/test_storage.py (7558 → 9069)

diff --git a/tests/test_storage.py b/tests/test_storage.py
index 6dc6027..931c237 100644
--- a/tests/test_storage.py
+++ b/tests/test_storage.py
@@ -3,20 +3,24 @@ Tests for backend storage implementations.
 """
 
 from abc import ABC, abstractmethod
-from collections.abc import Generator, Mapping
+from collections.abc import Generator
 from contextlib import closing, contextmanager
+from dataclasses import dataclass
 from pathlib import Path
 import sqlite3
 from typing import Any
 from unittest.mock import MagicMock
 
+from pydantic import BaseModel
 import pytest
+from _pytest.mark.structures import ParameterSet
 
 from funkycache.storage import (
     CacheStorage,
     MemoryCacheStorage,
     SQLiteCacheStorage,
     CannotOverwriteValueException,
+    _encode_key_as_json,
 )
 
 
@@ -50,11 +54,13 @@ class CacheStorageTestSuite(ABC):
             # A dict with Path keys isn't serialisable by json.dumps(…),
             # even if you pass default=str.
             pytest.param({Path("n"): "numbers"}, id="path_key"),
-            pytest.param([{Path("n"): "numbers"}], id="path_key_nested_in_list"),
+            pytest.param(
+                {"args": [{Path("n"): "numbers"}]}, id="path_key_nested_in_list"
+            ),
             pytest.param({"1": {Path("n"): "numbers"}}, id="path_key_nested_in_obj"),
         ],
     )
-    def test_cache(self, key: Mapping[str, Any], tmp_path: Path) -> None:
+    def test_cache(self, key: dict[str, Any], tmp_path: Path) -> None:
         """
         Test the basic properties of a cache.
         """
@@ -224,3 +230,58 @@ class TestSQLiteCacheStorage(CacheStorageTestSuite):
 
         with pytest.raises(sqlite3.OperationalError, match="no such column: key"):
             SQLiteCacheStorage[int](db_path, data_type="int")
+
+
+class Shape(BaseModel):
+    """A basic model that uses Pydantic."""
+
+    sides: int
+    colour: str
+
+
+@dataclass
+class Greeting:
+    """A basic model that uses dataclasses."""
+
+    name: str
+    message: str
+
+
+KEY_ENCODING_TEST_CASES: list[ParameterSet] = [
+    pytest.param({"n": "one"}, '{"n": "one"}', id="str"),
+    pytest.param({"n": 1}, '{"n": 1}', id="int"),
+    pytest.param(
+        {"n": Shape(sides=4, colour="red")},
+        '{"n": {"colour": "red", "sides": 4}}',
+        id="pydantic",
+    ),
+    pytest.param(
+        {"n": Greeting(name="alex", message="hello")},
+        '{"n": {"message": "hello", "name": "alex"}}',
+        id="dataclass",
+    ),
+    pytest.param(
+        {"long": "a" * 5000, "short": "a"},
+        '{"long": "xxh64:b2b67943d4803cd6", "short": "a"}',
+        id="long_str",
+    ),
+    pytest.param(
+        {"n": {"long": "a" * 5000, "short": "a"}},
+        '{"n": {"long": "xxh64:b2b67943d4803cd6", "short": "a"}}',
+        id="long_str",
+    ),
+    pytest.param(
+        {"n": {Path("1"): "one"}}, '{"n": {"1": "one"}}', id="nested_path_key"
+    ),
+]
+
+
+@pytest.mark.parametrize(
+    "key, json_key",
+    KEY_ENCODING_TEST_CASES,
+)
+def test_encode_key_as_json(key: dict[str, Any], json_key: str) -> None:
+    """
+    Tests for _encode_key_as_json.
+    """
+    assert _encode_key_as_json(key) == json_key