title: Rate limiting for Google/Firebase cloud functions?
body: <p>I am using Firebase to develop an app that uses Cloud Functions as a REST API internally. My question is, is there an easy way to implement per-IP/per-user rate-limiting similar to what <a href="https://api.slack.com/docs/rate-limits" rel="noreferrer">slack uses</a>, except on a <strong>per-IP</strong> <em>and</em> <strong>per-user</strong> basis, rather than per-app (since it's all one app). Optional support for small bursts is preferable as well.</p>
  <p>Example code (see the <code>// TODO:</code> comments):</p>
  <pre><code>exports.myCoolFunction = functions.https.onRequest((req, res) =&gt; {
          // TODO: implement IP rate-limiting here
          unpackToken(req).then((token) =&gt; { // unpackToken resolves with a response similar to verifyIdToken based on the &quot;Authorization&quot; header contents
                  // TODO: implement user-based rate-limiting here (based on token.uid)
                  if (!req.body) return res.status(400).end();
                  if (typeof req.body.name !== &quot;string&quot;) return res.status(400).end();
                  if (typeof req.body.user !== &quot;string&quot;) return res.status(400).end();
  
                  // more input sanitization and function logic here
  
                  return res.status(501).end(); // fallback in all requests, do not remove
          }).catch(() =&gt; res.status(403).end());
  });
  </code></pre>
  <p>I want to terminate the request simply with a <code>529 Too Many Requests</code> status code if the rate limit is exceeded. This is to prevent application errors from flooding the network and to prevent abuse of the REST API.</p>
  <blockquote>
  <p>This should take into account Firebase spinning up/down server instances and having multiple instances running simultaneously.</p>
  <p>I am also using a Firestore database and can use the legacy real-time database if necessary.</p>
  </blockquote>