Skip to content

feat: broadcast persistence opt-in - #2235

Merged
leandrocp merged 9 commits into
mainfrom
persist-opt-in
Oct 29, 2026
Merged

leandrocp merged 9 commits into
mainfrom
persist-opt-in

Conversation

@leandrocp

@leandrocp leandrocp commented Sep 18, 2026 •

Copy link
Copy Markdown
Member

Broadcast Persistence Opt-in (enable/disable)

The parameter

Either a boolean to enable using default values or a map to overwrite the ttl. Usually I don't like two different data types for the same parameter but the alternative would be persist: {} to enable using defaults which reads worse than persist: true.

channel.send({ type: 'broadcast', event: 'message', payload, persist: true })
channel.send({ type: 'broadcast', event: 'message', payload, persist: { ttl: 3600 } })
post /broadcast/room:1/events/message?persist=true
post /broadcast/room:1/events/message?persist[ttl]=3600
What you send What happens
no persist not stored
persist: true stored, kept for the maximum
persist: { ttl: 3600 } stored, expires in one hour

Note: stored only if the policy allows, obviously.

TTL

Users can pass a positive integer from 1 to 259200 (72 hours) to define how long the message can be replayed. Invalid and out of bounds values are rejected.

The ttl is stored as expires_at and filtered at runtime, the row is deleted along with the partition after 72h independently of the expires_at value.

Notes:

  • That creates a new state where messages are either expired or not which is only useful for replay at the moment.
  • I could drop ttl for now and just do enable: true with max expiration. Either way we can see ttl is a good fit and works.

One probe instead of two (bench)

Persistence needs a second :persistence RLS check on top of :broadcast. Run both in one call to save resources:

Name                                            ips        average  deviation         median         99th %
broadcast only                              1300.82        0.77 ms    ±30.64%        0.75 ms        1.07 ms
broadcast and persistence, one call          999.13        1.00 ms    ±18.19%        0.97 ms        1.38 ms
broadcast then persistence, two calls        685.81        1.46 ms    ±18.48%        1.41 ms        2.08 ms

Comparison:
broadcast only                              1300.82
broadcast and persistence, one call          999.13 - 1.30x slower +0.23 ms
broadcast then persistence, two calls        685.81 - 1.90x slower +0.69 ms

Note that WS caches that probe in the channel, but HTTP has no caching so it must run on every request.

See bench/authorization_probe.exs

Replay

We need to increase the replay limit, currently set at @hard_limit 25, but it's out of scope, to be done in a follow-up PR.

Clients

Supabase-JS requires supabase/supabase-js#2690 to accept the :persist metadata. Other clients requires similar or more work to support Persistence.

@github-actions

github-actions Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

CRAP Score Report

Summary: files=256 functions=1434 scored=1434 worst_score=15944.76

** (Mix) CRAP threshold failed: max_score=30.00
High scores: 30
  lib/extensions/postgres_cdc_rls/subscription_manager.ex Extensions.PostgresCdcRls.SubscriptionManager.handle_info/2 score=37.16
  lib/realtime/adapters/postgres/oid_database.ex Realtime.Adapters.Postgres.OidDatabase.name_for_type_id/1 score=15944.76
  lib/realtime/application.ex Realtime.Application.setup_region_mapping/0 score=47.11
  lib/realtime/nodes.ex Realtime.Nodes.default_region_mapping/1 score=129.85
  lib/realtime/operations.ex Realtime.Operations.rebalance/0 score=42.00
  lib/realtime/operations.ex Realtime.Operations.kill_connections_to_tenant_id/2 score=90.00
  lib/realtime/tenants/connect.ex Realtime.Tenants.Connect.handle_info/2 score=41.41
  lib/realtime_web/channels/auth/jwt_verification.ex RealtimeWeb.JwtVerification.generate_signer/3 score=30.78
  lib/realtime_web/channels/realtime_channel.ex RealtimeWeb.RealtimeChannel.handle_info/2 score=51.06
  lib/realtime_web/dashboard/feature_flags.ex RealtimeWeb.Dashboard.FeatureFlags.handle_event/3 score=112.70
  lib/realtime_web/dashboard/node_info.ex RealtimeWeb.Dashboard.NodeInfo.fetch_node_data/2 score=42.00
  lib/realtime_web/dashboard/recon_trace.ex RealtimeWeb.Dashboard.ReconTrace.handle_event/3 score=552.00
  lib/realtime_web/dashboard/recon_trace.ex RealtimeWeb.Dashboard.ReconTrace.handle_info/2 score=210.00
  lib/realtime_web/dashboard/recon_trace.ex RealtimeWeb.Dashboard.ReconTrace.render_value/2 score=42.00
  lib/realtime_web/dashboard/recon_trace.ex RealtimeWeb.Dashboard.ReconTrace.load_module_functions/1 score=42.00
  lib/realtime_web/dashboard/recon_trace.ex RealtimeWeb.Dashboard.ReconTrace.parse_and_start/2 score=110.00
  lib/realtime_web/dashboard/recon_trace.ex RealtimeWeb.Dashboard.ReconTrace.format_value/1 score=552.00
  lib/realtime_web/dashboard/recon_trace.ex RealtimeWeb.Dashboard.ReconTrace.sort_entries/2 score=42.00
  lib/realtime_web/dashboard/sql_inspector.ex RealtimeWeb.Dashboard.SqlInspector.handle_event/3 score=72.00
  lib/realtime_web/dashboard/sql_inspector.ex RealtimeWeb.Dashboard.SqlInspector.execute_read_only/1 score=72.00
  lib/realtime_web/dashboard/sql_inspector.ex RealtimeWeb.Dashboard.SqlInspector.mask_sensitive_columns/1 score=42.00
  lib/realtime_web/dashboard/sql_inspector.ex RealtimeWeb.Dashboard.SqlInspector.compare_cells/2 score=42.00
  lib/realtime_web/dashboard/sql_inspector.ex RealtimeWeb.Dashboard.SqlInspector.format_cell/1 score=72.00
  lib/realtime_web/dashboard/tenant_migrations.ex RealtimeWeb.Dashboard.TenantMigrations.handle_info/2 score=156.00
  lib/realtime_web/live/components.ex RealtimeWeb.Components.input/1 score=90.00
  lib/realtime_web/live/inspector_live/conn_component.ex RealtimeWeb.InspectorLive.ConnComponent.handle_event/3 score=53.83
  lib/realtime_web/live/inspector_live/event_log_component.ex RealtimeWeb.InspectorLive.EventLogComponent.category_variant/1 score=35.00
  lib/realtime_web/live/inspector_live/event_log_component.ex RealtimeWeb.InspectorLive.EventLogComponent.event_label/1 score=51.43
  lib/realtime_web/live/inspector_live/index.ex RealtimeWeb.InspectorLive.Index.handle_event/3 score=30.84
  lib/realtime_web/live/status_live/index.ex RealtimeWeb.StatusLive.Index.handle_event/3 score=42.00

