Skip to content

Comments

perf: optimize free model usage IP limit counting in SQL#397

Open
kiloconnect[bot] wants to merge 3 commits intomainfrom
optimize-free-model-usage-query
Open

perf: optimize free model usage IP limit counting in SQL#397
kiloconnect[bot] wants to merge 3 commits intomainfrom
optimize-free-model-usage-query

Conversation

@kiloconnect
Copy link
Contributor

@kiloconnect kiloconnect bot commented Feb 20, 2026

Summary

  • Optimizes the free model usage stats query by moving IP limit counting from JavaScript to SQL
  • Replaces fetching all per-IP rows and iterating in JavaScript with a SQL subquery using HAVING COUNT(*) >= threshold
  • Avoids transferring potentially large result sets to the application layer

Changes

Before:

SELECT ip_address, COUNT(*) as request_count
FROM free_model_usage
WHERE created_at >= NOW() - INTERVAL '1 hours'
GROUP BY ip_address

Then iterate in JavaScript to count IPs with request_count >= 200

After:

SELECT COUNT(*) FROM (
  SELECT ip_address
  FROM free_model_usage
  WHERE created_at >= NOW() - INTERVAL '1 hours'
  GROUP BY ip_address
  HAVING COUNT(*) >= 200
) sub

Performance Impact

  • Reduces data transfer between database and application
  • Eliminates JavaScript iteration overhead
  • More efficient for large datasets with many IPs

File Changed

  • src/app/admin/api/free-model-usage/stats/route.ts:53-91

Move IP limit counting from JavaScript iteration to SQL HAVING clause.
Previously fetched all per-IP rows and counted in JS, now uses subquery
with HAVING COUNT(*) >= threshold to avoid transferring large result sets.
@kiloconnect
Copy link
Contributor Author

kiloconnect bot commented Feb 20, 2026

Code Review Summary

Status: No Issues Found | Recommendation: Merge

Clean optimization that pushes IP-at-limit counting from JavaScript to the database via SQL subqueries with HAVING COUNT(*) >= threshold. Both files apply the same pattern consistently:

  • The >= comparison matches the original JS logic
  • sql.raw() is only used with hardcoded numeric constants (no injection risk)
  • ANONYMOUS_FILTER composes correctly inside the Drizzle sql template
  • COUNT(*) from a subquery always returns exactly one row; the ?. / ?? 0 fallback is good defensive coding
  • Response shape is unchanged — no breaking API changes
Files Reviewed (2 files)
  • src/app/admin/api/free-model-usage/stats/route.ts - 0 issues
  • src/app/admin/api/promoted-model-usage/stats/route.ts - 0 issues

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant