Skip to content

add orjson - #6116

Draft
benedikt-bartscher wants to merge 83 commits into
reflex-dev:mainfrom
benedikt-bartscher:try-orjson
Draft

benedikt-bartscher wants to merge 83 commits into
reflex-dev:mainfrom
benedikt-bartscher:try-orjson

Conversation

@benedikt-bartscher

@benedikt-bartscher benedikt-bartscher commented Feb 6, 2026 •

Copy link
Copy Markdown
Contributor

State updates over the websocket and generated frontend files are serialized with orjson when the new reflex[orjson] extra is installed; without it Reflex falls back to the stdlib json module. Output is byte-compatible between the two backends, and inbound socket integers beyond 64 bits still reach event handlers exactly.

Benchmarks

Event wire path — decode 3 incoming events, process them, serialize 3 deltas — measured with each revision's own socket codec (_sio_dumps / _sio_loads). Python 3.14.7, 500 rounds, 3 interleaved repetitions; medians, ±1–2% run to run.

small delta (~2 KB) large delta (~200 KB)
this branch + orjson 217.0 µs (−5.0%) 1234.3 µs (−28.0%, 1.39×)
this branch, no orjson 234.8 µs (+2.8%) 1811.5 µs (+5.7%)
main 228.4 µs 1714.1 µs

Outgoing encode in isolation (95.7 KB payload):

encode
this branch + orjson 104.4 µs (2.44×)
this branch, no orjson 284.0 µs (+11.3%)
main 255.2 µs

Without the extra, the fallback adds two scans of the serialized string on top of the stdlib dump — the sentinel-collision check and the isascii() UTF-8 guard — about +29 µs on 95.7 KB.

@codspeed

codspeed Bot commented Feb 6, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 9.12%

3 warnings

⚠️ 19 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

⚠️ 1 benchmark with a significant change ran on different hardware

Its base and head results were measured on machines with a different CPU, core count or memory, so the change might not come from the code. Run base and head on the same runner type.

Learn more about Macro Runners

See affected benchmarks

⚠️ 1 benchmark with a significant change ran in a different software environment

Its base and head results were measured with a different OS or toolchain, such as compiler, runtime or library versions, so the change might come from this difference rather than from the code. Open the benchmark to see what changed.

See affected benchmarks

❌ 1 regressed benchmark
✅ 145 untouched benchmarks
🆕 2 new benchmarks
⏩ 8 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_route_matching[1000] 90 ms 99.1 ms -9.12%
🆕 test_process_event_wire[large_delta] N/A 31.5 ms N/A
🆕 test_process_event_wire[small_delta] N/A 3.1 ms N/A

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing benedikt-bartscher:try-orjson (0fdc0d3) with main (810bbd2)

Open in CodSpeed

Footnotes

  1. 8 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@benedikt-bartscher
benedikt-bartscher marked this pull request as ready for review February 7, 2026 13:38
@greptile-apps

greptile-apps Bot commented Feb 7, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The PR affects several JSON paths used by Reflex apps and generated frontend projects.

The custom-codec string issue still needs a complete fix before merging.

Findings

  1. P1 Custom codec strings change ▶

Summary

Adds optional orjson encoding for socket updates and generated frontend files, while keeping exact integer parsing for incoming events.

  • Generated frontend files and compiler output use optional orjson serialization.
  • Reflex sends websocket updates with a private, faster JSON codec.
  • Large integers stay exact when Reflex reads uploaded IDs and saved JSON.
  • Invalid package override values stay untouched.

Reviews (48) · Last reviewed commit: "Reuse one encoder for bare strings witho..." · Reviewed by Greptile

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

5 files reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Comment thread reflex/app.py Resolved
@adhami3310

Copy link
Copy Markdown
Member

the issue with orjson is that we lose NaN handling which is relevant for numpy, which is why we were using JSON5 as well

@benedikt-bartscher

benedikt-bartscher commented Feb 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Yeah, that's why i did not update it in all places

benedikt-bartscher and others added 3 commits February 24, 2026 21:41
…llback

Happy path uses native JSON.parse; the catch rewrites Python"s bare
Infinity/-Infinity/NaN tokens outside string literals before retrying,
so only payloads that actually contain specials pay the extra cost.
NaN has no JSON literal and becomes null (matches JSON.stringify).
…o null

Swap bare NaN for a sentinel string before JSON.parse and revive it back
to a real NaN so Python-side float(nan) round-trips to the frontend.
@benedikt-bartscher

Copy link
Copy Markdown
Contributor Author

related #6339

