MongoDB
Spring Data
Spring Boot
Transactions
Namespace Error

Cannot create namespace in multi-document transactionMongoDB 4.0, Spring Data 2.1.0, Spring Boot

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

The Cannot create namespace error in a MongoDB 4.0 transaction usually means the transaction tried to write to a collection that does not already exist. With Spring Data and Spring Boot, this often shows up when the first save to a collection happens inside an @Transactional method and MongoDB would have needed to create that collection implicitly.

Why This Fails in MongoDB 4.0 Transactions

MongoDB 4.0 supports multi-document transactions, but the rules are stricter than many developers expect. In particular, a transaction is meant to operate on existing collections. If the first write would cause MongoDB to create a new collection, the server rejects it with a namespace error.

That means this flow is unsafe:

  1. Spring opens a MongoDB transaction.
  2. The code saves a document to a collection that has never been created.
  3. MongoDB would normally auto-create the collection.
  4. The transaction fails because collection creation is not allowed in that transactional context.

The same idea applies to some lazy index-creation patterns. Transactional work should assume collections and required indexes already exist.

Configure Transaction Support Correctly

Before fixing the namespace error, make sure you actually have transaction support configured. MongoDB transactions require a replica set, even in local development, and Spring needs a MongoTransactionManager.

java
1import org.springframework.context.annotation.Bean;
2import org.springframework.context.annotation.Configuration;
3import org.springframework.data.mongodb.MongoDatabaseFactory;
4import org.springframework.data.mongodb.MongoTransactionManager;
5
6@Configuration
7public class MongoConfig {
8
9    @Bean
10    MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {
11        return new MongoTransactionManager(dbFactory);
12    }
13}

If you run against a standalone MongoDB instance instead of a replica set, transactions will fail for a different reason. It is worth checking that first so you do not chase the wrong problem.

Create Collections Before the Transaction Starts

The direct fix is to create the collection before any transactional business method touches it. An application startup hook is a simple place to do that:

java
1import org.springframework.boot.ApplicationRunner;
2import org.springframework.context.annotation.Bean;
3import org.springframework.context.annotation.Configuration;
4import org.springframework.data.mongodb.core.MongoTemplate;
5
6@Configuration
7public class MongoSetup {
8
9    @Bean
10    ApplicationRunner ensureCollections(MongoTemplate mongoTemplate) {
11        return args -> {
12            if (!mongoTemplate.collectionExists("orders")) {
13                mongoTemplate.createCollection("orders");
14            }
15            if (!mongoTemplate.collectionExists("auditEvents")) {
16                mongoTemplate.createCollection("auditEvents");
17            }
18        };
19    }
20}

Now your transactional code can assume the namespaces are already present:

java
1import org.springframework.stereotype.Service;
2import org.springframework.transaction.annotation.Transactional;
3
4@Service
5public class OrderService {
6
7    private final OrderRepository orderRepository;
8    private final AuditEventRepository auditEventRepository;
9
10    public OrderService(
11        OrderRepository orderRepository,
12        AuditEventRepository auditEventRepository
13    ) {
14        this.orderRepository = orderRepository;
15        this.auditEventRepository = auditEventRepository;
16    }
17
18    @Transactional
19    public void createOrder(Order order) {
20        orderRepository.save(order);
21        auditEventRepository.save(new AuditEvent(order.getId(), "CREATED"));
22    }
23}

Create Indexes Outside the Transaction Too

Indexes are another place where hidden namespace work can appear. If your application expects an index, create it during startup or through a migration step instead of relying on the first transactional request to trigger it.

Using MongoTemplate, you can prepare indexes explicitly:

java
1import org.springframework.data.domain.Sort;
2import org.springframework.data.mongodb.core.index.Index;
3
4mongoTemplate.indexOps("orders")
5    .ensureIndex(new Index().on("customerId", Sort.Direction.ASC));

This keeps schema-like setup outside the business transaction, which is where it belongs.

Common Pitfalls

One common mistake is assuming MongoDB collection auto-creation works the same inside and outside transactions. It does not. A save that succeeds without a transaction can fail once wrapped in @Transactional.

Another pitfall is forgetting the replica-set requirement. If local development uses a standalone server, transaction behavior will be inconsistent with production and errors become harder to interpret.

It is also easy to create the main collection up front but forget supporting collections such as audit or outbox collections. The first write to any missing namespace can still fail.

Finally, avoid hiding setup inside the first business request. Collection creation and index creation are deployment or startup concerns, not transactional application logic.

Summary

  • In MongoDB 4.0, transactions expect collections to already exist.
  • Spring transactional writes can fail with Cannot create namespace when the collection would be created implicitly.
  • Use a replica set and configure MongoTransactionManager before troubleshooting higher-level logic.
  • Create collections and indexes during startup or migrations, not inside the transaction.
  • Treat transactional methods as consumers of an already-prepared database schema.

Course illustration
Course illustration

All Rights Reserved.