Skip to content

Improve performance#1225

Merged
floitsch merged 5 commits intomainfrom
floitsch/slow-query.20.update-squashed
Feb 28, 2026
Merged

Improve performance#1225
floitsch merged 5 commits intomainfrom
floitsch/slow-query.20.update-squashed

Conversation

@floitsch
Copy link
Member

Fixes 504 Gateway Timeout in get_devices and get_events.

When PostgREST executes RPC functions with array parameters frequently,
PostgreSQL switches to a "generic query plan" after 5 executions. For
get_devices and get_events (which run as SECURITY INVOKER), the
generic plan defaulted to a Sequential Scan over the devices and
events tables, applying the RLS policy is_auth_in_org_of_alias to
every row and causing massive timeouts (~160s).

This commit wraps the queries in Dynamic SQL (EXECUTE ... USING ...).
This securely preserves the SECURITY INVOKER context (ensuring RLS is
enforced) while strictly preventing Postgres from caching a generic plan,
forcing it to compute an optimal index scan for the provided array on
every execution.

Fixes 504 Gateway Timeout in get_devices and get_events.

When PostgREST executes RPC functions with array parameters frequently,
PostgreSQL switches to a "generic query plan" after 5 executions. For
`get_devices` and `get_events` (which run as `SECURITY INVOKER`), the
generic plan defaulted to a Sequential Scan over the `devices` and
`events` tables, applying the RLS policy `is_auth_in_org_of_alias` to
every row and causing massive timeouts (~160s).

This commit wraps the queries in Dynamic SQL (`EXECUTE ... USING ...`).
This securely preserves the `SECURITY INVOKER` context (ensuring RLS is
enforced) while strictly preventing Postgres from caching a generic plan,
forcing it to compute an optimal index scan for the provided array on
every execution.
@floitsch floitsch requested a review from kasperl February 28, 2026 15:36
@floitsch
Copy link
Member Author

TBR. (The migration is already live).

@floitsch floitsch merged commit b51b31d into main Feb 28, 2026
14 checks passed
@floitsch floitsch deleted the floitsch/slow-query.20.update-squashed branch February 28, 2026 16:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant