0Pricing
PostgreSQL Performance & Query Optimization · Lección

Escalado de lecturas con Hot Standby y balanceo de carga

Aprenda a desviar el tráfico de lectura a réplicas en espera mediante streaming, comprender la latencia de replicación y dirigir las consultas entre el nodo principal y las réplicas para escalar horizontalmente las lecturas.

Escalado de lecturas con Hot Standby y balanceo de carga es una lección gratuita de PostgreSQL Performance & Query Optimization 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 PostgreSQL Performance & Query Optimization, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de PostgreSQL Performance & Query Optimization incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Why Scale Reads?

A single primary can become a bottleneck when read-heavy traffic grows. By sending SELECTs to read replicas, you free the primary to handle writes and scale reads horizontally by adding more standbys.

Hot Standby Basics

A hot standby is a streaming replica that accepts read-only queries while it continuously applies changes received from the primary. It stays nearly in sync via the write-ahead log (WAL).

Enabling Read Queries on a Standby

On the standby, hot_standby must be on (the default in modern versions) so it answers queries instead of just replaying WAL silently.

SHOW hot_standby;

Detecting Recovery Mode

Your application can ask any node whether it is a read-only standby. A true result means do not send writes here.

SELECT pg_is_in_recovery();

Understanding Replication Lag

Standbys apply WAL slightly behind the primary, so a read may not see the very latest write. This gap is replication lag. For most read traffic it is harmless, but read-after-write flows need care.

Measuring Lag

On a standby, compare how far replay is behind the last received WAL position to estimate lag in time.

SELECT now() - pg_last_xact_replay_timestamp() AS replay_lag;

Routing in the Application

The simplest pattern keeps two connection pools: one to the primary for writes, one to replicas for reads. The app chooses based on the operation.

Read-After-Write Consistency

Right after a user writes data, reading from a lagging replica may show stale results. Mitigations:

  • Route that user's next reads to the primary briefly
  • Wait until the replica catches up to the write's WAL position

Load Balancing Across Replicas

A pooler or proxy such as PgBouncer, Pgpool-II, or HAProxy can distribute read connections across several standbys, spreading load and providing failover if one replica goes down.

Trade-offs and Limits

Read replicas are powerful but not magic:

  • They do not scale write throughput
  • Lag means eventual, not immediate, consistency on replicas
  • Long queries on a standby can conflict with WAL replay

Plan routing around these realities.

Watching Replication from the Primary

The primary exposes every connected standby in a stats view, including how far behind each one is. Watch this to catch a replica falling dangerously behind.

SELECT client_addr, state,
       replay_lag
FROM pg_stat_replication;

Quick Check

Test your read-scaling knowledge.

Recap

You learned read scaling:

  • Hot standbys serve read-only queries while replaying WAL
  • pg_is_in_recovery() identifies a standby
  • Replication lag means replicas can be slightly stale
  • Route writes to primary, reads to replicas; handle read-after-write
  • Use a proxy to load-balance and fail over across replicas

Preguntas frecuentes

¿La lección «Escalado de lecturas con Hot Standby y balanceo de carga» es gratis?

Sí — el texto completo de «Escalado de lecturas con Hot Standby y balanceo de carga» 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 PostgreSQL Performance & Query Optimization, actualiza a CoddyKit PRO. El curso de PostgreSQL Performance & Query Optimization incluye 4 lecciones en total.

¿Qué aprenderé en «Escalado de lecturas con Hot Standby y balanceo de carga»?

Aprenda a desviar el tráfico de lectura a réplicas en espera mediante streaming, comprender la latencia de replicación y dirigir las consultas entre el nodo principal y las réplicas para escalar hori… Practicas PostgreSQL Performance & Query Optimization 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 PostgreSQL Performance & Query Optimization?

No se requiere experiencia previa. PostgreSQL Performance & Query Optimization 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 «Escalado de lecturas con Hot Standby y balanceo de carga»?

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 PostgreSQL Performance & Query Optimization?

Sí. Cada lección de PostgreSQL Performance & Query Optimization 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

  1. Agrupación de conexiones con PgBouncer
  2. Estrategias de replicación (streaming, lógica)
  3. Sharding y PostgreSQL distribuido
  4. Escalado de lecturas con Hot Standby y balanceo de carga
← Volver a PostgreSQL Performance & Query Optimization