Docs Menu
Docs Home
/ / /
Scala Driver
/

Limit Server Execution Time

When you use the Scala driver to perform a server operation, you can also limit the amount of time in which the server can finish the operation. To do so, specify a client-side operation timeout (CSOT). The timeout applies to all steps needed to complete the operation, including server selection, connection checkout, and server-side execution. When the timeout expires, the Scala driver raises a timeout exception.

Note

Experimental Feature

The CSOT feature is experimental and might change in future driver releases.

To specify a timeout when connecting to a MongoDB deployment, set the timeoutMS connection option to the timeout length in milliseconds. You can set the timeoutMS option in the following ways:

  • Calling the timeout() method from the MongoClientSettings.Builder class

  • Setting the timeoutMS parameter in your connection string

The following code examples set a client-level timeout of 200 milliseconds. Select the MongoClientSettings or Connection String tab to see the corresponding code.

val settings = MongoClientSettings.builder
.applyConnectionString(ConnectionString("<connection string>"))
.timeout(200L, MILLISECONDS)
.build
val mongoClient = MongoClient(settings)
val uri = "<connection string>/?timeoutMS=200"
val mongoClient = MongoClient(uri)

The following table describes the timeout behavior corresponding to the accepted values for timeoutMS:

Value
Behavior

Positive integer

Sets the timeout to use for operation completion.

0

Specifies that operations never time out.

null or unset

Defers the timeout behavior to the following settings:
  • waitQueueTimeoutMS

  • socketTimeoutMS

  • wTimeoutMS

  • maxTimeMS

  • maxCommitTimeMS

These settings are deprecated and are ignored if you set timeoutMS.

If you specify the timeoutMS option, the driver automatically applies the specified timeout to each server operation. The following code example specifies a timeout of 200 milliseconds at the client level, and then calls the MongoCollection.insertOne() method:

val settings = MongoClientSettings.builder
.applyConnectionString(ConnectionString("<connection string>"))
.timeout(200L, MILLISECONDS)
.build
val mongoClient = MongoClient(settings)
val database = mongoClient.getDatabase("db")
val collection = database.getCollection("people")
collection.insertOne(Document("name" -> "Francine Loews"))

When you specify the timeoutMS option, the driver applies the timeout according to the same inheritance behaviors as the other Scala driver options. The following table describes how the timeout value is inherited at each level:

Level
Inheritance Description

Operation

Takes the highest precedence and overrides the timeout options that you set at any other level.

Transaction

Takes precedence over the timeout value that you set at the session, collection, database, or client level.

Session

Applies to all transactions and operations within that session, unless you set a different timeout value at those levels.

Database

Applies to all sessions and operations within that database, unless you set a different timeout value at those levels.

Collection

Applies to all sessions and operations on that collection, unless you set a different timeout value at those levels.

Client

Applies to all databases, collections, sessions, transactions, and operations within that client that do not otherwise specify timeoutMS.

For more information on overrides and specific options, see the following Overrides section.

The Scala driver supports various levels of configuration to control the behavior and performance of database operations.

You can specify a timeoutMS option at a more specific level to override the client-level configuration. The table in the preceding section describes the levels at which you can specify a timeout setting. This allows you to customize timeouts based on the needs of individual operations.

The following example demonstrates how a collection-level timeout configuration can override a client-level timeout configuration:

val settings = MongoClientSettings.builder
.applyConnectionString(ConnectionString("<connection string>"))
.timeout(200L, MILLISECONDS)
.build
val mongoClient = MongoClient(settings)
val database = mongoClient.getDatabase("db")
val collection = database
.getCollection("people")
.withTimeout(300L, MILLISECONDS)
// ... perform operations on MongoCollection

When you create a new ScalaClientSession instance to implement a transaction, use the defaultTimeout() method when building a ClientSessionOptions instance. You can use this option to specify the timeout for the following methods:

The following code demonstrates how to set the defaultTimeout when instantiating a ClientSession:

val opts = ClientSessionOptions.builder
.defaultTimeout(200L, MILLISECONDS)
.build
val session = mongoClient.startSession(opts)
// ... perform operations on ClientSession

If you do not specify the defaultTimeout, the driver uses the timeout value set on the parent MongoClient.

You can also set a transaction-level timeout by calling the timeout() method when building a TransactionOptions instance. Setting this option applies a timeout to all operations performed in the scope of the transaction:

val transactionOptions = TransactionOptions.builder
.timeout(200L, MILLISECONDS)
.build

To learn more about transactions, see the Perform a Transaction guide.

When you use Client-Side Field Level Encryption (CSFLE), the driver uses the timeoutMS option to limit the time allowed for encryption and decryption operations. You can set a timeout option for your ClientEncryption instance by calling the timeout() method when building a ClientEncryptionSettings instance.

If you specify the timeout when you construct a ClientEncryption instance, the timeout controls the lifetime of all operations performed on that instance. If you do not provide a timeout when instantiating ClientEncryption, the instance inherits the timeout setting from the MongoClient used in the ClientEncryption constructor.

If you set timeoutMS both on the client and directly in ClientEncryption, the value provided to ClientEncryption takes precedence.

Observable instances offer configurable timeout settings when using the CSOT feature. You can adjust Observable handling by configuring the Observable lifetime. To configure the timeout mode, use the timeoutMode() method when performing any operation that returns a result that inherits Observable.

Note

Inherited Timeout

Setting a cursor timeout mode requires that you set a timeout either in the MongoClientSettings, on MongoDatabase, or on MongoCollection.

To learn more about observables, see the Access Data From an Observable guide.

The lifetime mode uses the timeout setting to limit the entire lifetime of an Observable. In this mode, your application must initialize the Observable, complete all calls to the Observable methods, and return all documents within the specified time limit. Otherwise, the Observable lifetime expires and the driver raises a timeout error.

The following example shows how to set an Observable timeout to ensure that the cursor is initialized and all documents are retrieved within the inherited timeout:

val observableWithLifetimeTimeout = collection
.find(gte("age", 40))
.timeoutMode(TimeoutMode.CURSOR_LIFETIME)

You can set a timeout option for GridFS operations when instantiating a GridFSBucket by using the withTimeout() method. This timeout applies to all operations performed on the bucket, such as uploading and downloading data. If you do not set a timeout, the GridFSBucket instance inherits the timeout setting from the MongoDatabase it is created with.

The following code demonstrates how to set a timeout when instantiating a GridFSBucket:

val gridFSBucket = GridFSBucket(database).withTimeout(200L, MILLISECONDS)

Important

Observable Timeout Support

When you call the uploadFromObservable() method on a GridFSBucket that has an operation timeout, timeout breaches might occur because the Observable class lacks inherent read timeout support. This might extend the operation beyond the specified timeout limit, causing a timeout exception.

To learn more about using timeouts with the Scala driver, see the following API documentation:

Back

Choose a Connection Target

On this page