⚡ How we made opening a chat 40× faster
This week we dug into why chats were slow to open. The culprit wasn't the network or the phone — it was the database access rules (Row Level Security in Postgres).
Before. The rule "only members can see a conversation's members" called a check function for every row. In a conversation with hundreds of people that's hundreds of calls per query: 117 ms.
After. The function now returns the whole set of the user's conversations, and the rule checks membership in it:
using (conversation_id in (select my_conversation_ids()))Postgres evaluates that subquery once and matches rows against a hash table: 3 ms. Message search got the same treatment — from ~0.7 s down to 18 ms.
💡 Tips if you run Postgres or Supabase too:
• wrap calls inside policies in (select …) — even auth.uid(): user_id = (select auth.uid());
• run EXPLAIN ANALYZE as the real role (set role authenticated), not as an admin — admins bypass policies, so everything looks "fast";
• before swapping a policy, compare what every user sees before and after inside a transaction ending in rollback. We checked 635 accounts this way — not a single extra or missing row.
Questions — DM @orbeo_help.
#orbeodev #postgres #performance