Spring Boot And Amazon DocumentDB with MongoDB Compatibility
Introduction
Amazon DocumentDB (with MongoDB compatibility) is a fully managed, SSD-backed, petabyte-scale document database service that supports the MongoDB 3.6, 4.0, and 5.0 wire protocols. For Spring Boot teams already fluent in Spring Data MongoDB, DocumentDB lets you keep the same programming model — MongoRepository, @Document, aggregations — while offloading cluster management, patching, failover, and backups to AWS.
This guide covers cluster creation, TLS configuration, connection pooling, transactions, Spring Data MongoDB repositories, observability, and production hardening.
Why DocumentDB vs. Self-Managed MongoDB?
| Concern | Self-managed MongoDB | Amazon DocumentDB |
|---|---|---|
| Replica management | Manual config/rs reconfiguration | Automated across 3 AZs |
| Patching / upgrades | Your team’s problem | AWS-managed engine & driver updates |
| Backups | Point-in-time snapshots + oplog | Automatic PITR to the second |
| Scaling | Re-planning shards manually | Storage auto-scales 10 GiB → 128 TiB |
| Security | KYC audits + CIS baselines | KMS encryption, TLS, CloudWatch, IAM-knowledge integrations |
| Cost model | EC2 + ops headcount | Instance-hours + storage + IOPS |
Architecture Overview
flowchart LR
SB[Spring Boot App
• Spring Data MongoDB
• TLS + pool] -->|27017 over TLS| DOC[(DocumentDB Cluster
• 3 AZ replica set
• shard optional)]
VPC[VPC / Private Subnets] --- SB
VPC --- DOC
CW[(CloudWatch
metrics & logs)] --- DOC
SB ---|Micrometer| PROM[(Prometheus / Grafana)]
subgraph VPC
SB
DOC
end
Spring Boot connects over TLS to the cluster endpoint (or reader endpoint for load-balancing reads across replicas). Writes go to the primary; readPreference=secondaryPreferred spreads read traffic.
Prerequisites
- AWS account with permissions to create DocumentDB clusters, security groups, and KMS keys
- Spring Boot 3.x project (Java 17+) with Maven or Gradle
- App deployed inside (or peered to) the same VPC as DocumentDB
- AWS CLI configured
- Access to download the DocumentDB global bundle (TLS certificates) — link below
Step 1: Create the DocumentDB Cluster
Console or CLI makes little difference; use the v5.0 engine if you need multi-document transactions and change streams. Create a cluster with these settings:
| Setting | Recommended Value |
|---|---|
| Engine version | 5.0.x (supports transactions, change streams, aggregations) |
| DB instance class | db.r6g.large (dev) / db.r6g.2xlarge (prod) |
| Instances | 3 (1 writer + 2 readers across AZs) |
| VPC / Subnets | Private subnets in 3 AZs; No public accessibility |
| Encryption at rest | KMS default/alias key |
| Master username/password | Generated, stored in Secrets Manager |
| Parameter group | default.docdb5.0 with tls enforced |
| Security group (inbound) | Port 27017 from app ECS/EKS/EC2 security group only |
Capture the cluster endpoint, e.g.:
docdb-cluster.cluster-xyz12345abcd.us-east-1.docdb.amazonaws.com:27017
Step 2: Add Spring Data MongoDB to your project
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
Spring Boot 3.x will use the embedded MongoDB Java driver 4.11+ which fully speaks the MongoDB 4.0/5.0 wire protocol required by DocumentDB.
Step 3: Configure Connection URI, TLS & Pooling
Set the URI in application.yml. URL-encode the master password (@ → %40, etc.):
spring:
data:
mongodb:
database: orders_db
uri: ${DOCUMENTDB_URI}
# Example expansion:
# mongodb://admin:Pass%40word%23123@docdb-cluster.cluster-xyz12345abcd.us-east-1.docdb.amazonaws.com:27017/orders_db?ssl=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false&minPoolSize=10&maxPoolSize=50&maxLifeTimeMS=600000&heartbeatFrequencyMS=10000
WhyretryWrites=false? DocumentDB does not support MongoDB retryable writes. If you omit this, write operations may fail withWriteConcernExceptionat runtime. Always passretryWrites=false.
For advanced tuning, define a custom MongoClientSettings bean:
@Configuration
public class MongoClientConfig {
@Bean
public MongoClientSettings mongoClientSettings(
@Value("${spring.data.mongodb.uri}") String uri) {
ConnectionString conn = new ConnectionString(uri);
return MongoClientSettings.builder()
.applyConnectionString(conn)
.applyToConnectionPoolSettings(builder -> builder
.maxSize(50)
.minSize(10)
.maxWaitTime(60, TimeUnit.SECONDS)
.maxLifeTime(10, TimeUnit.MINUTES))
.applyToClusterSettings(builder -> builder
.serverSelectionTimeout(5, TimeUnit.SECONDS)
.heartbeatFrequency(10, TimeUnit.SECONDS))
.retryWrites(false) // MUST match URI; documentDB rejects retryable writes
.build();
}
@Bean
public MongoClient mongoClient(MongoClientSettings settings) {
return MongoClients.create(settings);
}
}
Step 4: Domain Model with @Document and Indexes
@Document(collection = "orders")
public class Order {
@Id
private String id;
@Indexed
private String customerId;
private List<OrderLine> lines;
private BigDecimal total;
@Enumerated(EnumType.STRING)
private OrderStatus status;
// TTL: auto-expire soft-deleted "cart" docs after 30 days
@Indexed(expireAfterSeconds = 2592000)
private Instant cartExpiry;
@Version
private Long version;
}
Create indexes via a startup runner once (also supports @CompoundIndex at class level):
@Component
public class MongoIndexInitializer implements ApplicationRunner {
private final MongoTemplate template;
@Override
public void run(ApplicationArguments args) {
template.indexOps(Order.class).ensureIndex(
new Index().on("customerId", Sort.Direction.ASC)
.on("status", Sort.Direction.ASC)
.named("idx_customer_status"));
}
}
Step 5: Spring Data MongoDB Repositories
public interface OrderRepository extends MongoRepository<Order, String> {
// Derived query (query derivation)
List<Order> findByCustomerIdAndStatus(String customerId, OrderStatus status);
// Paging + sorting
Page<Order> findByTotalGreaterThan(BigDecimal min, Pageable pageable);
// @Query with JSON syntax
@Query("{'lines.productSku': ?0, 'status': 'PLACED'}")
List<Order> findPlacedByProductSku(String sku);
// Text search (requires text index)
@Query("{ $text: { $search: ?0 } }")
List<Order> searchByText(String query);
// Aggregation pipeline
@Aggregation(pipeline = {
"{ $match: { status: 'PLACED' } }",
"{ $unwind: '$lines' }",
"{ $group: { _id: '$lines.productSku', quantity: { $sum: '$lines.quantity' } } }",
"{ $sort: { quantity: -1 } }"
})
List<Order> topProductsByVolume();
}
For more complex aggregations, implement a custom repository (slice pattern with @RepositoryImpl or call mongoTemplate.aggregate(...) directly).
Step 6: Transactions (Requires 5.0 Engine)
DocumentDB 5.0+ supports multi-document ACID transactions when the cluster replica set is used. Wrap with Spring’s @Transactional:
@Service
public class OrderService {
private final OrderRepository orders;
private final InventoryRepository inventory;
@Transactional
public Order placeOrder(OrderRequest request) {
Order order = orders.save(toEntity(request));
inventory.reserve(request.getLines());
eventBus.publish(new OrderPlacedEvent(order.getId()));
return order;
}
}
Behind the scenes Spring Data MongoDB starts a client session transaction (withSession(session -> session.startTransaction())). If the commit fails, the whole unit rolls back. Monitor transactions metrics in CloudWatch to spot contention early.
Step 7: Observability & Diagnostics
| Tool | What to watch |
|---|---|
| CloudWatch (DocumentDB metrics) | DatabaseConnections, CPUUtilization, SwapUsage, FreeLocalStorage, WriteLatency, ReadLatency, TransactionMetrics |
| Actuator | /actuator/health/mongo (readiness/liveness of cluster), /actuator/metrics/mongodb.servers.* |
| Micrometer | Command lifecycle via MicrometerCommandListener registered in MongoClientSettings |
| S.cam | MongoDB Log Insights in CloudWatch for slow queries (add a parameter group query profiler, profilerThreshold) |
@Bean
CommandListener commandListener(MeterRegistry registry) {
return new MicrometerCommandListener(registry,
MicrometerCommandListener.DEFAULT_COMMAND_METRIC_NAME);
}
// then .addCommandListener(commandListener) on the MongoClientSettings builder
Step 8: Integration Testing
There is no public DocumentDB Docker image, so test against a local MongoDB for unit/integration suites, and schedule true DocumentDB integration tests against a shared non-prod cluster:
@Testcontainers
class OrderRepositoryIT {
@Container
static final MongoDBContainer mongo =
new MongoDBContainer(DockerImageName.parse("mongo:7.0"));
@DynamicPropertySource
static void mongoProps(DynamicPropertyRegistry reg) {
reg.add("spring.data.mongodb.uri", mongo::getReplicaSetUrl);
}
@Test
void savesAndIndexes() { /* ... */ }
}
For staging-level validation of DocumentDB-specific features, a separate nightly GitHub Actions / CodePipeline job points at a real DocumentDB 5.0 cluster to validate transactions and TLS behavior end-to-end.
Security Hardening Checklist
- Force TLS: use
ssl=truein the URI and deny non-TLS connections via parameter group. - Certificate chain: DocumentDB uses the DocumentDB global bundle (or regional CA). Add it to your JVM
trustStoreor the MongoDB driver’ssslContext. - Host name verification: set
ssl=true; if using the older global bundle the CN may mismatch — thensslInvalidHostNameAllowed=trueis a pragmatic fallback while migrating to the regional CA. - Secrets: keep master password in AWS Secrets Manager, inject via env/SSM — never commit it.
- Network: disable public accessibility, lock the security group to application SG, enable AWS PrivateLink for cross-account access.
Trust store wiring in Java
@Bean
SslContext sslContext(@Value("${docdb.ca-bundle-path}") Path pemFile) throws Exception {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
try (InputStream in = Files.newInputStream(pemFile)) {
cf.generateCertificates(in).forEach(c -> {
try {
ks.setCertificateEntry(UUID.randomUUID().toString(), c);
} catch (KeyStoreException e) { throw new RuntimeException(e); }
});
}
TrustManagerFactory tmf = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
return SslContextBuilder.forClient()
.trustManager(tmf)
.build();
}
Troubleshooting Common Issues
| Symptom | Root Cause / Fix |
|---|---|
timed out connecting to server |
SG not allowing inbound 27017; check routing / NACL; use rs0 and cluster endpoint. |
WriteConcernException: retryable writes |
Missing retryWrites=false in URI/settings. |
Unknown command: transactions |
Cluster is on 4.0 engine — transaction support requires 5.0. |
| PKI certificate errors | Use the current global/regional bundle; update cacerts or driver SslContext. |
| Connection pool exhaustion | Increase maxPoolSize or provision larger instance; check DatabaseConnections. |
Best Practices Summary
| Category | Recommendation |
|---|---|
| Schema | Use embedded documents (denormalize) for 1:N read-heavy data; reference for shared/ritated entities. |
| Indexes | Verify with explain("executionStats"); use covered queries; add TTL for ephemeral data. |
| Connections | Size pool to instance maxConnections; set reasonable heartbeatFrequency. |
| Failover | Never hard-code a single endpoint; rely on the cluster endpoint + driver topology discovery. |
| Ops | Enable PITR backups + expedited snapshots before major config changes. |
Conclusion
Sprinking MongoDB ORM patterns onto Amazon DocumentDB is exactly what Spring Data MongoDB was made for. With TLS enabled, retryWrites=false, engine 5.0 for transactions, and CloudWatch-backed alerting, your Spring Boot services get MongoDB-compatible developer velocity with enterprise-grade ops. Combine this with the ElastiCache and CodeWhisperer pipelines from earlier posts and you have reference architecture for secure, observable, AI-assisted cloud-native Java.
Comments
Post a Comment