Docs Menu
Docs Home
/ / /
Kotlin Coroutine
/ /

Limit Server Execution Time

On this page

  • Overview
  • timeoutMS Option
  • Accepted Timeout Values
  • Timeout Inheritance
  • Overrides
  • Transactions
  • Client Encryption
  • Cursors
  • Cursor Lifetime Mode
  • API Documentation

When you use the Kotlin 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 Kotlin 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, TimeUnit.MILLISECONDS)
.build()
val client = MongoClient.create(settings)
val uri = "<connection string>/?timeoutMS=200"
val client = MongoClient.create(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, TimeUnit.MILLISECONDS)
.build()
val client = MongoClient.create(settings)
val collection = client
.getDatabase("db")
.getCollection<Document>("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 Kotlin 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 Kotlin 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, TimeUnit.MILLISECONDS)
.build()
val client = MongoClient.create(settings)
val database = client.getDatabase("db")
val collection = database
.getCollection<Document>("people")
.withTimeout(300L, TimeUnit.MILLISECONDS)

When you create a new ClientSession 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, TimeUnit.MILLISECONDS)
.build()
val session = client.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, TimeUnit.MILLISECONDS)
.build()

To learn more about transactions, see the Transactions 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.

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

For operations that create cursors, the timeout setting can either cap the lifetime of the cursor or be applied separately to the original operation and all subsequent calls.

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 cursors and flows, see the Access Data From a Flow guide.

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

When you close a cursor by calling the close() method, the timeout resets for the killCursors command to ensure server-side resources are cleaned up.

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

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

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

Back

MongoClient Settings