ExResilience.Coalesce (ex_resilience v0.4.0)

Copy Markdown View Source

Request deduplication (singleflight) implemented as a GenServer.

When multiple callers request the same key concurrently, only one execution runs and all callers receive the same result. Once the execution completes, subsequent calls for the same key trigger a new execution.

Uses ETS for the in-flight key lookup (hot path) and GenServer for waiter coordination.

Options

  • :name -- required. Registered name for this coalesce instance.

Examples

iex> {:ok, _} = ExResilience.Coalesce.start_link(name: :test_coal)
iex> ExResilience.Coalesce.call(:test_coal, :my_key, fn -> 42 end)
{:ok, 42}

Summary

Functions

Executes fun with request deduplication keyed by key.

Returns a specification to start this module under a supervisor.

Starts a coalesce process.

Types

option()

@type option() :: {:name, atom()}

result()

@type result() :: {:ok, term()} | {:error, term()}

Functions

call(name, key, fun)

@spec call(atom(), term(), (-> term())) :: result()

Executes fun with request deduplication keyed by key.

If no in-flight request exists for key, spawns a task to execute fun and registers the caller as the first waiter. If an in-flight request already exists, the caller joins the existing execution.

All waiters receive the same result when the execution completes.

Returns {:ok, result} on success or {:error, reason} on failure.

Examples

iex> {:ok, _} = ExResilience.Coalesce.start_link(name: :test_coal2)
iex> ExResilience.Coalesce.call(:test_coal2, :key_a, fn -> :hello end)
{:ok, :hello}

child_spec(init_arg)

Returns a specification to start this module under a supervisor.

See Supervisor.

start_link(opts)

@spec start_link([option()]) :: GenServer.on_start()

Starts a coalesce process.

See module docs for available options.