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

Resiliência de conexões no cliente

Faça os clientes sobreviverem a failovers e mudanças de topologia com novas tentativas, timeouts, pools de conexões e tratamento de redirecionamentos compatível com clusters.

Aula 4 de 413 etapas

Resiliência de conexões no cliente é 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.

HA Is a Two-Sided Deal

You configured replication, Sentinel, and Cluster on the server. But high availability only works if the client reacts correctly to failovers, moved slots, and dropped connections. This lesson covers client-side resilience.

Connection Pools

Opening a TCP connection per command is slow. A connection pool reuses a set of connections across requests, bounded by a maximum size to protect the server.

pool = redis.ConnectionPool(max_connections=50)
client = redis.Redis(connection_pool=pool)

Timeouts Matter

Without timeouts, a stalled node can hang your whole app. Set both a connect timeout and a socket/command timeout so failed nodes fail fast.

client = redis.Redis(socket_connect_timeout=2, socket_timeout=2)

Retries with Backoff

Transient errors (a brief failover) should be retried, ideally with exponential backoff to avoid hammering a recovering node.

for attempt in range(3):
    try:
        return client.get('key')
    except ConnectionError:
        time.sleep(2 ** attempt)

Sentinel-Aware Clients

With Sentinel, the client asks Sentinel for the current master address rather than hardcoding it. After a failover, the client re-queries and reconnects to the new master.

from redis.sentinel import Sentinel
s = Sentinel([('s1', 26379)], socket_timeout=0.5)
master = s.master_for('mymaster')

Reading from Replicas

For read-heavy workloads, route reads to replicas to offload the master. Be aware replicas may be slightly behind (eventual consistency).

replica = s.slave_for('mymaster')
value = replica.get('key')

Handling MOVED in Cluster

In a cluster, a key may live on a different node. The server replies MOVED with the correct node. A cluster-aware client follows the redirect and updates its slot map.

# (error) MOVED 3999 127.0.0.1:7002

Handling ASK Redirects

During slot migration the server may reply ASK, a one-time redirect. The client should send ASKING then the command to the target node, without permanently updating its slot map.

# (error) ASK 3999 127.0.0.1:7003
# client sends ASKING then retries on 7003

Refreshing the Topology

Cluster-aware clients periodically refresh their slot-to-node map and on receiving redirects, so they keep routing to the right node as the cluster reshards.

CLUSTER SLOTS
CLUSTER SHARDS

Idempotency and Retries

Retrying writes is risky if the first attempt actually succeeded. Prefer idempotent operations (SET, INCR with a dedup key) so a retry cannot double-apply an effect.

Putting It Together

Resilient clients combine pools, timeouts, backoff retries, Sentinel/cluster awareness, replica reads where safe, and idempotent writes. Together they turn server-side HA into end-to-end availability.

Quick Check

Test your understanding of client resilience.

Recap

You learned client-side resilience: connection pools, connect and command timeouts, exponential backoff retries, Sentinel-aware master discovery, replica reads, and handling MOVED/ASK redirections in a cluster. Combine these with idempotent writes for true end-to-end availability.

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 “Resiliência de conexões no cliente” é grátis?

Sim — o texto completo de “Resiliência de conexões no cliente” é 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 “Resiliência de conexões no cliente”?

Faça os clientes sobreviverem a failovers e mudanças de topologia com novas tentativas, timeouts, pools de conexões e tratamento de redirecionamentos compatível com clusters. 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 “Resiliência de conexões no cliente”?

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. Replicação do Redis para redundância
  2. Redis Sentinel para alta disponibilidade
  3. Redis Cluster para fragmentação
  4. Resiliência de conexões no cliente
← Voltar para Redis Caching & Messaging (Pub/Sub, Streams)