Redis state lock: a waiter on another instance can be passed over by an instance that modifies the same token back to back

Abierto
#7,805 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
25/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
python, redis

Línea de trabajo

Read _RELEASE_LOCK_SCRIPT and _wait_lock in reflex/istate/manager/redis.py, then run the real-Redis reproduction test_remote_waiter_not_passed_over_by_back_to_back_modifies in tests/units/istate/manager/test_redis.py using the command in the issue. Explore a contended-path hand-off protocol that preserves the listed lock guarantees and avoids added uncontended cost. Done when the waiter gets the lock before half the loop completes deterministically, the benchmark does not regress, and mixed-version safety is addressed.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

release-train
Summary

With StateManagerRedis, consider an instance (worker) that runs modify_state on one token in a tight loop, with no other waiter for that token on the same instance. That instance can keep retaking the token's lock before a waiter on another instance hears that the lock was released. There is no correctness problem: mutual exclusion, fencing, leases and final state are all fine. The cost is tail latency for the other instance's request.

This changed in 0.11.0a1. #7534 replaced the release's GETDEL with a compare-and-delete EVAL script (_RELEASE_LOCK_SCRIPT in reflex/istate/manager/redis.py). Redis then writes the releasing client's reply before the keyspace notification to the other instances' subscriber. So the releaser's event loop resumes first, and its next SET NX wins (the "instaque" fast path in _wait_lock). With GETDEL, the notification happened to be written first, and the waiter usually got in.

Measured impact (0.11.0a1 vs 0.10.1)
  • Real prod app (2 granian workers, real Redis 7.0, one worker running a 3000-iteration modify_state loop on a token): the worst latency of other-worker requests for that token rose from 14–24 ms to 77–165 ms. Medians are unchanged, and final counts are always exact.
  • Two StateManagerRedis instances in one event loop, one doing 1000 back-to-back modifies: the remote waiter stalls 3.8–4.4 s, versus 0.01–0.04 s on 0.10.1. Oplock on or off, redis-py 7 or 8. This setup is the deterministic worst case; real multi-process deployments see the milder number above.
Reproduction

A regression test is on the closed-out branch fix/redis-lock-fair-handoff (#7801): test_remote_waiter_not_passed_over_by_back_to_back_modifies in tests/units/istate/manager/test_redis.py. It needs a real Redis and is skipped on the mock.

  • One manager loops modify_state 200 times on a token, holding the lock about 2 ms each time.
  • After 5 iterations, a second manager (via other_state_manager()) calls modify_state on the same token.
  • The test asserts the second manager gets in before half the loop has finished.
  • On main today, the loop finishes all 200/200 iterations first.

Run it with REDIS_URL=redis://localhost:6379 uv run pytest tests/units/istate/manager/test_redis.py -k passed_over.

Why #7801 was not merged

#7801 sent a PING ahead of the release EVAL in one pipeline, which brings back 0.10.1's reply order. It fixed the latency (77–165 ms → 11–25 ms), but it was rejected for two reasons:

  • CPU cost on every event. It adds about 10–20% client-side CPU to every uncontended modify_state. On real redis-py, one release goes from about 92 µs to about 168 µs median, and from 345 to 576 Python calls. CodSpeed showed test_modify_state[redis] 13% slower. Making every event pay for a contended edge case is the wrong trade-off.
  • Fragile. It relies on Redis's undocumented reply write order, which can differ with io-threads, proxies, Valkey, KeyDB or Dragonfly.
What a fix must satisfy
  • No added cost on the uncontended path. tests/benchmarks/test_state_manager.py::test_modify_state[redis] must not regress, and an uncontended lock/release pair must keep the same number of Redis round trips.
  • No reliance on reply or notification write order between different Redis clients.
  • Keep the existing guarantees: mutual exclusion, the _instance_id fencing and lease checks, the cancellation cleanup in the release path (shielded re-send), lock expiry, and oplock behaviour, including the <lock>_waiters set.
  • A waiter on another instance gets the lock within a bounded number of hand-offs while one instance retakes it in a loop. The test above, with the bound looped_before_waiter < loops / 2 or tighter, should pass deterministically on real Redis.
  • Mixed versions during a rolling deploy: instances running the new protocol and instances running 0.11.0 against the same Redis must not deadlock or lose mutual exclusion. If the new protocol cannot coexist safely, document that.

Possible directions, none validated:

  • a per-lock waiter queue or ticket in Redis, consulted only when a waiter has registered;
  • making the releaser yield (skip the fast path) when the <lock>_waiters set (oplock) or a new waiter marker shows a remote waiter, with that check done only on the contended path.
Non-goals
  • Changing the lock's correctness semantics or its key layout for the uncontended case.
  • Fairness between waiters on the same instance; local waiters are already queued in-process.
  • Adding sleeps or fixed delays to the release or acquire path. A 3 ms gap does remove the effect, but it adds latency everywhere.
  • Pipelining extra commands into every release (the #7801 approach).

Found during reflex 0.11.0a1 pre-release testing.

Lenguaje dominante
Python
Estrellas
29k
Forks
1.8k
Merge medio
3 d 5 h
PR fusionados (30 d)
182

Preparar el entorno

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de reflex-dev/reflex

Todos los issues de reflex-dev/reflex

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.