Skill
applying-optimistic-locking
Apply when creating, refactoring, changing, planning (plan mode) or reviewing repository methods that save entities with optimistic locking.
From kotlin-patternsInstall
1
Run in your terminal$
npx claudepluginhub allousas/claude-code-plugins --plugin kotlin-patternsTool Access
This skill uses the workspace's default tool permissions.
Supporting Assets
View in Repositoryexamples.mdSkill Content
Purpose
Prevent lost updates when multiple processes modify the same entity concurrently. Each entity carries a version field that is checked during updates - if the version has changed since the entity was read, the update is rejected.
Typical Flow
- Entity includes a
versionfield (integer, starting at 0) - Repository reads entity with current version
- Application service performs domain operations on the entity
- Repository saves entity with
WHERE version = ?condition - If no rows are updated (version mismatch), throw
OptimisticLockingException - Caller decides retry strategy (controller retries, consumer relies on Kafka retry)
Guidelines
DO:
- Add a
version: Longfield to entities that can be concurrently modified - Let version increment to 0 automatically when creating a new entity
- Use
WHERE version = ?in UPDATE/INSERT ON CONFLICT SQL statements - Throw a specific
OptimisticLockingExceptionwhen zero rows are affected - Increment version in the SQL statement itself (
version = version + 1orversion = EXCLUDED.version + 1) - Keep the version check inside the repository - callers should not manage versions
DON'T:
- Increment the version in application code - let the database handle it
- Silently ignore zero affected rows - always throw to signal the conflict
- Use optimistic locking on entities that are rarely modified concurrently (unnecessary complexity)
- Retry indefinitely - set a maximum retry count
Examples
Please use always these examples as reference: examples.md
Similar Skills
Stats
Parent Repo Stars1
Parent Repo Forks0
Last CommitFeb 24, 2026