Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Optimize getUserIdMappingWithEitherSuperTokensUserIdOrExternalUserId query #1095

Merged
merged 6 commits into from
Jan 7, 2025

Conversation

mavwolverine
Copy link
Contributor

Summary of change

Optimize getUserIdMappingWithEitherSuperTokensUserIdOrExternalUserId query to use union all instead of or

Related issues

#1094

explain analyze 
SELECT * FROM subscriberdb.st_userid_mapping WHERE app_id = 'public' AND (supertokens_user_id = '123' OR external_user_id = '123');
-> Filter: ((subscriberdb.st_userid_mapping.supertokens_user_id = '123') or (subscriberdb.st_userid_mapping.external_user_id = '123'))  (cost=732 rows=6566) (actual time=38.3..120 rows=1 loops=1)
    -> Index lookup on st_userid_mapping using PRIMARY (app_id='public')  (cost=732 rows=34559) (actual time=0.0114..102 rows=72308 loops=1)

Also, for our environment, this query is taking around 0.100 ms.

With union all;

explain analyze 
SELECT *FROM subscriberdb.st_userid_mapping WHERE app_id = 'public' AND supertokens_user_id = '123'
union all
SELECT * FROM subscriberdb.st_userid_mapping WHERE app_id = 'public' AND external_user_id = '123';
-> Append  (cost=0..0 rows=1) (actual time=0.00295..0.00323 rows=1 loops=1)
    -> Stream results  (cost=0..0 rows=0) (actual time=678e-6..678e-6 rows=0 loops=1)
        -> Zero rows (no matching row in const table)  (cost=0..0 rows=0) (actual time=73e-6..73e-6 rows=0 loops=1)
    -> Stream results  (cost=0..0 rows=1) (actual time=0.00165..0.00182 rows=1 loops=1)
        -> Rows fetched before execution  (cost=0..0 rows=1) (actual time=72e-6..133e-6 rows=1 loops=1)

This query runs in less than 0.20ms.

As a single query, 0.100ms and 0.20ms doesn't seem to be a big difference, but with thousands of users suddenly jumping on the site at 9AM, it seems to be causing latency issues and eventually downtime for us.

@mavwolverine mavwolverine changed the title Optimize getUserIdMappingWithEitherSuperTokensUserIdOrExternalUserId query refactor: Optimize getUserIdMappingWithEitherSuperTokensUserIdOrExternalUserId query Jan 6, 2025
@mavwolverine
Copy link
Contributor Author

mavwolverine commented Jan 7, 2025

@sattvikc Can you please look into this? Our production is down for second time :(

@porcellus porcellus changed the base branch from master to 9.4 January 7, 2025 20:37
@porcellus porcellus merged commit ccf6b49 into supertokens:9.4 Jan 7, 2025
2 of 3 checks passed
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.

3 participants