Skip to content

fix(api): count Telegram connection slots under the company lock - #523

Merged
setkyar merged 1 commit into
mainfrom
fix/telegram-connect-quota-lock
Nov 23, 2026
Merged

setkyar merged 1 commit into
mainfrom
fix/telegram-connect-quota-lock

Conversation

@setkyar

@setkyar setkyar commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Fixes #379.

Problem

POST /channel-accounts/telegram-bot checked the paid connection quota before its insert transaction and took no lock. Two concurrent Telegram connects, or a Telegram connect racing a WhatsApp spawn, could both see the same slot count, both pass the check and both insert. The workspace then ends up over its plan's connection limit.

Fix

  • Count the used slots inside the insert transaction, behind the same per-company pg_advisory_xact_lock(hashtextextended(companyId, 0)) that spawnConnection already takes. Telegram and WhatsApp connects now take turns.
  • The route keeps its 402 MAX_CONNECTIONS_EXCEEDED response.
  • Reconnecting an existing account still does not use a slot.

Tests

  • New channel-accounts.quota.integration.test.ts drives the real route with the Telegram Bot API stubbed at fetch. Cases: two concurrent connects for the last slot admit exactly one (the other gets 402); a held WhatsApp-spawn lock makes the Telegram path wait and then see the slot as used; an existing account can still reconnect when the plan is full.
  • Rebased on main. Typecheck, biome and the new integration test pass on a fresh Postgres 18.

Release

No migration. worker: skip.

POST /channel-accounts/telegram-bot checked the paid connection quota
before its insert transaction and took no lock, so two concurrent
connects (or a connect racing a WhatsApp spawn) could both see the same
count and both insert, leaving the workspace over its plan limit.

Do the count inside the insert transaction behind the company-scoped
pg_advisory_xact_lock that spawnConnection already takes, and keep the
route's 402 MAX_CONNECTIONS_EXCEEDED response. Reconnecting an existing
account still does not consume a slot.

The integration test drives the real route with the Telegram Bot API
stubbed at fetch, and holds the company lock open to prove the Telegram
path waits on it and then sees the slot as used.

Fixes #379
@setkyar
setkyar merged commit 9d9eeba into main Nov 23, 2026
9 checks passed
@setkyar
setkyar deleted the fix/telegram-connect-quota-lock branch November 23, 2026 17:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Detail Bug] Connection quota: Concurrent Telegram bot connects can exceed plan connection slot limit

1 participant