Skip to content

Commit d5a53d8

Browse files
committed
feat: better concurrency with reddit
1 parent 490bd74 commit d5a53d8

File tree

3 files changed

+25
-24
lines changed

3 files changed

+25
-24
lines changed
Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,28 @@
11
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
2-
import { timer } from '@gitroom/helpers/utils/timer';
2+
import Bottleneck from 'bottleneck';
3+
4+
const connection = new Bottleneck.IORedisConnection({
5+
client: ioRedis,
6+
});
7+
8+
const bottleneck = new Bottleneck.Group({
9+
maxConcurrent: 1,
10+
datastore: 'ioredis',
11+
connection,
12+
});
313

414
export async function concurrencyService<T>(
515
identifier: string,
616
func: (...args: any[]) => Promise<T>
717
): Promise<T> {
8-
const key = `throttle:${identifier.split('-')[0]}`;
9-
const expirationSeconds = 180;
10-
11-
while (true) {
12-
const setLock = await ioRedis.set(
13-
key,
14-
'locked',
15-
'EX',
16-
expirationSeconds,
17-
'NX'
18-
);
19-
20-
if (setLock) {
21-
break;
22-
}
23-
24-
// Wait before trying again
25-
await timer(1000);
26-
}
27-
2818
let load: T;
2919
try {
30-
load = await func();
20+
load = await bottleneck
21+
.key(identifier.split('-')[0])
22+
.schedule<T>({ expiration: 60_000 }, async () => {
23+
return await func();
24+
});
3125
} catch (err) {}
32-
await timer(2000);
33-
await ioRedis.del(key);
3426

3527
return load;
3628
}

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@
127127
"array-move": "^4.0.0",
128128
"axios": "^1.7.7",
129129
"bcrypt": "^5.1.1",
130+
"bottleneck": "^2.19.5",
130131
"bs58": "^6.0.0",
131132
"bufferutil": "^4.0.8",
132133
"bullmq": "^5.12.12",

pnpm-lock.yaml

Lines changed: 8 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)