Skip to content

An AI-powered search engine with a generative UI

feat: make overall daily chat limit configurable via env (#919)

Yoshiki Miuraf24502abe015
diff --git a/lib/rate-limit/chat-limits.ts b/lib/rate-limit/chat-limits.ts
index 94ea4a5f..93e6d561 100644
--- a/lib/rate-limit/chat-limits.ts
+++ b/lib/rate-limit/chat-limits.ts
@@ -2,7 +2,16 @@ import { Redis } from '@upstash/redis'
import { perfLog } from '@/lib/utils/perf-logging'
-const DAILY_CHAT_LIMIT = 100
+const DEFAULT_DAILY_CHAT_LIMIT = 100
+
+function getDailyChatLimit(): number {
+ const raw = process.env.OVERALL_CHAT_DAILY_LIMIT
+ const parsed = raw ? Number(raw) : DEFAULT_DAILY_CHAT_LIMIT
+ if (!Number.isFinite(parsed) || parsed <= 0) {
+ return DEFAULT_DAILY_CHAT_LIMIT
+ }
+ return Math.floor(parsed)
+}
/**
* Get seconds until next midnight UTC
@@ -28,10 +37,13 @@ async function checkOverallChatLimit(userId: string): Promise<{
allowed: boolean
remaining: number
resetAt: number
+ limit: number
}> {
+ const limit = getDailyChatLimit()
+
// If not in cloud deployment mode, allow unlimited requests
if (process.env.MORPHIC_CLOUD_DEPLOYMENT !== 'true') {
- return { allowed: true, remaining: Infinity, resetAt: 0 }
+ return { allowed: true, remaining: Infinity, resetAt: 0, limit }
}
// If Upstash is not configured, allow unlimited requests
@@ -39,7 +51,7 @@ async function checkOverallChatLimit(userId: string): Promise<{
!process.env.UPSTASH_REDIS_REST_URL ||
!process.env.UPSTASH_REDIS_REST_TOKEN
) {
- return { allowed: true, remaining: Infinity, resetAt: 0 }
+ return { allowed: true, remaining: Infinity, resetAt: 0, limit }
}
try {
@@ -63,17 +75,18 @@ async function checkOverallChatLimit(userId: string): Promise<{
await redis.expire(key, secondsUntilMidnight)
}
- const remaining = Math.max(0, DAILY_CHAT_LIMIT - count)
+ const remaining = Math.max(0, limit - count)
const resetAt = getNextMidnightTimestamp()
return {
- allowed: count <= DAILY_CHAT_LIMIT,
+ allowed: count <= limit,
remaining,
- resetAt
+ resetAt,
+ limit
}
} catch (error) {
console.error('Rate limit check failed:', error)
- return { allowed: true, remaining: Infinity, resetAt: 0 }
+ return { allowed: true, remaining: Infinity, resetAt: 0, limit }
}
}
@@ -92,13 +105,13 @@ export async function checkAndEnforceOverallChatLimit(
error: 'Daily chat limit reached. Please try again tomorrow.',
remaining: 0,
resetAt: result.resetAt,
- limit: DAILY_CHAT_LIMIT
+ limit: result.limit
}),
{
status: 429,
headers: {
'Content-Type': 'application/json',
- 'X-RateLimit-Limit': String(DAILY_CHAT_LIMIT),
+ 'X-RateLimit-Limit': String(result.limit),
'X-RateLimit-Remaining': '0',
'X-RateLimit-Reset': String(result.resetAt)
}
@@ -106,9 +119,7 @@ export async function checkAndEnforceOverallChatLimit(
)
}
- perfLog(
- `Chat usage: ${DAILY_CHAT_LIMIT - result.remaining}/${DAILY_CHAT_LIMIT}`
- )
+ perfLog(`Chat usage: ${result.limit - result.remaining}/${result.limit}`)
return null
}