haskellstmunsafe-perform-io

Safe to use unsafeIOToSTM to read from database?


In this pseudocode block:

atomically $ do
  if valueInLocalStorage key
      then readValueFromLocalStorage key
      else do
        value <- unsafeIOToSTM $ fetchValueFromDatabase key
        writeValueToLocalStorage key value

Is it safe to use unsafeIOToSTM? The docs say:


Solution

  • I would suggest that doing I/O from an STM transaction is just a bad idea.

    Presumably what you want is to avoid two threads doing the DB lookup at the same time. What I would do is this: