Repository navigation
[13.x] Add PreventStaleDatabaseReads middleware - #62078
Conversation
|
Thanks for submitting a PR! Note that draft PRs are not reviewed. If you would like a review, please mark your pull request as ready for review in the GitHub user interface. Pull requests that are abandoned in draft may be closed due to inactivity. |
| $response = $next($request); | ||
|
|
||
| if ($connection->hasModifiedRecords()) { | ||
| $request->session()->put('_database_modified_at', Date::now()->getTimestamp()); |
There was a problem hiding this comment.
I went with underscores cos... feels more internal in my head
|
Cool 👍 |
|
Just a question, but is this race condition relevant here? #30996 |
|
@trevorgehman it could still apply I guess, though it means it'll use the read connection if it does overlap (not sure how rare that is). Possibly doing it via the cache is nicer, but I haven't run into the problem myself yet. |
Actually what will happen is the session will be overwritten and
I think it is a rare situation, but it is easily reproducible. It tends to surface when you have long-running requests, such as pulling in a chart that takes a few seconds to load. I actually don't think this is a serious issue, and using the session to store this sort of data is appropriate IMO. I want to just point this out in case it happens to someone else and they can't figure out what's going on :) Thank you for your PR! |
|
https://tim.macdonald.au/sticky-database-connections-across-requests-with-laravel/ Love that this is in the framework now |
|
@patrickomeara Dope, I didn't realise Tim had a post about it 😅! |
|
Great minds! @jackbayliss @timacdonald ;) |
|
Yooooo. Love this ❤️ Great work getting something into the FW, Jack. |
With using read/write connections and sticky connections I wanted to protect against users seeing stale data, as when using sticky the next request the user makes after a write goes back to the replica.
We have seen our replication time around 0-1 seconds average, but up to 15 (😱) depending on the operations occurring.
Today this can have a genuine effect:
This PR adds an opt in
PreventStaleDatabaseReadsmiddleware - so no b/c 🥇When a user makes a write, it stores a timestamp in the session. For the next few seconds (2 by default), that user’s reads use the write connection, so they always see their own changes. After that, reads go back to the replica.
The delay can also be fully customized:
We can handle this ourselves in userland, but felt like it would be something nice for the framework to do.. as it already offers sticky connections etc.
Couple things:
I found rails has middleware like this also before sending it, so thought this could be of interest.
Feel free to adjust etc, as wasn't 100% on the naming or throw it away if theres no interest.