Repository navigation
Description
I had Opus 5 do a deep dive analysis on some redis state lock performance issues we are having and it reported that this issue in the reflex framework might be a contributing factor
Summary
StateManagerRedis.set_state re-validates the session Redis lock once per
substate in the in-memory tree, even when nothing is dirty and no key is
written. For a root-token persist over N state classes this is 2N Redis
round trips (GET + PTTL of the same lock key) that can be done once.
Evidence
Against a 35-class application state tree with opportunistic locking disabled
and nothing marked dirty:
| Token | Redis commands in set_state |
Writes (SET) |
|---|---|---|
root (rx.State) |
70 (35× GET + 35× PTTL) |
0 |
| typical leaf substate | 6 (3× GET + 3× PTTL) |
0 |
The recursion in reflex/istate/manager/redis.py set_state is:
- If
lock_idis set:await self.redis.get(self._lock_key(token))and compare. - If
lock_idis set and the key is not in_local_leases:await self.redis.pttl(...). asyncio.create_task(self.set_state(...))for everybase_state.substatesvalue.- Serialize/write only when
_get_was_touched(). awaitevery child task.
Steps 1–2 therefore run once per visited substate, always against the same
token.lock_key (session ident). Payload size and pickle cost are negligible;
lock-held wall time scales with Redis RTT × substate count.
Production lock-timing logs showed the same signature:
persist_ms hundreds of ms with redis_sets=0 / persist_bytes=0 while a
neighboring cycle wrote ~5–7 KB in ~2 ms — Redis latency alone does not explain
exit-phase cost when the command fan-out is this large under event-loop load.
Proposed fix (upstream)
Hold the lock check (and optional PTTL warning sample) once at the top of
a set_state fan-out, then recurse with a flag such as lock_checked=True /
skip_lock_check=True so children only persist touched nodes.
Alternatively, collect touched states in one walk and issue a single pipeline
of SETs after one lock verification.
Why it matters
Reflex uses one Redis lock per client session (StateToken.lock_key ==
ident). Background handlers that open many short async with state cycles
(auth helpers, project load resets) each pay a full set_state walk. Cutting
the redundant checks removes O(substates) Redis RTT from every lock exit path.
Activity
linear-code commentedon Aug 5, 2026
ENG-10864
Iyamokuma commentedon Aug 6, 2026
Hi! I'd like to work on this issue. Could you please assign it to me?