Rails Postgres Query Fails to Return New Records

Rails Postgres Query Fails to Return New Records

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

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?

ruby-on-rails postgresql

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Ruby on Rails Developer | Hire RoR Developer

#1 Ruby on Rails development company. Hire Ruby on rails developer or a team to build secure, scalable and complex web solutions with a quick turnaround time.

Explain Ruby on rails MVC

Our Ruby on Rails Training will provide you to learn about Rails and web applications development with realty. Our Ruby on Rails Course also includes live sessions.

"Rewrite your Software," says Creator of Ruby on Rails

David Heinemeier Hansson is the creator of Ruby on Rails, co-founder & CTO of Basecamp, best-selling author, Le Mans class-winning race car driver, family man, frequent podcast guest, and inspirational conference speaker.

How To Use PostgreSQL with Your Ruby on Rails Application on macOS

In this tutorial, you will set up a Ruby on Rails development environment connected to a PostgreSQL database on a local macOS machine. You will install and configure PostgreSQL, and then test your setup by creating a Rails application that uses PostgreSQL as its database server.

How To Connect Ruby on Rails API, PostgreSQL And Heroku

Creating a new Rails app is super easy by itself. And, creating a Rails app set up as an API is not much different. Because we are planning on deploying our app to Heroku we need to set it up with PostgreSQL as the database.