How do Optimistic Locks work? 🤔

Publicado el: 18 mayo 2024
en el canal de: mostdevwill
3,179
64

How do Optimistic Locks work? 🤔

Let’s discuss how a similar process to Will planning a call with Sam happens in databases.

🔹 First, there are different implementations of Optimistic Locks, but the most popular ones use either Versions (1, 2, 654…) or Timestamps.

🔹 Second, Optimistic Locks are mostly implemented at the APPLICATION LEVEL. So, your database won’t support this mechanism out of the box. Your program needs to communicate with the database and control the locks.

Ok, let’s dive in.

📝 The READ stage:
At this stage, the transaction reads some data (a row record) and memorizes the Version (e.g., 1).

🔍 In the real-world example, this is when Will checks if Sam is available at 2 p.m. and memorizes it.

📝 The UPDATE stage:
The transaction makes changes to the row and updates the Version (1 to 2). But the changes are not in the database yet. The SQL query might look like:
UPDATE accounts SET balance = ?, version = 2 WHERE id = ? AND version = 1

📌 The most important part is the condition. The version should be == 1 (the old version the transaction memorized on the READ stage).

🔍 In the real-world example, this is when Will plans his own schedule to have a call with Sam, but the time is not booked yet.

📝 The COMMIT stage:
If the row was updated, then we commit the transaction.
If no row was updated, another transaction has already updated it, so we roll back the changes and try again.

🚫 The key point here is that we didn’t block other transactions.

🔍 In the real-world example, this is like 2 p.m. arriving and Will trying to call Sam. Since he didn’t block Sam, there’s a possibility Sam is on another call.

🔒 There’s another type of lock called Pessimistic Locking.

📹 I’ll make a video about it as well. Follow me so you don’t miss it!

#Programming #Coding #Developer #SoftwareEngineer #Code #Tech


En esta página del sitio puede ver el video en línea How do Optimistic Locks work? 🤔 de Duración hora minuto segunda en buena calidad , que subió el usuario mostdevwill 18 mayo 2024, comparta el enlace con amigos y conocidos, en youtube este video ya ha sido visto 3,179 veces y le gustó 64 a los espectadores. Disfruta viendo!