Use database invariants

Context

I want to create a city but I want to ensure that the city with the same name doesn't exist.

dont_Check_Uniqueness_In_Code_Because_Of_Race_Conditions

I check whether Chennai exists in database.

You write Chennai to db.

I write Chennai to db.

There are two Chennai(s) in db.

Context

I want to make sure that customer's email is unique.

let_Database_Verify_Uniqueness

Database has unique constraint for Customers Email column. Whenever I save customer I catch the ConstraintViolationException and based on that I find whether customer's email is unique or not.

This is very common scenario, with simple resolution and often implemented by doing unique check in the program.