AWS RDS database can't read record that was just written to database

user83358

I'm seeing an error with some Laravel code that uses an AWS RDS database. The code writes a record to the database and then immediately does a search to load that record using the primary key and gets no results.

If I try it manually afterwards I find the record. If I insert a 1-second sleep in the code it works correctly.

I've tried this using Laravel's separate settings for read and write hosts. I've also tried setting them to the same host and only using one host. The result is always the same. However other environments with the same configuration do not have the error.

Is there an option in RDS that needs to be changed to have the record available immediately after it's written.

Paras

The error is due to the mySQL master-slave replication lag.

A common mistake is to use a mySQL cluster and then perform a read immediately after a write.

Since the read occurs on one of the slave/read hosts and the write occurs on the master, the data would not be replicated at the time of the read.

There are a couple of ways to rectify the error:

  1. The read immediately after must be performed on the master (not the slave). Even though you've mentioned that you changed it to a single host, often people make a mistake while switching the connection. Refer this SO post to properly switch connections in Laravel
  2. An easier way may be to use the sticky database option in Laravel. Beware: this may cause performance issues if not used carefully for only the use case you desire. From the docs:

The sticky option is an optional value that can be used to allow the immediate reading of records that have been written to the database during the current request cycle. If the sticky option is enabled and a "write" operation has been performed against the database during the current request cycle, any further "read" operations will use the "write" connection.

  1. The most "non-obvious" way is to NOT perform a read immediately after a write. Think about whether this can be avoided depending on your use case.

  2. Other methods: refer this SO post

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related