Fixing error “The Request uses too many resources.” in CSOM / REST operation

This post is a contribution from Sohail Sayed, an engineer with the SharePoint Developer Support team

You may occasionally run into the following error when calling a CSOM API in SharePoint

Error : The Request uses too many resources.

If you check the ULS logs you can see the below error

Potentially excessive number of SPRequest objects (16) currently unreleased on thread 54. Ensure that this object or its parent (such as an SPWeb or SPSite) is being properly disposed. This object is holding on to a separate native heap.This object will not be automatically disposed. Allocation Id for this object: {D1CD1BB2-B94B-4129-8791-68DD2ED3C95A} Stack trace of current allocation:   

at Microsoft.SharePoint.SPGlobal.CreateSPRequestAndSetIdentity(SPSite site, String name, Boolean bNotGlobalAdminCode, String strUrl, Boolean bNotAddToContext, Byte[] UserToken, SPAppPrincipalToken appPrincipalToken, String userName, Boolean bIgnoreTokenTimeout, Boolean bAsAnonymous)   

at Microsoft.SharePoint.SPRequestManager.GetContextRequest(SPRequestAuthenticationMode authenticationMode)   

 

There is a check in the SPGlobal.CreateSPRequestAndSetIdentity method whether the number of SPRequest objects exceed a certain limit. If yes you will see the above error in the ULS logs and your CSOM request will fail with the error "The Request uses too many resources.". The SPRequest objects may get created due to large number of SPSite / SPWeb objects being created by the CSOM request.

The default setting for the maximum number of SPRequest objects that can be created by the CSOM / REST calls is 16. Please note this limit is per CSOM request i.e. per ClientContext.ExecuteQuery call or REST call. This means that you can split your CSOM requests to overcome this error.

However, in some cases a single atomic CSOM operation will throw this error. This may happen in case of activating a feature which creates a lot of SPRequest objects or when provisioning a sub site using CSOM/REST.

The good news is that the default setting for the maximum number of SPRequest objects that can be created by the CSOM / REST calls can be modified using the below powershell command. Run this command from any one of the SharePoint servers.

 $webApp = Get-SPWebApplication "<SITEURL>"

$webApp.ClientCallableSettings.MaxResourcesPerRequest = 50

$webApp.Update()

 

Note

This solution applies only for SharePoint On-Premises. This is server side setting and hence you cannot update this for SharePoint Online.

Keep a track on the memory usage on your servers after you update this setting. It is possible there is some custom component on server which is running bad code and may cause high memory usage. In such cases you may be able to fix the issue by optimizing the custom component code without update this setting.