Discussion of Alamofire Best Practices

While many best practices for Alamofire depend on the server you're communicating with, there are some which are generally applicable. This thread attempts to document some of these, with the intention of eventually adding a summary to Alamofire's documentation.

  1. URLSession best practices apply to Alamofire too! Since an Alamofire SessionManager wraps a URLSession, you can treat a SessionManager like a URLSession. This means:
    • You should never create one SessionManager per request. A general rule is to have one SessionManager per host, if possible. At most, one SessionManager per unique host configuration is a good limit. This prevents duplication of resources and allows the system to optimize URLSession usage.
    • While you can increase the number of simultaneous URLSessionTasks in flight at once by increasing the URLSessionConfiguration.httpMaximumConnectionsPerHost value before initializing your SessionManager, it's not usually necessary or a good idea. Since URLSesssion's delegateQueue is serial, there is a limit to the amount of benefit that can buy you, and URLSession may have undocumented maximums that you'll run into regardless of this value.
  2. Be careful how many Alamofire Requests you enqueue at once. Enqueuing more than a few dozen at a time can negatively impact system performance, as each Alamofire Request has it's own internal DispatchQueue, so trying to enqueue thousands at a time can lead to system resource contention and your app being killed by the system watchdog. This issue will be fixed in Alamofire 5, which redoes Alamofire's queue usage to better follow recommended best practices.
  3. Embrace Alamofire's generics and our URLRequestConvertible protocol, as it can form the basis of a powerful system to let you easily convert from Swift types to network requests. Even something as simple as the Router outlined in our documentation can make network layers much less code intensive by requiring only the bare minimum of configuration per request. It also lets you build more reusable components that you plug only the definition of your API and types into, much like Moya does.

What other best practices would be good to include in our documentation?