user-2147482509
user-2147482509

Reputation: 23

MongoDB transactions spanning multiple web requests

I'm trying to implement a MongoDB transactions API service over HTTP using Go where the client sends a request to: /db/transaction/begin to acquire a Transaction ID in order to bind all subsequent transaction-related CRUD operations API requests with that Transaction ID and finally the client either sends a request to /db/transaction/{transaction_id}/commit or /db/transaction/{transaction_id}/rollback (something somewhat similar to Firestore Transaction)

I was able to implement this kind of behavior with ArangoDB since it's Go Driver allows me to set the Transaction ID of each CRUD operation (https://godoc.org/github.com/arangodb/go-driver#WithTransactionID)

but unfortunately i couldn't achieve this with the official MongoDB Go Driver

Am I missing something? Is there a workaround or any custom implementation which could help me?

Upvotes: 1

Views: 919

Answers (1)

D. SM
D. SM

Reputation: 14480

The simpler solution is to store (buffer) the operations in your application and submit them all together to MongoDB when the commit endpoint runs.

Technically you can manually manage transaction lifecycle in your application and implement transactions spanning web requests but this is 1) going to be quite awkward and 2) you are going to lose the various transient error handling that the driver does for you in the withTransaction API.

To do this:

  • Familiarize yourself with sessions specification
  • Familiarize yourself with transactions specification
  • Read the convenient tx api spec so that you know what you won't be getting for free, if your customer asks why you are exposing errors that drivers don't
  • Review the code in your driver implementing these specifications
  • Implement enough of session and transaction management for your requirements in your application

Might be easier to fork & patch the driver but this obviously has other issues resulting from your codebase diverging from the official driver codebase.

Upvotes: 1

Related Questions