I wrote a simple (I thought...) rate limiter to keep an event driven system under our licensed API hit limits. For some reason it seizes up sometimes after 400-500 requests are sent through.
My best idea is that I have screwed up the wait function so in some circumstances it never returns, but I have been unable to locate the flawed logic. Another idea is that I have botched the Async/Task interop causing issues. It always works initially and then later. A single instance of ApiRateLimiter
is being shared across several components in order to honor hit limits system wide.
type RequestWithReplyChannel = RequestWithKey * AsyncReplyChannel<ResponseWithKey>
type public ApiRateLimiter(httpClient: HttpClient, limitTimePeriod: TimeSpan, limitCount: int) =
let requestLimit = Math.Max(limitCount,1)
let agent = MailboxProcessor<RequestWithReplyChannel>.Start(fun inbox ->
let rec waitUntilUnderLimit (recentRequestsTimeSent: seq<DateTimeOffset>) = async{
let cutoffTime = DateTimeOffset.UtcNow.Subtract limitTimePeriod
let requestsWithinLimit =
recentRequestsTimeSent
|> Seq.filter(fun x -> x >= cutoffTime)
|> Seq.toList
if requestsWithinLimit.Length >= requestLimit then
let! _ = Async.Sleep 100 //sleep for 100 milliseconds and check request limit again
return! waitUntilUnderLimit requestsWithinLimit
else
return requestsWithinLimit
}
let rec messageLoop (mostRecentRequestsTimeSent: seq<DateTimeOffset>) = async{
// read a message
let! keyedRequest,replyChannel = inbox.Receive()
// wait until we are under our rate limit
let! remainingRecentRequests = waitUntilUnderLimit mostRecentRequestsTimeSent
let rightNow = DateTimeOffset.UtcNow
let! response =
keyedRequest.Request
|> httpClient.SendAsync
|> Async.AwaitTask
replyChannel.Reply { Key = keyedRequest.Key; Response = response }
return! messageLoop (seq {
yield rightNow
yield! remainingRecentRequests
})
}
// start the loop
messageLoop (Seq.empty<DateTimeOffset>)
)
member this.QueueApiRequest keyedRequest =
async {
return! agent.PostAndAsyncReply(fun replyChannel -> (keyedRequest,replyChannel))
} |> Async.StartAsTask
Some of the requests are large and take a little bit of time, but nothing that could cause the total death of request sending that I am seeing with this thing.
Thanks for taking a second to look!