To ensure service availability and maintain service health, some HTTP requests may be prioritized over others. Our documentation recommends decorating the User-Agent header of the HTTP request as a design practice for reducing or avoiding SPO request throttling (link). Although there are many examples of decorating CSOM calls in the context of a C# application, this article demonstrates how to decorate CSOM calls within a PowerShell script.
Setting User-Agent at runtime
Each call to the ClientRuntimeContext.ExecuteQuery method triggers an ExecutingWebRequest event. When your script first constructs the ClientRuntimeContext object, you can pass a function to ClientRuntimeContext.add_ExecutingWebRequest method. The function passed will be called at runtime as an event handler for the ExecutingWebRequest event. This event handler sets the User-Agent header of the HTTP request. The following code is adapted from https://techcommunity.microsoft.com/t5/SharePoint-Developer/Updated-Guidance-around-Identity-and-Sha....
The following script demonstrates CSOM HTTP request header decoration. The script reads and prints the title of the given Web multiple times. Each iteration of the loop sleeps for one second to avoid SPO service throttling.
To avoid throttling, it’s best to format the User-Agent in accordance with our published guidance linked above. In addition to decorating HTTP traffic, adding Start-Sleep statements helps to ensure a steady-state request rate of 1 request per second. It may be helpful to pair ExecuteQuery calls with Start-Sleep -Milliseconds 1000 statements, especially if calling ExecuteQuery in a loop.