Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimistic locking & the HTTP If-Match header

What are your experiences on using If-Match to implement an optimistic locking scheme on a web service?

To simplify things, let's say we're building a simple CMS, consisting solely on "pages", each having just a body. If two users begin editing the same page simultaneously, then only the changes made by the user who were last to save are committed (or rather, they overwrite the ones made by the other user.)

To prevent this, I plan on using conditional PUTs, i.e. fetching the value of the ETag response header, and supplying it as the value of the If-Match header on the PUT request. If this value does not match the one based on the current state of the page, the server rejects the PUT with a 412.

I'm aware of the obvious pitfall, in which race conditions can occur between the precondition check and the actual database update, but those can be remedied with transactions and the sort.

Have you tried this out in practice? Is it a bad idea?

like image 640
Daniel Schierbeck Avatar asked May 08 '26 19:05

Daniel Schierbeck


1 Answers

Well, this is one of the things If-Match was designed for, and yes, this works as designed.

like image 94
Julian Reschke Avatar answered May 11 '26 01:05

Julian Reschke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!