Skip to content

Commit 50c8d58

Browse files
committed
Await pending promise from ratelimit result
b2ba537 didn't actually fix the problem of the hanging lambdas. It just masked the issue by not being applied to GET requests. By awaiting the pending promise, also the POST invocations are finished properly. In addition, and unrelated, we're switching from a sliding to a fixed window.
1 parent b2ba537 commit 50c8d58

File tree

1 file changed

+21
-15
lines changed

1 file changed

+21
-15
lines changed

src/handler/ratelimit-middleware.ts

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,25 @@ import {Ratelimit} from '@upstash/ratelimit';
22
import {Redis} from '@upstash/redis';
33
import type {MiddlewareHandler} from 'hono';
44

5+
let ratelimit: Ratelimit;
6+
7+
try {
8+
ratelimit = new Ratelimit({
9+
redis: Redis.fromEnv(),
10+
limiter: Ratelimit.fixedWindow(10, `10 m`),
11+
});
12+
} catch (error) {
13+
if (process.env.UPSTASH_REDIS_REST_URL) {
14+
console.error(error);
15+
} else {
16+
console.warn(
17+
`Unable to create Redis instance, no rate limits are applied.`,
18+
);
19+
}
20+
}
21+
522
export const ratelimitMiddleware: MiddlewareHandler = async (context, next) => {
6-
if (context.req.method !== `POST`) {
23+
if (!ratelimit || context.req.method !== `POST`) {
724
return next();
825
}
926

@@ -16,14 +33,9 @@ export const ratelimitMiddleware: MiddlewareHandler = async (context, next) => {
1633
}
1734

1835
try {
19-
const ratelimit = new Ratelimit({
20-
redis: Redis.fromEnv(),
21-
limiter: Ratelimit.slidingWindow(10, `10 m`),
22-
analytics: true,
23-
});
24-
25-
const {success, reset, remaining} = await ratelimit.limit(address);
36+
const {success, reset, remaining, pending} = await ratelimit.limit(address);
2637
console.debug(`Rate limit result`, {address, success, remaining});
38+
await pending;
2739

2840
if (!success) {
2941
console.warn(`Too Many Requests by ${address}`);
@@ -33,13 +45,7 @@ export const ratelimitMiddleware: MiddlewareHandler = async (context, next) => {
3345
});
3446
}
3547
} catch (error) {
36-
if (process.env.UPSTASH_REDIS_REST_URL) {
37-
console.error(error);
38-
} else {
39-
console.warn(
40-
`Unable to create Redis instance, no rate limits are applied.`,
41-
);
42-
}
48+
console.error(error);
4349
}
4450

4551
return next();

0 commit comments

Comments
 (0)