If I understand the question correctly, you have set a very high bar for yourself. Obviously, your resilience layer does not see the future. Therefore, it is not possible to maintain a validator that ensures that the insert is successful (and not throw a UniqueConstraintViolationException) using only your domain objects. Somewhere you will need to maintain an extra state.
If you need some incremental improvement, you need to somehow reserve a username during verification. Of course, this is quite simple - you just create a list somewhere to keep track of usernames on the fly, and check this list in addition to checking the persistence level during validation.
Where this is difficult, a reasonable way should be developed to crop this list and release usernames that are sent for verification but have never been used for successful registration.
This is an implementation detail, and you will need to think about how long the username is stored.
A simple implementation from my head: maintain a table in your database with (username, session_id, reserved_at) and periodically process all rows where reserved_at <:. date and time
You will need to keep track of session_id, since you are backing up a username for a specific user. Since the user has not yet created an account, the only way to identify them is through the session identifier.
timdev
source share