Post a message with one statement under the chat lock

Sending a message used to be BEGIN, a SELECT ... FOR UPDATE of the
chat with its members, a lookup of the idempotency key, the insert CTE
and COMMIT. Three of those round trips ran under the chat row lock, and
each one waited for the replica's event loop, so under load the lock
holders sat idle in transaction while everyone else queued behind
them.

The new MessageLog port has one PostgreSQL adapter that does it all in
a single statement with an implicit transaction: lock the chat row
joined with the sender's membership, stamp the message with the later
of the replica clock and the last message plus one microsecond, claim
the key (overwriting it only if it has expired), insert the message
only when the key was claimed, and move last_message_at. The foreign
key from the key to the message is checked at the end of the statement,
so the key may be written first. When the key is already taken the
adapter reads the stored result with a second statement outside the
lock, which also covers a concurrent duplicate that waited for the
first one; the handler then replays it or answers 409 as before.

The chat aggregate no longer takes part in posting, so its post,
membership and last_message_at members and their unit tests are gone;
Message.posted() builds the event. An invalid text is still answered
404 for an outsider: only then the handler reads the membership. A new
API test pins the clock rule against a real database: a lagging
replica clock gets the last stamp plus one microsecond, a clock ahead
is kept. The concurrency, same-key race, expiry and access tests pass
unchanged.

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:49 +03:00
co-authored by Claude Opus 5.5
parent edc091dbc4
commit 22f0e6244d
8 changed files with 146 additions and 173 deletions
@@ -1,4 +1,5 @@
from collections.abc import Sequence
from dataclasses import replace
from datetime import datetime
from uuid import UUID
@@ -8,6 +9,7 @@ from messenger.messaging.domain.errors import InvalidChatData
from messenger.messaging.domain.keys import HistoryKey
from messenger.messaging.domain.models import Chat, Message, Receipt
from messenger.messaging.domain.values import ChatTitle, MessageText
from messenger.shared.application.errors import Unavailable
from messenger.shared.infrastructure.postgres import (
Connection,
Database,
@@ -21,35 +23,35 @@ INSERT INTO chat_members (chat_id, user_id, position, chat_created_at)
SELECT $1, member.user_id, member.position, $3
FROM unnest($2::uuid[]) WITH ORDINALITY AS member (user_id, position)
"""
LOCK_CHAT = """
SELECT c.id, c.title, c.created_at, c.last_message_at,
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids
FROM chats c
WHERE c.id = $1
FOR UPDATE
POST_MESSAGE = """
WITH chat AS (
SELECT c.id, GREATEST($5::timestamptz, c.last_message_at + interval '1 microsecond') AS stamp
FROM chats c JOIN chat_members m ON m.chat_id = c.id AND m.user_id = $3
WHERE c.id = $2
FOR UPDATE OF c
), receipt AS (
INSERT INTO idempotency_keys (chat_id, user_id, key, fingerprint, message_id, created_at)
SELECT id, $3, $6, $7, $1, stamp FROM chat
ON CONFLICT (chat_id, user_id, key) DO UPDATE
SET fingerprint = EXCLUDED.fingerprint,
message_id = EXCLUDED.message_id,
created_at = EXCLUDED.created_at
WHERE idempotency_keys.created_at <= $8
RETURNING created_at
), message AS (
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT $1, $2, $3, $4, created_at FROM receipt
RETURNING created_at
), touched AS (
UPDATE chats SET last_message_at = message.created_at FROM message WHERE chats.id = $2
)
SELECT EXISTS (SELECT FROM chat) AS member, (SELECT created_at FROM message) AS created_at
"""
RECEIPT = """
SELECT k.fingerprint, m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
WHERE k.chat_id = $1 AND k.user_id = $2 AND k.key = $3 AND k.created_at > $4
"""
APPEND_MESSAGE = """
WITH message AS (
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1, $2, $3, $4, $5)
RETURNING id, chat_id, sender_id, created_at
), receipt AS (
INSERT INTO idempotency_keys (chat_id, user_id, key, fingerprint, message_id, created_at)
SELECT chat_id, sender_id, $6, $7, id, created_at FROM message
ON CONFLICT (chat_id, user_id, key) DO UPDATE
SET fingerprint = EXCLUDED.fingerprint,
message_id = EXCLUDED.message_id,
created_at = EXCLUDED.created_at
)
UPDATE chats SET last_message_at = message.created_at
FROM message
WHERE chats.id = message.chat_id
"""
CHAT_OF_MEMBER = """
SELECT c.id, c.title, c.created_at,
ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY position) AS member_ids
@@ -94,7 +96,6 @@ def chat_of(row: Record) -> Chat:
title=ChatTitle(row["title"]),
member_ids=row["member_ids"],
created_at=row["created_at"],
last_message_at=row.get("last_message_at"),
)
@@ -129,32 +130,37 @@ class PostgresChatRepository:
raise InvalidChatData("поле member_ids содержит неизвестного пользователя") from error
self._seen.append(chat)
async def get(self, chat_id: UUID) -> Chat | None:
row = await self._connection.fetchrow(LOCK_CHAT, chat_id)
if row is None:
return None
chat = chat_of(row)
self._seen.append(chat)
return chat
async def receipt(
self, chat_id: UUID, sender_id: UUID, key: str, since: datetime
class PostgresMessageLog:
__slots__ = ("_database",)
def __init__(self, database: Database) -> None:
self._database = database
async def post(
self, message: Message, key: str, fingerprint: bytes, since: datetime
) -> Receipt | None:
row = await self._connection.fetchrow(RECEIPT, chat_id, sender_id, key, since)
return None if row is None else Receipt(key, row["fingerprint"], message_of(row))
async def append(self, receipt: Receipt) -> None:
message = receipt.message
await self._connection.execute(
APPEND_MESSAGE,
message.id,
message.chat_id,
message.sender_id,
message.text.value,
message.created_at,
receipt.key,
receipt.fingerprint,
)
chat_id, sender_id = message.chat_id, message.sender_id
async with self._database.connection() as connection:
row = await connection.fetchrow(
POST_MESSAGE,
message.id,
chat_id,
sender_id,
message.text.value,
message.created_at,
key,
fingerprint,
since,
)
if row is None or not row["member"]:
return None
if row["created_at"] is not None:
return Receipt(key, fingerprint, replace(message, created_at=row["created_at"]))
known = await connection.fetchrow(RECEIPT, chat_id, sender_id, key, since)
if known is None:
raise Unavailable("ключ идемпотентности занят незавершённой записью")
return Receipt(key, known["fingerprint"], message_of(known))
class PostgresMessagingUnitOfWork(PostgresUnitOfWork):