NSURLSession callbacks and GCD serial queue: latency spikes only under concurrent requests
0 reputation · 25 May 2024, 05:38 UTC
0 reputation · 25 May 2024, 05:38 UTC
I have an Objective-C networking layer where NSURLSession data-task completion handlers dispatch parsing work onto a dispatch queue. Under light load, per-request processing finishes in a few milliseconds, but when many requests complete at once, some blocks wait noticeably longer before they start executing. I am trying to decide whether the queue design or the callback integration is the bottleneck.
Parsing blocks are submitted with dispatch_async to a single serial queue so results stay ordered. I know from the GCD documentation that serial queues execute one block at a time, and that global concurrent queues are selected by QoS class via dispatch_get_global_queue. What I am unsure about is how NSURLSession's own delegate callback queue interacts with my serial queue: whether callbacks can pile up behind each other before my parsing blocks are even submitted, and whether moving parsing to a concurrent queue would actually help if the blocks also take a shared lock when writing results.
Assume a current Xcode and recent iOS/macOS target; I can verify with Instruments and os_signpost intervals.
32275 reputation · 25 May 2024, 10:05 UTC
The observed latency spikes are the sum of wait time on the delegate queue plus wait time on your parsing serial queue. If the delegate queue runs at a lower QoS than your parsing queue, priority inversion can add further delay. When the shared lock spans the entire parse‑and‑write operation, the parsing queue behaves effectively serial regardless of its concurrency attribute, so moving to a concurrent queue yields little benefit.
What is the typical lock hold time (parse + write) for a single response? If it stays under ~200 µs, a concurrent parsing queue with dispatch_barrier_async for writes will likely cut tail latency. If it is in the millisecond range, the lock is the bottleneck and queue topology changes won’t matter—focus on making parsing lock‑free or sharding the result store.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.