Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Move to a per-space API rate limit (RAL-1262) (#2651)

Luke Vella235b0cc3c082
diff --git a/apps/web/src/app/api/private/[...route]/route.test.ts b/apps/web/src/app/api/private/[...route]/route.test.ts
index b97dd3368..32b5fb367 100644
--- a/apps/web/src/app/api/private/[...route]/route.test.ts
+++ b/apps/web/src/app/api/private/[...route]/route.test.ts
@@ -58,6 +58,7 @@ vi.mock("@/lib/kv", () => ({
import { prisma } from "@rallly/database";
import { after } from "next/server";
import { hashApiKey, verifyApiKey } from "@/features/api-keys/utils";
+import { RATE_LIMIT_PER_MINUTE } from "../utils/rate-limit";
import { app } from "./route";
// Pre-generated test API key fixture. The stored hash deliberately uses the
@@ -1106,6 +1107,65 @@ describe("Private API - /polls", () => {
});
});
+ describe("Rate limiting", () => {
+ // The rate limiter is keyed per space and shares a module-level memory
+ // store across the whole file. Use a dedicated space id here so the
+ // requests below don't count against (or get counted by) other tests.
+ const rateLimitSpaceId = "rate-limit-space-id";
+
+ beforeEach(() => {
+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([
+ {
+ ...mockApiKey,
+ hashedKey: hashApiKey(testApiKey),
+ spaceId: rateLimitSpaceId,
+ lastUsedAt: new Date(),
+ },
+ ]);
+ });
+
+ it("should include standard RateLimit headers on successful responses", async () => {
+ vi.mocked(prisma.poll.findFirst).mockResolvedValue(null);
+
+ const res = await app.request("/api/private/polls/some-poll", {
+ method: "GET",
+ headers: { Authorization: `Bearer ${testApiKey}` },
+ });
+
+ expect(res.headers.get("RateLimit-Limit")).toBe(
+ String(RATE_LIMIT_PER_MINUTE),
+ );
+ expect(res.headers.get("RateLimit-Remaining")).not.toBeNull();
+ });
+
+ it("should return 429 with RATE_LIMIT_EXCEEDED once the per-space limit is exceeded", async () => {
+ vi.mocked(prisma.poll.findFirst).mockResolvedValue(null);
+
+ const request = () =>
+ app.request("/api/private/polls/some-poll", {
+ method: "GET",
+ headers: { Authorization: `Bearer ${testApiKey}` },
+ });
+
+ // The limit is RATE_LIMIT_PER_MINUTE requests/minute per space; one more trips it.
+ let limited: Response | undefined;
+ for (let i = 0; i < RATE_LIMIT_PER_MINUTE + 1; i++) {
+ const res = await request();
+ if (res.status === 429) {
+ limited = res;
+ break;
+ }
+ }
+
+ expect(limited).toBeDefined();
+ expect(limited?.status).toBe(429);
+ expect(limited?.headers.get("Retry-After")).not.toBeNull();
+
+ const json = await limited?.json();
+ expect(json.error.code).toBe("RATE_LIMIT_EXCEEDED");
+ });
+ });
+
describe("Get poll participants", () => {
it("should return participants", async () => {
mockGetPollParticipants.mockResolvedValue({
diff --git a/apps/web/src/app/api/private/[...route]/route.ts b/apps/web/src/app/api/private/[...route]/route.ts
index f37c459d4..eef74b336 100644
--- a/apps/web/src/app/api/private/[...route]/route.ts
+++ b/apps/web/src/app/api/private/[...route]/route.ts
@@ -1,4 +1,3 @@
-import { RedisStore } from "@hono-rate-limiter/redis";
import type { SpaceTier } from "@rallly/database";
import { prisma } from "@rallly/database";
import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";
@@ -11,10 +10,8 @@ import {
resolver,
validator,
} from "hono-openapi";
-import { rateLimiter } from "hono-rate-limiter";
import { getPollParticipants, getPollResults } from "@/features/poll/data";
import { createPoll, deletePoll } from "@/features/poll/mutations";
-import { redis } from "@/lib/kv";
import { isMaintenanceModeEnabled } from "@/lib/maintenance";
import {
createPollInputSchema,
@@ -27,6 +24,7 @@ import {
} from "../schemas";
import { spaceApiKeyAuth } from "../utils/api-key";
import { apiError } from "../utils/poll";
+import { RATE_LIMIT_PER_MINUTE, rateLimit } from "../utils/rate-limit";
import type { SlotGeneratorInput } from "../utils/time-slots";
import {
dedupeTimeSlots,
@@ -70,6 +68,16 @@ const spaceNotProResponse = {
},
};
+const rateLimitExceededResponse = {
+ description:
+ "Rate limit exceeded. Includes a `Retry-After` header indicating how many seconds to wait before retrying.",
+ content: {
+ "application/json": {
+ schema: resolver(errorResponseSchema),
+ },
+ },
+};
+
app.get(
"/openapi",
openAPIRouteHandler(app, {
@@ -77,6 +85,13 @@ app.get(
info: {
title: "Rallly Private API",
version: "0.0.1",
+ description: [
+ "## Rate limits",
+ "",
+ `All endpoints share a single limit of **${RATE_LIMIT_PER_MINUTE} requests per minute per space**. The limit is per space, not per API key, so creating additional keys does not increase throughput.`,
+ "",
+ "Every response includes the standard `RateLimit-*` headers describing the current limit, remaining quota, and reset time. When the limit is exceeded the API responds with `429 Too Many Requests`, a `RATE_LIMIT_EXCEEDED` error body, and a `Retry-After` header indicating how many seconds to wait before retrying.",
+ ].join("\n"),
},
components: {
securitySchemes: {
@@ -102,15 +117,7 @@ app.get(
app.post(
"/polls",
spaceApiKeyAuth,
- rateLimiter<Env>({
- windowMs: 60 * 1000,
- limit: 60,
- keyGenerator: (c) => {
- const { apiKeyId } = c.get("apiAuth");
- return `private-api:polls-create:${apiKeyId}`;
- },
- store: redis ? new RedisStore({ client: redis }) : undefined,
- }),
+ rateLimit,
describeRoute({
tags: ["Polls"],
summary: "Create a poll",
@@ -135,6 +142,7 @@ app.post(
},
},
403: spaceNotProResponse,
+ 429: rateLimitExceededResponse,
},
}),
validator("json", createPollInputSchema),
@@ -336,15 +344,7 @@ app.post(
app.get(
"/polls/:pollId",
spaceApiKeyAuth,
- rateLimiter<Env>({
- windowMs: 60 * 1000,
- limit: 120,
- keyGenerator: (c) => {
- const { apiKeyId } = c.get("apiAuth");
- return `private-api:polls-get:${apiKeyId}`;
- },
- store: redis ? new RedisStore({ client: redis }) : undefined,
- }),
+ rateLimit,
describeRoute({
tags: ["Polls"],
summary: "Get a poll",
@@ -361,6 +361,7 @@ app.get(
},
},
403: spaceNotProResponse,
+ 429: rateLimitExceededResponse,
404: {
description: "Poll not found",
content: {
@@ -448,15 +449,7 @@ app.get(
app.get(
"/polls/:pollId/results",
spaceApiKeyAuth,
- rateLimiter<Env>({
- windowMs: 60 * 1000,
- limit: 120,
- keyGenerator: (c) => {
- const { apiKeyId } = c.get("apiAuth");
- return `private-api:polls-results:${apiKeyId}`;
- },
- store: redis ? new RedisStore({ client: redis }) : undefined,
- }),
+ rateLimit,
describeRoute({
tags: ["Polls"],
summary: "Get poll results",
@@ -473,6 +466,7 @@ app.get(
},
},
403: spaceNotProResponse,
+ 429: rateLimitExceededResponse,
404: {
description: "Poll not found",
content: {
@@ -508,15 +502,7 @@ app.get(
app.get(
"/polls/:pollId/participants",
spaceApiKeyAuth,
- rateLimiter<Env>({
- windowMs: 60 * 1000,
- limit: 120,
- keyGenerator: (c) => {
- const { apiKeyId } = c.get("apiAuth");
- return `private-api:polls-participants:${apiKeyId}`;
- },
- store: redis ? new RedisStore({ client: redis }) : undefined,
- }),
+ rateLimit,
describeRoute({
tags: ["Polls"],
summary: "Get poll participants",
@@ -533,6 +519,7 @@ app.get(
},
},
403: spaceNotProResponse,
+ 429: rateLimitExceededResponse,
404: {
description: "Poll not found",
content: {
@@ -568,15 +555,7 @@ app.get(
app.delete(
"/polls/:pollId",
spaceApiKeyAuth,
- rateLimiter<Env>({
- windowMs: 60 * 1000,
- limit: 60,
- keyGenerator: (c) => {
- const { apiKeyId } = c.get("apiAuth");
- return `private-api:polls-delete:${apiKeyId}`;
- },
- store: redis ? new RedisStore({ client: redis }) : undefined,
- }),
+ rateLimit,
describeRoute({
tags: ["Polls"],
summary: "Delete a poll",
@@ -593,6 +572,7 @@ app.delete(
},
},
403: spaceNotProResponse,
+ 429: rateLimitExceededResponse,
404: {
description: "Poll not found",
content: {
diff --git a/apps/web/src/app/api/private/utils/rate-limit.ts b/apps/web/src/app/api/private/utils/rate-limit.ts
new file mode 100644
index 000000000..8aaa5d34f
--- /dev/null
+++ b/apps/web/src/app/api/private/utils/rate-limit.ts
@@ -0,0 +1,42 @@
+import { RedisStore } from "@hono-rate-limiter/redis";
+import { rateLimiter } from "hono-rate-limiter";
+import { redis } from "@/lib/kv";
+import { apiError } from "./poll";
+
+/**
+ * Requests per minute allowed for a single space, uniform across all
+ * endpoints. Adding more API keys to a space does not raise this limit.
+ */
+export const RATE_LIMIT_PER_MINUTE = 60;
+
+type RateLimitEnv = {
+ Variables: {
+ apiAuth: {
+ spaceId: string;
+ };
+ };
+};
+
+/**
+ * A single per-space rate limit shared by every endpoint. Must run after
+ * `spaceApiKeyAuth` so that `apiAuth.spaceId` is populated.
+ *
+ * Known limitation: when Redis/KV is unavailable the fallback is a per
+ * instance memory store, which on Vercel is effectively no limit. Accepted
+ * for now; request logging makes it observable.
+ */
+export const rateLimit = rateLimiter<RateLimitEnv>({
+ windowMs: 60 * 1000,
+ limit: RATE_LIMIT_PER_MINUTE,
+ keyGenerator: (c) => `private-api:${c.get("apiAuth").spaceId}`,
+ store: redis ? new RedisStore({ client: redis }) : undefined,
+ handler: (c) => {
+ return c.json(
+ apiError(
+ "RATE_LIMIT_EXCEEDED",
+ "Rate limit exceeded. Retry after the time indicated in the Retry-After header.",
+ ),
+ 429,
+ );
+ },
+});