# Add Rate Limiting to Firebase Callable Functions

Yes. An agent adds a per-user limit to your Firebase callable function with a Realtime Database transaction and App Check, tests it in the emulator, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-rate-limiting/firebase-functions/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads what the function already knows about its caller. In a project laid out like the `callable-functions` quickstart under `Node/quickstarts` in firebase/functions-samples, `functions/index.js` exports two second-generation callables from `firebase-functions/https`: `addnumbers`, which takes two numbers and needs no sign-in, and `addmessage`, which rejects a call without `request.auth` with a `failed-precondition` `HttpsError`, reads `request.auth.uid`, runs the text through `sanitizer.js` and the `bad-words` package, and pushes to `/messages` in the Realtime Database through `firebase-admin/database`. `functions/package.json` pins `firebase-functions` at `^7.4.0` and `firebase-admin` at `^14.5.0` on Node 24, lists `firebase-functions-test` as a dev dependency with no test file using it, and `firebase.json` names the codebase `callable-functions` with a lint predeploy. Nothing counts calls per user, and nothing asks the client for an App Check token.

It then reads how the repository checks itself. The root `.github/workflows/test_node.yml` runs `lint-2nd-gen`, `compile-2nd-gen` and `test-2nd-gen` across every `Node/**` package with pnpm, `pnpm-workspace.yaml` sets `minimumReleaseAge: 4320`, and the sample's `eslint.config.js` applies the Google config, so the new code has to pass that style. There is no `database.rules.json` in the sample, which matters for where the counters live, and the agent says so rather than inventing one.

The limit goes where the identity already is. `addmessage` gains a fixed window: a `rateLimits/{uid}/addmessage` node holds `windowStart` and `count`, a `ref.transaction` resets the window when a minute has passed and increments otherwise, and a count past the limit throws `HttpsError('resource-exhausted', ...)` with the seconds until the window ends in the message, so the client SDK surfaces a typed error. The transaction runs on the same database the function already writes to, through the Admin SDK, which bypasses security rules; the agent adds a note that client rules must deny reads and writes under `rateLimits` once a rules file exists. The `onCall` options gain `enforceAppCheck: true` and `consumeAppCheckToken: true` on `addmessage`, so each call carries a limited-use App Check token that cannot be replayed, and a `maxInstances` cap bounds what a burst can cost. `addnumbers` has no caller identity and is left as it is, with the description saying why. The limit and window are module constants with a comment.

In its sandbox the agent installs the Firebase CLI and Java for the database emulator, writes `functions/index.test.js` with `firebase-functions-test` that wraps `addmessage`, calls it eleven times as one `uid` and once as another, and asserts the eleventh answers `resource-exhausted` while the other user's call succeeds, then runs it under `firebase emulators:exec --only database`. It runs `npm run lint` in the sample and the root `pnpm` lint and compile scripts the workflow runs, and keeps all of it.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add rate limiting to the callable functions in this Firebase project. Read functions/index.js, functions/sanitizer.js, functions/package.json, functions/eslint.config.js, firebase.json, the root package.json, pnpm-workspace.yaml and .github/workflows/test_node.yml first. For the authenticated callable, add a per-user fixed window stored under a rateLimits node in the Realtime Database the function already uses, updated with a transaction, with the limit and window as named constants, and throw a resource-exhausted HttpsError that says when the window resets. Turn on App Check enforcement with limited-use token consumption on that function and set a maxInstances cap. Leave the unauthenticated callable alone and explain why in the pull request. Add a note about security rules for the rateLimits node, since the sample has no rules file. Write a test with firebase-functions-test that calls the function past the limit as one user and once as another, run it with the database emulator, and run the lint and compile scripts the CI workflow runs. Open a pull request that pastes the test output and the lint result. Do not add a dependency for the limiter.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request changes `functions/index.js` and adds `functions/index.test.js` with a `test` script in `functions/package.json`, and nothing else; no package is added, since the transaction uses the Admin SDK already present. Its description pastes the emulator test output, with the eleventh call rejected as `resource-exhausted` and the second user's call accepted, and the lint and compile results from the sample and from the root scripts.

