I am working with Salesforce Connect and I am storing my token and expiration times in an encrypted custom setting. My connection is through the client credentials Oauth 2 flow.

When a user queries an external object, it makes sense to me in the initial method of salesforce connect DataSource.Connection class to:

  1. Update the custom settings fields if there is no information or the token has expired.

  2. Use the custom settings to get the access token if the token has not expired.

This would be fine, however within the same transaction, in the query method of the DataSource.Connection class, webservice callouts to fetch the external objects with the newly updated token must occur. This results in an "uncommitted work pending" error as we would expect because webservice callouts cannot be made after DML statements.

Future methods don't seem to be a plausible solution here because if the token is expired I need those custom settings to be updated at that time otherwise the rest callout will fail.

I thought calling a new instance of another class with a method to update the custom setting might be considered a new transactions, but my assumption was wrong.

I could have users request a token every rest call and store them within the class and not within the custom setting, but that seems so absurdly excessive where as the custom setting would allow multiple users to utilize the same token and only make a token callout when necessary since it's a client connection anyways.



1 Answer 1


I could have users request a token every rest call and store them within the class and not within the custom setting

You can take the advantages of both approaches. Set up your callout so you can use a token from within memory. If you need to update your setting, move that DML to the end of your transaction.


String token = MySetting__c.getOrgDefaults().Token__c;

// if the token is blank or expired, get a new one
// and reassign the value in your token variable

// make your callout using the valid token

// if the token was blank or expired, update your setting

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .