Redis Caching & Messaging (Pub/Sub, Streams) · Aula

Rastreamento de presença e status online

Crie um sistema de presença em tempo real que rastreie quais usuários estão online usando conjuntos do Redis, TTLs e sinais periódicos de Pub/Sub.

Aula 4 de 413 etapas

Rastreamento de presença e status online é uma aula grátis de Redis Caching & Messaging (Pub/Sub, Streams) no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Redis Caching & Messaging (Pub/Sub, Streams), e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Redis Caching & Messaging (Pub/Sub, Streams) inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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 online

Heartbeats 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 seconds

Listing 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:7

Sorted 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:id on each heartbeat
  • ZREMRANGEBYSCORE online -inf <cutoff> removes timed-out users
ZADD online 1716900010 user:42
ZREMRANGEBYSCORE online -inf 1716899980

Broadcasting 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.events

Detecting 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__:expired

Per-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:online

Multi-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:42

Putting 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.

Grátis para começar

Aprenda Redis Caching & Messaging (Pub/Sub, Streams) com um tutor de IA — grátis

Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.

Cursos
12
Aulas
48

Perguntas Frequentes

A aula “Rastreamento de presença e status online” é grátis?

Sim — o texto completo de “Rastreamento de presença e status online” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Redis Caching & Messaging (Pub/Sub, Streams), atualize para CoddyKit PRO. O curso de Redis Caching & Messaging (Pub/Sub, Streams) inclui 4 aulas no total.

O que vou aprender em “Rastreamento de presença e status online”?

Crie um sistema de presença em tempo real que rastreie quais usuários estão online usando conjuntos do Redis, TTLs e sinais periódicos de Pub/Sub. Você pratica Redis Caching & Messaging (Pub/Sub, Streams) com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Redis Caching & Messaging (Pub/Sub, Streams)?

Nenhuma experiência prévia é necessária. Redis Caching & Messaging (Pub/Sub, Streams) no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Rastreamento de presença e status online”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Redis Caching & Messaging (Pub/Sub, Streams)?

Sim. Cada aula de Redis Caching & Messaging (Pub/Sub, Streams) inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Assinaturas com correspondência de padrões
  2. Projeto de um bate-papo em tempo real
  3. Arquitetura orientada a eventos
  4. Rastreamento de presença e status online
← Voltar para Redis Caching & Messaging (Pub/Sub, Streams)