{"id":64,"date":"2009-07-18T20:33:07","date_gmt":"2009-07-19T00:33:07","guid":{"rendered":"http:\/\/joemorrison.org\/blog\/?p=64"},"modified":"2009-07-18T20:33:07","modified_gmt":"2009-07-19T00:33:07","slug":"serializable-synchronized-especially-not-with-oracle","status":"publish","type":"post","link":"https:\/\/morrison.today\/blog\/2009\/07\/18\/serializable-synchronized-especially-not-with-oracle\/","title":{"rendered":"Serializable != Synchronized, especially not with Oracle"},"content":{"rendered":"<p>Recently I wrote some database code and tried to convince myself that it was threadsafe. I realized I&#8217;d made a basic mistake about the <strong>serializable<\/strong> isolation level, and thought it was worth a quick blog entry to post the explanation, in case anyone else runs into this situation. The problem can be represented by this simplified example:<\/p>\n<figure id=\"attachment_66\" aria-describedby=\"caption-attachment-66\" style=\"width: 747px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-66\" title=\"Transaction Example\" src=\"https:\/\/morrison.today\/blog\/wp-content\/uploads\/2009\/07\/serializableexample1.png\" alt=\"Transaction Example\" width=\"747\" height=\"285\" srcset=\"https:\/\/morrison.today\/blog\/wp-content\/uploads\/2009\/07\/serializableexample1.png 747w, https:\/\/morrison.today\/blog\/wp-content\/uploads\/2009\/07\/serializableexample1-300x114.png 300w\" sizes=\"auto, (max-width: 747px) 100vw, 747px\" \/><figcaption id=\"caption-attachment-66\" class=\"wp-caption-text\">Transaction Example<\/figcaption><\/figure>\n<p>Both transactions are trying to process withdrawals of $100. In either case, if the balance is sufficient, a status message is sent to a downstream system and the balance is reduced. Otherwise the transaction is aborted. If these transactions are run in the <strong>serializable<\/strong> isolation level, can they be executed concurrently without fear of overdrawing the account, sending the status message more than once, or creating any other problems? Actually, no.<\/p>\n<p><!--more-->A cursory read of the documentation on database isolation levels might lead you to believe that <strong>serializable <\/strong>means that transactions act as though they are being run serially, i.e. as if they had been <strong>synchronized<\/strong> (using Java terminology). But that would be wrong. Databases are only required to honor commitments about serializability from the perspective of the data they store. So in the example above, the database&#8217;s only responsibility is to ensure that the balance doesn&#8217;t go negative.<\/p>\n<p><strong>Oracle <\/strong>read the fine print carefully and came up with a creative way to improve performance. It lets both transactions proceed full steam ahead, but only permits the first update statement to succeed. The second update will fail with an error:<\/p>\n<pre class=\"CE\">ORA-08177: Can't serialize access for this transaction.<\/pre>\n<p>Your application has to check for this error and retry the whole transaction until it succeeds. It&#8217;s really quite smart. Essentially, Oracle is optimistically running the transactions as quickly as possible, hoping they <em>would have been<\/em> serializable. If that turns out to be wrong, Oracle tries to forget the whole thing happened by aborting the transaction. The result is higher concurrency and better performance than the more obvious locking based design, and it faithfully preserves the serializability rule.<\/p>\n<p>The only problem is that in our example, the status message will get sent too many times. Oracle doesn&#8217;t care about the serializability of your non database-related application code. In the example above, only one of the transactions should succeed because the initial balance is $100. But both of them will send the message. The moral here is that you can&#8217;t use the <strong>serializable<\/strong> database isolation level to manage concurrency in your application code.<\/p>\n<p>So what can you do? You could serialize the whole application code sequence (i.e. wrap it all in a synchronized block) but that would be needlessly throwing away performance. You could create a thread pool that guarantees that requests for the same ID will get serviced by the same thread, but that would be needlessly complicated. The simplest solution (which will work even if you run multiple instances of your entire application) is to have the database lock the row during the transaction, so that if any other transactions touch that row they will block until the running transaction completes. <\/p>\n<p>Oracle allows you to do this by adding the clause <strong>FOR UPDATE<\/strong> to your select command, i.e.<\/p>\n<pre>select balance from account where id = 123 for update<\/pre>\n<p>That&#8217;s nice and simple, allows you to run your transaction in the usual, uncomplicated <strong>READ_COMMITTED<\/strong> isolation level, allows concurrent processing of different database rows without any possibility of race conditions, and doesn&#8217;t require any synchronization in your application code. Unfortunately it&#8217;s not portable. It works with Oracle and Sybase, but the rules for MS SQLServer are different.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Recently I wrote some database code and tried to convince myself that it was threadsafe. I realized I&#8217;d made a basic mistake about the serializable isolation level, and thought it was worth a quick blog entry to post the explanation, in case anyone else runs into this situation. The problem can be represented by this [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[10,8],"tags":[29,28,27,30],"class_list":["post-64","post","type-post","status-publish","format-standard","hentry","category-architecture","category-general-development","tag-isolation","tag-oracle","tag-serializable","tag-synchronized"],"blocksy_meta":"","_links":{"self":[{"href":"https:\/\/morrison.today\/blog\/wp-json\/wp\/v2\/posts\/64","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/morrison.today\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/morrison.today\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/morrison.today\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/morrison.today\/blog\/wp-json\/wp\/v2\/comments?post=64"}],"version-history":[{"count":12,"href":"https:\/\/morrison.today\/blog\/wp-json\/wp\/v2\/posts\/64\/revisions"}],"predecessor-version":[{"id":78,"href":"https:\/\/morrison.today\/blog\/wp-json\/wp\/v2\/posts\/64\/revisions\/78"}],"wp:attachment":[{"href":"https:\/\/morrison.today\/blog\/wp-json\/wp\/v2\/media?parent=64"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/morrison.today\/blog\/wp-json\/wp\/v2\/categories?post=64"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/morrison.today\/blog\/wp-json\/wp\/v2\/tags?post=64"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}