title: Cloud Functions Http Request return cached Firebase database
body: <p>I'm new in Node.js and Cloud Functions for Firebase, I'll try to be specific for my question.</p>
  
  <p>I have a firebase-database with objects including a "score" field. I want the data to be retrieved based on that, and that can be done easily in client side.</p>
  
  <p>The issue is that, if the database gets to grow big, I'm worried that either it will take too long to return and/or will consume a lot of resources. That's why I was thinking of a http service using Cloud Functions to store a cache with the top N objects that will be updating itself when the score of any objects change with a listener.</p>
  
  <p>Then, client side just has to call something like <a href="https://myexampleprojectroute/givemethetoplevels" rel="nofollow noreferrer">https://myexampleprojectroute/givemethetoplevels</a> to receive a Json with the top N levels.</p>
  
  <p>Is it reasonable? If so, how can I approach that? Which structures do I need to use this cache, and how to return them in json format via http?</p>
  
  <p>At the moment I'll keep doing it client side but I'd really like to have that both for performance and learning purpose.</p>
  
  <p>Thanks in advance.</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p><strong>In the end I did not implement the optimization. The reason why is, first, that the firebase database does not contain a "child count" so I didn't find a way with my newbie javascript knowledge to implement that. Second, and most important, is that I'm pretty sure it won't scale up to millions, having at most 10K entries, and firebase has rules for sorted reading optimization. For more information please check out <a href="https://firebase.google.com/docs/database/security/indexing-data" rel="nofollow noreferrer">this link.</a></strong></p>
  
  <p>Also, I'll post a simple code snippet to retrieve data from your database via http request using cloud-functions in case someone is looking for it. Hope this helps!</p>
  
  <pre><code>// Simple Test function to retrieve a json object from the DB
  // Warning: No security methods are being used such authentication, request methods, etc
  exports.request_all_levels = functions.https.onRequest((req, res) =&gt; {
    const ref = admin.database().ref('CustomLevels');
    ref.once('value').then(function(snapshot) {
      res.status(200).send(JSON.stringify(snapshot.val()));
    });
  });
  </code></pre>