Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(api): per-company API rate limit override

Claudef52b28178aeb
diff --git a/.claude/rules/authentication-system.md b/.claude/rules/authentication-system.md
index c578a4e6ad..3a4b6d35df 100644
--- a/.claude/rules/authentication-system.md
+++ b/.claude/rules/authentication-system.md
@@ -420,12 +420,24 @@ writer is the 30s TTL. Then:
- Rate-limit via `checkApiKeyRateLimit` (`@carbon/database/ratelimit`, Postgres function
`check_api_key_rate_limit`) using per-key `rateLimit` + `rateLimitWindow`
(`"1m"|"1h"|"1d"`). 429 with `X-RateLimit-*` + `Retry-After` headers on exceed.
- The same function also holds a company to **60/minute across all its keys** (constant
- in the function, migration `20261002153217`): it sums the keys' counters for the
- current minute, each capped at its own limit so requests refused on one key do not
- lock out the others. No separate table — so deleting a key drops its share, and a key
- on an hourly/daily window is not counted (none exist). A company refusal returns
- `limit: 60`. Pinned by `supabase/tests/api-key-rate-limit.test.sql`.
+ The same function also holds a company to a per-minute total across all its keys:
+ `companyPlan.apiRateLimit`, or **60** when that is NULL or the company has no
+ `companyPlan` row (`v_default_company_limit`, migration `20261015143857`). It sums the
+ keys' counters for the current minute, each capped at its own limit so requests refused
+ on one key do not lock out the others. No separate table — so deleting a key drops its
+ share, and a key on an hourly/daily window is not counted (none exist). A company
+ refusal returns the company's limit as `limit`. Pinned by
+ `supabase/tests/api-key-rate-limit.test.sql`.
+- **Raising a limit is a support operation, not a setting.** One key: `apiKey.rateLimit`
+ (tenants with `settings_update` can also write it through the Data API, so the company
+ total is the real ceiling). A company: `companyPlan.apiRateLimit`, which only the
+ service role writes (the table has a SELECT policy and no other) and which company
+ backups never carry. A key's limit above its company's total is capped by the total.
+ Both are read per request through the 30s key cache. Only a company with a
+ `companyPlan` row (every paying Cloud company) can be given an override: do not insert
+ one just for this, since `company-cleanup` treats a plan row as a paying company. The
+ Stripe `customer.subscription.deleted` webhook deletes the row, override included;
+ the subscription sync upserts named columns only, so a plan change keeps it.
- `lastUsedAt` is written by `check_api_key_rate_limit` itself, at most once a minute per
key, so the Node path and the edge functions both record it. (The app used to build
this update with `void client.from(…).update(…)`, which never sends: a supabase-js
diff --git a/docs/app/api/data/authentication/page.tsx b/docs/app/api/data/authentication/page.tsx
index d4b5452d93..f885e399cd 100644
--- a/docs/app/api/data/authentication/page.tsx
+++ b/docs/app/api/data/authentication/page.tsx
@@ -195,7 +195,7 @@ export default async function AuthenticationPage() {
cols="72px 1fr"
cells={[
<Code key="c">429</Code>,
- "Rate limit exceeded — every key allows 60 requests per minute by default, a platform-set limit shown (not editable) in Settings → API Keys. Back off and retry per the X-RateLimit-* and Retry-After response headers."
+ "Rate limit exceeded — a new key allows 20 requests per minute (shown, not editable, in Settings → API Keys) and all of a company's keys share 60 per minute. Back off and retry per the X-RateLimit-* and Retry-After response headers; contact Carbon support to raise either limit."
]}
/>
</Table>
diff --git a/docs/app/api/mcp/page.tsx b/docs/app/api/mcp/page.tsx
index bd9a65a7a5..fa6808e79c 100644
--- a/docs/app/api/mcp/page.tsx
+++ b/docs/app/api/mcp/page.tsx
@@ -83,7 +83,7 @@ const FAQ: FaqEntry[] = [
},
{
q: "Is there a rate limit?",
- a: "Each key has its own limit and window — 60 requests per minute by default. It's platform-controlled: the Rate Limit column in Settings → API Keys shows the limit in force, but there's no field to change it. Go over it and calls return 429 with X-RateLimit-* and Retry-After headers telling the client when to retry."
+ a: "Each key has its own limit — 20 requests per minute for a new key, shown in the Rate Limit column in Settings → API Keys — and all of a company's keys share 60 requests per minute. Both are platform-controlled, with no field to change them; contact Carbon support to raise them for your company. Go over either and calls return 429 with X-RateLimit-* and Retry-After headers telling the client when to retry."
},
{
q: "I'm getting 401 Unauthorized",
diff --git a/docs/content/docs/building/api-keys.mdx b/docs/content/docs/building/api-keys.mdx
index cf24b07c44..f8049748dd 100644
--- a/docs/content/docs/building/api-keys.mdx
+++ b/docs/content/docs/building/api-keys.mdx
@@ -39,7 +39,7 @@ API keys require no login or refresh flow. Carbon hashes each submitted key and
A key has only its stored `module_action` scopes, such as `sales_view` or `inventory_create`, and can access only its company. A key with no scopes can authenticate but cannot read or write data. Scope changes and deletion take effect immediately. On Carbon Cloud, API access requires the **Business** plan; Starter-plan requests return `403` regardless of scope. See [Licensing](/docs/platform/licensing).
-New keys allow **20 requests per minute**. Existing keys retain the rate limit shown in the **Rate Limit** column. All keys for a company share a separate limit of **60 requests per minute**. Neither limit is configurable. A rejected request returns `429` with `Retry-After` and `X-RateLimit-*` headers; retry after the specified interval.
+New keys allow **20 requests per minute**. Existing keys retain the rate limit shown in the **Rate Limit** column. All keys for a company share a separate limit of **60 requests per minute**. Neither limit can be changed in Carbon. If an integration needs more, contact Carbon support: both limits can be raised for one company. A rejected request returns `429` with `Retry-After` and `X-RateLimit-*` headers; retry after the specified interval.
## What the key unlocks
@@ -67,7 +67,7 @@ An **API key** authorizes requests to Carbon. A **[webhook](/docs/building/webho
<AgentContext>
## Internals and troubleshooting
-Key format is `crbn_` + random token; storage is SHA-256 hash + last-five preview. `insertApiKey`/`updateApiKey` strip rate-limit columns from any submission (`settings.service.ts:1282`). The 429 response headers come from `packages/auth/src/services/auth.server.ts:255`.
+Key format is `crbn_` + random token; storage is SHA-256 hash + last-five preview. `upsertApiKey` strips rate-limit columns from any submission (`packages/ee/src/api-keys.server.ts`). The 429 response headers come from `packages/auth/src/services/auth.server.ts:255`.
### "API key lacks required permissions"
The call needs a `module_action` scope the key doesn't carry — checked per request against the key's record (`packages/auth/src/services/auth.server.ts:295`), never the creator's permissions. Add the exact scope in the permission matrix; it applies immediately.
@@ -76,7 +76,7 @@ The call needs a `module_action` scope the key doesn't carry — checked per req
On Carbon Cloud, API access is Business-tier: the key path blocks Starter-plan companies outright (`packages/auth/src/services/auth.server.ts:312-330`). Upgrade the plan; the key itself is fine. A 403 on a single operation is the scope problem above instead. Connectors (OAuth) hit the same plan gate through the identity they inherit.
### "Rate limit exceeded"
-Over the key's per-minute limit, or over the company's 60/minute total across its keys; `X-RateLimit-Limit` carries the limit that refused it (`auth.server.ts:249`). Platform-controlled, no field to raise it. Honor `Retry-After`; if the ceiling is genuinely too tight, batch reads (PostgREST `in.(...)` filters, embedded relations) or talk to us.
+Over the key's per-minute limit, or over the company's total across its keys (60/minute unless `companyPlan.apiRateLimit` is set); `X-RateLimit-Limit` carries the limit that refused it (`auth.server.ts:249`). Platform-controlled, with no field in the app: support raises one key with `apiKey.rateLimit` and the company total with `companyPlan.apiRateLimit`, and a key above its company's total is still capped by it. Honor `Retry-After`; if the ceiling is genuinely too tight, batch reads (PostgREST `in.(...)` filters, embedded relations) or talk to us.
### "API key has expired"
`expiresAt` is in the past (`auth.server.ts:227`). Expiry can't be extended on a used key — create a new one and swap it in.
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index b6d77dc365..e06ad9d2db 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -68010,6 +68010,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companyPlan.updatedAt"
},
+ {
+ $ref: "#/parameters/rowFilter.companyPlan.apiRateLimit"
+ },
{
$ref: "#/parameters/select"
},
@@ -68105,6 +68108,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companyPlan.updatedAt"
},
+ {
+ $ref: "#/parameters/rowFilter.companyPlan.apiRateLimit"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -68154,6 +68160,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companyPlan.updatedAt"
},
+ {
+ $ref: "#/parameters/rowFilter.companyPlan.apiRateLimit"
+ },
{
$ref: "#/parameters/body.companyPlan"
},
@@ -149849,6 +149858,12 @@ export default {
default: "now()",
format: "timestamp with time zone",
type: "string"
+ },
+ apiRateLimit: {
+ description:
+ "Requests per minute across all of the company's API keys. NULL is the platform default (60).",
+ format: "integer",
+ type: "integer"
}
},
type: "object"
@@ -203453,6 +203468,14 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.companyPlan.apiRateLimit": {
+ name: "apiRateLimit",
+ description:
+ "Requests per minute across all of the company's API keys. NULL is the platform default (60).",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.approvalRequest": {
name: "approvalRequest",
description: "approvalRequest",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 59a9fb40cb..f5a4b1ce0c 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -8233,6 +8233,7 @@ export type Database = {
companyPlan: {
Row: {
aiTokensLimit: number
+ apiRateLimit: number | null
createdAt: string
id: string
planId: string
@@ -8247,6 +8248,7 @@ export type Database = {
}
Insert: {
aiTokensLimit?: number
+ apiRateLimit?: number | null
createdAt?: string
id?: string
planId: string
@@ -8261,6 +8263,7 @@ export type Database = {
}
Update: {
aiTokensLimit?: number
+ apiRateLimit?: number | null
createdAt?: string
id?: string
planId?: string
diff --git a/packages/database/supabase/migrations/20261015143857_api-company-rate-limit-override.sql b/packages/database/supabase/migrations/20261015143857_api-company-rate-limit-override.sql
new file mode 100644
index 0000000000..11dd296418
--- /dev/null
+++ b/packages/database/supabase/migrations/20261015143857_api-company-rate-limit-override.sql
@@ -0,0 +1,121 @@
+-- A company's API keys together were held to a fixed 60 requests per minute.
+-- `companyPlan."apiRateLimit"` now overrides that for one company. It lives on
+-- companyPlan because only the platform writes that table: tenants have a
+-- SELECT policy and no other, and company backups never carry it. NULL keeps
+-- the platform default, so changing the default later needs no backfill.
+
+ALTER TABLE "companyPlan" ADD COLUMN "apiRateLimit" INTEGER;
+
+ALTER TABLE "companyPlan" ADD CONSTRAINT "companyPlan_apiRateLimit_positive"
+ CHECK ("apiRateLimit" > 0);
+
+COMMENT ON COLUMN "companyPlan"."apiRateLimit" IS
+ 'Requests per minute across all of the company''s API keys. NULL is the platform default (60).';
+
+-- Same signature and return shape as 20261002153217, so the Node
+-- `requirePermissions` path and the edge functions need no code change. The
+-- only change is where the company limit comes from.
+CREATE OR REPLACE FUNCTION check_api_key_rate_limit(
+ p_api_key_id TEXT,
+ p_limit INTEGER,
+ p_window TEXT -- '1m', '1h', '1d'
+) RETURNS JSONB
+LANGUAGE plpgsql
+SECURITY INVOKER
+SET search_path = public
+AS $$
+DECLARE
+ -- Requests per minute across all of one company's keys, unless its
+ -- companyPlan row sets "apiRateLimit".
+ v_default_company_limit CONSTANT INTEGER := 60;
+ v_minute CONSTANT TIMESTAMPTZ := date_trunc('minute', NOW());
+ v_window_start TIMESTAMPTZ;
+ v_interval INTERVAL;
+ v_count INTEGER;
+ v_company_id TEXT;
+ v_company_limit INTEGER;
+ v_company_count INTEGER;
+BEGIN
+ v_interval := CASE p_window
+ WHEN '1m' THEN INTERVAL '1 minute'
+ WHEN '1h' THEN INTERVAL '1 hour'
+ WHEN '1d' THEN INTERVAL '1 day'
+ ELSE INTERVAL '1 hour'
+ END;
+
+ v_window_start := date_trunc(
+ CASE p_window
+ WHEN '1m' THEN 'minute'
+ WHEN '1h' THEN 'hour'
+ WHEN '1d' THEN 'day'
+ ELSE 'hour'
+ END,
+ NOW()
+ );
+
+ -- Atomic upsert: insert or increment counter in one statement
+ INSERT INTO "apiKeyRateLimit" ("apiKeyId", "windowStart", "requestCount")
+ VALUES (p_api_key_id, v_window_start, 1)
+ ON CONFLICT ("apiKeyId", "windowStart")
+ DO UPDATE SET "requestCount" = "apiKeyRateLimit"."requestCount" + 1
+ RETURNING "requestCount" INTO v_count;
+
+ -- Every API-key request passes through here, on the Node path and in the edge
+ -- functions, so this is the one place that records use. At most one write per
+ -- key per minute.
+ UPDATE "apiKey" SET "lastUsedAt" = NOW()
+ WHERE "id" = p_api_key_id
+ AND ("lastUsedAt" IS NULL OR "lastUsedAt" < v_minute);
+
+ -- A company with no companyPlan row (self-hosted, or Carbon-owned on Cloud)
+ -- gets the default.
+ SELECT k."companyId", COALESCE(p."apiRateLimit", v_default_company_limit)
+ INTO v_company_id, v_company_limit
+ FROM "apiKey" k
+ LEFT JOIN "companyPlan" p ON p."id" = k."companyId"
+ WHERE k."id" = p_api_key_id;
+
+ -- Probabilistic cleanup: ~1% of requests clean up expired windows
+ IF random() < 0.01 THEN
+ DELETE FROM "apiKeyRateLimit"
+ WHERE "apiKeyId" = p_api_key_id
+ AND "windowStart" < v_window_start;
+ END IF;
+
+ -- The company total is the sum of its keys' counters for this minute, so it
+ -- needs no table of its own. Each key counts up to its own limit only: a
+ -- counter keeps rising while its key is being refused, and those refused
+ -- requests must not lock the company's other keys out.
+ -- Two known ceilings, both fixed by a dedicated per-company counter table:
+ -- deleting a key drops its share of the total (the counters cascade), and a
+ -- key on an hourly or daily window is not counted (none exist: the window is
+ -- platform-controlled and every key is '1m').
+ SELECT COALESCE(SUM(LEAST(r."requestCount", k."rateLimit")), 0)
+ INTO v_company_count
+ FROM "apiKey" k
+ JOIN "apiKeyRateLimit" r
+ ON r."apiKeyId" = k."id" AND r."windowStart" = v_minute
+ WHERE k."companyId" = v_company_id;
+
+ IF v_count <= p_limit AND v_company_count > v_company_limit THEN
+ RETURN jsonb_build_object(
+ 'success', false,
+ 'count', v_company_count,
+ 'limit', v_company_limit,
+ 'remaining', 0,
+ 'resetAt', EXTRACT(EPOCH FROM (v_minute + INTERVAL '1 minute'))::BIGINT * 1000
+ );
+ END IF;
+
+ RETURN jsonb_build_object(
+ 'success', v_count <= p_limit,
+ 'count', v_count,
+ 'limit', p_limit,
+ 'remaining', GREATEST(
+ LEAST(p_limit - v_count, v_company_limit - v_company_count),
+ 0
+ ),
+ 'resetAt', EXTRACT(EPOCH FROM (v_window_start + v_interval))::BIGINT * 1000
+ );
+END;
+$$;
diff --git a/packages/database/supabase/tests/api-key-rate-limit.test.sql b/packages/database/supabase/tests/api-key-rate-limit.test.sql
index a3ddbada43..ccd92a3442 100644
--- a/packages/database/supabase/tests/api-key-rate-limit.test.sql
+++ b/packages/database/supabase/tests/api-key-rate-limit.test.sql
@@ -1,5 +1,5 @@
--- check_api_key_rate_limit: the per-key limit, the per-company limit across keys,
--- and the lastUsedAt it records.
+-- check_api_key_rate_limit: the per-key limit, the per-company limit across keys
+-- (and a company's companyPlan override of it), and the lastUsedAt it records.
-- Run from the repository root against an existing local database:
-- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/api-key-rate-limit.test.sql
-- All fixtures are confined to the rolled-back transaction. NOW() is the
@@ -38,8 +38,8 @@ $fn$;
DO $proof$
DECLARE
- group_id text; company_a text; company_b text; company_c text;
- a1 text; a2 text; a3 text; a4 text; b1 text; b2 text; c1 text;
+ group_id text; plan_id text; company_a text; company_b text; company_c text; company_d text;
+ a1 text; a2 text; a3 text; a4 text; b1 text; b2 text; c1 text; d1 text; d2 text;
r jsonb;
BEGIN
INSERT INTO "companyGroup" (name, "createdBy") VALUES ('Rate limit ' || id(), 'system') RETURNING id INTO group_id;
@@ -49,11 +49,17 @@ BEGIN
VALUES ('Rate limit B', group_id, 'USD', 'America/New_York') RETURNING id INTO company_b;
INSERT INTO company (name, "companyGroupId", "baseCurrencyCode", timezone)
VALUES ('Rate limit C', group_id, 'USD', 'America/New_York') RETURNING id INTO company_c;
+ INSERT INTO company (name, "companyGroupId", "baseCurrencyCode", timezone)
+ VALUES ('Rate limit D', group_id, 'USD', 'America/New_York') RETURNING id INTO company_d;
+ INSERT INTO plan (name, "stripePriceId") VALUES ('Rate limit', 'price_rate_limit_' || id()) RETURNING id INTO plan_id;
+ INSERT INTO "companyPlan" (id, "planId", "subscriptionStartDate", "apiRateLimit")
+ VALUES (company_d, plan_id, NOW(), 150);
a1 := pg_temp.new_key(company_a); a2 := pg_temp.new_key(company_a);
a3 := pg_temp.new_key(company_a); a4 := pg_temp.new_key(company_a);
b1 := pg_temp.new_key(company_b); b2 := pg_temp.new_key(company_b);
c1 := pg_temp.new_key(company_c, 120);
+ d1 := pg_temp.new_key(company_d, 120); d2 := pg_temp.new_key(company_d, 120);
ASSERT (SELECT "rateLimit" = 20 AND "rateLimitWindow" = '1m' FROM "apiKey" WHERE id = a1),
'a new key gets 20 requests per minute';
@@ -96,6 +102,20 @@ BEGIN
r := pg_temp.hit(c1);
ASSERT NOT (r->>'success')::boolean AND (r->>'limit')::int = 60, 'and is held to the company limit after that';
RAISE NOTICE 'PASS a key above the company limit is capped by it';
+
+ r := pg_temp.hit(d1, 120);
+ ASSERT (r->>'success')::boolean AND (r->>'remaining')::int = 0,
+ 'a company whose plan raises the limit passes a key''s 120th request';
+ r := pg_temp.hit(d1);
+ ASSERT NOT (r->>'success')::boolean AND (r->>'limit')::int = 120, 'and the key is still held to its own limit';
+ r := pg_temp.hit(d2, 30);
+ ASSERT (r->>'success')::boolean AND (r->>'remaining')::int = 0, 'the company''s 150th request passes';
+ r := pg_temp.hit(d2);
+ ASSERT NOT (r->>'success')::boolean AND (r->>'limit')::int = 150 AND (r->>'count')::int = 151,
+ 'the plan''s limit, not 60, refuses the company''s 151st request';
+ r := pg_temp.hit(c1);
+ ASSERT NOT (r->>'success')::boolean AND (r->>'limit')::int = 60, 'a company with no override keeps 60';
+ RAISE NOTICE 'PASS a company''s plan overrides the company limit';
END
$proof$;
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index 3c62ecfabf..7444ba436f 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -1,11 +1,11 @@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20261014164752",
+ "schemaVersion": "20261015143857",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-10-14T17:39:46.819Z",
+ "exportedAt": "2026-10-15T14:43:10.531Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",