Rate Limiting on iOS

Aryaman Sharda
2 min readOct 31, 2022
Photo by Chris Liverani on Unsplash

Whenever you enter an address into Google Maps or search for a video on YouTube, you may have noticed that the auto-complete suggestions update at regular intervals rather than with every change to the search query.

When you consider the scale of these platforms, limiting requests in this manner is a necessary optimization. This helps prevent unnecessary HTTP requests while still ensuring a smooth user experience.

Today, we’ll look at a simple implementation you can use to replicate this behavior in your applications.

Let’s continue with our auto-complete suggestions use case and imagine we have a function that makes an asynchronous HTTP request and returns an updated list of suggestions:

func getAutocompleteSuggestions(from query: String,
completion: (([String]) -> Void)?)

Ideally, we would like to be able to call this function directly within the delegate callback of our searchBar or textField and have some other mechanism that guarantees the request fires only once every X seconds.

Implementation

We can create the following ThrottleExecution utility to handle these requirements:

struct ThrottleExecution {

private static var previousExecution = Date.distantPast

static func

--

--

Aryaman Sharda

Staff iOS Engineer @ Turo. Previously, Scoop Technologies & Porsche Digital