perf: cut per-event overhead on the state/event hot path (−28% CPU/event, +20% throughput)
Summary
Second pass over the backend event loop (write-up with method and profiles: https://claude.ai/code/artifact/8d136694-b64f-487c-9de9-30b350d03778, section "Event loop, second pass"). The framework's cost per trivial event has not moved since the August audit and still has the same shape: attribute access and asyncio plumbing. Five small, independent changes, each measured alone and together:
| µs of framework CPU per event (in-process, main @ 812bb475, py3.14) | main | this PR | |
|---|---|---|---|
serial, one session (count += 1) | 137 | 103 | −25% |
| pipelined, one session, 1,000 queued | 101 | 64 | −37% |
| 50 sessions interleaved | 68 | 48 | −29% |
| route match on a 1,000-page app, per event | 47 | 0.02 | cached |
Over the wire (socket.io client, granian dev backend, one worker, same session, interleaved runs):
| main | this PR | |
|---|---|---|
| 1 client, round trip p50 | 0.40 ms | 0.35 ms |
| 20 clients, p50 / p99 | 2.68 / 3.50 ms | 2.14 / 3.06 ms |
| 20 clients, throughput | 5,800 ev/s | 6,900 ev/s |
| 50 clients, p50 / p99 | 6.16 / 8.11 ms | 5.05 / 6.78 ms |
| 50 clients, throughput | 6,960 ev/s | 8,370 ev/s |
The changes
- Fast-path the framework's own state attributes (
state.py). Every read on a state goes through_get_attribute; the framework's bookkeeping does 146 such reads per event (21 ofdirty_vars, 8 each ofbase_vars/computed_vars, 7 ofparent_state, theget_fields/get_skip_vars/get_namemethods, ...) and a singleself.count += 1costs 43 reads inside__setattr__. Class-level names already bypassed var resolution; instance bookkeeping fields and framework methods now do too. Afterwards 6 reads per event take the slow path, all user vars. Serial 143 → 116 µs, pipelined 112 → 75 µs on its own. This is the attribute-access core of #6757 as a standalone change (that PR sits at the top of the #6743 chain, which is why it has not been reviewable on its own). - Eager-start foreground handler tasks on 3.12+ (
asyncio.Task(..., eager_start=True)): the handler runs and emits its delta before its first real suspension instead of after another loop iteration. Serial −9%, pipelined −21%. Background tasks keep the deferred start: eager start changes their interleaving with later events, whichtest_background_task_*caught. - Cache which computed vars have an interval per class, so the expiry check that runs four times per event only looks at those. ~3%. Looked up via
__class__, nottype(), because aStateProxyreports the wrapped class; regression test added (it fails ontype(self)). - Memoize route matching (
route.py): the matcher regex-matched the path against every page on every event. Boundedlru_cacheon the per-app matcher. async_handlers=Falseon the socket.io server: the handlers only parse and enqueue (or emit a pong), so the per-message task python-socketio spawns is pure overhead. Within noise on a small app; one fewer of the three task creations per event.
What is left (not in this PR)
After these, asyncio plumbing is the largest remaining share (~13 call_soon handles per event across python-socketio's receive loop, engine.io's send queue, the dispatcher queue and the delta emit); _mark_dirty_computed_vars still runs 4× per event (the dirty-propagation frontier in #6743 is the right fix); on_event rebuilds the decoded header dict per message (#6744); uuid4 per event and stdlib json.dumps on the wire (#6162).
Review round (e86220d9)
_reflex_internal_linksis a backend var stored in_backend_vars; the fast path returned the class default and the linked-state integration tests failed with aTypeError. Removed, and the set's comment now states the invariants (nothing from_backend_vars, nothing parent-delegated).- A subclass that defines a fast-pathed name itself (var, backend var, event handler, or a marked method override, which
setattr(cls, name, handler)replaces on the class) drops it from its own_fast_attr_namesin__init_subclass__, so the full lookup still applies there._check_overridden_methodsalready rejects unmarked overrides. Test added; the per-class lookup costs ~2µs per event (numbers above are after it). - Eager start only when the loop has no custom task factory.
- Route cache keyed on
(path, frontend_path).
Tests
State, proxy, event-processor, app and route unit suites pass on the patched tree; full unit suite likewise except the pyi golden-file tests, which fail identically on main in the mixed worktree environment used here. Plus the live socket A/B above.
🤖 Generated with Claude Code