A paragraph gives the shape of a `rateLimits/{uid}/addmessage` node after the run, explains that a fixed window needs no cleanup job because the next call after the window resets the node, and sets out why `addnumbers` is unchanged: it has no `request.auth`, so a counter would have to key on an address, and the sample's point is a function without sign-in.

Before merging, a reviewer picks the limit and window for real traffic, decides whether the counters should move to Firestore if the project's data lives there, checks that the web client passes `limitedUseAppCheckTokens: true` so enforcement does not lock it out, and adds the rules for `rateLimits` to the project's rules file.

## Run it on every Linear issue labelled abuse

In the Project that holds the functions, add an automation with this prompt and a `linear` trigger on `linear.issue.labeled` filtered to the `abuse` label. Each labelled issue starts one run in its own sandbox and ends in one pull request; the issue's text follows the prompt as data, so an issue naming a different function, a stricter window or a Firestore counter makes its own change. Changes made by an app integration never fire the trigger, so the agent's comment on the issue starts no further run.

From your own server the same run is one `POST /o/{org}/sessions` per issue, with the repository in `resources` and the issue's `https://linear.app/<workspace>/issue/<ID>` URL there too, so Rush reads it through your Linear connection into the prompt. A `webhook_url` on the key reports `run.completed` or `run.failed` with the `session_url` when the turn finishes.

## Why run it on Rush?

A rate limit written without running it tends to fail in one of two ways: it never fires, or it fires for everyone. The agent's sandbox installs the Firebase CLI and the Java runtime the database emulator needs, wraps the function with the test package the sample already lists, and calls it past the limit as two different users, so the pull request shows the eleventh call rejected and the other user untouched.

The design comes from this repository: the database the function already writes to, the `uid` it already reads, the typed error the client SDK already handles, and the CI scripts the root workflow runs. The emulator output and the lint result stay with the run, and the same prompt runs against every Firebase project a team owns.

## Frequently asked questions

### Why count in the Realtime Database rather than memory?

A second-generation function can run on several instances at once, and each instance has its own memory, so an in-memory counter undercounts. The transaction on `rateLimits/{uid}/addmessage` is atomic across instances and uses the database `addmessage` already writes to, so nothing new is provisioned.

### What does the client see when the limit is hit?

An `HttpsError` with code `resource-exhausted` and a message naming the seconds until the window resets, which the Functions client SDKs surface as a typed error like the sample's existing `invalid-argument` and `failed-precondition` cases. The description shows the message from the emulator run.

### Does App Check break existing clients?

With `enforceAppCheck: true`, a call without a valid token is rejected, and with `consumeAppCheckToken: true` the web client must request limited-use tokens with `limitedUseAppCheckTokens: true` on `httpsCallable`. The pull request names both client-side changes and leaves the option off on `addnumbers`.

### Why is addnumbers not limited?

It accepts calls with no sign-in, so there is no `uid` to count against, and keying on an address behind Cloud Run's proxies is unreliable. The description says so and suggests App Check enforcement as the lever for that function if abuse appears.

## More Firebase Functions jobs

- [Turn On Safe Retries for Event-Driven Firebase Cloud Functions](https://getrush.ai/run/add-retry-policies/firebase-functions/)
- [Convert Firebase Cloud Functions From JavaScript to TypeScript](https://getrush.ai/run/convert-javascript-to-typescript/firebase-functions/)
- [Move Firebase Functions From process.env to Params and Secrets](https://getrush.ai/run/migrate-to-params/firebase-functions/)

## The same job on other stacks

- [Add Rate Limiting to a Flask API](https://getrush.ai/run/add-rate-limiting/flask/)
- [Add Rate Limiting to a Gin API](https://getrush.ai/run/add-rate-limiting/gin/)
- [Add Rate Limiting to a grammY Telegram Bot](https://getrush.ai/run/add-rate-limiting/grammy/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
