Composable Shared State in Haskell with STM
Use Haskell's software transactional memory to update shared memory atomically across threads without manual locks.
27 Sept 2025, 15:39 UTC

The problem: shared mutable state across threads
Imagine a Haskell program where several threads need to move money between two in-memory accounts. If you use IORef or MVar, you must manually acquire locks, order them consistently to avoid deadlock, and remember to release them in every error path. A missed lock or an inconsistent lock order produces race conditions that are hard to reproduce.
Haskell's stm package offers a different model: software transactional memory. You describe what should happen to shared variables inside a transaction, and the GHC runtime commits all changes together or none at all. If two transactions conflict, the runtime retries one automatically instead of making you manage locks.
Core STM primitives
A TVar is a transactional variable: a box for shared mutable state that can only be read or written inside an atomically block. atomically runs a STM action as one indivisible unit. retry suspends the transaction until one of the TVars it read is modified, then tries again. orElse runs the first transaction and, if it retries, runs the second instead. Together they let you compose blocking coordination without condition variables.
STM is a GHC concurrency feature from the stm package, not Haskell 98 or Haskell 2010 syntax. It coordinates memory only; files, sockets, and database connections are outside its scope.
Worked example: transferring between accounts
This example models two bank accounts and transfers funds between them atomically. If the source account lacks sufficient funds, the transaction retries instead of committing a negative balance.
import Control.Concurrent.STM
import Control.Concurrent (forkIO, threadDelay)
import Control.Monad (forever, replicateM_)
type Account = TVar Int
transfer :: Account -> Account -> Int -> STM ()
transfer from to amount = do
balance <- readTVar from
if balance >= amount
then do
writeTVar from (balance - amount)
target <- readTVar to
writeTVar to (target + amount)
else retry
main :: IO ()
main = do
a <- atomically $ newTVar 100
b <- atomically $ newTVar 100
replicateM_ 5 $ forkIO $ atomically $ transfer a b 10
replicateM_ 5 $ forkIO $ atomically $ transfer b a 10
threadDelay 1000000
finalA <- atomically $ readTVar a
finalB <- atomically $ readTVar b
putStrLn $ "Account A: " ++ show finalA
putStrLn $ "Account B: " ++ show finalB
putStrLn $ "Total: " ++ show (finalA + finalB)
Run this with GHC: save it as transfer.hs, then compile and run with ghc -threaded transfer.hs && ./transfer +RTS -N. No special permissions are required; an ordinary user account is enough. The +RTS -N flag lets the GHC runtime use multiple capabilities so the forked threads actually run concurrently.
Expected check: both accounts stay non-negative and the total remains 200. If you accidentally call atomically inside another atomically block, GHC raises a runtime error instead of silently nesting transactions. Do not perform file or network I/O inside atomically; because a transaction may retry, side effects can run more than once and break atomicity.
Trade-offs and limits
- STM works for memory, not external resources. A transaction that writes to a
TVarand then appends to a log file is not atomic across both systems. - Long transactions read and write more
TVars, which raises conflict probability. Under high contention, repeated retries can reduce throughput. atomicallycannot be nested. Keep transaction boundaries explicit and callatomicallyfromIO, not from inside another transaction.
Verify before you rely on it
- Confirm the package is available for your GHC release:
ghc-pkg list stm. - Compile a minimal module importing
Control.Concurrent.STMand check thatTVar,atomically,retry, andorElseresolve without missing-module errors. - Run the transfer example sequentially first, then with
+RTS -N, and confirm noatomicallynesting exception appears.
Use STM when you need composable, atomic updates to in-memory state. Reach for MVar, channels, or resource-specific libraries when you must coordinate files, sockets, or database connections alongside memory.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.