Skip to content

Comments

fix: remove redundant ORDER BY in QueryForCredentials#4522

Open
wyh0626 wants to merge 1 commit intoory:masterfrom
wyh0626:fix/remove-redundant-order-by
Open

fix: remove redundant ORDER BY in QueryForCredentials#4522
wyh0626 wants to merge 1 commit intoory:masterfrom
wyh0626:fix/remove-redundant-order-by

Conversation

@wyh0626
Copy link

@wyh0626 wyh0626 commented Jan 16, 2026

The database-level ORDER BY is redundant since identifiers are already sorted in-memory (line 917-921 in persistence/sql/identity/persister_identity.go) Removing this improves PostgreSQL performance as it cannot use index hints.

Fixes #4520

Related issue(s)

Fixes #4520

This PR addresses a performance regression reported after upgrading from v1.3.0 to v25.4.0. Users observed:

  • Significantly higher P95/P99 latencies for credential queries on PostgreSQL
  • Increased database CPU usage

Root cause: The ORDER BY identifier ASC clause in QueryForCredentials is redundant because identifiers are already sorted in-memory using sort.Strings(). Additionally, PostgreSQL cannot use index hints (unlike MySQL/CockroachDB/SQLite), causing the optimizer to potentially choose suboptimal execution plans.

Checklist

  • I have read the contributing guidelines.
  • I have referenced an issue containing the design document if my change introduces a new feature.
  • I am following the contributing code guidelines.
  • I have read the security policy.
  • I confirm that this pull request does not address a security vulnerability.
  • I have added tests that prove my fix is effective or that my feature works.
  • I have added or changed the documentation.

Further Comments

This is a minimal fix that removes redundant database sorting. The in-memory sort.Strings() already guarantees deterministic ordering for testing purposes (as noted in the existing code comment).

No new tests are added because:

  1. Existing tests already verify the correctness of credential retrieval
  2. The change only removes redundant sorting - the final result remains identical
  3. This is a performance optimization, not a behavioral change

The database-level ORDER BY is redundant since identifiers are already
sorted in-memory (line 919-923). Removing this improves PostgreSQL
performance as it cannot use index hints.

Fixes ory#4520
@wyh0626 wyh0626 requested review from a team and aeneasr as code owners January 16, 2026 17:36
@Pedr0Rocha
Copy link
Contributor

The query plan seems ok for this specific query. I'm not sure if this will do much since the average returning rows is 1.

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.

DB performance issues after upgrading to v25.4.0

3 participants