Seguimiento de presencia y estado en línea
Cree un sistema de presencia en tiempo real que registre qué usuarios están en línea mediante conjuntos de Redis, TTL y heartbeats de Pub/Sub.
Seguimiento de presencia y estado en línea es una lección gratuita de Redis Caching & Messaging (Pub/Sub, Streams) en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Redis Caching & Messaging (Pub/Sub, Streams), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Redis Caching & Messaging (Pub/Sub, Streams) incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
What Is Presence?
Presence is the real-time indication of whether a user is online, away, or offline. Chat apps, collaborative editors, and games all rely on it. Redis is ideal because presence data is ephemeral and high-churn.
The Naive Approach
A first idea: store a flag per user. The problem is detecting when someone disconnects ungracefully (closed laptop, lost network). A stale flag would mark them online forever.
SET presence:user:42 onlineHeartbeats with TTL
The robust pattern uses heartbeats. The client refreshes a key with a short TTL every few seconds. If heartbeats stop, the key expires and the user is considered offline.
SET presence:user:42 1 EX 15
# client re-issues this every 10 secondsListing Online Users
To list everyone online, keep a set of active users and check membership, or scan presence keys. A sorted set keyed by last-seen timestamp is efficient.
ZADD online 1716900000 user:42
ZADD online 1716900005 user:7Sorted Set by Timestamp
Storing last-seen as the score lets you both list members and prune the stale ones in one query.
ZADD online <now> user:idon each heartbeatZREMRANGEBYSCORE online -inf <cutoff>removes timed-out users
ZADD online 1716900010 user:42
ZREMRANGEBYSCORE online -inf 1716899980Broadcasting Status Changes
When a user comes online or drops off, publish an event so other clients update their UI immediately.
PUBLISH presence.events "user:42 online"
SUBSCRIBE presence.eventsDetecting Going Offline
Combine the sorted set prune with keyspace expiry. When a presence key expires, a keyevent fires, and a worker publishes a went-offline event to subscribers.
CONFIG SET notify-keyspace-events Ex
SUBSCRIBE __keyevent@0__:expiredPer-Room Presence
In a chat app you often need presence per room. Use one set per room and add or remove the user as they join or leave.
SADD room:general:online user:42
SREM room:general:online user:42
SMEMBERS room:general:onlineMulti-Device Presence
A user may be online from several devices. Count active connections so the user only goes offline when the last device disconnects.
INCR conns:user:42
DECR conns:user:42
GET conns:user:42Putting It Together
A complete presence system: heartbeat TTL keys, a last-seen sorted set, connection counters for multi-device, and Pub/Sub events to push changes to clients in real time.
Tuning the Intervals
Choose a heartbeat interval shorter than the TTL (for example heartbeat every 10s, TTL 15s) so a single missed beat does not flap a user offline. Shorter intervals mean faster detection but more traffic.
Quick Check
Test your understanding of presence design.
Recap
You built a real-time presence system using heartbeat TTL keys, a last-seen sorted set with score-based pruning, per-room presence sets, multi-device connection counters, and Pub/Sub broadcasts for instant status updates. Tune heartbeat and TTL intervals to balance detection speed against traffic.
Aprende Redis Caching & Messaging (Pub/Sub, Streams) con un tutor de IA — gratis
Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.
- Cursos
- 12
- Lecciones
- 48
Preguntas frecuentes
¿La lección «Seguimiento de presencia y estado en línea» es gratis?
Sí — el texto completo de «Seguimiento de presencia y estado en línea» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Redis Caching & Messaging (Pub/Sub, Streams), actualiza a CoddyKit PRO. El curso de Redis Caching & Messaging (Pub/Sub, Streams) incluye 4 lecciones en total.
¿Qué aprenderé en «Seguimiento de presencia y estado en línea»?
Cree un sistema de presencia en tiempo real que registre qué usuarios están en línea mediante conjuntos de Redis, TTL y heartbeats de Pub/Sub. Practicas Redis Caching & Messaging (Pub/Sub, Streams) con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Redis Caching & Messaging (Pub/Sub, Streams)?
No se requiere experiencia previa. Redis Caching & Messaging (Pub/Sub, Streams) en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Seguimiento de presencia y estado en línea»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Redis Caching & Messaging (Pub/Sub, Streams)?
Sí. Cada lección de Redis Caching & Messaging (Pub/Sub, Streams) incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Suscripciones con coincidencia de patrones
- Diseño de un chat en tiempo real
- Arquitectura dirigida por eventos
- Seguimiento de presencia y estado en línea