:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(db): decode JSONField values with orjson (#66710)
Julian Bez04fae36680a0
diff --git a/posthog/apps.py b/posthog/apps.pyindex dc5216b79913..7a1ce2792c57 100644--- a/posthog/apps.py+++ b/posthog/apps.py@@ -26,6 +26,12 @@ class PostHogConfig(AppConfig):verbose_name = "PostHog"def ready(self):+ # Route all JSONField (jsonb) decode through orjson before any query runs.+ if settings.JSONFIELD_ORJSON_DECODE:+ from posthog.helpers.orjson_jsonfield import apply as apply_orjson_jsonfield # noqa: PLC0415++ apply_orjson_jsonfield()+import posthog.storage.team_access_cache_signal_handlers # noqa: F401from posthog.storage.gateway_credential_signal_handlers import (connect_signal_handlers as connect_gateway_credential_signal_handlers,diff --git a/posthog/helpers/orjson_jsonfield.py b/posthog/helpers/orjson_jsonfield.pynew file mode 100644index 000000000000..2cfb218d54e1--- /dev/null+++ b/posthog/helpers/orjson_jsonfield.py@@ -0,0 +1,64 @@+"""Decode Django ``JSONField`` values with orjson instead of the stdlib ``json`` module.++Postgres returns ``jsonb`` as raw text — Django registers a no-op psycopg loader+(``register_default_jsonb(..., loads=lambda x: x)``) so it can apply ``JSONField.decoder``+itself. Every jsonb read therefore parses in Python via ``JSONField.from_db_value``: scalar+columns once, and ``ArrayField(JSONField)`` once per element (psycopg splits the array in C,+each element still raw text). orjson parses that text ~2.5-3.6x faster than stdlib ``json``,+so swapping the parser at this one method claws back CPU across every model and product with+no schema, query, or per-field changes. Applied once from ``PostHogConfig.ready()``, gated by+``settings.JSONFIELD_ORJSON_DECODE`` (default on) so it can be disabled via env given the+process-wide blast radius.++Caveats:+- Subclasses that override ``from_db_value`` (e.g. ``EncryptedJSONField``) keep their own+ decode — MRO means this base-class patch never reaches them, which is intentional.+- orjson decodes integers outside the 64-bit range to a float (lossy) with no exception, unlike+ stdlib's arbitrary-precision int. jsonb config/filter/query data doesn't carry such values+ (epoch-ns and bigint IDs are in range); disable the setting if a column needs exact ints+ beyond ``2**64``.+"""++import json++from django.db.models.fields.json import JSONField++import orjson++_patched = False+++def _orjson_from_db_value(self, value, expression, connection):+ if value is None:+ return value+ # A non-text value means the driver/backend already produced a native Python type+ # (KeyTransform on a scalar, SQLite, or a driver that deserializes jsonb itself —+ # Django #36371). Hand it back as-is rather than trying to parse it again.+ if not isinstance(value, (str, bytes, bytearray)):+ return value+ # orjson can't accept a custom json.JSONDecoder, so honor that field opt-out with stdlib.+ if self.decoder is not None:+ try:+ return json.loads(value, cls=self.decoder)+ except json.JSONDecodeError:+ return value+ try:+ return orjson.loads(value)+ except orjson.JSONDecodeError:+ # orjson is stricter than stdlib on some valid JSON; fall back so we never decode+ # less than Django would. Only return raw text if stdlib also can't parse it.+ try:+ return json.loads(value)+ except json.JSONDecodeError:+ return value+++def apply() -> None:+ """Route JSONField decode through orjson. Idempotent; safe to call more than once."""+ global _patched+ if _patched:+ return+ # setattr (not direct assignment) keeps mypy/ty from flagging the method swap;+ # B010 would "fix" it back to a direct assignment, which reintroduces that error.+ setattr(JSONField, "from_db_value", _orjson_from_db_value) # noqa: B010+ _patched = Truediff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.pyindex 96d62d6ff05c..94e009ac8b6c 100644--- a/posthog/settings/base_variables.py+++ b/posthog/settings/base_variables.py@@ -26,6 +26,9 @@ TEST = get_from_env(# `dbshell` there is no Python REPL (it execs the DB client), so nothing to restore.IS_INTERACTIVE_SHELL: bool = len(sys.argv) > 1 and sys.argv[1] in ("shell", "dbshell")COMMAND_EXEC_AUDIT_ENABLED: bool = get_from_env("COMMAND_EXEC_AUDIT_ENABLED", not TEST, type_cast=str_to_bool)+# Kill-switch for routing JSONField (jsonb) decode through orjson (see posthog/helpers/orjson_jsonfield.py).+# Process-wide once applied in ready(), so keep it disable-able via env without a code revert.+JSONFIELD_ORJSON_DECODE: bool = get_from_env("JSONFIELD_ORJSON_DECODE", True, type_cast=str_to_bool)STATIC_COLLECTION = get_from_env("STATIC_COLLECTION", False, type_cast=str_to_bool)DEMO: bool = get_from_env("DEMO", False, type_cast=str_to_bool) # Whether this is a managed demo environmentCLOUD_DEPLOYMENT: str | None = get_from_env(diff --git a/posthog/test/test_orjson_jsonfield.py b/posthog/test/test_orjson_jsonfield.pynew file mode 100644index 000000000000..de17fc56e5b4--- /dev/null+++ b/posthog/test/test_orjson_jsonfield.py@@ -0,0 +1,75 @@+import json+from typing import Any, cast++from django.db.models import JSONField+from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.helpers.orjson_jsonfield import _orjson_from_db_value++# from_db_value ignores expression/connection in our patch; typed None keeps mypy happy.+_NULL = cast(Any, None)+++class TestOrjsonJSONFieldDecode(SimpleTestCase):+ @parameterized.expand(+ [+ ("dict", {"key": "value", "count": 1}),+ ("nested", {"a": [1, 2, {"b": True}], "c": None}),+ ("list", [{"key": "x"}, {"key": "y"}]),+ ("unicode", {"name": "café ☕ 日本語"}),+ ("int64", {"id": 9007199254740993}),+ ("float", {"ratio": 1.5}),+ ("empty", {}),+ ("entitlements", [{"key": "sso", "name": "SSO", "limit": None}, {"key": "rbac"}]),+ ]+ )+ def test_decodes_identically_to_stdlib(self, _name: str, payload: Any) -> None:+ decoded = JSONField().from_db_value(json.dumps(payload), _NULL, _NULL)+ self.assertEqual(decoded, payload)+ self.assertEqual(decoded, json.loads(json.dumps(payload)))++ def test_patch_is_installed(self) -> None:+ # The other cases pass under unpatched Django too; this is what proves apply() ran.+ self.assertIs(JSONField.from_db_value, _orjson_from_db_value)++ def test_decodes_bytes_input(self) -> None:+ # psycopg can hand back bytes; Django types value as str|None, so cast for the type checker.+ self.assertEqual(JSONField().from_db_value(cast(Any, b'{"a": 1}'), _NULL, _NULL), {"a": 1})+ self.assertEqual(JSONField().from_db_value(cast(Any, bytearray(b'{"a": 1}')), _NULL, _NULL), {"a": 1})++ def test_none_passes_through(self) -> None:+ self.assertIsNone(JSONField().from_db_value(None, _NULL, _NULL))++ @parameterized.expand([("dict", {"a": 1}), ("list", [1, 2]), ("int", 5), ("bool", True)])+ def test_already_decoded_value_passes_through(self, _name: str, value: Any) -> None:+ # Django #36371: a backend/driver that returns a native type must not be re-parsed.+ self.assertEqual(JSONField().from_db_value(value, _NULL, _NULL), value)++ def test_invalid_json_returns_raw(self) -> None:+ self.assertEqual(JSONField().from_db_value("not json", _NULL, _NULL), "not json")++ def test_integers_within_64bit_stay_exact(self) -> None:+ for n in (9223372036854775807, 18446744073709551615): # i64 max, u64 max+ self.assertEqual(JSONField().from_db_value(json.dumps({"n": n}), _NULL, _NULL), {"n": n})++ def test_integer_beyond_64bit_is_lossy_float(self) -> None:+ # Documents orjson's known limit (see module docstring): integers >= 2**64 decode to a+ # lossy float, not an exact int. Gated by JSONFIELD_ORJSON_DECODE; not present in jsonb config data.+ decoded = JSONField().from_db_value(json.dumps({"n": 2**64}), _NULL, _NULL)+ self.assertIsInstance(decoded["n"], float)++ def test_custom_decoder_still_uses_stdlib(self) -> None:+ # orjson can't accept a json.JSONDecoder, so a field with decoder= must fall back to stdlib.+ class TaggingDecoder(json.JSONDecoder):+ def __init__(self, **kwargs: Any) -> None:+ super().__init__(object_hook=self._hook, **kwargs)++ @staticmethod+ def _hook(obj: dict) -> dict:+ obj["_decoded_by"] = "custom"+ return obj++ decoded = JSONField(decoder=TaggingDecoder).from_db_value('{"a": 1}', _NULL, _NULL)+ self.assertEqual(decoded, {"a": 1, "_decoded_by": "custom"})