DocumentDB via SDK Best Practices
This is the checklist to run before and after building on Amazon DocumentDB from the SDK. Each item is a rule stated positively with a one-line rationale.
Search across all documentation pages
This is the checklist to run before and after building on Amazon DocumentDB from the SDK. Each item is a rule stated positively with a one-line rationale.
Work top to bottom - the groups run roughly in dependency order, from provisioning outward to connections and cost. Remember the model throughout: the SDK provisions and operates the cluster, but a MongoDB driver runs your documents over TLS. Most rules hold whether you provision from the SDK or from IaC.
CreateDBCluster makes the storage; CreateDBInstance adds the compute - a cluster with no instance is not connectable.StorageEncrypted=True at create time - you cannot enable it in place later without a snapshot-copy-restore.db_instance_available before using an endpoint. The endpoint is unusable while the instance is creating; size maxWaitTime generously.Engine="docdb" and a deliberate EngineVersion. Pick the MongoDB compatibility version your app needs and keep it consistent across the cluster.Create an encrypted cluster with a managed credential, then attach a writer.
# --- Python (boto3) ---
docdb.create_db_cluster(
DBClusterIdentifier="app-docdb", Engine="docdb", EngineVersion="5.0.0",
MasterUsername="appuser", ManageMasterUserPassword=True,
StorageEncrypted=True,
DBSubnetGroupName="app-docdb-subnets",
VpcSecurityGroupIds=["sg-0123456789abcdef0"],
)
docdb.create_db_instance(
DBInstanceIdentifier="app-docdb-writer", DBClusterIdentifier="app-docdb",
Engine="docdb", DBInstanceClass="db.r6g.large",
)// --- TypeScript (AWS SDK v3) ---
import { CreateDBClusterCommand, CreateDBInstanceCommand } from "@aws-sdk/client-docdb";
await docdb.send(new CreateDBClusterCommand({
DBClusterIdentifier: "app-docdb", Engine: "docdb", EngineVersion: "5.0.0",
MasterUsername: "appuser", ManageMasterUserPassword: true,
StorageEncrypted: true,
DBSubnetGroupName: "app-docdb-subnets",
VpcSecurityGroupIds: ["sg-0123456789abcdef0"],
}));
await docdb.send(new CreateDBInstanceCommand({
DBInstanceIdentifier: "app-docdb-writer", DBClusterIdentifier: "app-docdb",
Engine: "docdb", DBInstanceClass: "db.r6g.large",
}));ManageMasterUserPassword so DocumentDB stores and rotates it in Secrets Manager, or use IAM database authentication.DBSubnetGroupName and keep it off the public internet.global-bundle.pem and pass it to the driver; never disable TLS to work around a certificate error.MONGODB-AWS mechanism removes stored passwords entirely for supported engine versions and clients.BackupRetentionPeriod above 0 turns on continuous backups plus point-in-time recovery.PreferredBackupWindow so backups do not compete with peak load.CreateDBClusterSnapshot persists until you delete it.CopyDBClusterSnapshot with a destination-region KMS key survives a regional event.Enable retention and checkpoint before a release.
# --- Python (boto3) ---
docdb.modify_db_cluster(
DBClusterIdentifier="app-docdb",
BackupRetentionPeriod=7, PreferredBackupWindow="03:00-04:00",
ApplyImmediately=True,
)
docdb.create_db_cluster_snapshot(
DBClusterIdentifier="app-docdb",
DBClusterSnapshotIdentifier="app-docdb-pre-release",
)// --- TypeScript (AWS SDK v3) ---
import { ModifyDBClusterCommand, CreateDBClusterSnapshotCommand } from "@aws-sdk/client-docdb";
await docdb.send(new ModifyDBClusterCommand({
DBClusterIdentifier: "app-docdb",
BackupRetentionPeriod: 7, PreferredBackupWindow: "03:00-04:00",
ApplyImmediately: true,
}));
await docdb.send(new CreateDBClusterSnapshotCommand({
DBClusterIdentifier: "app-docdb",
DBClusterSnapshotIdentifier: "app-docdb-pre-release",
}));Endpoint for writes and read-after-write, and ReaderEndpoint for read-only queries.CreateGlobalCluster gives cross-region replication with read-only secondaries and fast failover.Add a reader and route reads to the reader endpoint.
# --- Python (boto3) ---
docdb.create_db_instance(
DBInstanceIdentifier="app-docdb-reader-2", DBClusterIdentifier="app-docdb",
Engine="docdb", DBInstanceClass="db.r6g.large",
)
cl = docdb.describe_db_clusters(DBClusterIdentifier="app-docdb")["DBClusters"][0]
print("reads ->", cl["ReaderEndpoint"], " writes ->", cl["Endpoint"])// --- TypeScript (AWS SDK v3) ---
import { CreateDBInstanceCommand, DescribeDBClustersCommand } from "@aws-sdk/client-docdb";
await docdb.send(new CreateDBInstanceCommand({
DBInstanceIdentifier: "app-docdb-reader-2", DBClusterIdentifier: "app-docdb",
Engine: "docdb", DBInstanceClass: "db.r6g.large",
}));
const dc = await docdb.send(new DescribeDBClustersCommand({ DBClusterIdentifier: "app-docdb" }));
console.log("reads ->", dc.DBClusters![0].ReaderEndpoint, " writes ->", dc.DBClusters![0].Endpoint);pymongo / node mongodb).retryWrites=false. DocumentDB rejects retryable writes, which are on by default in modern drivers.MongoClient once at module scope; opening a client per request exhausts the instance's connection budget.secondaryPreferred in the driver so read traffic reaches reader instances.docdb client at module scope so warm Lambda invocations skip re-creating it.Reuse one pooled client for the whole process.
# --- Python (pymongo driver - NOT the AWS SDK) ---
from pymongo import MongoClient
# Module scope: created once, connection-pooled, reused across requests.
client = MongoClient(
"app-docdb.cluster-abc123.us-east-1.docdb.amazonaws.com",
port=27017, tls=True, tlsCAFile="global-bundle.pem",
username="appuser", password="from-secrets-manager",
retryWrites=False, readPreference="secondaryPreferred",
maxPoolSize=50,
)DBInstanceClass to real CPU and memory use; oversized instances waste money idle.docdb-elastic clusters scale horizontally and can be resized as demand moves.ApplyImmediately false for changes that can wait, to avoid surprise downtime.Separating the planes: the SDK provisions and manages the cluster, and a MongoDB driver runs your documents over TLS. DocumentDB has no Data API, so once you know a task is a query, the answer is always the driver, not the SDK.
DocumentDB does not implement retryable writes, and modern MongoDB drivers enable them by default. A connection with retryWrites on will fail. Set retryWrites=False in every driver connection.
Never store it in code. Use ManageMasterUserPassword so DocumentDB keeps and rotates the credential in Secrets Manager, or use IAM database authentication for a passwordless model. Your app reads the secret at connect time.
No. Automated backups are removed with the cluster, aside from an optional final snapshot. For anything you must keep, take a manual cluster snapshot, which persists until you delete it, and copy it cross-region for DR.
Add reader instances with CreateDBInstance; they attach to shared storage in seconds. Route read-only queries to the reader endpoint and set readPreference=secondaryPreferred in the driver so reads reach the replicas.
When writes or data outgrow a single writer, or when capacity swings and you want to scale horizontally. Elastic clusters (the docdb-elastic client) shard data and are sized by shard capacity and count. Standard clusters are simpler for steady, single-writer load.
The cluster has storage but no instance yet, or the instance is still creating. Attach an instance with CreateDBInstance and wait on db_instance_available before reading or connecting to the endpoint.
Create one MongoClient at module scope and let the driver pool connections, rather than opening a client per request. Reuse it across warm Lambda invocations, and bound maxPoolSize so a burst of callers cannot overwhelm the instance.
Mostly yes. Encryption, private networking, managed credentials, backups and retention, multi-instance availability, and tagging are architectural habits that hold whether you provision from the SDK or from CloudFormation, CDK, or Terraform.
Stack versions: This page was written for boto3 1.43.x (Python 3.10+) and the AWS SDK for JavaScript v3 (Node.js 18+).
Reviewed by Chris St. John·Last updated Jul 24, 2026