Chapter 11. Connecting to a Replica Set from Your Application

This chapter covers how applications interact with replica sets, including:

  • How connections and failovers work

  • Waiting for replication on writes

  • Routing reads to the correct member

Client-to-Replica-Set Connection Behavior

From an application’s point of view, a replica set behaves much like a standalone server. By default, client libraries will connect to the primary and route all traffic to it. Your application can perform reads and writes as though it were talking to a standalone server while your replica set quietly keeps hot standbys ready in the background.

Connections to a replica set are similar to connections to a single server. Use the MongoClient-equivalent in your driver and provide a list of seeds for the driver to connect to. Seeds are members of the replica set. You do not have to list all members (although you can): when the driver connects to the seeds, it will discover the other members from them. A connection string usually looks something like this:

"mongodb://server-1:27017,server-2:27017"

See your driver’s documentation for details.

When a primary goes down, the driver will automatically find the new primary (once one is elected) and will route requests to it as soon as possible. However, while there is no reachable primary your application will be unable to perform writes.

There may be no primary available for a brief time (during an election) or for an extended period of time (if no reachable member can become ...

Get MongoDB: The Definitive Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.