Skip to content

Commit d85234a

Browse files
AchoArnoldCopilot
andcommitted
refactor: optimize heartbeats MongoDB indexes
Replace two separate indexes (owner_1_timestamp_-1, user_id_1) with a single compound index {user_id: 1, owner: 1, timestamp: -1} that covers all query patterns. Old indexes are dropped automatically on startup. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 2bc05d0 commit d85234a

1 file changed

Lines changed: 7 additions & 2 deletions

File tree

api/pkg/repositories/mongodb.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,14 @@ func parseMongoDBName(uri string) (string, error) {
106106
func createMongoIndexes(ctx context.Context, db *mongo.Database) error {
107107
// Heartbeats indexes
108108
heartbeatsCol := db.Collection(collectionHeartbeats)
109+
110+
// TODO: Remove this block after deploying once — old indexes will have been dropped in production.
111+
for _, name := range []string{"owner_1_timestamp_-1", "user_id_1"} {
112+
_ = heartbeatsCol.Indexes().DropOne(ctx, name)
113+
}
114+
109115
_, err := heartbeatsCol.Indexes().CreateMany(ctx, []mongo.IndexModel{
110-
{Keys: bson.D{{"owner", 1}, {"timestamp", -1}}},
111-
{Keys: bson.D{{"user_id", 1}}},
116+
{Keys: bson.D{{"user_id", 1}, {"owner", 1}, {"timestamp", -1}}},
112117
})
113118
if err != nil {
114119
return stacktrace.Propagate(err, "cannot create indexes on heartbeats collection")

0 commit comments

Comments
 (0)