This Rails code is supposed to prevent duplicate records from being recorded by the server within 20 seconds:

```
@transit = Transit.new(tag: params[:tag])
if Transit.where(tag: @transit.tag).where("created_at > ?", 20.seconds.ago).first
  logger.warn "Duplicate tag"
else
  @transit.save!
end

```

However, this is not working. I can see in my production database (hosted on Heroku) two different records getting created with the same tag 10 seconds apart. 

Logs show the correct query is executed on the second request, but it returns no results and saves a new record anyway.

Why does this happen? I thought Postgres' default isolation level of read\_committed would prevent this from happening. The query that returns no records should miss Rails' SQL cache. Logs show both requests were handled by the same WEB.1 Dyno on Heroku, and my Puma.rb is set up for 4 workers and 5 threads.

What am I missing?

Here are the two records in the db:

```
=> #<Transit id: 1080116, tag: 33504, 
             created_at: "2019-01-30 12:36:11", 
             updated_at: "2019-01-30 12:41:23">

=> #<Transit id: 1080115, tag: 33504, 
             created_at: "2019-01-30 12:35:56", 
             updated_at: "2019-01-30 12:35:56">

```

Log of the first insert:

```
30 Jan 2019 07:35:56.203132 <190>1 2019-01-30T12:35:56.050681+00:00 app web.1 - - [1m [36m (0.8ms) [0m [1mBEGIN [0m
30 Jan 2019 07:35:56.203396 <190>1 2019-01-30T12:35:56.055097+00:00 app web.1 - - [1m [35mSQL (1.0ms) [0m INSERT INTO "transits" ("tag", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"
30 Jan 2019 07:35:56.269133 <190>1 2019-01-30T12:35:56.114572+00:00 app web.1 - - [1m [36m (2.0ms) [0m [1mCOMMIT [0m

```

Log of the query from right before the duplicate is inserted:

```
30 Jan 2019 07:36:12.160359 <190>1 2019-01-30T12:36:11.863973+00:00 app web.1 - - [1m [35mTransit Load (5.1ms) [0m SELECT "transits".* FROM "transits" WHERE "transits"."tag" = 33504 AND created_at > '2019-01-30 12:35:51.846431' ORDER BY "transits"."id" ASC LIMIT 1

```

And here is the postgres transaction isolation level, which to be clear is for a different connection opened after this issue came up:

```
SHOW default_transaction_isolation;

 default_transaction_isolation 
-------------------------------
 read committed
(1 row)

```