I have a database table where the primary key is defined as a timestamp. The application inserts records to the database based on a certain event that is triggered and the timestamp used will be the one that created this instance. Since this application is running on multiple servers and that event is triggering at the same time in more than one of these servers at the same time, in some cases, the data doesn't get inserted to the database due to the primary key violation.
What could I possible change in order to avoid this situation? The ideas that I have at the moment are,
Waiting a random time before executing the database insertion.
Random r = new Random(); long time = r.nextLong() % 1000; time = time < 0 ? -time : time; // making sure that the waiting time is positive try { Thread.sleep(time); } catch (InterruptedException e) { throw new CustomeException(e); } Table1DataAccess.getInstance().insert(new Date(), "some description"); // inserting data into the table which has two fields.
Making the primary key a composite one.
Neither of them seems like good solutions to me, could anyone point me in the right direction?
P.S. The table to which I tried inserting data had the timestamp column in Date
type and I guess it only has it's precision down to seconds. When I used the type timestamp
instead, it offered a default precision of microseconds and it can offer nanoseconds at maximum.