Skip to content
|By Muhammad Wilayat Shah|2 views • 2 unique IPs

PostgreSQL Read Replicas vs Database Sharding

Compare postgresql read replicas and sharding for read-heavy apps: replication lag, Laravel sticky reads and when sharding is actually justified.

ShareLinkedInX
PostgreSQL Read Replicas vs Database Sharding

When dashboards scream that the database is slow and ninety-five percent of statements are reads, "shard immediately" is usually the wrong move. PostgreSQL read replicas scale SELECT traffic by replaying WAL onto standbys, while sharding splits row ownership across primaries. This article compares them, explains replication lag, shows Laravel read/write hosts and outlines when sharding finally becomes rational.

Classify the Workload First

Reads fetch; writes mutate. Many "scale" emergencies are missing indexes or chatty ORMs. Run EXPLAIN ANALYZE on slow queries before buying topology. If the pain is truly read throughput on healthy SQL, replicas are the natural lever.

How Read Replicas Work

The primary accepts writes. Standbys receive WAL and serve read-only queries. Applications route eligible SELECTs to replicas and keep INSERT/UPDATE/DELETE on the primary. You multiply read capacity; you do not multiply single-primary write capacity.

Replication Lag and Read-Your-Writes

Asynchronous replicas can briefly return pre-update data. After a profile save, a follow-up read on a lagging standby shows the old phone number. Mitigations include reading the primary after writes, Laravel's request-scoped sticky option, short primary-read windows per user and lag-aware routing. Sticky does not magically span separate HTTP requests.

Code
// config/database.php (simplified)
'pgsql' => [
  'read' => ['host' => ['replica1', 'replica2']],
  'write' => ['host' => 'primary'],
  'sticky' => true,
],

Sharding Solves a Different Problem

Shards hold different subsets of data. That spreads storage and write load but complicates cross-shard joins, transactions and rebalancing. Choose a stable shard key and accept routing logic in the application or a proxy. Large platforms often shard and then attach replicas to each shard.

Side-by-Side

  • Replicas: scale reads, manage lag and failover candidates.
  • Sharding: scale data size and writes, manage routing complexity.
  • Neither replaces indexing, pooling or caching.

Practical Architecture

Primary for bookings and payments; replicas for search and reporting that tolerate controlled lag; Redis for stable hot reads; PgBouncer for connection pooling (guide). Never decide final inventory on a lagged replica at checkout. Watch session counts with too many connections.

Code
-- primary
SELECT application_name, state, replay_lag FROM pg_stat_replication;
-- replica
SELECT pg_is_in_recovery();
PostgreSQL read replicas vs sharding checklist
Fix SQL, add replicas, handle lag—shard only with evidence.

When Sharding Is Justified

After indexes, pooling, cache, replicas and partitioning still cannot meet write throughput or storage needs—and the team can operate distributed data. Sharding to look advanced in an interview without that evidence is a red flag.

FAQs

95% reads—should you shard?

Usually no. Optimize queries, add replicas, manage lag. Shard for write or size ceilings.

Do replicas replace PgBouncer?

No. Replicas add read servers; PgBouncer manages connection multiplicity.

Is synchronous replication mandatory?

Only when durability and visibility requirements justify the write-latency cost.

Operational Checklist Teams Actually Use

Write the runbook while the system is healthy. Name the dashboards that show latency, error rate, saturation and dependency health. Record which alerts page which engineers, and which feature flags disable expensive paths when a dependency falters. After every incident, add one concrete prevention item—an index, a probe, a lock, a backoff—and assign an owner with a date.

Load-test the golden journeys before campaigns: authentication, search, write paths and payment or booking confirmation. Synthetic traffic that only hits health endpoints will not reveal stampede, lock or migration bugs. Prefer realistic payloads and concurrency patterns captured from production anonymized traces.

Keep environment parity honest. Staging should exercise the same session store, cache backend, queue driver and migration path as production, even at smaller scale. Many "works on my machine" deploy failures are really "staging used the file session driver." Align configuration templates and fail CI when critical env keys diverge.

