Choose a one-statement message write as the track 1 improvement

Series B located the bottleneck. At eight replicas the API has 40 % of
its CPU spare and the balancer 60 % of a core, yet three quarters of
the pool connections wait for a chat row lock: the locking SELECT of
the chat averages 14.2 ms and the lock holders sit idle in transaction
while the replica's event loop gets round to the next statement. The
critical section, three round trips long, is what more replicas
lengthen.

The design now records the choice: one CTE that locks the chat with
the membership check, stamps the message no earlier than the last one,
claims the idempotency key and inserts the message, committed by the
statement itself, so the lock never waits for the application. A taken
key is read back by a second statement outside the lock. The price is
that the chat aggregate no longer guards posting; the rules move into
the adapter's SQL and are held by integration tests. The rejected
alternatives and the before/after plan are listed, and the spec gains
the observable requirement of a short critical section.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V1d3RLHNBBMA6UqBLLJv27
This commit is contained in:
Artyom
2026-10-29 01:06:10 +03:00
co-authored by Claude Opus 5.5
parent 3bdc8fad23
commit edc091dbc4
3 changed files with 29 additions and 2 deletions
@@ -68,3 +68,18 @@
- **WHEN** после внедрения улучшения выполняются `make test`, `make student-test` и `make lint`
- **THEN** все проходят
### Requirement: Короткая критическая секция отправки сообщения
Отправка сообщения SHALL держать блокировку строки чата только на время одной команды PostgreSQL: проверка участия, отметка времени не раньше последнего сообщения чата, запись ключа идемпотентности и сообщения SHALL выполняться одной атомарной командой без обращений к приложению между ними. Наблюдаемое поведение API (коды, тела, идемпотентность, порядок истории) SHALL NOT меняться.
#### Scenario: Под нагрузкой транзакции не ждут приложение
- **WHEN** выполняется `make track1-compare` на 8×1 при насыщающей интенсивности
- **THEN** у варианта «после» в `pg_stat_activity` среднее число соединений `idle in transaction` близко к нулю, ожиданий блокировки меньше, чем «до», а пик успешных RPS выше, чем «до», с непересекающимися интервалами повторов
#### Scenario: Отстающие часы реплики не ломают порядок
- **WHEN** часы реплики отстают от отметки последнего сообщения чата
- **THEN** новое сообщение получает `created_at` на 1 мкс позже последнего, а история остаётся упорядоченной по `(created_at, id)`