
Your Driver Defaults Are Fine. Until They're Not.
Things always work on your machine - the problem is that the defaults that make local development frictionless can be silently wrong in production. This article walks through exactly which settings will betray you, why, and how the amazon-documentdb-python-client wrapper fixes them automatically for your Amazon DocumentDB deployments so you can deploy on a Friday at 4:58 PM and actually make it home for Silo episodes (no spoilers here).
Meet our developer. It is Friday afternoon. He has been building against a local document database all week, the sprint is done, the feature works, and there is exactly one task left before the weekend: point the app at the Amazon DocumentDB cluster in production. A nothing task. Like Indiana Jones swapping a sandbag for the Chachapoyan Idol - same weight, same shape, what could possibly go wrong?

He changes one line.
localhost:27017 becomes the DocumentDB cluster endpoint. Adds TLS because he got 75% of the LinkedIn security quiz questions right, so he's something of a SecOps expert. Everything else stays exactly as it was - same driver defaults that worked perfectly all week.from pymongo import MongoClientclient = MongoClient("docdb_cluster_endpoint")And good news, everyone! The driver is compatible, the API calls are the same, and the app is querying documents in seconds.

He deploys at 4:47 PM, watches the health check go green, and closes his laptop. He has plans. Not exciting plans. Just the Raspberry Pi sitting on his desk at home. A DNS server he set up six months ago that worked perfectly for three days and has been subtly misbehaving ever since. Something about it drops lookups at random, and consequently, keeps freezing his stream of Silo. He is three episodes behind. He doesn't know why Juliette lost her memory. He doesn't know what the politician is actually building toward. He absolutely does not know why the silos were built, and at this point it has become a genuine quality-of-life issue.
"This weekend...", he decides. "This weekend I fix the Pi".
His phone buzzes at 5:23 PM.
It's not an alarm. It's an alert. The kind that means users. He opens the dashboard expecting a blip, maybe a latency spike that self-resolves in thirty seconds. Instead he sees an error count climbing. Steady. Every second. He stares at it for a moment with the particular confusion of someone whose deploy went green.
The health checks are still passing. The database metrics look fine. The service is responding to requests.
But no data is saving.
What he doesn't know yet is that the driver defaults he never touched - perfectly harmless against a local instance - are quietly wrong for production. His reads succeed. His writes have been failing since 5:01 PM, and his application has been swallowing the error without a sound. Twenty-two minutes of orders, form submissions, and user events have gone nowhere.
He will spend Friday night debugging this. He will not fix the Pi. He will not find out why the silos were built. Juliette's memory will remain a mystery.
This is what happens when you don't know which defaults change meaning when you cross the line from local development to a managed, production-grade cluster.
Even better news, everyone!
The
amazon-documentdb-python-client exists so this story doesn't happen to you. It's a thin wrapper around PyMongo that enforces the right configuration for DocumentDB, closes the common failure modes, and adds enterprise-grade capabilities with a single config block. Your queries don't change. Your application code doesn't change. You just stop having to know which defaults will betray you at 5:47 PM on a Friday.The problem with defaults
When you connect to DocumentDB with
MongoClient , you're responsible for getting these right:Setting | PyMongo default | DocumentDB value |
|---|---|---|
retryWrites | True | Must be False - DocumentDB rejects retryable write sessions with error 301 |
directConnection | False | Correct default, but easy to copy from a connection string example that overrides it to True - breaks topology discovery and failover recovery |
replicaSet | Not set | Not required, but needed for HA workloads with multiple instances - without it, PyMongo skips topology discovery and won't re-route after a failover |
readPreference | primary | Should be secondaryPreferred if you have a reader instance |
Client lifecycle | No enforcement | PyMongo pools connections within a MongoClient , but nothing prevents accidentally creating a new client per request in request-scoped frameworks, bypassing the pool entirely |
The one that hurts most is
retryWrites . PyMongo 3.x+ defaults to retryWrites=True , which works perfectly on any self-managed replica set. On DocumentDB, inserts succeed silently (asymmetric behavior) and updates/deletes fail. You often won't see this in your test suite.The wrapper makes all of these decisions for you and makes the wrong ones unavailable.
Two lines to a production-ready connection
Before:
from pymongo import MongoClient
client = MongoClient( "mongodb://mycluster.docdb.amazonaws.com:27017", tls=True, tlsCAFile="/certs/global-bundle.pem", # retryWrites? replicaSet? directConnection? readPreference?)db = client["mydb"]After:
import docdbfrom docdb import DocumentDBConfig
docdb.init(DocumentDBConfig( host="mycluster.cluster-abc123.us-east-1.docdb.amazonaws.com", username="...", password="...", tls_ca_file="global-bundle.pem", app_name="my-order-app",))
db = docdb.get_client().db("mydb")Everything after
docdb.init() looks exactly like PyMongo. The wrapper is transparent - db.orders.find_one(...) , aggregation pipelines, bulk operations - all unchanged.What gets enforced automatically
Replica set mode and failover recovery
The wrapper enforces
replicaSet=rs0 and directConnection=False . Together, these give PyMongo full topology awareness: it knows your cluster is a replica set, it monitors which node is primary via background heartbeats, and it re-routes automatically after a failover.The failure mode this prevents is severe. A
directConnection=True configuration puts PyMongo into Single topology mode, which caches the resolved IP at startup and never re-queries DNS. After a failover, the cluster endpoint CNAME points to the new primary - but the driver never asks DNS again. It retries a dead socket to a stale IP indefinitely. The service will not recover until you restart the process.Retryable writes disabled
retryWrites=False is enforced unconditionally. This is the single most common migration gotcha when moving to DocumentDB. The wrapper sets it once and removes it from your checklist permanently. And before you worry about losing retry behavior entirely - we have something better built into the wrapper. You'll see soon, below.Connection pooling - singleton client with a warm pool
docdb.get_client() always returns the same managed MongoClient instance, initialized at docdb.init() time with min_pool_size=5 . Connections to each node are established at startup and held open.The alternative is creating a new
MongoClient per request (a common mistake in FastAPI dependencies and other request-scoped frameworks). Each invocation pays a full TCP handshake, TLS negotiation, and SASL authentication round-trip before the first query executes. That can be a 15-20ms overhead on every call, and it scales with network conditions. The wrapper makes the singleton the only option: there is no code path that creates a second client.Read distribution to your reader instance
The wrapper defaults to
readPreference=secondaryPreferred . Reads route to your reader instance; writes go to the primary. Both nodes handle traffic proportional to what they were provisioned for.The practical consequence of leaving this at
primary (PyMongo's default) goes beyond underutilized hardware. Teams see an idle reader and rationally downsize it. Later, a failover promotes that undersized reader to primary. It can't handle the workload. Connection limits hit, memory exhausts. A routine failover becomes an outage because a capacity decision was made on misleading utilization data.When reads are distributed, the writer's buffer cache holds only what the write path needs. No read and write I/O competing for the same pages. That stability is what lets you set P99 latency SLAs with confidence.
Note: These are enforced defaults, not locked settings. Any of them can be overridden viaDocumentDBConfigif your workload has specific requirements. The goal is to give you the right production baseline without requiring you to know every DocumentDB-specific nuance upfront.
Adding enterprise capabilities with plugins
The wrapper has a plugin chain that intercepts every operation transparently. Add retry and CloudWatch telemetry in one config block:
from docdb import DocumentDBConfig, PluginConfigfrom docdb.telemetry import TelemetryConfig, MetricsBackend
docdb.init(DocumentDBConfig( host="mycluster.cluster-abc123.us-east-1.docdb.amazonaws.com", app_name="my-order-app", username="...", password="...", tls_ca_file="global-bundle.pem", plugins=[ PluginConfig("retry"), PluginConfig("telemetry"), ], telemetry=TelemetryConfig( enabled=True, metrics_backend=MetricsBackend.CLOUDWATCH, ),))Your queries are unchanged. The plugins run on every operation without a decorator, middleware registration, or wrapper function in your business logic.
Retry plugin
This is McDonalds.
retryWrites is the McDonalds you have at home.Configurable attempts with exponential backoff. When a transient failure hits (packet loss, a connection dropped during failover) the plugin absorbs it and retries transparently. When it gives up, the log entry tells you exactly what failed, which attempt, and why:
RetryPlugin: mydb.orders.insert_one attempt 2 failed (AutoReconnect), retrying in 200ms...The alternative is scatter-gunning retry logic across every query in your service:
# Without the plugin - multiplied by every query in your codebase for attempt in range(3): try: result = db.orders.find_one({"_id": oid}) break except (AutoReconnect, ConnectionFailure): if attempt == 2: raise time.sleep(0.1 * 2**attempt)Telemetry plugin
Per-application, per-command CloudWatch metrics published from the application layer. One config line instruments every operation:
telemetry=TelemetryConfig(enabled=True, metrics_backend=MetricsBackend.CLOUDWATCH)CloudWatch's built-in DocumentDB metrics answer "how is the database performing?" The telemetry plugin answers "how is my application performing?" Those are different questions:
# What you see with the telemetry pluginmy-catalog-app → find → avg 2msmy-order-app → find → avg 450ms ← problem is hereWithout per-application attribution, you have a symptom with no vector. A server-side
find averaging 2ms doesn't tell you that my-order-app is seeing 450ms end-to-end because of connection acquisition overhead or retry delays. The plugin captures full client-side latency, not the database's view of the query. And if there's an active incident, details matters.Migration path
If you have existing PyMongo code, the migration is a config swap. Replace your
MongoClient(...) construction with docdb.init(...) and docdb.get_client() . Everything else - queries, aggregations, indexes, collection operations - is unchanged.Get started
The defaults table, plugin API reference, and connection tracker documentation are all in
docs/ . The examples directory has runnable patterns for Flask, FastAPI, Lambda, IAM auth, and custom plugins.If you're building new, start here. If you have existing code, it's a config swap - your queries don't change. Either way, you get replica set awareness, correct retry semantics, read distribution, and CloudWatch telemetry from the first line of code.
Oh, and olur developer? He's doing just fine. The Pi is fixed. He still isn't entirely sure what the politician was planning, but at this point neither is anyone else. He deployed last Friday at 4:58 PM and was home by 5:02. Because this time, he used the wrapper.

Join the Community
Also, if you are working with DocumentDB or other NoSQL databases, then come join the AWS NoSQL Launchpad ! This is where developers help each other figure out NoSQL design decisions, and it's filled with AWS NoSQL experts.
People share real scenarios, discuss when to use which service, and work through access pattern design together. Practical discussions about the decisions that matter.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article