perf: cut per-event overhead on the state/event hot path (−28% CPU/event, +20% throughput)

Merged
AL
2mo ago
+245-14

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)mainthis PR
serial, one session (count += 1)137103−25%
pipelined, one session, 1,000 queued10164−37%
50 sessions interleaved6848−29%
route match on a 1,000-page app, per event470.02cached

Over the wire (socket.io client, granian dev backend, one worker, same session, interleaved runs):

mainthis PR
1 client, round trip p500.40 ms0.35 ms
20 clients, p50 / p992.68 / 3.50 ms2.14 / 3.06 ms
20 clients, throughput5,800 ev/s6,900 ev/s
50 clients, p50 / p996.16 / 8.11 ms5.05 / 6.78 ms
50 clients, throughput6,960 ev/s8,370 ev/s

The changes

  1. 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 of dirty_vars, 8 each of base_vars / computed_vars, 7 of parent_state, the get_fields / get_skip_vars / get_name methods, ...) and a single self.count += 1 costs 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).
  2. 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, which test_background_task_* caught.
  3. 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__, not type(), because a StateProxy reports the wrapped class; regression test added (it fails on type(self)).
  4. Memoize route matching (route.py): the matcher regex-matched the path against every page on every event. Bounded lru_cache on the per-app matcher.
  5. async_handlers=False on 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_links is a backend var stored in _backend_vars; the fast path returned the class default and the linked-state integration tests failed with a TypeError. 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_names in __init_subclass__, so the full lookup still applies there. _check_overridden_methods already 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