Extending the Wait-Retry Pattern in Power Query

Share your love
Possible limitations on the number of simultaneous connections

Simultaneously, web services of any type, whether public or internal, often have RPS/RPM (Requests Per Second/ Requests Per Minute) limitations on the number of HTTP requests that can be sent to them from a single client. These limitations are implemented for several reasons, such as ensuring that the service can maintain high performance and availability for all users and protection against abusive behaviors such as denial-of-service attacks.

Therefore, if the client application sends multiple requests to the server simultaneously, and we know in advance the limitation on the number of sessions allocated to the client, we can apply the so-called “API throttling” technique. It involves deliberately pacing the client’s requests to stay within the rate limits of the web service we are interacting with. Instead of sending requests as fast as possible, we may send a ” batch” of requests, wait for some time, and then send another batch.

Implementation of a Simple API Throttling Strategy
  1. To add a request sequence number. While we can only control the “parallelism” of requests in Power Query to a limited extent, assigning an incremental number to each request allows us to distribute them into “deferred buckets.”
  2. Modify the “interval” function while preserving the exponential back-off algorithm for retrying a request with the same number. In my case, this is the calculated value of RequestDelay.

In addition, the original function ideally should include error handling mechanisms and server response logging.

Errors Handling and Logging

In addition to catching standard HTTP request error codes, the function implements handling and logging of the following types of errors:

  1. The remote server is unavailable.
  2. Incorrect connection parameters (host, port) or authentication credentials are provided.
  3. An incorrect authentication method is used.
  4. An HTTP request is sent when an encrypted HTTPS request is expected, and vice versa.
  5. The application server uses a self-signed certificate.
  6. The server received an incorrect HTTP request.

The result of executing (or failing to execute) a request is placed in the SysHttpRequestLog table. The number of execution attempts for each request type, a description and the reason for the error (if the request was not executed), as well as other service information, are logged.

Example of logging:

http requests logging

PQ Code