@benedikt-bartscher
benedikt-bartscher requested a review from a team as a code owner April 25, 2026 22:13
Apply orjson_dumps/orjson_loads helpers to the new reflex_base
package locations after upstream's restructuring.
@benedikt-bartscher
benedikt-bartscher marked this pull request as draft April 26, 2026 16:50
benedikt-bartscher and others added 3 commits September 18, 2026 15:46
Route main's new stateful-pages marker reader/writer through the orjson
helpers and keep both new event-processing benchmarks.
# Conflicts:
#	reflex/app.py
#	reflex/utils/frontend_skeleton.py
#	tests/benchmarks/test_event_processing.py
#	tests/units/test_prerequisites.py
#	tests/units/utils/test_exec.py
Upstream's new JSON emitters in the compile path now go through
orjson_dumps like the PR's other call sites: the stateSchema export in
app_root_template (templates.py no longer imports json) and the
useStateContext hook in VarData.from_state. The stateful pages marker
read keeps orjson_loads with upstream's ValueError comment.

The orjson test's datetime.timezone.utc becomes datetime.UTC, which ruff
now requires after upstream raised the minimum Python to 3.11.
@benedikt-bartscher

benedikt-bartscher commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor Author

#7448 seems like a better approach

@benedikt-bartscher
benedikt-bartscher marked this pull request as draft October 20, 2026 21:22
@FarhanAliRaza FarhanAliRaza added the enhancement Anything you want improved label Nov 12, 2026 — with ChatGPT Codex Connector
Comment thread tests/units/test_prerequisites.py Resolved
orjson emits an Enum's value without consulting default, so a serializer
registered for a non-Enum base of an Enum was bypassed only when the extra
was installed. Registration now also checks existing subclasses, and
resolving an Enum or UUID to a non-native serializer disables the orjson
paths for Enums created later.
The real socket path decodes with the stdlib, so decoding with orjson_loads
overstated the gain.
Comment on lines +12 to +16
if (v === NAN_SENTINEL) return NaN;
if (v === INF_SENTINEL) return Infinity;
if (v === NEG_INF_SENTINEL) return -Infinity;
if (v.startsWith(SENTINEL_ESCAPE_PREFIX))
return v.slice(SENTINEL_ESCAPE_PREFIX.length);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Custom codec strings change

Reflex keeps an explicitly supplied Socket.IO JSON codec, but parseJson now assumes that every sender escapes reserved strings. If a custom codec sends {"v":"__reflex_nan__"}, the browser receives NaN instead of the string. Strings starting with __reflex_esc__ lose that prefix. Custom codecs did not previously need Reflex-specific escaping. Preserve these strings unless the sender explicitly uses the new encoding.

orjson writes None, NaN and infinities all as null, so a delta with a
null takes a different socket codec path than one without. The wire
benchmark had no null at all and measured only the best case. Put a
None (small and large delta) or a NaN (large delta) in the first row's
balance; locally the large None delta takes 2.23 ms against 1.29 ms
without it.
The socket codec escaped user strings starting with __reflex_ and, when
one appeared, re-serialized the payload with NaN and infinities turned
into sentinel strings that a new reviver in parseJson restored. Main's
parseJson already decodes the bare NaN/Infinity tokens the stdlib emits,
deriving a placeholder no string in the payload can collide with, so the
sentinels only added cost: a byte scan of every orjson payload, a str
scan of every stdlib one, and includes("__reflex_") on every message in
the browser (11 us on an 18 KB table delta in node, next to a 53 us
JSON.parse). Restore main's json.js and stop installing the codec on a
custom socket.io server, whose only reason was the escaping.

100-row table delta with orjson: 26.1 -> 22.7 us; small delta: 0.85 ->
0.76 us. A test now runs the codec's output through parseJson and pins
that it decodes to what the stdlib encoding decodes to.
OPT_NON_STR_KEYS doubled orjson's own time on every payload (5.8 ->
10.7 us on a 100-row table delta). Without it orjson raises TypeError
on a non-str key and the existing stdlib fallback writes what main
writes; it also stops orjson from accepting Enum, date and UUID keys
that the stdlib, and so the default install, rejects.

100-row table delta: 22.7 -> 14.1 us; small delta: 0.76 -> 0.67 us.
orjson writes None, NaN and infinities all as null, so every payload
with a None (an unset Optional var) or a string containing "null" was
serialized a second time by the stdlib, which made it slower than main.
Now a null only triggers a walk for non-finite floats over the payload
and over what default returned for orjson (a StateUpdate, dataclasses,
models), so no custom object is serialized twice; only a payload that
really holds a NaN or an infinity goes to the stdlib, which keeps the
bare tokens main sends. default is a functools.partial rather than a
closure, whose annotations would be rebuilt on every call, and the null
scan uses a compiled regex, a third faster than `in` on bytes.

Per message, before -> after (main):
  small delta + None     2.02 -> 1.25 us (1.33)
  100-row table + None   65.5 -> 25.7 us (57.7)
  100-row table + NaN    65.3 -> 64.9 us (57.3)
  100-row table          14.1 -> 11.3 us (57.9)
  small delta            0.67 -> 0.75 us (1.35)
Without the orjson extra, the bare-string fast path called
json.dumps(obj, ensure_ascii=False), which builds a new encoder because
it is given an option. A module-level encoder produces the same output:
LiteralStringVar.create("hello") 930 -> 555 ns (main 570 ns).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement Anything you want improved perf Performance-improving changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants