0PricingLogin
MongoDB Academy · Lesson

Error Handling and Retry Logic

Learners will catch TransientTransactionError and UnknownTransactionCommitResult and implement the recommended retry loop for production reliability.

Why Transactions Need Retry Logic

MongoDB transactions can fail with transient errors—temporary conditions like network blips, primary failovers, or write conflicts—that do not indicate a logical problem with your code. These errors are safe to retry: the transaction was rolled back cleanly, and retrying it will produce correct results. Without retry logic, your application will surface unnecessary errors to users for conditions that a simple retry would resolve.

Two Error Labels to Understand

MongoDB classifies transaction errors with two important error labels: TransientTransactionError and UnknownTransactionCommitResult. TransientTransactionError means the entire transaction failed and it is safe to retry from the beginning. UnknownTransactionCommitResult means the commit was sent but the client does not know if it succeeded—the commit must be retried (not the whole transaction). Each requires a different retry strategy.

// Checking error labels
if (error.hasErrorLabel('TransientTransactionError')) {
  // Retry the whole transaction from scratch
  console.log('Transient error — retrying transaction');
} else if (error.hasErrorLabel('UnknownTransactionCommitResult')) {
  // Retry only the commit, not the whole transaction
  console.log('Unknown commit result — retrying commit only');
} else {
  // Application error (e.g., InsufficientFunds) — do not retry
  throw error;
}

All lessons in this course

  1. ACID Guarantees in a Distributed Document Store
  2. Starting a Session and Multi-Document Transaction
  3. Error Handling and Retry Logic
  4. Transaction Performance Considerations
← Back to MongoDB Academy