title: Firebase Database Slow Observing
body: <p>When observing a FIRDatabaseQuery with the observe method, it sometimes takes 10~13 seconds to get the data from the remote database. This mostly happens when the app is coming from the background or when it has just started up. After this query has completed, subsequent queries are returning super fast with remote data. And the problem doesn't occur anymore.</p>
  
  <p>This is the code I am using to observe:</p>
  
  <pre><code>public static func observeMatchEvents(match: Match) -&gt; QueryObserver
  {
      FIRDatabase.database().reference().child("events").queryOrdered(byChild: "match_id").queryEqual(toValue: match.identifier)
  
      log.debug("Started getting match events...")
      let observer = query.observe(FIRDataEventType.value, with: { (snapshot) in
         log.debug("This sometimes takes 10~13 seconds before it gets executed")
      // Handle data
      })
  
      return QueryObserver(query: query, handle: observer)
  }
  </code></pre>
  
  <p>This is the structure I have in my Firebase Database:</p>
  
  <p><img src="https://i.stack.imgur.com/R4b73.png" alt="Firebase Database Structure"></p>
  
  <p>Where events is a child of the root of the database.</p>
  
  <p>I am using Firebase Rules to improve the indexing as described in the documentation:</p>
  
  <pre><code>"events": {
          ".indexOn": ["match_id", "type", "sub_type"]
      }
  </code></pre>
  
  <p>I am thinking this has something to do with sockets having to be opened upon startup. However 10~13 seconds takes really long. Is anyone else experiencing this behaviour and does someone have an idea to speed this up?</p>
  
  <p>EDIT:
  So after trying the suggestions posted here and trying other things I finally found a solution. There were actually two problems:</p>
  
  <p>1) The slowdown occured when I started observing too queries at the same time. As the amount of data was pretty huge it took a subsequent long time to complete those observe calls. This was also visible in the timeprofiler where you would see that the CPU load at this time was pretty huge.</p>
  
  <p>2) Something that I found out that is more troubling is that was setting FIRDatabase.database().persistenceEnabled = true dramatically increased callback time from queries. When doing a clean install of the app and getting data from Firebase it was really fast. However the response times would increase everytime the Firebase Database would write more data to disk, this was increasing over 10 ms per request. This way the app would eventually take up to 10 seconds to complete a request to the database. We noticed this same behaviour for our Android app aswell. The only solution here was to disabled persistence on the database entirely.</p>