@coveralls

coveralls commented Sep 18, 2026 •

Copy link
Copy Markdown

Coverage Status

Coverage is 92.853% — persist-opt-in into main. No base build found for main.

@leandrocp
leandrocp force-pushed the persist-opt-in branch 3 times, most recently from 1290865 to 885a454 Compare October 7, 2026 14:57
@leandrocp leandrocp changed the title chore: broadcast persistence opt-in poc feat: broadcast persistence opt-in Oct 7, 2026
@leandrocp
leandrocp force-pushed the persist-opt-in branch 3 times, most recently from a2fcb86 to bc27e16 Compare October 7, 2026 21:48
Comment thread lib/realtime/messages.ex
@typedoc """
What the sender asked for, once parsed. `nil` means they did not ask to save the message.
"""
@type persist :: %{ttl: pos_integer()} | nil

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ttl is pretty much the standard name used everywhere so I reused the same name because it's already familiar.

@leandrocp
leandrocp marked this pull request as ready for review October 8, 2026 13:54
GoTrue's add_auth_jwt_function migration replaces auth.jwt(), which fails
with 'must be owner of function jwt' when the init script created it as
supabase_admin. The e2e stack runs GoTrue against this database since #2369.
@blacksmith-sh

This comment has been minimized.

Comment thread lib/realtime/messages.ex Resolved
Comment thread lib/realtime/messages.ex Resolved
@mandar1045

Copy link
Copy Markdown
Contributor

Just a heads up, the payload field in Message is still typed as :map, so trying to persist an array or a plain string fails and nothing gets saved. In #2390, I changed it to accept any JSON value. I tested your branch with that change, and both arrays and strings got saved fine. Let me know if I need to tweak anything in #2390 to make it work with this.

# Conflicts:
#	lib/realtime_web/channels/realtime_channel/broadcast_handler.ex
#	test/realtime_web/channels/realtime_channel/broadcast_handler_test.exs
@leandrocp

Copy link
Copy Markdown
Member Author

Hey @mandar1045 noted and thanks for that one as well! We'll follow up with #2390 as soon as possible 🙏🏻


def up do
execute """
CREATE INDEX IF NOT EXISTS messages_replay_index ON realtime.messages

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we should create index concurrently ? I don't have a strong preference tbh as each partition will have a separate index etc. Just thought I would bring the question.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

create index concurrently on the partitioned realtime.messages is not supported, the alternative is creating the index on each one separated but I don't think it's worth it.

@edgurgel edgurgel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Great work

# Conflicts:
#	lib/realtime/tenants/authorization.ex
#	lib/realtime/tenants/migrations.ex
#	priv/repo/tenant_db_dump_15.sql
#	priv/repo/tenant_db_dump_17.sql
@blacksmith-sh

This comment has been minimized.

@leandrocp
leandrocp merged commit f8f7208 into main Oct 29, 2026
57 checks passed
@leandrocp
leandrocp deleted the persist-opt-in branch October 29, 2026 15:30
@realtime-release-bot

Copy link
Copy Markdown

🎉 This PR is included in version 2.150.0 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants