$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[March 15, 2024] MongoDB

MongoDB Read Preferences: Replica Sets

MongoDB Read Preferences: Replica Sets

────────────────────────────────────────────────────────

MongoDB Read Preferences: Replica Sets

Tip: Read Preference Modes

  • primary — default, always reads from primary
  • primaryPreferred — reads from primary, falls back to secondary
  • secondary — reads from secondary only
  • secondaryPreferred — reads from secondary, falls back to primary
  • nearest — reads from the closest member

Gotcha: Stale Reads from Secondaries

Secondaries may lag behind the primary. secondary reads can return stale data.

Tip: Set Read Preference in Laravel

'options' => [
    'readPreference' => 'secondaryPreferred',
],

Gotcha: Tag Sets for Regional Reads

'readPreferenceTags' => [['region' => 'us-east'], ['region' => 'eu-west']],

Directs reads to specific replica set members.

Tip: Read Concern

'readConcern' => ['level' => 'majority'],

Ensures reads are acknowledged by majority of replica set members.

Gotcha: Read Preference and Transactions

Transactions always read from the primary, regardless of read preference setting.

Tip: Embed or Reference? The 80/20 Rule

If you always access data together, embed it. If you access it independently, reference it. The 16MB document size limit is the hard boundary — stay under 1MB for most documents.

Tip: Index Your Query Patterns, Not All Fields

Creating indexes on every field wastes RAM. Use explain() to find in-memory sorts and collection scans. Index only what your actual queries filter on.

Gotcha: No Transaction Rollback for Index Builds

Building an index on a large collection can take hours. If it fails midway, the partial index is silently discarded. Plan index builds during maintenance windows.

Senior Insight

Read preferences in MongoDB determine whether queries go to the primary or a secondary replica. I've used readPreference: secondaryPreferred for reporting queries to offload the primary. But there's a risk: reading from a secondary returns eventually-consistent data, which may lag behind the primary. I've seen reporting dashboards show stale data because the secondary was lagging by seconds. Use primaryPreferred for reads that need current data and secondaryPreferred for tolerance of stale data.

Source: MongoDB Developer Center (https://www.mongodb.com/developer/), MongoDB Engineering Blog (https://www.mongodb.com/blog/channel/engineering-blog), Studio 3T Blog (https://studio3t.com/blog/)

────────────────────────────────────────────────────────
<-- back to posts