From 745e13d032dd8a46654c473fb1a689b1afc217ef Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 7 Nov 2026 12:50:00 -0500 Subject: [PATCH 01/15] test(subscriptions): catch the lock error clause and catch-up retry mutants the suite let through The existing tests reached these paths only through a missing schema, which the lock probe and Postgrex errors absorb, so removing the clause, narrowing the error match, dropping the delay or the state guard went unnoticed. Closes #114 Signed-off-by: Yordis Prieto --- .../subscription_lock_refused_test.exs | 53 +++++++++++++++++++ test/subscriptions/subscription_fsm_test.exs | 47 ++++++++++++++-- 2 files changed, 96 insertions(+), 4 deletions(-) create mode 100644 test/storage/subscription_lock_refused_test.exs diff --git a/test/storage/subscription_lock_refused_test.exs b/test/storage/subscription_lock_refused_test.exs new file mode 100644 index 0000000..621ef3f --- /dev/null +++ b/test/storage/subscription_lock_refused_test.exs @@ -0,0 +1,53 @@ +defmodule EventStore.Storage.SubscriptionLockRefusedTest do + use EventStore.StorageCase + + alias EventStore.Storage.Lock + + @database "eventstore_test_xact_lock_denied" + @role "eventstore_xact_lock_denied" + + setup %{conn: conn, postgrex_config: postgrex_config} do + drop = fn -> + Postgrex.query!(conn, ~s|DROP DATABASE IF EXISTS "#{@database}" WITH (FORCE)|, []) + Postgrex.query!(conn, ~s|DROP ROLE IF EXISTS "#{@role}"|, []) + end + + drop.() + on_exit(fn -> drop.() end) + + Postgrex.query!(conn, ~s|CREATE ROLE "#{@role}" LOGIN PASSWORD 'secret'|, []) + Postgrex.query!(conn, ~s|CREATE DATABASE "#{@database}" TEMPLATE template0|, []) + + {:ok, admin} = Postgrex.start_link(Keyword.put(postgrex_config, :database, @database)) + + Postgrex.query!( + admin, + "CREATE TABLE public.subscriptions (subscription_id bigint PRIMARY KEY, " <> + "lock_generation bigint NOT NULL DEFAULT 0, last_seen bigint)", + [] + ) + + Postgrex.query!(admin, "INSERT INTO public.subscriptions (subscription_id) VALUES (1)", []) + Postgrex.query!(admin, ~s|GRANT SELECT, UPDATE ON public.subscriptions TO "#{@role}"|, []) + + Postgrex.query!( + admin, + "REVOKE EXECUTE ON FUNCTION pg_catalog.pg_try_advisory_xact_lock(integer, integer) FROM PUBLIC", + [] + ) + + GenServer.stop(admin) + + role_config = + Keyword.merge(postgrex_config, database: @database, username: @role, password: "secret") + + [role_conn: start_supervised!({Postgrex, role_config}, id: :role_conn)] + end + + test "a claim returns the error when only the advisory lock statement is refused", context do + assert {:error, %Postgrex.Error{postgres: %{code: :insufficient_privilege} = postgres}} = + Lock.claim_subscription_lock(context.role_conn, 1, schema: "public") + + assert postgres.message =~ "pg_try_advisory_xact_lock" + end +end diff --git a/test/subscriptions/subscription_fsm_test.exs b/test/subscriptions/subscription_fsm_test.exs index e707757..8933c7f 100644 --- a/test/subscriptions/subscription_fsm_test.exs +++ b/test/subscriptions/subscription_fsm_test.exs @@ -569,10 +569,49 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do assert_received {:events, [%{event_number: 1}, %{event_number: 2}, %{event_number: 3}]} end - test "ignores a retry for a subscription that is no longer waiting on one", context do - fsm = fsm(context, state: :subscribed) + test "retries a read that fails because the pool has no connection to give", context do + %{conn: conn} = context + fsm = fsm(context, state: :request_catch_up, retry_interval: 20, query_timeout: 100) + test_pid = self() + + holder = + Task.async(fn -> + Postgrex.transaction(conn, fn _held -> + send(test_pid, :connection_held) + receive do: (:release -> :ok) + end) + end) + + assert_receive :connection_held, 5_000 + + assert %SubscriptionFsm{state: :catching_up} = SubscriptionFsm.catch_up(fsm) + assert_receive :retry_catch_up, 1_000 + + send(holder.pid, :release) + assert {:ok, :ok} = Task.await(holder) + end - assert ^fsm = SubscriptionFsm.retry_catch_up(fsm) + test "waits the retry interval before reading again", context do + fsm = + fsm(context, state: :request_catch_up, schema: "no_such_schema", retry_interval: 5_000) + + assert %SubscriptionFsm{state: :catching_up} = SubscriptionFsm.catch_up(fsm) + refute_receive :retry_catch_up, 300 + end + + for state <- [:subscribed, :max_capacity] do + test "ignores a retry for a #{state} subscription even with events to read", context do + fsm = + context + |> fsm(state: unquote(state)) + |> SubscriptionFsm.connect_subscriber(self(), buffer_size: 10) + + :ok = + TestEventStore.append_to_stream(context.stream_uuid, 0, EventFactory.create_events(3)) + + assert ^fsm = SubscriptionFsm.retry_catch_up(fsm) + refute_received {:events, _events} + end end end @@ -646,7 +685,7 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do checkpoint_after: Keyword.get(overrides, :checkpoint_after, 0), checkpoint_threshold: Keyword.get(overrides, :checkpoint_threshold, 1), retry_interval: Keyword.get(overrides, :retry_interval, 60_000), - query_timeout: 15_000, + query_timeout: Keyword.get(overrides, :query_timeout, 15_000), event_store: TestEventStore, serializer: context.serializer, correlation_id_type: context.correlation_id_type, From a1933c172e6d3842c2255838738b27330ec84143 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 7 Nov 2026 12:55:02 -0500 Subject: [PATCH 02/15] test(subscriptions): keep a single catch-up retry pending while in-flight events are acked Each ack during a failed read started another retry chain, multiplying reads against a pool that was already failing. Signed-off-by: Yordis Prieto --- test/subscriptions/subscription_fsm_test.exs | 29 ++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/test/subscriptions/subscription_fsm_test.exs b/test/subscriptions/subscription_fsm_test.exs index 8933c7f..c76d5f8 100644 --- a/test/subscriptions/subscription_fsm_test.exs +++ b/test/subscriptions/subscription_fsm_test.exs @@ -599,6 +599,35 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do refute_receive :retry_catch_up, 300 end + test "keeps a single retry pending when in-flight events are acked one by one", context do + :ok = + TestEventStore.append_to_stream(context.stream_uuid, 0, EventFactory.create_events(10)) + + %SubscriptionFsm{data: data} = + context + |> fsm(state: :request_catch_up, retry_interval: 200, checkpoint_threshold: 100) + |> SubscriptionFsm.connect_subscriber(self(), buffer_size: 10) + |> SubscriptionFsm.catch_up() + + assert_received {:events, events} + assert length(events) == 10 + + failed = + SubscriptionFsm.catch_up(%SubscriptionFsm{ + state: :request_catch_up, + data: %SubscriptionState{data | schema: "no_such_schema"} + }) + + acked = + Enum.reduce(events, failed, fn %{event_number: event_number}, fsm -> + SubscriptionFsm.ack(fsm, event_number, self()) + end) + + assert %SubscriptionFsm{state: :catching_up} = acked + assert_receive :retry_catch_up, 1_000 + refute_receive :retry_catch_up, 400 + end + for state <- [:subscribed, :max_capacity] do test "ignores a retry for a #{state} subscription even with events to read", context do fsm = From 4e1cd3c5da48893e0e0a4e4635a157f8033402b9 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 7 Nov 2026 12:58:35 -0500 Subject: [PATCH 03/15] fix(subscriptions): keep one catch-up retry pending when events are acked during a failed read Every ack read at once and armed a timer nothing cancelled, so a subscription with ten events in flight ran eleven retry chains against a failing pool and its acks could time out. Closes #113 Signed-off-by: Yordis Prieto --- .../subscriptions/subscription_fsm.ex | 32 ++++++++++++++++--- .../subscriptions/subscription_state.ex | 1 + 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/lib/event_store/subscriptions/subscription_fsm.ex b/lib/event_store/subscriptions/subscription_fsm.ex index b967bb5..82d60ec 100644 --- a/lib/event_store/subscriptions/subscription_fsm.ex +++ b/lib/event_store/subscriptions/subscription_fsm.ex @@ -143,7 +143,7 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do def catch_up(%__MODULE__{data: %SubscriptionState{}} = fsm), do: fsm def retry_catch_up(%__MODULE__{state: :catching_up, data: %SubscriptionState{} = data} = fsm) do - catch_up_from_stream(fsm, data) + catch_up_from_stream(fsm, %SubscriptionState{data | retry_timer_ref: nil}) end def retry_catch_up(%__MODULE__{} = fsm), do: fsm @@ -160,6 +160,21 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do end end + # A failed read already has a retry pending, so an ack must not start another one. + def ack( + %__MODULE__{state: :catching_up, data: %SubscriptionState{retry_timer_ref: ref} = data} = + fsm, + ack, + subscriber + ) + when is_reference(ref) do + with {:ok, data} <- ack_events(data, ack, subscriber) do + %__MODULE__{fsm | state: :catching_up, data: data} + else + reply -> {reply, fsm} + end + end + def ack( %__MODULE__{state: :catching_up, data: %SubscriptionState{} = data} = fsm, ack, @@ -506,10 +521,7 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do {:error, _error} -> # A failed read says nothing about the stream, so wait out the retry interval and read again - %SubscriptionState{retry_interval: retry_interval} = data - Process.send_after(self(), :retry_catch_up, retry_interval) - - %__MODULE__{fsm | state: :catching_up, data: data} + %__MODULE__{fsm | state: :catching_up, data: schedule_retry(data)} end end @@ -517,6 +529,16 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do %__MODULE__{fsm | state: :catching_up, data: data} end + defp schedule_retry(%SubscriptionState{} = data) do + %SubscriptionState{retry_interval: retry_interval, retry_timer_ref: retry_timer_ref} = data + + if retry_timer_ref, do: Process.cancel_timer(retry_timer_ref) + + retry_timer_ref = Process.send_after(self(), :retry_catch_up, retry_interval) + + %SubscriptionState{data | retry_timer_ref: retry_timer_ref} + end + defp read_stream_forward(%SubscriptionState{} = data) do %SubscriptionState{ conn: conn, diff --git a/lib/event_store/subscriptions/subscription_state.ex b/lib/event_store/subscriptions/subscription_state.ex index 8df1eb7..2142a63 100644 --- a/lib/event_store/subscriptions/subscription_state.ex +++ b/lib/event_store/subscriptions/subscription_state.ex @@ -33,6 +33,7 @@ defmodule EventStore.Subscriptions.SubscriptionState do checkpoint_after: 0, checkpoint_threshold: 1, checkpoint_timer_ref: nil, + retry_timer_ref: nil, checkpoints_pending: 0, checkpoint_unwritten: false, subscribers: %{}, From aa642bdfaa537f47dbd1dd1a69d8fb33ab360794 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 7 Nov 2026 12:59:21 -0500 Subject: [PATCH 04/15] test(subscriptions): log why a catch-up read failed A failure in the stream lookup logged nothing above debug, so a lasting cause such as a missing grant retried forever without a trace. Signed-off-by: Yordis Prieto --- test/subscriptions/subscription_fsm_test.exs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/test/subscriptions/subscription_fsm_test.exs b/test/subscriptions/subscription_fsm_test.exs index c76d5f8..ab68026 100644 --- a/test/subscriptions/subscription_fsm_test.exs +++ b/test/subscriptions/subscription_fsm_test.exs @@ -1,6 +1,8 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do use EventStore.StorageCase + import ExUnit.CaptureLog + alias EventStore.{EventFactory, Storage, UUID} alias EventStore.Storage.Lock alias EventStore.Subscriptions.{Subscription, SubscriptionFsm, SubscriptionState} @@ -535,6 +537,15 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do assert %SubscriptionFsm{state: :catching_up} = SubscriptionFsm.catch_up(fsm) end + test "logs why the read failed", context do + fsm = fsm(context, state: :request_catch_up, schema: "no_such_schema") + + log = capture_log([level: :warning], fn -> SubscriptionFsm.catch_up(fsm) end) + + assert log =~ "failed to catch up" + assert log =~ "no_such_schema" + end + test "asks to read again after the retry interval", context do fsm = fsm(context, state: :request_catch_up, schema: "no_such_schema", retry_interval: 20) From b94534ba26c84cbda9620a0a0c0b754066839b27 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 7 Nov 2026 13:08:42 -0500 Subject: [PATCH 05/15] fix(subscriptions): log why a catch-up read failed and when it will retry A failure in the stream lookup logged nothing above debug, leaving a lasting cause such as a missing grant invisible while the subscription stopped delivering. Signed-off-by: Yordis Prieto --- lib/event_store/subscriptions/subscription_fsm.ex | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/event_store/subscriptions/subscription_fsm.ex b/lib/event_store/subscriptions/subscription_fsm.ex index 82d60ec..197909e 100644 --- a/lib/event_store/subscriptions/subscription_fsm.ex +++ b/lib/event_store/subscriptions/subscription_fsm.ex @@ -519,7 +519,12 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do # Allow subscriptions to streams which don't yet exist, but might be created later %__MODULE__{fsm | state: :subscribed, data: data} - {:error, _error} -> + {:error, error} -> + Logger.warning( + describe(data) <> + " failed to catch up, retrying in #{data.retry_interval}ms due to: " <> inspect(error) + ) + # A failed read says nothing about the stream, so wait out the retry interval and read again %__MODULE__{fsm | state: :catching_up, data: schedule_retry(data)} end From 493fa04eea06eff8c2469b2b96829819d2d5f440 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 7 Nov 2026 13:09:51 -0500 Subject: [PATCH 06/15] test(subscriptions): read again on a catch-up request or new events instead of waiting out a failed read's retry With the default retry interval a subscription stopped delivering for a minute after one failed read, even once the cause was gone and new events arrived. Signed-off-by: Yordis Prieto --- test/subscriptions/subscription_fsm_test.exs | 51 ++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/test/subscriptions/subscription_fsm_test.exs b/test/subscriptions/subscription_fsm_test.exs index ab68026..4b4cc81 100644 --- a/test/subscriptions/subscription_fsm_test.exs +++ b/test/subscriptions/subscription_fsm_test.exs @@ -610,6 +610,44 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do refute_receive :retry_catch_up, 300 end + test "reads again on a catch-up request instead of waiting out the retry", context do + failed = failed_read(context) + + :ok = TestEventStore.append_to_stream(context.stream_uuid, 0, EventFactory.create_events(2)) + + assert %SubscriptionFsm{state: :request_catch_up} = + failed |> recover_schema(context) |> SubscriptionFsm.catch_up() + + assert_received {:events, [%{event_number: 1}, %{event_number: 2}]} + end + + test "reads again on a notification of new events instead of waiting out the retry", + context do + failed = failed_read(context) + + :ok = TestEventStore.append_to_stream(context.stream_uuid, 0, EventFactory.create_events(2)) + {:ok, events} = TestEventStore.read_stream_forward(context.stream_uuid) + + assert %SubscriptionFsm{state: :request_catch_up} = + failed |> recover_schema(context) |> SubscriptionFsm.notify_events(events) + + assert_received {:events, [%{event_number: 1}, %{event_number: 2}]} + end + + test "leaves no retry pending once an early read succeeds", context do + failed = failed_read(context, retry_interval: 200) + + failed |> recover_schema(context) |> SubscriptionFsm.catch_up() + + refute_receive :retry_catch_up, 400 + end + + test "waits on in-flight events without a pending retry", context do + fsm = in_flight_fsm(context, 1, state: :catching_up) + + assert ^fsm = SubscriptionFsm.catch_up(fsm) + end + test "keeps a single retry pending when in-flight events are acked one by one", context do :ok = TestEventStore.append_to_stream(context.stream_uuid, 0, EventFactory.create_events(10)) @@ -655,6 +693,19 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do end end + defp failed_read(context, overrides \\ []) do + context + |> fsm( + [state: :request_catch_up, schema: "no_such_schema", checkpoint_threshold: 100] ++ overrides + ) + |> SubscriptionFsm.connect_subscriber(self(), buffer_size: 10) + |> SubscriptionFsm.catch_up() + end + + defp recover_schema(%SubscriptionFsm{data: data} = fsm, context) do + %SubscriptionFsm{fsm | data: %SubscriptionState{data | schema: context.schema}} + end + defp in_flight_fsm(context, count, overrides) do %SubscriptionFsm{data: data} = fsm = fsm(context, overrides) From 30ca64aa735ba431643d2c59cb65876f949673de Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 7 Nov 2026 13:15:43 -0500 Subject: [PATCH 07/15] fix(subscriptions): read again on a catch-up request or new events instead of waiting out a failed read's retry After one failed read a subscription stopped delivering for a full retry interval, a minute by default, even once the cause was gone and new events arrived. Closes #112 Signed-off-by: Yordis Prieto --- guides/Getting Started.md | 2 +- .../subscriptions/subscription_fsm.ex | 33 +++++++++++++++++-- test/subscriptions/subscription_fsm_test.exs | 2 +- 3 files changed, 32 insertions(+), 5 deletions(-) diff --git a/guides/Getting Started.md b/guides/Getting Started.md index c07629e..d053521 100644 --- a/guides/Getting Started.md +++ b/guides/Getting Started.md @@ -86,7 +86,7 @@ EventStore is [available in Hex](https://hex.pm/packages/eventstore) and can be Subscription options: - - `:subscription_retry_interval` - interval between subscription connection retry attempts (default: 60,000ms). + - `:subscription_retry_interval` - interval between a subscription's attempts to take its lock, and between its attempts to read again after a catch-up read fails (default: 60,000ms). A failed read is logged as a warning, and a catch-up request or a notification of new events makes the subscription read again without waiting out the interval. - `:subscription_hibernate_after` - subscriptions will automatically hibernate to save memory after a period of inactivity (default: 15,000ms). 4. Add your event store module to the `event_stores` list for your app in mix config: diff --git a/lib/event_store/subscriptions/subscription_fsm.ex b/lib/event_store/subscriptions/subscription_fsm.ex index 197909e..7deafe9 100644 --- a/lib/event_store/subscriptions/subscription_fsm.ex +++ b/lib/event_store/subscriptions/subscription_fsm.ex @@ -140,6 +140,15 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do %__MODULE__{fsm | state: :request_catch_up, data: data} end + # A catch-up request is a reason to try again now rather than wait out a failed read's retry. + def catch_up( + %__MODULE__{state: :catching_up, data: %SubscriptionState{retry_timer_ref: ref} = data} = + fsm + ) + when is_reference(ref) do + catch_up_from_stream(fsm, cancel_retry(data)) + end + def catch_up(%__MODULE__{data: %SubscriptionState{}} = fsm), do: fsm def retry_catch_up(%__MODULE__{state: :catching_up, data: %SubscriptionState{} = data} = fsm) do @@ -320,6 +329,18 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do end end + # New events are a reason to try again now rather than wait out a failed read's retry. + def notify_events( + %__MODULE__{state: :catching_up, data: %SubscriptionState{retry_timer_ref: ref} = data} = + fsm, + events + ) + when is_reference(ref) do + data = data |> track_last_received(events) |> cancel_retry() + + catch_up_from_stream(fsm, data) + end + # Ignore notify events unless subscribed def notify_events(%__MODULE__{data: %SubscriptionState{} = data} = fsm, events) do %__MODULE__{fsm | data: track_last_received(data, events)} @@ -535,15 +556,21 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do end defp schedule_retry(%SubscriptionState{} = data) do - %SubscriptionState{retry_interval: retry_interval, retry_timer_ref: retry_timer_ref} = data - - if retry_timer_ref, do: Process.cancel_timer(retry_timer_ref) + %SubscriptionState{retry_interval: retry_interval} = data = cancel_retry(data) retry_timer_ref = Process.send_after(self(), :retry_catch_up, retry_interval) %SubscriptionState{data | retry_timer_ref: retry_timer_ref} end + defp cancel_retry(%SubscriptionState{retry_timer_ref: nil} = data), do: data + + defp cancel_retry(%SubscriptionState{retry_timer_ref: retry_timer_ref} = data) do + Process.cancel_timer(retry_timer_ref) + + %SubscriptionState{data | retry_timer_ref: nil} + end + defp read_stream_forward(%SubscriptionState{} = data) do %SubscriptionState{ conn: conn, diff --git a/test/subscriptions/subscription_fsm_test.exs b/test/subscriptions/subscription_fsm_test.exs index 4b4cc81..953c3bb 100644 --- a/test/subscriptions/subscription_fsm_test.exs +++ b/test/subscriptions/subscription_fsm_test.exs @@ -702,7 +702,7 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do |> SubscriptionFsm.catch_up() end - defp recover_schema(%SubscriptionFsm{data: data} = fsm, context) do + defp recover_schema(%SubscriptionFsm{data: %SubscriptionState{} = data} = fsm, context) do %SubscriptionFsm{fsm | data: %SubscriptionState{data | schema: context.schema}} end From 1a7043f62ede702b45d67ba728058f11ef5c57c8 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 7 Nov 2026 13:15:44 -0500 Subject: [PATCH 08/15] docs(cluster): say PgBouncer's reset query releases a dead node's locks, and fix the PgBouncer links An empty server_reset_query keeps the dead node's locks on a pooled server connection, the client_idle_timeout warning did not match what PgBouncer does, and both links to the PgBouncer section were broken on GitHub. Closes #115 Signed-off-by: Yordis Prieto --- README.md | 2 +- guides/Cluster.md | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 2106260..17f15fd 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ MIT License - [Using Postgres schemas](guides/Getting%20Started.md#using-postgres-schemas) - [Event data and metadata data type](guides/Getting%20Started.md#event-data-and-metadata-data-type) - [Using the `jsonb` data type](guides/Getting%20Started.md#using-the-jsonb-data-type) - - [Using with PgBouncer](guides/Getting%20Started.md#using-with-pg-bouncer) + - [Using with PgBouncer](guides/Getting%20Started.md#using-with-pgbouncer) - [Using the EventStore](guides/Usage.md) - [Writing to a stream](guides/Usage.md#writing-to-a-stream) - [Using correlation and causation identifiers](guides/Usage.md#using-correlation-and-causation-identifiers) diff --git a/guides/Cluster.md b/guides/Cluster.md index 26b66cd..dba08f6 100644 --- a/guides/Cluster.md +++ b/guides/Cluster.md @@ -27,7 +27,7 @@ PostgreSQL only releases the locks of a session once it notices the client is go ### Keepalives when PgBouncer is in front of the lock connection -When `session_mode_url` points at PgBouncer in session mode, as suggested in [Using with PgBouncer](Getting Started.md#using-with-pgbouncer), the server's keepalives no longer protect you. The client of the lock session, as PostgreSQL sees it, is PgBouncer, which is still running after a node's host dies, so the server finds nothing wrong and the session keeps its advisory locks. They are released only when PgBouncer notices that its own client is gone and resets the server connection. By default PgBouncer leaves that to the operating system's keepalive settings, which on Linux default to 7,200 seconds before the first probe and then 9 probes 75 seconds apart. That is roughly 2 hours and 11 minutes before PgBouncer can notice, and the lock is released only after it does, so the actual wait depends on PgBouncer and the network as well. Until then no other node can take over the subscriptions. +When `session_mode_url` points at PgBouncer in session mode, as suggested in [Using with PgBouncer](Getting%20Started.md#using-with-pgbouncer), the server's keepalives no longer protect you. The client of the lock session, as PostgreSQL sees it, is PgBouncer, which is still running after a node's host dies, so the server finds nothing wrong and the session keeps its advisory locks. They are released only when PgBouncer notices that its own client is gone and resets the server connection with its `server_reset_query`. By default PgBouncer leaves that to the operating system's keepalive settings, which on Linux default to 7,200 seconds before the first probe and then 9 probes 75 seconds apart. That is roughly 2 hours and 11 minutes before PgBouncer can notice, and the lock is released only after it does, so the actual wait depends on PgBouncer and the network as well. Until then no other node can take over the subscriptions. Configure the keepalives on PgBouncer as well, in the `[pgbouncer]` section of `pgbouncer.ini`, with the same values as the server advice above: @@ -41,7 +41,9 @@ tcp_keepcnt = 3 `tcp_keepalive` is on by default and uses the operating system's values; `tcp_keepidle`, `tcp_keepintvl` and `tcp_keepcnt` are unset by default and override them, so set them together. In a test that cut a node off from PgBouncer, these values released the lock after about 27 seconds, the same as a connection straight to PostgreSQL, while with the defaults it was still held after 120 seconds. Keep the server's own keepalives as well, since they cover PgBouncer's host dying. -Do not use PgBouncer's `client_idle_timeout` for this. The lock connection is idle between queries by design, so the timeout would close healthy lock sessions and make subscriptions lose their locks. +Keep PgBouncer's `server_reset_query` at its default, `DISCARD ALL`, which releases the session's advisory locks. With an empty reset query, or one that leaves advisory locks in place, PgBouncer drops the dead client but keeps the server connection, and the dead node's locks with it. No node connecting straight to PostgreSQL can take them, while the next client PgBouncer hands that server connection to inherits them without having claimed them. + +Do not rely on PgBouncer's `client_idle_timeout` for this. In a test on PgBouncer 1.24.1 in session mode, `client_idle_timeout = 10` did not close a cut-off node's lock session after 10 seconds; the lock was released only when the keepalives noticed, 25 seconds after the cut, so the setting does not speed up the hand-off. Keepalives set on the node's side, such as `socket_options: [keepalive: true]` in `session_mode_pool`, do not help here. Those probes are sent by the node's host, which is the machine that died, so nothing is left to send them. From 0a86462f91f2bfd455abdf77ca263b6e7d199f80 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 7 Nov 2026 14:28:34 -0500 Subject: [PATCH 09/15] test(subscriptions): run the lock refusal test on PostgreSQL 12 and match the subscription state in FSM tests CI runs PostgreSQL 12, which has no DROP DATABASE ... WITH (FORCE), and Elixir 1.19 warns on struct updates of untyped data. Signed-off-by: Yordis Prieto --- test/storage/subscription_lock_refused_test.exs | 9 ++++++++- test/subscriptions/subscription_fsm_test.exs | 4 ++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/test/storage/subscription_lock_refused_test.exs b/test/storage/subscription_lock_refused_test.exs index 621ef3f..924cb37 100644 --- a/test/storage/subscription_lock_refused_test.exs +++ b/test/storage/subscription_lock_refused_test.exs @@ -8,7 +8,14 @@ defmodule EventStore.Storage.SubscriptionLockRefusedTest do setup %{conn: conn, postgrex_config: postgrex_config} do drop = fn -> - Postgrex.query!(conn, ~s|DROP DATABASE IF EXISTS "#{@database}" WITH (FORCE)|, []) + # DROP DATABASE ... WITH (FORCE) needs PostgreSQL 13, so end the sessions first. + Postgrex.query!( + conn, + "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1", + [@database] + ) + + Postgrex.query!(conn, ~s|DROP DATABASE IF EXISTS "#{@database}"|, []) Postgrex.query!(conn, ~s|DROP ROLE IF EXISTS "#{@role}"|, []) end diff --git a/test/subscriptions/subscription_fsm_test.exs b/test/subscriptions/subscription_fsm_test.exs index 953c3bb..c866d08 100644 --- a/test/subscriptions/subscription_fsm_test.exs +++ b/test/subscriptions/subscription_fsm_test.exs @@ -561,7 +561,7 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do fsm = SubscriptionFsm.connect_subscriber(fsm, self(), buffer_size: 10) - %SubscriptionFsm{data: data} = failed = SubscriptionFsm.catch_up(fsm) + %SubscriptionFsm{data: %SubscriptionState{} = data} = failed = SubscriptionFsm.catch_up(fsm) :ok = TestEventStore.append_to_stream(context.stream_uuid, 0, EventFactory.create_events(3)) @@ -652,7 +652,7 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do :ok = TestEventStore.append_to_stream(context.stream_uuid, 0, EventFactory.create_events(10)) - %SubscriptionFsm{data: data} = + %SubscriptionFsm{data: %SubscriptionState{} = data} = context |> fsm(state: :request_catch_up, retry_interval: 200, checkpoint_threshold: 100) |> SubscriptionFsm.connect_subscriber(self(), buffer_size: 10) From 36f3a06cda001c11ddd28c0ebef5de15891c6f51 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 7 Nov 2026 14:31:20 -0500 Subject: [PATCH 10/15] test(subscriptions): ignore a retry that was already due when an early read armed the next one Signed-off-by: Yordis Prieto --- test/subscriptions/subscription_fsm_test.exs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/test/subscriptions/subscription_fsm_test.exs b/test/subscriptions/subscription_fsm_test.exs index c866d08..5260411 100644 --- a/test/subscriptions/subscription_fsm_test.exs +++ b/test/subscriptions/subscription_fsm_test.exs @@ -642,6 +642,18 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do refute_receive :retry_catch_up, 400 end + test "ignores a retry that was already due when an early read armed the next one", context do + failed = failed_read(context, retry_interval: 200) + + assert_receive :retry_catch_up, 1_000 + + rearmed = SubscriptionFsm.catch_up(failed) + + assert %SubscriptionFsm{state: :catching_up} = SubscriptionFsm.retry_catch_up(rearmed) + assert_receive :retry_catch_up, 1_000 + refute_receive :retry_catch_up, 400 + end + test "waits on in-flight events without a pending retry", context do fsm = in_flight_fsm(context, 1, state: :catching_up) From e30df740a178da438d7ada4ab41195f05329ffe4 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 7 Nov 2026 15:18:16 -0500 Subject: [PATCH 11/15] fix(subscriptions): ignore a retry that was already due when an early read armed the next one Signed-off-by: Yordis Prieto --- lib/event_store/subscriptions/subscription.ex | 4 +-- .../subscriptions/subscription_fsm.ex | 12 ++++++-- test/subscriptions/subscription_fsm_test.exs | 28 ++++++++++--------- 3 files changed, 26 insertions(+), 18 deletions(-) diff --git a/lib/event_store/subscriptions/subscription.ex b/lib/event_store/subscriptions/subscription.ex index 0c5d50f..73dad4b 100644 --- a/lib/event_store/subscriptions/subscription.ex +++ b/lib/event_store/subscriptions/subscription.ex @@ -236,12 +236,12 @@ defmodule EventStore.Subscriptions.Subscription do end @impl GenServer - def handle_info(:retry_catch_up, %Subscription{} = state) do + def handle_info({:timeout, ref, :retry_catch_up}, %Subscription{} = state) do %Subscription{subscription: subscription} = state state = subscription - |> SubscriptionFsm.retry_catch_up() + |> SubscriptionFsm.retry_catch_up(ref) |> apply_subscription_to_state(state) {:noreply, state} diff --git a/lib/event_store/subscriptions/subscription_fsm.ex b/lib/event_store/subscriptions/subscription_fsm.ex index 7deafe9..204ee85 100644 --- a/lib/event_store/subscriptions/subscription_fsm.ex +++ b/lib/event_store/subscriptions/subscription_fsm.ex @@ -151,11 +151,17 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do def catch_up(%__MODULE__{data: %SubscriptionState{}} = fsm), do: fsm - def retry_catch_up(%__MODULE__{state: :catching_up, data: %SubscriptionState{} = data} = fsm) do + # A retry already in the mailbox when an early read armed the next one must not start a second retry. + def retry_catch_up( + %__MODULE__{state: :catching_up, data: %SubscriptionState{retry_timer_ref: ref} = data} = + fsm, + ref + ) + when is_reference(ref) do catch_up_from_stream(fsm, %SubscriptionState{data | retry_timer_ref: nil}) end - def retry_catch_up(%__MODULE__{} = fsm), do: fsm + def retry_catch_up(%__MODULE__{} = fsm, _ref), do: fsm def ack( %__MODULE__{state: :request_catch_up, data: %SubscriptionState{} = data} = fsm, @@ -558,7 +564,7 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do defp schedule_retry(%SubscriptionState{} = data) do %SubscriptionState{retry_interval: retry_interval} = data = cancel_retry(data) - retry_timer_ref = Process.send_after(self(), :retry_catch_up, retry_interval) + retry_timer_ref = :erlang.start_timer(retry_interval, self(), :retry_catch_up) %SubscriptionState{data | retry_timer_ref: retry_timer_ref} end diff --git a/test/subscriptions/subscription_fsm_test.exs b/test/subscriptions/subscription_fsm_test.exs index 5260411..2c297dc 100644 --- a/test/subscriptions/subscription_fsm_test.exs +++ b/test/subscriptions/subscription_fsm_test.exs @@ -552,7 +552,7 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do SubscriptionFsm.catch_up(fsm) - assert_receive :retry_catch_up, 1_000 + assert_receive {:timeout, _ref, :retry_catch_up}, 1_000 end test "reads again and delivers events once storage recovers", context do @@ -565,7 +565,7 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do :ok = TestEventStore.append_to_stream(context.stream_uuid, 0, EventFactory.create_events(3)) - assert_receive :retry_catch_up, 1_000 + assert_receive {:timeout, ref, :retry_catch_up}, 1_000 refute_received {:events, _events} recovered = %SubscriptionFsm{ @@ -574,7 +574,7 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do } assert %SubscriptionFsm{state: :request_catch_up, data: data} = - SubscriptionFsm.retry_catch_up(recovered) + SubscriptionFsm.retry_catch_up(recovered, ref) assert data.last_sent == 3 assert_received {:events, [%{event_number: 1}, %{event_number: 2}, %{event_number: 3}]} @@ -596,7 +596,7 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do assert_receive :connection_held, 5_000 assert %SubscriptionFsm{state: :catching_up} = SubscriptionFsm.catch_up(fsm) - assert_receive :retry_catch_up, 1_000 + assert_receive {:timeout, _ref, :retry_catch_up}, 1_000 send(holder.pid, :release) assert {:ok, :ok} = Task.await(holder) @@ -607,7 +607,7 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do fsm(context, state: :request_catch_up, schema: "no_such_schema", retry_interval: 5_000) assert %SubscriptionFsm{state: :catching_up} = SubscriptionFsm.catch_up(fsm) - refute_receive :retry_catch_up, 300 + refute_receive {:timeout, _ref, :retry_catch_up}, 300 end test "reads again on a catch-up request instead of waiting out the retry", context do @@ -639,19 +639,21 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do failed |> recover_schema(context) |> SubscriptionFsm.catch_up() - refute_receive :retry_catch_up, 400 + refute_receive {:timeout, _ref, :retry_catch_up}, 400 end test "ignores a retry that was already due when an early read armed the next one", context do failed = failed_read(context, retry_interval: 200) - assert_receive :retry_catch_up, 1_000 + assert_receive {:timeout, stale, :retry_catch_up}, 1_000 rearmed = SubscriptionFsm.catch_up(failed) - assert %SubscriptionFsm{state: :catching_up} = SubscriptionFsm.retry_catch_up(rearmed) - assert_receive :retry_catch_up, 1_000 - refute_receive :retry_catch_up, 400 + assert %SubscriptionFsm{state: :catching_up} = + SubscriptionFsm.retry_catch_up(rearmed, stale) + + assert_receive {:timeout, _ref, :retry_catch_up}, 1_000 + refute_receive {:timeout, _ref, :retry_catch_up}, 400 end test "waits on in-flight events without a pending retry", context do @@ -685,8 +687,8 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do end) assert %SubscriptionFsm{state: :catching_up} = acked - assert_receive :retry_catch_up, 1_000 - refute_receive :retry_catch_up, 400 + assert_receive {:timeout, _ref, :retry_catch_up}, 1_000 + refute_receive {:timeout, _ref, :retry_catch_up}, 400 end for state <- [:subscribed, :max_capacity] do @@ -699,7 +701,7 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do :ok = TestEventStore.append_to_stream(context.stream_uuid, 0, EventFactory.create_events(3)) - assert ^fsm = SubscriptionFsm.retry_catch_up(fsm) + assert ^fsm = SubscriptionFsm.retry_catch_up(fsm, make_ref()) refute_received {:events, _events} end end From 590224793adb291b82dceae3e053ffd45523411e Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 7 Nov 2026 15:18:16 -0500 Subject: [PATCH 12/15] docs(cluster): link the PgBouncer section so it resolves on HexDocs, and say what the idle timeout test leaves open Signed-off-by: Yordis Prieto --- guides/Cluster.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/guides/Cluster.md b/guides/Cluster.md index dba08f6..ee8b399 100644 --- a/guides/Cluster.md +++ b/guides/Cluster.md @@ -27,7 +27,7 @@ PostgreSQL only releases the locks of a session once it notices the client is go ### Keepalives when PgBouncer is in front of the lock connection -When `session_mode_url` points at PgBouncer in session mode, as suggested in [Using with PgBouncer](Getting%20Started.md#using-with-pgbouncer), the server's keepalives no longer protect you. The client of the lock session, as PostgreSQL sees it, is PgBouncer, which is still running after a node's host dies, so the server finds nothing wrong and the session keeps its advisory locks. They are released only when PgBouncer notices that its own client is gone and resets the server connection with its `server_reset_query`. By default PgBouncer leaves that to the operating system's keepalive settings, which on Linux default to 7,200 seconds before the first probe and then 9 probes 75 seconds apart. That is roughly 2 hours and 11 minutes before PgBouncer can notice, and the lock is released only after it does, so the actual wait depends on PgBouncer and the network as well. Until then no other node can take over the subscriptions. +When `session_mode_url` points at PgBouncer in session mode, as suggested in [Using with PgBouncer](https://hexdocs.pm/eventstore/getting-started.html#using-with-pgbouncer), the server's keepalives no longer protect you. The client of the lock session, as PostgreSQL sees it, is PgBouncer, which is still running after a node's host dies, so the server finds nothing wrong and the session keeps its advisory locks. They are released only when PgBouncer notices that its own client is gone and resets the server connection with its `server_reset_query`. By default PgBouncer leaves that to the operating system's keepalive settings, which on Linux default to 7,200 seconds before the first probe and then 9 probes 75 seconds apart. That is roughly 2 hours and 11 minutes before PgBouncer can notice, and the lock is released only after it does, so the actual wait depends on PgBouncer and the network as well. Until then no other node can take over the subscriptions. Configure the keepalives on PgBouncer as well, in the `[pgbouncer]` section of `pgbouncer.ini`, with the same values as the server advice above: @@ -43,7 +43,7 @@ tcp_keepcnt = 3 Keep PgBouncer's `server_reset_query` at its default, `DISCARD ALL`, which releases the session's advisory locks. With an empty reset query, or one that leaves advisory locks in place, PgBouncer drops the dead client but keeps the server connection, and the dead node's locks with it. No node connecting straight to PostgreSQL can take them, while the next client PgBouncer hands that server connection to inherits them without having claimed them. -Do not rely on PgBouncer's `client_idle_timeout` for this. In a test on PgBouncer 1.24.1 in session mode, `client_idle_timeout = 10` did not close a cut-off node's lock session after 10 seconds; the lock was released only when the keepalives noticed, 25 seconds after the cut, so the setting does not speed up the hand-off. +Do not rely on PgBouncer's `client_idle_timeout` for this. In a test on PgBouncer 1.24.1 in session mode, `client_idle_timeout = 10` did not close a cut-off node's lock session after 10 seconds; the lock was released only when the keepalives noticed, 25 seconds after the cut, so the setting does not speed up the hand-off. The test cut a node off, so it does not show whether the setting disconnects a healthy client that is idle. Keepalives set on the node's side, such as `socket_options: [keepalive: true]` in `session_mode_pool`, do not help here. Those probes are sent by the node's host, which is the machine that died, so nothing is left to send them. From 327f2453c7efff861e8bb8f497dcd53947791e59 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 7 Nov 2026 15:39:19 -0500 Subject: [PATCH 13/15] test(subscriptions): drop the pending catch-up retry when the subscription loses its lock Signed-off-by: Yordis Prieto --- test/subscriptions/subscription_fsm_test.exs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/test/subscriptions/subscription_fsm_test.exs b/test/subscriptions/subscription_fsm_test.exs index 2c297dc..fd7e25c 100644 --- a/test/subscriptions/subscription_fsm_test.exs +++ b/test/subscriptions/subscription_fsm_test.exs @@ -656,6 +656,21 @@ defmodule EventStore.Subscriptions.SubscriptionFsmTest do refute_receive {:timeout, _ref, :retry_catch_up}, 400 end + test "drops the pending retry when the subscription loses its lock", context do + lock_ref = make_ref() + + %SubscriptionFsm{data: %SubscriptionState{} = data} = + failed = failed_read(context, retry_interval: 200) + + failed = %SubscriptionFsm{failed | data: %SubscriptionState{data | lock_ref: lock_ref}} + + assert %SubscriptionFsm{state: :disconnected, data: data} = + SubscriptionFsm.disconnect(failed, lock_ref) + + assert data.retry_timer_ref == nil + refute_receive {:timeout, _ref, :retry_catch_up}, 400 + end + test "waits on in-flight events without a pending retry", context do fsm = in_flight_fsm(context, 1, state: :catching_up) From f3f7a894a5d9d63e09c50c512c87b0e7814bdbad Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 7 Nov 2026 15:39:46 -0500 Subject: [PATCH 14/15] fix(subscriptions): drop the pending catch-up retry when the subscription loses its lock Signed-off-by: Yordis Prieto --- lib/event_store/subscriptions/subscription_fsm.ex | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/event_store/subscriptions/subscription_fsm.ex b/lib/event_store/subscriptions/subscription_fsm.ex index 204ee85..19e4d0f 100644 --- a/lib/event_store/subscriptions/subscription_fsm.ex +++ b/lib/event_store/subscriptions/subscription_fsm.ex @@ -377,6 +377,8 @@ defmodule EventStore.Subscriptions.SubscriptionFsm do %SubscriptionState{data | lock_ref: nil, fencing_token: nil} |> SubscriptionState.reset_event_tracking() |> purge_in_flight_events() + # A retry left over from before the lock was lost would hold back acks after reconnecting. + |> cancel_retry() %__MODULE__{fsm | state: :disconnected, data: data} end From ea96143d9dc8b12fe2652976b54bc04513423db2 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 7 Nov 2026 15:39:55 -0500 Subject: [PATCH 15/15] test(storage): wait for the lock test's sessions to end before dropping its database Signed-off-by: Yordis Prieto --- .../subscription_lock_refused_test.exs | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/test/storage/subscription_lock_refused_test.exs b/test/storage/subscription_lock_refused_test.exs index 924cb37..75cd416 100644 --- a/test/storage/subscription_lock_refused_test.exs +++ b/test/storage/subscription_lock_refused_test.exs @@ -15,6 +15,9 @@ defmodule EventStore.Storage.SubscriptionLockRefusedTest do [@database] ) + # Sessions end asynchronously and the drop waits only five seconds for them. + await_no_sessions(conn, 100) + Postgrex.query!(conn, ~s|DROP DATABASE IF EXISTS "#{@database}"|, []) Postgrex.query!(conn, ~s|DROP ROLE IF EXISTS "#{@role}"|, []) end @@ -57,4 +60,23 @@ defmodule EventStore.Storage.SubscriptionLockRefusedTest do assert postgres.message =~ "pg_try_advisory_xact_lock" end + + defp await_no_sessions(conn, attempts) do + %Postgrex.Result{rows: [[sessions]]} = + Postgrex.query!(conn, "SELECT count(*) FROM pg_stat_activity WHERE datname = $1", [ + @database + ]) + + cond do + sessions == 0 -> + :ok + + attempts > 0 -> + Process.sleep(100) + await_no_sessions(conn, attempts - 1) + + true -> + flunk("#{sessions} sessions on #{@database} did not end") + end + end end