title: Keep Transactions Short to Reduce Lock Contentionimpact: MEDIUM-HIGHimpactDescription: 3-5x throughput improvement, fewer deadlockstags: transactions, locking, contention, performance保持事务简短以减少锁竞争长时间运行的事务会持有锁从而阻塞其他查询。应尽可能缩短事务。错误做法包含外部调用的事务begin;select*fromorderswhereid1forupdate;-- 获取锁-- 应用程序调用支付 API耗时 2-5 秒-- 其他针对该行的查询被阻塞updateorderssetstatuspaidwhereid1;commit;-- 锁在整个过程中一直被持有正确做法最小化事务范围-- 在事务外验证数据并调用 API-- 应用程序response await paymentAPI.charge(...)-- 仅在真正更新时才持有锁begin;updateorderssetstatuspaid,payment_id$1whereid$2andstatuspendingreturning*;commit;-- 锁仅持有几毫秒使用statement_timeout防止失控的事务-- 中止运行超过 30 秒的查询setstatement_timeout30s;-- 或按会话设置setlocalstatement_timeout5s;参考事务管理