Use Cats Effect Ref for shared state without lost updates. Build an atomic in-flight job registry, understand retryable callbacks, and handle cleanup on failure and cancellation.
Use Cats Effect Ref for shared state without lost updates. Build an atomic in-flight job registry, understand retryable callbacks, and handle cleanup on failure and cancellation.
Ref in Cats Effect gives fibers a shared state cell with atomic operations. It is useful for counters, small in-memory registries, and immutable configuration snapshots. The difficult part is choosing which reads and changes must happen together.
A counter can still lose updates even when both its reads and writes use Ref. A callback can still be unsafe if it performs side effects. A local state transition can succeed while the external operation that follows it fails. Understanding those boundaries makes Ref useful beyond the introductory counter example.
In this article in the Cats, Cats Effect & fs2 series, I will start with the core operations, then build a small in-flight job registry. The registry admits a job only when its ID is not already active and capacity remains. Both checks and the state change will happen in one transition.
Ref[F, A] holds a value of type A and exposes operations through the effect F. Here, Ref[IO, Int] is a reference containing an integer, while counter.get is an IO[Int] that reads it when executed.
The cell can change. The values stored in it should be immutable. Updating a reference from one immutable set to another is a controlled state transition. Placing a mutable collection inside the reference and changing that collection directly bypasses the API.
The examples use these pinned dependencies and imports:
//> using scala "3.3.8"
//> using dep "org.typelevel::cats-core:2.13.0"
//> using dep "org.typelevel::cats-effect:3.6.3"
import cats.effect.{Deferred, IO, IOApp, Ref, Resource}
import cats.syntax.all.*The file uses Scala 3.3.8, Cats Core 2.13.0, and Cats Effect 3.6.3. These are tested example versions, rather than a claim about the newest release. IOApp.Simple runs the complete program. Resource scopes accepted job claims. Deferred appears in the checks to coordinate fibers without relying on timing guesses.
The basic operations make the effect boundary visible:
def basicOperations: IO[(Int, Int, Int)] =
for
counter <- Ref.of[IO, Int](0)
_ <- counter.set(10)
_ <- counter.update(_ + 1)
before <- counter.getAndUpdate(_ + 1)
after <- counter.updateAndGet(_ + 1)
current <- counter.get
yield (before, after, current)When this sequential example runs, it returns (11, 13, 13). The reference starts at zero, set replaces it with ten, and update increments it to eleven. getAndUpdate returns eleven while storing twelve. updateAndGet stores and returns thirteen. The final get reads thirteen.
| Operation | Return value | Purpose |
|---|---|---|
get | F[A] | Read the current value. |
set(a) | F[Unit] | Replace it with the supplied value. |
update(f) | F[Unit] | Atomically calculate and store a replacement. |
getAndUpdate(f) | F[A] | Update and return the prior value. |
updateAndGet(f) | F[A] | Update and return the committed new value. |
modify(f) | F[B] | Atomically calculate next state and a returned result. |
get returns a snapshot. Another fiber can change the reference immediately afterward. Similarly, updateAndGet returns the value committed by that operation; it does not promise that a later read will see the same value. The Ref API documents these return contracts.
The integer is deliberately small fixture data. Atomic operations do not change integer overflow behavior or validate a business invariant automatically. The transition function and the chosen value type still need to represent the intended calculation.
Ref.of[IO, A](initial) returns an allocation program. It does not return the reference directly. Evaluating that program creates a cell, and the resulting handle identifies which cell later operations use.
def allocationExample: IO[(Int, Int)] =
val allocate = Ref.of[IO, Int](0)
for
first <- allocate
second <- allocate
_ <- first.update(_ + 1)
fromFirst <- first.get
fromSecond <- second.get
yield (fromFirst, fromSecond)This returns (1, 0). The same allocate value is evaluated twice, so it creates two references. Incrementing the first does not change the second. Assigning an allocation IO to a val does not memoize its result.
For service-wide state, allocate the reference while constructing the service, then pass that handle to every operation that should share it. Allocating a fresh reference inside every request creates per-request state. Both lifetimes can be useful, but they answer different questions.
The job registry below follows this pattern: its factory allocates one reference, and the returned registry retains that handle. Creating two registries creates two independent sets of active jobs.
Consider this increment:
def incrementSeparately(counter: Ref[IO, Int]): IO[Unit] =
counter.get.flatMap(current => counter.set(current + 1))The individual read and write are safe operations. The pair is not one atomic read-modify-write. Two fibers can both read zero, calculate one, and each store one. The final counter is one even though both increments completed.
The operation that needs atomicity is the whole transition from the current value to its successor:
def incrementAtomically(counter: Ref[IO, Int]): IO[Unit] =
counter.update(_ + 1)update makes that transition atomic. Two completed increments from zero produce two, even when the fibers compete. It does not make every surrounding statement atomic, and it does not establish an order for unrelated work elsewhere in the program.
The complete source includes a deterministic lost-update check. Two Deferred signals arrange for both reads to finish before either write proceeds. That demonstrates the problematic interleaving directly. An uncontrolled concurrency test may happen to pass without exposing the race.
A backend admission decision often needs more than an increment. Suppose this process should run at most two distinct job IDs at once. A claim can be accepted, rejected because the ID is already active, or rejected because the registry is full.
Checking activeIds and then adding an ID in a separate operation would recreate the counter problem. Another fiber could claim the same ID or consume the remaining capacity between those operations.
modify accepts a pure function with the shape A => (A, B). The first tuple element is the next state. The second is the result returned to the caller. That lets one transition choose the outcome and record the state that makes it valid.
enum Claim:
case Accepted, AlreadyActive, AtCapacity
final class InFlight private (
capacity: Int,
state: Ref[IO, Set[String]]
):
def claim(id: String): IO[Claim] =
state.modify { active =>
if active.contains(id) then (active, Claim.AlreadyActive)
else if active.size >= capacity then (active, Claim.AtCapacity)
else (active + id, Claim.Accepted)
}
def release(id: String): IO[Unit] = state.update(_ - id)
def activeIds: IO[Set[String]] = state.get
def permit(id: String): Resource[IO, Claim] =
Resource.make(claim(id)) {
case Claim.Accepted => release(id)
case _ => IO.unit
}
object InFlight:
def create(capacity: Int): IO[InFlight] =
if capacity <= 0 then
IO.raiseError(new IllegalArgumentException("capacity must be positive"))
else
Ref.of[IO, Set[String]](Set.empty)
.map(state => new InFlight(capacity, state))InFlight.create validates that capacity is positive and allocates one Ref[IO, Set[String]]. Capacity is fixed configuration for this instance. The set contains only active IDs, and every claim examines and replaces that one state value.
The order of the checks is deliberate. An existing ID receives AlreadyActive even if the registry is also full. A new ID receives AtCapacity when no slot remains. An accepted claim adds the ID and returns Accepted as part of the same atomic operation.
With capacity two and Set("job-1") already active, claiming "job-2" stores Set("job-1", "job-2") and returns Accepted. Another new ID is then rejected. Without an intervening release, two claims for the same previously absent ID cannot both be accepted.
The reference is private, so normal callers cannot replace its set arbitrarily. activeIds returns an immutable snapshot. It is useful for observation, but a later decision should still use claim rather than trusting that snapshot as a reservation.
A transition callback describes how to calculate a candidate next state. It may be evaluated more than once. In the pinned JVM implementation, an update reads the current value, computes a candidate, and tries a compare-and-set. If another writer wins first, the operation can read again and retry the callback.
That implementation detail explains an important programming rule: do not send a request, write a log, mutate another object, read the clock, or generate a random value inside the callback. Those actions could occur for a candidate that is never committed, or occur more than once. The registry callback only examines an immutable set, creates a replacement, and returns a decision.
The caller receives the result associated with the successful transition. That does not mean the callback itself ran exactly once. Keep the calculation short as well as pure: repeated expensive work and contention on one cell can make updates costly. The JVM implementation is not a promise of bounded latency for each caller, and other target platforms use different implementations.
Run external effects after deciding what state transition to commit. That ordering still leaves a boundary: committing a state change and performing an external action are separate events. Ref cannot make a local claim and a remote job execution into one durable transaction.
The registry’s permit method returns a Resource[IO, Claim]. Its acquisition calls claim; its finalizer removes the ID only if that acquisition was accepted. Application code can then scope the actual work:
def runJob(registry: InFlight, id: String)(work: IO[Unit]): IO[Claim] =
registry.permit(id).use {
case Claim.Accepted => work.as(Claim.Accepted)
case rejected => IO.pure(rejected)
}An accepted job runs the supplied work. An AlreadyActive or AtCapacity result skips it. When the accepted scope exits normally, fails, or is canceled under the running Cats Effect program, Resource releases the claim. A rejected scope must not release another job’s existing claim.
Resource also handles the boundary between acquisition and installing cleanup. Writing a separate claim followed later by work.guarantee(release(id)) requires care: cancellation can occur after the claim succeeds but before the finalizer has been installed. Keeping acquisition and release in a resource expresses the intended lifetime directly.
The low-level claim and release methods remain visible for the demonstration and checks. Application callers should use the scoped API and avoid mixing it with manual releases. This example has no ownership token: manually releasing an ID owned by another scope, or releasing it again after it has been reclaimed, can break the registry protocol.
Cleanup is also not persistence. Process termination loses this in-memory registry, and an external system may continue an operation after local cancellation. The registry tracks the lifetime of the wrapped local scope. It does not prove exactly-once job execution.
If a transition must preserve an invariant across several fields, consider storing those fields in one immutable case class inside one reference. Then a single modify can derive a valid replacement for the whole state.
Updating two references separately does not create a transaction across them. A fiber can observe the state between the two operations, and failure or cancellation can leave only the first update completed. Ref does not add rollback for a sequence of updates.
Immutability matters inside the value too. A case class that contains a mutable map still contains mutable state. If callers obtain that map and mutate it directly, they can bypass the reference’s atomic operations and invalidate snapshot reasoning.
The scope is local to the process. Another service replica has its own references, and restarting this process creates new state. A local in-flight guard can reduce duplicate concurrent work in one instance. Global uniqueness, durable quotas, inventory, and financial balances need an appropriate external consistency design.
The registry intentionally rejects work when it cannot admit it. It does not queue callers, promise fairness, or wait for capacity to become free. Busy-polling activeIds would add work without providing a good coordination protocol.
| Requirement | Starting point |
|---|---|
| Read or atomically replace a current value. | Ref |
| Wait for a one-time result or signal. | Deferred |
| Wait for a bounded execution permit. | Semaphore |
| Run a cooperating effectful critical section exclusively. | Mutex |
| Keep state across restarts or coordinate replicas. | An appropriate durable store or distributed coordination system. |
A Deferred lets a fiber suspend until a one-time result is available. A Semaphore manages permits when work should wait for capacity. A Mutex coordinates exclusive access around an effectful critical section. These solve different problems from storing a current state snapshot.
I would reach for Ref when the shared value has a clear immutable representation and its transition can be calculated quickly without effects. If the requirement is primarily waiting, queueing, or serializing effectful work, start with the primitive that already supplies those semantics.
Save the expanded source as RefExamples.scala and run scala run RefExamples.scala with Scala CLI. It includes the dependency pins, core operations, allocation example, registry, scoped job execution, and checks. The concurrency checks coordinate entry explicitly rather than assuming a sleep is enough to expose a race.
//> using scala "3.3.8"
//> using dep "org.typelevel::cats-core:2.13.0"
//> using dep "org.typelevel::cats-effect:3.6.3"
import cats.effect.{Deferred, IO, IOApp, Ref, Resource}
import cats.syntax.all.*
object RefExamples extends IOApp.Simple:
def basicOperations: IO[(Int, Int, Int)] =
for
counter <- Ref.of[IO, Int](0)
_ <- counter.set(10)
_ <- counter.update(_ + 1)
before <- counter.getAndUpdate(_ + 1)
after <- counter.updateAndGet(_ + 1)
current <- counter.get
yield (before, after, current)
def incrementSeparately(counter: Ref[IO, Int]): IO[Unit] =
counter.get.flatMap(current => counter.set(current + 1))
def incrementAtomically(counter: Ref[IO, Int]): IO[Unit] =
counter.update(_ + 1)
def allocationExample: IO[(Int, Int)] =
val allocate = Ref.of[IO, Int](0)
for
first <- allocate
second <- allocate
_ <- first.update(_ + 1)
fromFirst <- first.get
fromSecond <- second.get
yield (fromFirst, fromSecond)
enum Claim:
case Accepted, AlreadyActive, AtCapacity
final class InFlight private (
capacity: Int,
state: Ref[IO, Set[String]]
):
def claim(id: String): IO[Claim] =
state.modify { active =>
if active.contains(id) then (active, Claim.AlreadyActive)
else if active.size >= capacity then (active, Claim.AtCapacity)
else (active + id, Claim.Accepted)
}
def release(id: String): IO[Unit] = state.update(_ - id)
def activeIds: IO[Set[String]] = state.get
def permit(id: String): Resource[IO, Claim] =
Resource.make(claim(id)) {
case Claim.Accepted => release(id)
case _ => IO.unit
}
object InFlight:
def create(capacity: Int): IO[InFlight] =
if capacity <= 0 then
IO.raiseError(new IllegalArgumentException("capacity must be positive"))
else
Ref.of[IO, Set[String]](Set.empty)
.map(state => new InFlight(capacity, state))
def runJob(registry: InFlight, id: String)(work: IO[Unit]): IO[Claim] =
registry.permit(id).use {
case Claim.Accepted => work.as(Claim.Accepted)
case rejected => IO.pure(rejected)
}
private def check(condition: Boolean): IO[Unit] = IO(assert(condition))
private def lostUpdate: IO[Int] =
for
counter <- Ref.of[IO, Int](0)
firstRead <- Deferred[IO, Unit]
secondRead <- Deferred[IO, Unit]
first = counter.get.flatMap { current =>
firstRead.complete(()).void *> secondRead.get *> counter.set(current + 1)
}
second = counter.get.flatMap { current =>
secondRead.complete(()).void *> firstRead.get *> counter.set(current + 1)
}
_ <- (first, second).parTupled
result <- counter.get
yield result
def run: IO[Unit] =
for
basic <- basicOperations
_ <- check(basic == (11, 13, 13))
separate <- allocationExample
_ <- check(separate == (1, 0))
shared <- Ref.of[IO, Int](0)
_ <- incrementAtomically(shared)
_ <- incrementAtomically(shared)
sharedResult <- shared.get
_ <- check(sharedResult == 2)
lost <- lostUpdate
_ <- check(lost == 1)
atomic <- Ref.of[IO, Int](0)
_ <- List.fill(100)(incrementAtomically(atomic)).parSequence
atomicResult <- atomic.get
_ <- check(atomicResult == 100)
sequential <- Ref.of[IO, Int](0)
_ <- incrementSeparately(sequential) *> incrementSeparately(sequential)
sequentialResult <- sequential.get
_ <- check(sequentialResult == 2)
invalid <- InFlight.create(0).attempt
negative <- InFlight.create(-1).attempt
_ <- check(invalid.isLeft && negative.isLeft)
duplicateRegistry <- InFlight.create(2)
duplicateResults <- List.fill(20)(duplicateRegistry.claim("job-1")).parSequence
duplicateState <- duplicateRegistry.activeIds
_ <- check(duplicateResults.count(_ == Claim.Accepted) == 1)
_ <- check(duplicateResults.count(_ == Claim.AlreadyActive) == 19)
_ <- check(duplicateState == Set("job-1"))
boundedRegistry <- InFlight.create(3)
capacityResults <- (1 to 20).toList.map(n => boundedRegistry.claim(s"job-$n")).parSequence
boundedState <- boundedRegistry.activeIds
_ <- check(capacityResults.count(_ == Claim.Accepted) == 3)
_ <- check(capacityResults.count(_ == Claim.AtCapacity) == 17)
_ <- check(boundedState.size == 3)
_ <- boundedRegistry.release(boundedState.head)
reduced <- boundedRegistry.activeIds
_ <- check(reduced.size == 2)
replacement <- boundedRegistry.claim("replacement")
_ <- check(replacement == Claim.Accepted)
afterReplacement <- boundedRegistry.activeIds
_ <- check(afterReplacement.size == 3 && afterReplacement.contains("replacement"))
lifecycleRegistry <- InFlight.create(1)
workRan <- Ref.of[IO, Int](0)
completed <- runJob(lifecycleRegistry, "normal")(workRan.update(_ + 1))
normalState <- lifecycleRegistry.activeIds
workCount <- workRan.get
_ <- check(completed == Claim.Accepted && normalState.isEmpty && workCount == 1)
_ <- lifecycleRegistry.permit("held").use { result =>
for
_ <- check(result == Claim.Accepted)
duplicate <- runJob(lifecycleRegistry, "held")(workRan.update(_ + 1))
full <- runJob(lifecycleRegistry, "other")(workRan.update(_ + 1))
whileHeld <- lifecycleRegistry.activeIds
_ <- check(duplicate == Claim.AlreadyActive && full == Claim.AtCapacity)
_ <- check(whileHeld == Set("held"))
yield ()
}
afterHeld <- lifecycleRegistry.activeIds
afterRejectedWork <- workRan.get
_ <- check(afterHeld.isEmpty && afterRejectedWork == 1)
problem = new RuntimeException("job failed")
failed <- runJob(lifecycleRegistry, "failed")(IO.raiseError(problem)).attempt
afterFailure <- lifecycleRegistry.activeIds
_ <- check(failed == Left(problem) && afterFailure.isEmpty)
started <- Deferred[IO, Unit]
running <- runJob(lifecycleRegistry, "cancelled")(started.complete(()).void *> IO.never).start
_ <- started.get
whileRunning <- lifecycleRegistry.activeIds
_ <- check(whileRunning == Set("cancelled"))
_ <- running.cancel
afterCancellation <- lifecycleRegistry.activeIds
_ <- check(afterCancellation.isEmpty)
_ <- IO.println(s"Counter before/after/current: $basic")
_ <- IO.println(s"Two allocations: $separate")
_ <- IO.println(s"Lost update: $lost; atomic updates: $atomicResult")
_ <- IO.println(s"Accepted duplicate claims: ${duplicateResults.count(_ == Claim.Accepted)}")
_ <- IO.println(s"Capacity: ${boundedState.size}; final scoped state: $afterCancellation")
_ <- IO.println("All Ref checks passed.")
yield ()The useful question is where the state transition begins and ends. Allocate the cell at the intended lifetime, share its handle, keep the stored value immutable, and use update or modify when a decision depends on the current state. Keep effects and resource lifetimes explicit around that transition. Continue from the Cats, Cats Effect & fs2 series page or explore the Scala and functional programming articles.
Scala, JVM, AI, and backend systems. I send practical articles when there is something worth reading.
Join the newsletterNecessary cookies keep the site working. With your permission, I use analytics cookies to understand which articles are useful.