let func = (RequestContent as text, optional RawBody as text, optional RequstNo as nullable number) =>  
    let 
        //fn_checkRequestError Start
        fn_checkRequestError = (Response as nullable any, ServerResponse as nullable any) as record =>
            if Response[HasError]?
                then [HasError = Response[HasError]?, ErrorReason = Response[Error]?[Reason]?, ErrorMessage = Response[Error]?[Message]?, ErrorDetails = Response[Error]?[Details]?]
                else 
                    if ServerResponse[HasError]? 
                        then [ HasError = ServerResponse[HasError]?, ErrorReason = ServerResponse[Error]?[Reason]?, ErrorMessage = ServerResponse[Error]?[Message]?, ErrorDetails = ServerResponse[Error]?[Details]? ]
                        else if not ServerResponse[HasError] and ServerResponse[Value] = null
                        then [ HasError = true, ErrorReason = "Unknown", ErrorMessage = "Incorrect connection or authorization parameters may have been specified", ErrorDetails = null ]
                        else [ HasError = false, ErrorReason = null, ErrorMessage = null, ErrorDetails = null ],
        //fn_checkRequestError End

        //fn_trySendReques Start
        fn_trySendRequest = (AttemptNo as number, ResponseMetaData as table) =>
            let
                // Request parameteres
                NumberInPool = if (RequstNo = null) then 1 else RequstNo,  
                RequestDelay =  (Number.IntegerDivide(NumberInPool - 1, HttpRequestPool) + 1) * HttpRequestLatencySec * Number.Power(2, (AttemptNo - 1)) - HttpRequestLatencySec, // throttling
                                    
                // Request URL, headers, options
                // Avoiding a dynamic data source when updating on the Service
                Request = #"HTTP(S)://HOST:PORT" & PATH,
                Options = [
                        Headers = [
                                    #"Authorization" = AuthType & " " & Auth, 
                                    #"Content-Type" = "application/json;charset=utf-8",
                                    #"Cache-Control" = "no-cache, must-revalidate"
                        ],
                        RelativePath = RequestContent,
                        Content = Text.ToBinary(RawBody),
                        Timeout = #duration(0, 0, 0, HttpRequestTimeoutSec),
                        IsRetry = true,
                        ManualStatusHandling = 
                            {
                                200, 201, 202,                  // Success, record the request result  
                                408, 429, 503, 504, 509,        // Handled error, repeat the request, if failure again - record the request result
                                401, 403, 404                   // Handled error, record the request result  
                            }
                ], 

                //Send Request & BufferData
                SendRequest = Function.InvokeAfter( () => try Web.Contents(Request, Options), #duration(0, 0, 0, RequestDelay) ),

                BufferedData = SendRequest[[HasError]] & [Value = Binary.Buffer(SendRequest[Value])],  //avoid a risk of multple PQ calls     
                ResponseStatus = try Value.Metadata(SendRequest[Value]?)[Response.Status]?,

                Error = fn_checkRequestError(BufferedData, ResponseStatus),
                HttpResponseStatus = if ResponseStatus[HasError]? then null else ResponseStatus[Value], 
                RequestResponseTime = if HttpResponseStatus <> null then DateTime.LocalNow() else null, // avoid lazy evaluation
                AppendResponseMetaData = Table.InsertRows(    ResponseMetaData
                                                            , Table.RowCount(ResponseMetaData)
                                                            , {[  RequstNo = RequstNo
                                                                , RequestContent = RequestContent
                                                                , RequestBody = RawBody
                                                                , AttemptNo = AttemptNo
                                                                , RequestDelay = RequestDelay
                                                                , RequestResponseTime = RequestResponseTime
                                                                , HasConnectionError = Error[HasError]
                                                                , ConnectionErrorReason = Error[ErrorReason]
                                                                , ConnectionErrorMessage = Error[ErrorMessage]
                                                                , ConnectionErrorDetails = Error[ErrorDetails]
                                                                , HttpResponseStatus = HttpResponseStatus
                                                            ]}
                                                        ), 
                RequestResult = if (Error[HasError]) 
                then 
                    Record.AddField([], "@metadata", AppendResponseMetaData)
                else
                    let                                
                        HttpRequestResult = if (List.MatchesAny({408, 429, 503, 504, 509}, each _ = HttpResponseStatus) and AttemptNo < HttpRequestMaxAttempts)
                                        then
                                            @fn_trySendRequest(AttemptNo + 1, AppendResponseMetaData)                                                       // Repeat the request
                                        else 
                                            Record.AddField(try Json.Document(BufferedData[Value]) otherwise [], "@metadata", AppendResponseMetaData)       // Add @metadata field to the request result
                    in
                        HttpRequestResult
                in
                   RequestResult, 
        //fn_trySendReques End
        
        AuthType = "Basic",
        Auth = Binary.ToText(
                    Text.ToBinary(LOGIN & ":" & PASSWORD
                )               
                , BinaryEncoding.Base64), 
        
        HttpRequestPool = SettingsConfigDefault[HttpRequestPool], 
        HttpRequestLatencySec = SettingsConfigDefault[HttpRequestLatencySec],
        HttpRequestMaxAttempts = SettingsConfigDefault[HttpRequestMaxAttempts],
        HttpRequestTimeoutSec = SettingsConfigDefault[HttpRequestTimeoutSec],
        ResponseTable = fn_trySendRequest(1, #table(type table[
                                                                  RequstNo = number
                                                                , RequestContent = text
                                                                , RequestBody = text
                                                                , AttemptNo = number
                                                                , RequestDelay = number
                                                                , RequestResponseTime = datetime                                                                
                                                                , HasConnectionError = logical
                                                                , ConnectionErrorReason = text
                                                                , ConnectionErrorMessage = text
                                                                , ConnectionErrorDetails = text
                                                                , HttpResponseStatus = number
                                                            ], {}) )
    in
        ResponseTable,

    documentation = [
    Documentation.Name =  " fn_sendHttpRequest",
    Documentation.Description = " ",
    Documentation.LongDescription = " Managing HTTP requests",
    Documentation.Category = " Data extraction ",
    Documentation.Source = " ",
    Documentation.Version = " 1.82.bc ",
    Documentation.Author = " Alex Zaitsev ",
    Documentation.Examples = {[Description =  "",
    Code = " fn_sendHttpRequest( ""Users"", null, 1 ) ",
    Result = "A record in the format [ @odata.context as text, value as List, @metadata as Table ]"]}
    ]
in
    Value.ReplaceType(func, Value.ReplaceMetadata(Value.Type(func), documentation))
Share your love

19 Comments

Comments are closed.