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.

fix(tables): at most 4 exports and bulk actions run at once across companies; past that the request is refused with a toast, never queued

aashu45d5ba72fba2
diff --git a/.claude/rules/table-csv-export.md b/.claude/rules/table-csv-export.md
index 4a4e2af560..b66800a65f 100644
--- a/.claude/rules/table-csv-export.md
+++ b/.claude/rules/table-csv-export.md
@@ -151,6 +151,12 @@ list and re-read every loaded page. The steps:
`tableJobBusyMessage`: "An export is already running for your company.
Try again when it ends, at the latest in N minutes." N comes from the
lock's TTL.
+ - The same script takes one of `MAX_RUNNING_TABLE_JOBS` (4) slots shared by
+ every company's exports and bulk actions (`TABLE_JOB_SLOTS_KEY`, a sorted
+ set scored by expiry). With none free the route answers 503 with
+ `TABLE_JOBS_FULL_MESSAGE` ("Too many exports and bulk actions are running
+ right now…"). It refuses, never queues: a queue many companies fill
+ would make every user wait. Release and extend free and renew the slot.
- If Redis does not answer, the route starts the job anyway and logs a
warning. Inngest's per-company concurrency still runs one export at a time.
4. It triggers `table-export` (`packages/jobs/src/inngest/functions/tasks/table-export.ts`,
diff --git a/.claude/rules/table-infinite-scroll.md b/.claude/rules/table-infinite-scroll.md
index 6845501f84..444c31fb09 100644
--- a/.claude/rules/table-infinite-scroll.md
+++ b/.claude/rules/table-infinite-scroll.md
@@ -302,7 +302,9 @@ A bulk route that gets `allMatching` in place of ids calls
limit of 2,000. The menu item shows "Filter the list to 2,000 rows or fewer"
(`useAllMatchingLimitLabel`).
3. It takes the company's bulk lock (`takeTableJobLock("bulk", …)`, the same
- Lua lock as the export). A busy lock answers the remaining time.
+ Lua lock as the export). A busy lock answers the remaining time. With all
+ `MAX_RUNNING_TABLE_JOBS` (4) slots across companies taken it refuses
+ (`refusal: { code: "full" }`, see `table-csv-export.md`).
4. It triggers `table-bulk-action`
(`packages/jobs/src/inngest/functions/tasks/table-bulk-action.ts`,
`retries: 0`, one run per company at a time).
@@ -338,8 +340,11 @@ balancer cuts a request at 600 s.
- `TODO(scale)` (`packages/jobs/src/inngest/functions/tasks/table-export.ts`):
the table jobs run in the ERP containers (`api+/inngest.ts`) and share CPU
- with web requests. One job per company runs at a time, but many companies
- can run one each. A separate worker service removes this risk.
+ with web requests. One job per company runs at a time, and at most
+ `MAX_RUNNING_TABLE_JOBS` (4) across all companies; a request past that is
+ refused with a toast, not queued. While Redis is down the lock fails open
+ and neither limit holds there (Inngest still runs one per company). A
+ separate worker service removes this limit.
- Footer totals (`meta.renderTotal`) add up the loaded rows only. The footer
says "Total of N loaded rows".
- 49 services put the raw search text into `.or()`. This is independent of
diff --git a/apps/erp/app/components/Table/components/SelectAllMatching.tsx b/apps/erp/app/components/Table/components/SelectAllMatching.tsx
index 211a722b5b..a74879bc5b 100644
--- a/apps/erp/app/components/Table/components/SelectAllMatching.tsx
+++ b/apps/erp/app/components/Table/components/SelectAllMatching.tsx
@@ -157,6 +157,8 @@ export function useTableJobRefusalMessage() {
? t`A bulk action is already running for your company. Try again when it ends, at the latest in ${minutes} min.`
: t`A bulk action is already running for your company. Try again when it ends.`;
}
+ case "full":
+ return t`Too many exports and bulk actions are running right now. Try again in a few minutes.`;
case "row-limit": {
const rows = i18n.number(refusal.maxRows);
return t`This action runs on at most ${rows} rows. Filter the list to ${rows} rows or fewer.`;
diff --git a/apps/erp/app/routes/api+/table.export.ts b/apps/erp/app/routes/api+/table.export.ts
index 1004d38f95..add5b79067 100644
--- a/apps/erp/app/routes/api+/table.export.ts
+++ b/apps/erp/app/routes/api+/table.export.ts
@@ -13,6 +13,7 @@ import { z } from "zod";
import { getListDefinition } from "~/utils/list-registry/index.server";
import {
newTableExportId,
+ TABLE_JOBS_FULL_MESSAGE,
type TableJobRefusal,
tableJobBusyMessage,
tableJobBusyRefusal
@@ -86,6 +87,19 @@ export async function action({ request }: ActionFunctionArgs) {
{ status: 409 }
);
}
+ if (lock.status === "full") {
+ logger.warn("Refused a table export: every table-job slot is taken", {
+ companyId,
+ listKey
+ });
+ return data(
+ {
+ error: TABLE_JOBS_FULL_MESSAGE,
+ refusal: { code: "full" } satisfies TableJobRefusal
+ },
+ { status: 503 }
+ );
+ }
if (lock.status === "unavailable") {
// Fail-open: Inngest's per-company concurrency still runs one at a time.
logger.warn("Starting a table export without the Redis lock", {
diff --git a/apps/erp/app/utils/table-jobs.server.ts b/apps/erp/app/utils/table-jobs.server.ts
index ba0dbf6c9f..d70f077e45 100644
--- a/apps/erp/app/utils/table-jobs.server.ts
+++ b/apps/erp/app/utils/table-jobs.server.ts
@@ -50,6 +50,7 @@ import {
parseAllMatching,
refreshingClientFactory,
rowLimitRefusal,
+ TABLE_JOBS_FULL_MESSAGE,
type TableBulkActionKey,
type TableJobClaims,
tableJobBusyMessage,
@@ -593,6 +594,17 @@ async function startBulkRun({
refusal: tableJobBusyRefusal("bulk", lock.retryAfterSeconds)
};
}
+ if (lock.status === "full") {
+ logger.warn("Refused a table bulk action: every table-job slot is taken", {
+ companyId,
+ actionKey
+ });
+ return {
+ success: false,
+ message: TABLE_JOBS_FULL_MESSAGE,
+ refusal: { code: "full" }
+ };
+ }
if (lock.status === "unavailable") {
// Fail-open: Inngest's per-company concurrency still runs one at a time.
logger.warn("Starting a table bulk action without the Redis lock", {
diff --git a/apps/erp/app/utils/table-jobs.ts b/apps/erp/app/utils/table-jobs.ts
index db36861e73..3fd62435a6 100644
--- a/apps/erp/app/utils/table-jobs.ts
+++ b/apps/erp/app/utils/table-jobs.ts
@@ -65,6 +65,11 @@ export function tableJobBusyMessage(
}.`;
}
+/** The answer when every table-job slot across companies is taken
+ * (`MAX_RUNNING_TABLE_JOBS`): the request is refused, never queued. */
+export const TABLE_JOBS_FULL_MESSAGE =
+ "Too many exports and bulk actions are running right now. Try again in a few minutes.";
+
const LIST_KEY = /^[a-z0-9-]{1,64}$/;
const EXPORT_TOKEN = /^[A-Za-z0-9_-]{10,64}$/;
@@ -161,6 +166,7 @@ export type AllMatchingRequest = { listKey: string; search: string };
*/
export type TableJobRefusal =
| { code: "busy"; kind: "export" | "bulk"; minutes: number }
+ | { code: "full" }
| { code: "row-limit"; maxRows: number }
| { code: "not-supported" }
| { code: "no-permission" }
diff --git a/packages/jobs/src/table-jobs/handlers.ts b/packages/jobs/src/table-jobs/handlers.ts
index 5ecb7b9be5..60facb94c6 100644
--- a/packages/jobs/src/table-jobs/handlers.ts
+++ b/packages/jobs/src/table-jobs/handlers.ts
@@ -134,3 +134,18 @@ export function tableJobLockKey(kind: TableJobKind, companyId: string): string {
/** Seconds a lock lives if its job never deletes it (a crashed process). Each
* step of a running job sets it back to this (`extendTableJobLock`). */
export const TABLE_JOB_LOCK_TTL_SECONDS = 60 * 60;
+
+/**
+ * The running table jobs of every company: a sorted set of job ids, scored by
+ * when each one's slot expires. A job takes a slot with its company lock.
+ */
+export const TABLE_JOB_SLOTS_KEY = "table-job:running";
+
+/**
+ * The most table jobs (exports and bulk actions together) that run at once
+ * across all companies. They share CPU with web requests in the ERP
+ * containers, so a request past this is refused, never queued: a queue that
+ * many companies fill would make every user wait.
+ * TODO(scale): move the table jobs to a dedicated worker service, then raise this.
+ */
+export const MAX_RUNNING_TABLE_JOBS = 4;
diff --git a/packages/jobs/src/table-jobs/lock.test.ts b/packages/jobs/src/table-jobs/lock.test.ts
index 5f08debbb6..9d9fb973db 100644
--- a/packages/jobs/src/table-jobs/lock.test.ts
+++ b/packages/jobs/src/table-jobs/lock.test.ts
@@ -32,6 +32,10 @@ describe("decideTableJobLock", () => {
});
});
+ it("refuses while every slot across companies is taken", () => {
+ expect(decideTableJobLock([2, 0])).toEqual({ status: "full" });
+ });
+
it("fails open when Redis answers nothing", () => {
expect(decideTableJobLock(null)).toEqual({ status: "unavailable" });
expect(decideTableJobLock([])).toEqual({ status: "unavailable" });
diff --git a/packages/jobs/src/table-jobs/lock.ts b/packages/jobs/src/table-jobs/lock.ts
index 6ec03b776f..30a539b8f1 100644
--- a/packages/jobs/src/table-jobs/lock.ts
+++ b/packages/jobs/src/table-jobs/lock.ts
@@ -4,7 +4,9 @@
import { redis } from "@carbon/kv";
import {
+ MAX_RUNNING_TABLE_JOBS,
TABLE_JOB_LOCK_TTL_SECONDS,
+ TABLE_JOB_SLOTS_KEY,
type TableJobKind,
tableJobLockKey
} from "./handlers";
@@ -14,6 +16,9 @@ import {
* value is the job's id, so a job only ever deletes or extends its own lock:
* a lock that expired and was taken by the next job belongs to that job.
*
+ * Taking the lock also takes one of the `MAX_RUNNING_TABLE_JOBS` slots
+ * shared by every company (`TABLE_JOB_SLOTS_KEY`); with none free it refuses.
+ *
* Each operation is one Lua script, so the read and the write are atomic.
* `@carbon/kv` answers `null` for any command while Redis is down, which every
* caller treats as "no lock": the route starts the job anyway (Inngest's
@@ -29,20 +34,32 @@ export type LockClient = {
): Promise<unknown>;
};
-// SET NX EX, and the remaining TTL when another job holds the key.
-const TAKE_SCRIPT = `if redis.call("SET", KEYS[1], ARGV[1], "NX", "EX", ARGV[2]) then
- return {1, 0}
+// The company lock (SET NX EX) and a slot, or `{0, ttl}` while another job of
+// the company holds the lock, or `{2, 0}` while every slot is taken. Slots of
+// crashed jobs expire by their score.
+const TAKE_SCRIPT = `local now = tonumber(redis.call("TIME")[1])
+if redis.call("EXISTS", KEYS[1]) == 1 then
+ return {0, redis.call("TTL", KEYS[1])}
+end
+redis.call("ZREMRANGEBYSCORE", KEYS[2], "-inf", now)
+if redis.call("ZCARD", KEYS[2]) >= tonumber(ARGV[3]) then
+ return {2, 0}
end
-return {0, redis.call("TTL", KEYS[1])}`;
+redis.call("SET", KEYS[1], ARGV[1], "EX", ARGV[2])
+redis.call("ZADD", KEYS[2], now + tonumber(ARGV[2]), ARGV[1])
+return {1, 0}`;
-// Compare-and-delete: only the holder deletes the key.
-const RELEASE_SCRIPT = `if redis.call("GET", KEYS[1]) == ARGV[1] then
+// Compare-and-delete: only the holder deletes the key. The slot goes either way.
+const RELEASE_SCRIPT = `redis.call("ZREM", KEYS[2], ARGV[1])
+if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
end
return 0`;
-// Compare-and-expire: only the holder sets the TTL back.
+// Compare-and-expire: only the holder sets the TTL back, and its slot's.
const EXTEND_SCRIPT = `if redis.call("GET", KEYS[1]) == ARGV[1] then
+ local now = tonumber(redis.call("TIME")[1])
+ redis.call("ZADD", KEYS[2], "XX", now + tonumber(ARGV[2]), ARGV[1])
return redis.call("EXPIRE", KEYS[1], ARGV[2])
end
return 0`;
@@ -53,20 +70,23 @@ return 0`;
* - `acquired`: the lock is ours.
* - `busy`: another job of the company holds it; it expires in
* `retryAfterSeconds` at the latest.
+ * - `full`: `MAX_RUNNING_TABLE_JOBS` jobs are running across all companies.
* - `unavailable`: Redis did not answer. The job starts anyway.
*/
export type TableJobLock =
| { status: "acquired" }
| { status: "busy"; retryAfterSeconds: number }
+ | { status: "full" }
| { status: "unavailable" };
-/** Reads the take script's reply: `[1, 0]`, `[0, ttl]`, or null. */
+/** Reads the take script's reply: `[1, 0]`, `[0, ttl]`, `[2, 0]`, or null. */
export function decideTableJobLock(reply: unknown): TableJobLock {
if (!Array.isArray(reply) || reply.length < 2) {
return { status: "unavailable" };
}
const [taken, ttl] = reply as [unknown, unknown];
if (Number(taken) === 1) return { status: "acquired" };
+ if (Number(taken) === 2) return { status: "full" };
const seconds = Number(ttl);
// TTL is -2 when the key vanished between the two calls and -1 without an
// expiry; neither should promise a wait that is not real.
@@ -84,22 +104,30 @@ export async function takeTableJobLock(
): Promise<TableJobLock> {
const reply = await client.eval(
TAKE_SCRIPT,
- 1,
+ 2,
tableJobLockKey(kind, companyId),
+ TABLE_JOB_SLOTS_KEY,
jobId,
- TABLE_JOB_LOCK_TTL_SECONDS
+ TABLE_JOB_LOCK_TTL_SECONDS,
+ MAX_RUNNING_TABLE_JOBS
);
return decideTableJobLock(reply);
}
-/** Deletes the lock while it still holds `jobId`. */
+/** Deletes the lock while it still holds `jobId`, and frees the job's slot. */
export async function releaseTableJobLock(
kind: TableJobKind,
companyId: string,
jobId: string,
client: LockClient = redis
): Promise<void> {
- await client.eval(RELEASE_SCRIPT, 1, tableJobLockKey(kind, companyId), jobId);
+ await client.eval(
+ RELEASE_SCRIPT,
+ 2,
+ tableJobLockKey(kind, companyId),
+ TABLE_JOB_SLOTS_KEY,
+ jobId
+ );
}
/** Sets the lock's TTL back to the full hour while it still holds `jobId`:
@@ -112,8 +140,9 @@ export async function extendTableJobLock(
): Promise<void> {
await client.eval(
EXTEND_SCRIPT,
- 1,
+ 2,
tableJobLockKey(kind, companyId),
+ TABLE_JOB_SLOTS_KEY,
jobId,
TABLE_JOB_LOCK_TTL_SECONDS
);
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 3ae782a1fc..cfeead82fc 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -23862,6 +23862,9 @@ msgstr "Toleranz (Tage)"
msgid "Tomorrow"
msgstr "Morgen"
+msgid "Too many exports and bulk actions are running right now. Try again in a few minutes."
+msgstr "Gerade laufen zu viele Exporte und Massenaktionen. Versuchen Sie es in ein paar Minuten erneut."
+
msgid "tool"
msgstr "Werkzeug"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 8d59f6587a..2b5306c10b 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -23862,6 +23862,9 @@ msgstr "Tolerance (days)"
msgid "Tomorrow"
msgstr "Tomorrow"
+msgid "Too many exports and bulk actions are running right now. Try again in a few minutes."
+msgstr "Too many exports and bulk actions are running right now. Try again in a few minutes."
+
msgid "tool"
msgstr "tool"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 6f1aad5e04..c43b214a71 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -23862,6 +23862,9 @@ msgstr "Tolerancia (días)"
msgid "Tomorrow"
msgstr "Mañana"
+msgid "Too many exports and bulk actions are running right now. Try again in a few minutes."
+msgstr "Hay demasiadas exportaciones y acciones masivas en curso. Inténtelo de nuevo en unos minutos."
+
msgid "tool"
msgstr "Herramienta"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index b10e6f7f2b..e51356d291 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -23862,6 +23862,9 @@ msgstr "Tolérance (jours)"
msgid "Tomorrow"
msgstr "Demain"
+msgid "Too many exports and bulk actions are running right now. Try again in a few minutes."
+msgstr "Trop d'exports et d'actions groupées sont en cours. Réessayez dans quelques minutes."
+
msgid "tool"
msgstr "Outil"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 98c92823c7..da40c58d47 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -23862,6 +23862,9 @@ msgstr "सहनशीलता (दिन)"
msgid "Tomorrow"
msgstr "कल"
+msgid "Too many exports and bulk actions are running right now. Try again in a few minutes."
+msgstr "अभी बहुत सारे एक्सपोर्ट और बल्क एक्शन चल रहे हैं। कुछ मिनट बाद फिर से कोशिश करें।"
+
msgid "tool"
msgstr "उपकरण"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index b9a7d0b173..367d4ffec1 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -23862,6 +23862,9 @@ msgstr "Tolleranza (giorni)"
msgid "Tomorrow"
msgstr "Domani"
+msgid "Too many exports and bulk actions are running right now. Try again in a few minutes."
+msgstr "Ci sono troppe esportazioni e azioni di massa in corso. Riprova tra qualche minuto."
+
msgid "tool"
msgstr "Strumento"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 42a1b55fb9..07689dce11 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -23862,6 +23862,9 @@ msgstr "許容値(日)"
msgid "Tomorrow"
msgstr "明日"
+msgid "Too many exports and bulk actions are running right now. Try again in a few minutes."
+msgstr "現在、実行中のエクスポートと一括操作が多すぎます。数分後にもう一度お試しください。"
+
msgid "tool"
msgstr "ツール"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 6e754ce509..4a50c86b00 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -23862,6 +23862,9 @@ msgstr "허용치 (일)"
msgid "Tomorrow"
msgstr "내일"
+msgid "Too many exports and bulk actions are running right now. Try again in a few minutes."
+msgstr "현재 실행 중인 내보내기와 일괄 작업이 너무 많습니다. 몇 분 후에 다시 시도하세요."
+
msgid "tool"
msgstr "공구"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 7864486e5b..bf13fb6f29 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -23862,6 +23862,9 @@ msgstr "Tolerancja (dni)"
msgid "Tomorrow"
msgstr "Jutro"
+msgid "Too many exports and bulk actions are running right now. Try again in a few minutes."
+msgstr "Trwa zbyt wiele eksportów i działań zbiorczych. Spróbuj ponownie za kilka minut."
+
msgid "tool"
msgstr "Narzędzie"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index d555f5069e..a20d5cedb7 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -23862,6 +23862,9 @@ msgstr "Tolerância (dias)"
msgid "Tomorrow"
msgstr "Amanhã"
+msgid "Too many exports and bulk actions are running right now. Try again in a few minutes."
+msgstr "Há muitas exportações e ações em massa em andamento. Tente novamente em alguns minutos."
+
msgid "tool"
msgstr "Ferramenta"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 6f805a6176..0d28ab77ba 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -23862,6 +23862,9 @@ msgstr "Допуск (дней)"
msgid "Tomorrow"
msgstr "Завтра"
+msgid "Too many exports and bulk actions are running right now. Try again in a few minutes."
+msgstr "Сейчас выполняется слишком много экспортов и массовых действий. Повторите попытку через несколько минут."
+
msgid "tool"
msgstr "Инструмент"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index cc73c62acc..2a3df2df98 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -23862,6 +23862,9 @@ msgstr "Tolerans (gün)"
msgid "Tomorrow"
msgstr "Yarın"
+msgid "Too many exports and bulk actions are running right now. Try again in a few minutes."
+msgstr "Şu anda çok fazla dışa aktarma ve toplu işlem çalışıyor. Birkaç dakika sonra tekrar deneyin."
+
msgid "tool"
msgstr "Araç"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index dce873dc8b..8a977bf7bc 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -23862,6 +23862,9 @@ msgstr "容差(天)"
msgid "Tomorrow"
msgstr "明天"
+msgid "Too many exports and bulk actions are running right now. Try again in a few minutes."
+msgstr "当前正在运行的导出和批量操作过多。请几分钟后重试。"
+
msgid "tool"
msgstr "工具"