Security and reliability meet in the same releases. Rotate credentials when workers or containers may have logged them, limit debug endpoints and ensure readiness checks never expose secrets. Customer-facing promises—fast pages, safe checkout, always-on apps—depend on these unglamorous controls as much as on clever algorithms.

How This Fits Customer-Facing Messaging

Engineering topics translate cleanly into buyer language when you stay specific. Faster page loads come from caching and query work. Fewer failed checkouts come from idempotent retries and primary reads after writes. Continuous releases without maintenance banners come from zero-downtime deployment discipline. Instant "username taken" feedback comes from probabilistic filters backed by real constraints. Use those outcomes in titles and meta descriptions so searchers who care about reliability find the technical depth behind the promise.

Operational Checklist Teams Actually Use

Write the runbook while the system is healthy. Name the dashboards that show latency, error rate, saturation and dependency health. Record which alerts page which engineers, and which feature flags disable expensive paths when a dependency falters. After every incident, add one concrete prevention item—an index, a probe, a lock, a backoff—and assign an owner with a date.

Load-test the golden journeys before campaigns: authentication, search, write paths and payment or booking confirmation. Synthetic traffic that only hits health endpoints will not reveal stampede, lock or migration bugs. Prefer realistic payloads and concurrency patterns captured from production anonymized traces.

Keep environment parity honest. Staging should exercise the same session store, cache backend, queue driver and migration path as production, even at smaller scale. Many "works on my machine" deploy failures are really "staging used the file session driver." Align configuration templates and fail CI when critical env keys diverge.

Security and reliability meet in the same releases. Rotate credentials when workers or containers may have logged them, limit debug endpoints and ensure readiness checks never expose secrets. Customer-facing promises—fast pages, safe checkout, always-on apps—depend on these unglamorous controls as much as on clever algorithms.

How This Fits Customer-Facing Messaging

Engineering topics translate cleanly into buyer language when you stay specific. Faster page loads come from caching and query work. Fewer failed checkouts come from idempotent retries and primary reads after writes. Continuous releases without maintenance banners come from zero-downtime deployment discipline. Instant "username taken" feedback comes from probabilistic filters backed by real constraints. Use those outcomes in titles and meta descriptions so searchers who care about reliability find the technical depth behind the promise.

Operational Checklist Teams Actually Use

Write the runbook while the system is healthy. Name the dashboards that show latency, error rate, saturation and dependency health. Record which alerts page which engineers, and which feature flags disable expensive paths when a dependency falters. After every incident, add one concrete prevention item—an index, a probe, a lock, a backoff—and assign an owner with a date.

Load-test the golden journeys before campaigns: authentication, search, write paths and payment or booking confirmation. Synthetic traffic that only hits health endpoints will not reveal stampede, lock or migration bugs. Prefer realistic payloads and concurrency patterns captured from production anonymized traces.

Keep environment parity honest. Staging should exercise the same session store, cache backend, queue driver and migration path as production, even at smaller scale. Many "works on my machine" deploy failures are really "staging used the file session driver." Align configuration templates and fail CI when critical env keys diverge.

Security and reliability meet in the same releases. Rotate credentials when workers or containers may have logged them, limit debug endpoints and ensure readiness checks never expose secrets. Customer-facing promises—fast pages, safe checkout, always-on apps—depend on these unglamorous controls as much as on clever algorithms.

How This Fits Customer-Facing Messaging

Engineering topics translate cleanly into buyer language when you stay specific. Faster page loads come from caching and query work. Fewer failed checkouts come from idempotent retries and primary reads after writes. Continuous releases without maintenance banners come from zero-downtime deployment discipline. Instant "username taken" feedback comes from probabilistic filters backed by real constraints. Use those outcomes in titles and meta descriptions so searchers who care about reliability find the technical depth behind the promise.

ShareLinkedInX
Back to blog

Keep reading

Newsletter

Occasional notes on Laravel, React, and shipping production systems — no spam.

Comments

Join the discussion. Replies load on demand, up to 5 levels.

0 threads

Loading editor…
Reviewed before publishing

No comments yet

Be the first to start the conversation.