Skip to content

Add members_hash for O(1) direct room lookup#164

Open
ashwin47 wants to merge 1 commit intobasecamp:mainfrom
ashwin47:add-members-hash-for-direct-room-lookup
Open

Add members_hash for O(1) direct room lookup#164
ashwin47 wants to merge 1 commit intobasecamp:mainfrom
ashwin47:add-members-hash-for-direct-room-lookup

Conversation

@ashwin47
Copy link
Contributor

Problem

Finding existing DM rooms scans ALL direct rooms in memory (O(n)):

# FIXME: Find a more performant algorithm that won't be a problem                                                        
# on accounts with 10K+ direct rooms                                                                                     
all.joins(:users).detect do |room|                                                                                       
  Set.new(room.user_ids) == Set.new(users.pluck(:id))                                                                    
end                                                                                                                      

Solution

Add indexed members_hash column for O(1) lookup:

  • Hash computed from sorted user IDs: MD5("1,3,9")
  • Instant room discovery regardless of room count
  • Fallback to user matching for gradual backfill

Impact Area

Starting a DM conversation (Rooms::DirectsController#create)

  • When clicking a user to start a direct message
  • When creating a group DM with multiple users

Migration

  • Adds members_hash column with index
  • Backfills existing Direct rooms automatically

Replace O(n) scan through all direct rooms with indexed hash lookup.
The hash is computed from sorted user IDs, enabling instant room
discovery when starting DMs. Includes migration to backfill existing
rooms and fallback logic for gradual population.

Fixes the FIXME comment about performance with 10K+ direct rooms.
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