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
+12 -46
View File
@@ -1,16 +1,14 @@
from collections.abc import Sequence
from dataclasses import dataclass
from datetime import datetime, timedelta
from datetime import datetime
from uuid import UUID
from messenger.messaging.domain.errors import ChatNotFound, IdempotencyConflict, InvalidChatData
from messenger.messaging.domain.errors import IdempotencyConflict, InvalidChatData
from messenger.messaging.domain.events import ChatCreated, MessagePosted
from messenger.messaging.domain.keys import HistoryKey
from messenger.messaging.domain.values import CHAT_MEMBERS_MAX, ChatTitle, MessageText
from messenger.shared.domain.events import DomainEvent
TICK = timedelta(microseconds=1)
@dataclass(frozen=True, slots=True)
class Message:
@@ -24,6 +22,15 @@ class Message:
def key(self) -> HistoryKey:
return (self.created_at, self.id.int)
def posted(self) -> MessagePosted:
return MessagePosted(
message_id=self.id,
chat_id=self.chat_id,
sender_id=self.sender_id,
text_length=len(self.text.value),
created_at=self.created_at,
)
@dataclass(frozen=True, slots=True)
class Receipt:
@@ -38,15 +45,7 @@ class Receipt:
class Chat:
__slots__ = (
"_events",
"_members",
"created_at",
"id",
"last_message_at",
"member_ids",
"title",
)
__slots__ = ("_events", "created_at", "id", "member_ids", "title")
def __init__(
self,
@@ -55,14 +54,11 @@ class Chat:
title: ChatTitle,
member_ids: Sequence[UUID],
created_at: datetime,
last_message_at: datetime | None = None,
) -> None:
self.id = chat_id
self.title = title
self.member_ids: tuple[UUID, ...] = tuple(member_ids)
self.created_at = created_at
self.last_message_at = last_message_at
self._members: frozenset[UUID] = frozenset(member_ids)
self._events: list[DomainEvent] = []
@classmethod
@@ -107,36 +103,6 @@ class Chat:
def record(self, event: DomainEvent) -> None:
self._events.append(event)
def is_member(self, user_id: UUID) -> bool:
return user_id in self._members
def require_member(self, user_id: UUID) -> None:
if not self.is_member(user_id):
raise ChatNotFound("чат не найден")
def post(self, *, message_id: UUID, sender_id: UUID, text: str, now: datetime) -> Message:
self.require_member(sender_id)
last = self.last_message_at
created_at = now if last is None or now > last else last + TICK
message = Message(
id=message_id,
chat_id=self.id,
sender_id=sender_id,
text=MessageText(text),
created_at=created_at,
)
self.last_message_at = created_at
self.record(
MessagePosted(
message_id=message.id,
chat_id=self.id,
sender_id=sender_id,
text_length=len(message.text.value),
created_at=created_at,
)
)
return message
def collect_events(self) -> list[DomainEvent]:
events, self._events = self._events, []
return events