The problem

Sometimes one request starts a piece of work and another request needs to wait until that work is finished. The requests may be handled by different Rails processes, so a mutex or a condition variable stored in memory will not help.

Redis lists are a convenient way to coordinate this because Redis is shared by all application processes and provides a blocking pop operation.

The implementation

module CompletionLatch
  KEY_EXPIRE_SECONDS = 60
  TIMEOUT_SECONDS    = 20

  def self.key(id)
    "completion_latch:#{id}"
  end

  def self.start(id)
    Redis.current.rpush(key(id), "started")
    Redis.current.expire(key(id), KEY_EXPIRE_SECONDS)
  end

  def self.done(id)
    Redis.current.rpush(key(id), "done")
  end

  def self.block_until_done(id)
    DonePredicate.new(key(id)).call
  end

  class DonePredicate < ConstantStruct[:key]
    def call
      value = Redis.current.rpop(key)

      consume(value)
    end

    protected

    def consume(value)
      case value
      when nil,
           "done"
        true
      when "started"
        _, value = Redis.current.brpop(key, timeout: TIMEOUT_SECONDS)

        if value.nil?
          false
        else
          consume(value)
        end
      else
        raise "Unsupported value #{value}"
      end
    end
  end
end

ConstantStruct[:key] is the immutable value-object helper used in this application; for this example its relevant job is to expose the Redis key to the predicate.

The list is a small state machine. start pushes a "started" marker and gives the key a TTL, so abandoned synchronization state eventually disappears. done pushes a "done" marker.

The interesting part is block_until_done. It first uses RPOP, which does not block:

  • When it gets "done", the work has already finished.
  • When the list does not exist, there is no work to wait for, so it also returns true.
  • When it gets "started", it uses BRPOP and waits for the next value, but no longer than TIMEOUT_SECONDS.

If the producer pushes "done" during that time, BRPOP returns it and the predicate succeeds. If the timeout is reached first, Redis returns no value and the predicate returns false.

It also handles the case where the work finishes before the second request starts waiting. The list then contains both markers:

["started", "done"]

Because values are popped from the right, block_until_done sees "done" immediately and does not wait.

A concrete example

Let’s say that refreshing a vehicle requires a call to an external VIN decoder. The call normally takes a few seconds. While the refresh request is in progress, a concurrent show request should wait for the new data instead of returning the old data.

resources :vehicles, only: :show do
  member do
    post :refresh
  end
end

Both actions can live in the same controller even when different Rails processes handle their requests:

class VehiclesController < ApplicationController
  def refresh
    vehicle   = current_user.vehicles.find(params[:id])
    lookup_id = SecureRandom.uuid

    CompletionLatch.start(lookup_id)

    begin
      vehicle.update!(vin_lookup_id:     lookup_id,
                      vin_lookup_status: :refreshing)

      vin_data = VinDecoder.lookup(vehicle.vin)
      vehicle.update!(vin_data: vin_data, vin_lookup_status: :ready)
    rescue StandardError => error
      vehicle.update!(vin_lookup_status: :failed,
                      vin_lookup_error:  error.message)
      raise
    ensure
      CompletionLatch.done(lookup_id)
    end

    render json: vehicle
  end

  def show
    vehicle = current_user.vehicles.find(params[:id])

    if vehicle.refreshing? &&
       !CompletionLatch.block_until_done(vehicle.vin_lookup_id)
      response.set_header("Retry-After", "2")
      head :accepted
      return
    end

    render json: vehicle.reload
  end
end

The lookup has a unique id for every refresh, which prevents an old completion signal from being reused. Putting done in ensure wakes the waiting request on both success and failure. The show action reloads the vehicle after waiting because the database remains the source of truth; Redis only coordinates the two requests.

If the VIN decoder responds within 20 seconds, show continues as soon as the new data has been saved. If not, it responds with 202 Accepted and the client can retry later.

Important limitations

This is deliberately a one-shot synchronization mechanism. It assumes one producer, one waiter, and one start/done cycle for a given id. A Redis list is a queue: a popped message is consumed. It does not broadcast completion to multiple waiting requests.

There is also an intentional ordering assumption. The request which calls start must do so before another request calls block_until_done; otherwise a missing key is interpreted as “nothing to wait for”. Use a unique id for each run rather than reusing an id for several executions.

The completion signal is expected before KEY_EXPIRE_SECONDS elapses. If the "started" key expires first, a later call to done creates a new Redis list without a TTL. If late completions are possible, done should set an expiry as well.

BRPOP blocks the Rails request thread and holds a Redis connection while it is waiting. The timeout therefore needs to be short, and the Redis connection pool must be sized for the maximum number of simultaneous waiters. For longer jobs I would return a pending response and let the client poll, or notify it asynchronously instead.

Within those constraints, the list gives us a small cross-process latch without polling Redis in a loop. The application either observes that the work has already completed, waits for its completion signal, or gives up after a bounded amount of time.