Skip to content

Commit 8393845

Browse files
authored
Merge pull request #15 from reedsy/performance-improvement
💥 Improve database performance
2 parents d4da1aa + 795a8d9 commit 8393845

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

mongodb-queue.ts

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,17 @@ export class MongoDBQueue<T = any> {
8585

8686
public async createIndexes(): Promise<void> {
8787
await Promise.all([
88-
this.col.createIndex({deleted: 1, visible: 1}),
88+
this.col.createIndex({visible: 1}, {sparse: true}),
8989
this.col.createIndex({ack: 1}, {unique: true, sparse: true}),
9090
this.col.createIndex({deleted: 1}, {sparse: true}),
91+
92+
// Index for efficient counts on in-flight
93+
this.col.createIndex({visible: 1, ack: 1}, {
94+
partialFilterExpression: {
95+
visible: {$exists: true},
96+
ack: {$exists: true},
97+
},
98+
}),
9199
]);
92100
}
93101

@@ -121,7 +129,6 @@ export class MongoDBQueue<T = any> {
121129
public async get(opts: GetOptions = {}): Promise<ExternalMessage<T> | null> {
122130
const visibility = opts.visibility || this.visibility;
123131
const query: Filter<Partial<Message<T>>> = {
124-
deleted: {$exists: false},
125132
visible: {$lte: now()},
126133
};
127134
const sort: Sort = {
@@ -172,7 +179,6 @@ export class MongoDBQueue<T = any> {
172179
const query: Filter<Partial<Message<T>>> = {
173180
ack: ack,
174181
visible: {$gt: now()},
175-
deleted: {$exists: false},
176182
};
177183
const update: UpdateFilter<Message<T>> = {
178184
$set: {
@@ -202,7 +208,6 @@ export class MongoDBQueue<T = any> {
202208
const query: Filter<Partial<Message<T>>> = {
203209
ack: ack,
204210
visible: {$gt: now()},
205-
deleted: {$exists: false},
206211
};
207212
const update: UpdateFilter<Message<T>> = {
208213
$set: {
@@ -237,16 +242,17 @@ export class MongoDBQueue<T = any> {
237242

238243
public async size(): Promise<number> {
239244
return this.col.countDocuments({
240-
deleted: {$exists: false},
241245
visible: {$lte: now()},
242246
});
243247
}
244248

245249
public async inFlight(): Promise<number> {
246250
return this.col.countDocuments({
247-
ack: {$exists: true},
251+
// For some unknown reason, MongoDB refuses to use the partial index with
252+
// {$exists: true}, but *will* use it if we use {$gt: ''}
253+
// https://www.mongodb.com/community/forums/t/partial-index-is-not-used-during-search/290507/2
254+
ack: {$gt: ''},
248255
visible: {$gt: now()},
249-
deleted: {$exists: false},
250256
});
251257
}
252258

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@reedsy/mongodb-queue",
3-
"version": "7.1.1",
3+
"version": "8.0.0",
44
"description": "Message queues which uses MongoDB.",
55
"main": "mongodb-queue.js",
66
"scripts": {

0 commit comments

Comments
 (0)