forked from mtusi2026/mtusi2026lab3
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