1

I am working on a Swift project which requires a lot of consumption of APIs. Everything is working fine but sometimes, I get Code=-1001 "The request timed out." error while calling the API. To test it properly, I am using loop and iterating it for 1000 times, calling the same API.

I am using public API. The API is

let apiString = "https://oc-index.library.ubc.ca"

and my loop is

for i in 0 ..< 1000 {
    Alamofire.request(.POST, apiString).responseJSON { response in
        print(response.debugDescription)

        if response.result.isFailure {
            print("Failure")
        }
    }
}

Now while checking print responses, I see Latency is increased on every new api response and goes to 60.14 secs and finally the request timeouts. First time while calling API, the latency was 2.225 secs and the in timeline in logs, the latency of last successful API was 60.14 secs.

Timeline of API when it is being hit for the first time in the loop (when i = 1).

[Timeline]: Timeline: { "Request Start Time": 493671593.424, "Initial Response Time": 493671595.649, "Request Completed Time": 493671595.684, "Serialization Completed Time": 493671595.688, "Latency": 2.225 secs, "Request Duration": 2.260 secs, "Serialization Duration": 0.004 secs, "Total Duration": 2.264 secs }

Timeline of last successful API

[Timeline]: Timeline: { "Request Start Time": 493671593.859, "Initial Response Time": 493671621.500, "Request Completed Time": 493671621.513, "Serialization Completed Time": 493671621.519, "Latency": 60.140 secs, "Request Duration": 60.140 secs, "Serialization Duration": 0.007 secs, "Total Duration": 60.147 secs }

But if I execute it synchronously, there is no case of such timeouts. The API is called 1000 times and there is no case of Failure.

I don't understand why latency is increasing in such a way when I hit the API multiple time asynchronously. I know the error can be avoided by increasing timeout time. But I want to know the reason why it is happening at first place.

Any help would be appreciated.

Rahul Garg
  • 153
  • 1
  • 1
  • 12

1 Answers1

1

The networking stack will only allow a certain number of requests to execute simultaneously, and will block the issuance of new requests until some have completed. So, your 1000 requests are being started as soon as possible but the ones in the back need to wait for the ones in the front to finish before they can actually connect, hence the increasing amount of time.

See this thread for some details on how to deal with that situation: NSURLSession concurrent requests with Alamofire

Community
  • 1
  • 1
jlew
  • 10,491
  • 1
  • 35
  • 58