# One API key per customer environment: attribution, caps and rotation

> If you resell astrology features to several customers, a key per customer environment tells you who made which call and lets you cut one customer off without touching the others. It does not give each customer their own quota or plan - those stay per account - and this page is exact about which is which.

Source: https://astronode.dev/recipes/multi-tenant-api-keys · Updated: 2026-12-05

**What you build:** Per-customer routing, usage attribution and a per-customer cap, plus a key rotation with no failed requests (Node.js, Python)

## What is per key, and what is per account

*Behaviour as the API and dashboard implement it*

| Feature | Scope | Detail |
| --- | --- | --- |
| Named keys, `test` or `live` | Per key | Created in the dashboard (signed in); there is no API for creating keys. Live keys need a paid plan. |
| Per-minute rate limit | Per key | Each key has its own sliding 60-second window, so one customer's burst does not use another's minute. |
| Monthly quota | Per account | Billable calls (status below 400) from every key, test keys included, count against one quota. |
| Plan and endpoint access | Per account | Set by your subscription; you cannot give one key Starter endpoints and another Free. |
| `GET /v1/usage` | Per key, plus the account's quota | Today, month to date and `by_endpoint` for the calling key, billable calls only; also the account's `plan`, `quota` and `quota_used`. It is unmetered: reading it uses no quota. |
| Async reports, idempotency keys | Per key | A report is readable only with the key that started it - see [async report jobs](https://astronode.dev/recipes/async-report-jobs). |
| Rotate | Per key | Revokes the old key and issues a new one with the same name and env, under a new id. |
| Revoke (delete) | Per key | Takes effect on the key's next request, on every API server. |

So keys give you attribution and isolation of bursts, not separate allowances. The `test` / `live` choice changes the key's prefix (`aie_test_` / `aie_live_`) and nothing else: the same engine answers, and test calls count toward the same quota. There are no sub-accounts and no per-key caps on the platform; the cap below is code you run.

## Route each request through the customer's key

Name each key after the customer environment it serves (`acme-live`, `acme-staging`) when you create it, and keep the plaintext in your secret store - the dashboard shows it once. Your server picks the key from the tenant, counts that tenant's billable calls against a cap you set, and can ask the API for the per-key breakdown at any time:

tenants.mjs

```js
// tenants.mjs - one AstroNode key per customer environment, chosen server-side per request
const API = process.env.ASTRONODE_API_URL ?? "https://api.astronode.dev";

// Keys come from your secret store; one per customer environment, named after it in the dashboard.
const TENANTS = {
  "acme:live": { key: process.env.ASTRONODE_KEY_ACME_LIVE, monthlyCap: 4 },
  "globex:live": { key: process.env.ASTRONODE_KEY_GLOBEX_LIVE, monthlyCap: 20_000 },
  "acme:staging": { key: process.env.ASTRONODE_KEY_ACME_STAGING, monthlyCap: 500 },
};
const used = new Map(); // tenant -> billable calls this month (a counter in Redis or your DB)

export async function astronode(tenant, path, body) {
  const t = TENANTS[tenant];
  if (!t) throw new Error(`unknown tenant ${tenant}`);
  // The monthly quota is shared by every key on the account, so the per-customer cap is yours.
  if ((used.get(tenant) ?? 0) >= t.monthlyCap) return { status: 429, error: "TENANT_CAP_REACHED" };
  const res = await fetch(API + path, {
    method: body ? "POST" : "GET",
    headers: { authorization: `Bearer ${t.key}`, "content-type": "application/json" },
    body: body && JSON.stringify(body),
  });
  if (res.status < 400) used.set(tenant, (used.get(tenant) ?? 0) + 1); // only these are billed
  const json = await res.json();
  return res.ok ? { status: res.status, data: json.data } : { status: res.status, error: json.error.code };
}

// Per-key usage straight from the API: GET /v1/usage answers for the key that calls it.
export async function usageByTenant() {
  const rows = [];
  for (const [tenant, t] of Object.entries(TENANTS)) {
    const res = await fetch(`${API}/v1/usage`, { headers: { authorization: `Bearer ${t.key}` } });
    const { data } = await res.json();
    // month: this key's billable calls; account: the whole account's, which the quota is checked against.
    rows.push({ tenant, month: data.month_to_date.requests, account: data.month_to_date.quota_used, billable_here: used.get(tenant) ?? 0, by_endpoint: data.by_endpoint });
  }
  return rows;
}

// --- exercise it -------------------------------------------------------------------
const mumbai = { tz_offset_minutes: 330, lat: 19.076, lng: 72.8777 };
const days = ["2026-12-05", "2026-12-06", "2026-12-07", "2026-12-08", "2026-12-09"];
for (const [i, d] of days.entries()) {
  if (i === 2) console.log("acme:live    bad lat  ", (await astronode("acme:live", "/v1/panchang", { date: d, ...mumbai, lat: 95 })).error);
  const r = await astronode("acme:live", "/v1/panchang", { date: d, ...mumbai });
  console.log("acme:live    panchang", d, r.status, r.error ?? r.data.tithi.name);
}
for (const sign of ["Leo", "Virgo"]) console.log("globex:live  horoscope", sign, (await astronode("globex:live", `/v1/horoscope/daily/${sign}?date=2026-12-05`)).status);
console.log("acme:staging chart", (await astronode("acme:staging", "/v1/charts/birth", { date: "1990-01-01", time: "12:00:00", ...mumbai })).status);
for (const row of await usageByTenant()) console.log(JSON.stringify(row));
```

Output (three keys on one Starter account):

```text
acme:live    panchang 2026-12-05 200 Dwadashi
acme:live    panchang 2026-12-06 200 Trayodashi
acme:live    bad lat   VALIDATION_ERROR
acme:live    panchang 2026-12-07 200 Chaturdashi
acme:live    panchang 2026-12-08 200 Amavasya
acme:live    panchang 2026-12-09 429 TENANT_CAP_REACHED
globex:live  horoscope Leo 200
globex:live  horoscope Virgo 200
acme:staging chart 200
{"tenant":"acme:live","month":4,"account":7,"billable_here":4,"by_endpoint":{"/v1/panchang":4}}
{"tenant":"globex:live","month":2,"account":7,"billable_here":2,"by_endpoint":{"/v1/horoscope/daily/:sign":2}}
{"tenant":"acme:staging","month":1,"account":7,"billable_here":1,"by_endpoint":{"/v1/charts/birth":1}}
```

The fifth Acme request never reached the API: the tenant cap of 4 stopped it, which is the only thing that keeps one customer from spending the whole account's month. `GET /v1/usage` counts billable calls only, so Acme's `month` is 4: the `400` for `lat: 95` is not usage, here or in the quota. `account` is the same 7 from every key - the account's billable calls this month, the number the shared quota is checked against. Bill your customers from your own counter (or from statuses you log), and use `/v1/usage` for the per-key, per-endpoint picture and to reconcile.

## Rotate without a gap

The dashboard's **Rotate** button revokes the old key at the moment it issues the new one. Any server still holding the old key starts failing on its next request, before your deploy has necessarily finished. To rotate with no failed requests, do it in the other order: create a second key with the same name, deploy it, then delete the old one - and confirm the old one is really refused:

rotate_key.py

```python
# rotate_key.py - replace one customer's key without a window of failed requests
import os, time, urllib.error, urllib.request

API = os.environ.get("ASTRONODE_API_URL", "https://api.astronode.dev")
OLD, NEW = os.environ["OLD_KEY"], os.environ["NEW_KEY"]  # NEW: created in the dashboard, same name

def key_status(key):
    # GET /v1/usage is unmetered: checking a key this way costs no quota.
    req = urllib.request.Request(API + "/v1/usage", headers={"Authorization": "Bearer " + key})
    try:
        with urllib.request.urlopen(req) as r:
            return r.status
    except urllib.error.HTTPError as e:
        return e.code

t0 = time.time()
assert key_status(NEW) == 200, "new key does not authenticate - stop before switching"
print("new key: 200 - write it to the secret store and redeploy, then revoke the old key")
# ... your deploy step here; every instance must be on NEW before the next line matters ...
while True:
    s = key_status(OLD)
    print(f"[{time.time() - t0:3.0f}s] old key: {s}")
    if s == 401:
        break
    time.sleep(15)
print("old key refused everywhere this check can see; rotation done")
```

Output (the old key was revoked 3 seconds in):

```text
new key: 200 - write it to the secret store and redeploy, then revoke the old key
[  0s] old key: 200
[ 15s] old key: 401
old key refused everywhere this check can see; rotation done
```

The old key was refused at the first check after it was revoked; the 15 seconds is only the loop's interval. Until December 2026 a revoked key kept answering for up to a minute, because each API server cached a verified key; it no longer does. Checking with `GET /v1/usage` costs nothing, so the loop is free to run.

## Offboarding a customer

- **Read their usage first.** `GET /v1/usage` answers only for a working key; after revocation it is a [`401`](https://astronode.dev/docs/errors/unauthorized). Rotation also starts the new key's counts at zero, so map every key id that served a customer (the dashboard lists each key's prefix and name) to that customer in your own records.
- **Their calls still count this month.** Usage from a revoked key stays in the account's monthly total.
- **Their reports go with the key.** Reports are readable only by the key that created them, so fetch anything you owe the customer before deleting it.
- **Expect the security email.** Creating, rotating and revoking a key each send an email to the account owner, which is useful as an audit trail of who changed what.

## Questions

**What do I end up with?**

Per-customer routing, usage attribution and a per-customer cap, plus a key rotation with no failed requests. The code is in Node.js and Python.

**Which endpoints does this recipe call, and in what order?**

3 endpoints, in this order: Panchang (`POST /v1/panchang`), then Daily Sun Sign Horoscope (`GET /v1/horoscope/daily/:sign`), then Birth Chart (Kundli) (`POST /v1/charts/birth`).

## Endpoints, in call order

- [`POST /v1/panchang`](https://astronode.dev/capabilities/vedic/panchang) - Panchang API
- [`GET /v1/horoscope/daily/:sign`](https://astronode.dev/capabilities/western/horoscope-daily-sign) - Daily Sun Sign Horoscope API
- [`POST /v1/charts/birth`](https://astronode.dev/capabilities/vedic/charts-birth) - Birth Chart (Kundli) API
