Ref in Cats Effect: Safe Shared State and Atomic Updates

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.

A shared cell with an effectful API

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.

Start with get, set, and update

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.

OperationReturn valuePurpose
getF[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.

Allocate once when callers should share state

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.

Why get followed by set loses updates

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.

A get followed by set can lose an increment while atomic update preserves both One possible interleaving begins at counter zero. Fiber A reads zero, fiber B reads zero, A writes one and B writes one. The final counter is one. Each get and set is atomic but the pair is not. With atomic update plus one, a successful transition changes zero to one and the next changes one to two. The final counter is two. Two atomic operations do not form one atomic step.One possible interleaving. The shared counter starts at 0.get, then setupdate(_ + 1)1. Fiber A reads 02. Fiber B reads 03. Fiber A writes 14. Fiber B writes 1Final counter: 1One increment is lost.Fiber A updates0 → 1Fiber B updates1 → 2Final counter: 2Each step uses current state.get and set are each atomic. Their combination is not.
A get followed by set can lose an increment while atomic update preserves both One possible interleaving begins at counter zero. Fiber A reads zero, fiber B reads zero, A writes one and B writes one. The final counter is one. Each get and set is atomic but the pair is not. With atomic update plus one, a successful transition changes zero to one and the next changes one to two. The final counter is two. Atomic calls do not makean atomic workflow.Counter starts at 0.get, then set1. Fiber A reads 02. Fiber B reads 03. Fiber A writes 14. Fiber B writes 1Final counter: 1One increment is lost.update(_ + 1)Fiber A updates0 → 1Fiber B updates1 → 2Final counter: 2Each update uses current state.get and set are each atomic.Their combination is not.
This is an explicit interleaving, not a timing prediction. Each get and set is atomic on its own. Ref.update combines the read and state transition into one atomic operation, so both increments are retained.

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.

Use modify when the decision and change belong together

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.

InFlight atomically claims an active job ID while enforcing fixed capacity InFlight has fixed capacity two configured outside a private Ref of IO of Set of String. The Ref starts with job-1. claim job-2 runs a pure modify callback that checks membership and capacity, commits the new set containing job-1 and job-2 and returns Claim.Accepted. A new job ID now receives AtCapacity and a duplicate receives AlreadyActive. The callback may be retried. External work runs afterward as a separate effect. One atomic claim protects registry capacity.InFlight: capacity = 2 (fixed configuration)Ref[IO, Set[String]]claim("job-2")Before: {"job-1"}Already active? No. At capacity? No.pure modify callbackNext: {"job-1", "job-2"}Result: Claim.AcceptedThe state transition and decision belong to one commit.A new ID now gets AtCapacity. A duplicate gets AlreadyActive.The modify callback may run more than once.Keep it pure. External work runs afterward in a separate effect.One process. One shared Ref. No transaction across external systems.
InFlight atomically claims an active job ID while enforcing fixed capacity InFlight has fixed capacity two configured outside a private Ref of IO of Set of String. The Ref starts with job-1. claim job-2 runs a pure modify callback that checks membership and capacity, commits the new set containing job-1 and job-2 and returns Claim.Accepted. A new job ID now receives AtCapacity and a duplicate receives AlreadyActive. The callback may be retried. External work runs afterward as a separate effect. One atomic claim protectsregistry capacity.InFlight: capacity = 2Fixed configuration outside Ref.Ref[IO, Set[String]]claim("job-2")Before{"job-1"}Already active? No.At capacity? No.pureNext{"job-1", "job-2"}Claim.AcceptedState and decision commit together.New ID: AtCapacity.Duplicate: AlreadyActive.The callback may run again.Keep it pure.External work runs afterwardin a separate effect.One process. One shared Ref.No external transaction.
The capacity is fixed configuration. A private Ref contains only the immutable active-ID set. One modify checks the current set, commits the next set and returns its Claim decision. The callback can be retried, so external work belongs outside it. Work that follows can fail or be canceled; Ref does not make it transactional.

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.

Keep update and modify callbacks pure

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.

Scope accepted claims so cleanup survives failure and cancellation

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.

One reference is one atomicity boundary

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.

Use a coordination primitive when callers need to wait

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.

RequirementStarting 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.

Run the complete example

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.

Complete runnable RefExamples.scala and checks
//> 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.

Share
Edit Template

Get new engineering deep dives

Scala, JVM, AI, and backend systems. I send practical articles when there is something worth reading.

Join the newsletter