I have a Classic ASP site using ADODB with the sqloledb provider to connect to SQL Server 2012. When a user clicks on a link, I am inserting a record into a table to track the clicks. The table has a primary key comprised of three columns: id [int], clickTime [datetime2(7)], and remoteAddress [varchar(15)]. My insert statement is providing the id and remoteAddress values, and the clickTime column is set to a default of SYSDATETIME(). An example would be:
INSERT MyClick (id, remoteAddress) VALUES (766319,'108.178.236.50')
I am capturing a few thousand clicks per day, but I am getting a handful of errors each day for duplicate keys. Here is an example:
Violation of PRIMARY KEY constraint 'PK_MyClick_1'. Cannot insert duplicate key in object 'dbo.MyClick'. The duplicate key value is (766319, 2016-01-20 15:30:14.1570772, 108.178.236.50).
With the relatively light traffic, inclusion of the user's IP address in the key, and extreme precision of datetime2, I cannot understand how I am still getting occasional duplicate keys. I understand that I could add an identity or GUID column to the key to guarantee uniqueness. I also understand that I could retry the insert in the event it fails. However, I'd really like to understand this:
How is it possible to get duplicate keys in my scenario?
EDIT: I figured out why the web site was attempting to insert two similar records (for the same id and remoteAddress). It stems from an ill-conceived attempt years ago to get around the problem of pop-up blockers breaking our site. The page had an <a>
tag wrapped around a <div>
tag. The <a>
tag opened the page with a _blank target, and the <div>
had an onClick event that used window.open to open the same page in a a new window. This onClick is usually blocked by pop-up blockers, so only one page would be opened as expected. But if the user allowed pop-ups for the site (or used a browser with no pop-up blocking), it would actually open the same page in two different tabs. Both of the pages were trying to insert the database record, and if they hit close enough together, the duplicate key error occurred. What I found in the database was that we have many cases of near-duplicate records separated by a fraction of a second. So if I fix the site to not open the page in two different windows, I believe this duplicate problem will go away (even though it's still technically possible). Thanks to those who offered suggestions to help me figure it out.