Skip to content

feat(assistant): add per-user daily quota and anti-flood limits - #110

Merged
hugoalves-dev merged 1 commit into
mainfrom
hugo/quirky-edison-i9ysz4
Nov 23, 2026
Merged

hugoalves-dev merged 1 commit into
mainfrom
hugo/quirky-edison-i9ysz4

Conversation

@hugoalves-dev

Copy link
Copy Markdown
Owner

Closes #109

Summary

Ask ApplyWell limits are now checked in AssistantService.stream() before any ChatModel call. Because the check sits above Spring AI's ChatModel abstraction, it applies to OpenRouter, Gemini and any future provider the same way.

  • Per user: daily quota (default 30/day, reset at local midnight in APP_ASSISTANT_QUOTA_RESET_ZONE, default America/Sao_Paulo), sliding-window rate limit (5/min), and one in-flight generation across tabs and instances.
  • Global: daily (500) and per-window (20/min) limits protect the shared provider key.
  • Per request: a portable maxTokens cap (ChatOptions, merged into each provider's defaults) and a tool-call budget per message (8). Each tool call is an extra provider round-trip.
  • Atomic without Redis: check-and-reserve runs in one READ COMMITTED transaction holding SELECT ... FOR UPDATE on a single row in assistant_quota_locks. Rows in assistant_request_reservations (migration V36) are the source of truth.
  • Crash safety: an IN_PROGRESS slot stops blocking the user after stream-timeout + 30s, but stays charged.
  • Accounting:
    • Blocked requests and failures before the provider is called are free.
    • Provider errors before any token are refunded from the daily quota, but still count toward the rate window and the global limits.
    • Partial output, disconnects and timeouts are charged.
  • API:
    • Rejections return HTTP 429 JSON before the SSE stream opens, with a stable code (ASSISTANT_DAILY_QUOTA_EXCEEDED, ASSISTANT_RATE_LIMITED, ASSISTANT_REQUEST_IN_PROGRESS, ASSISTANT_GLOBAL_LIMIT_REACHED), retryAfterSeconds, retryAt and the Retry-After header.
    • Provider 429s keep the existing SSE error event with code RATE_LIMITED.
    • New GET /api/v1/assistant/usage returns only the caller's daily usage.
  • Observability: Micrometer metrics for quota decisions, in-flight generations, outcomes, provider errors, prompt/completion tokens and tool calls. Token usage is also stored per request. Prompts are never logged.
  • Housekeeping: a scheduled job purges old reservation rows (minimum 2 days of retention).
  • Configuration: limits are set through APP_ASSISTANT_QUOTA_*, APP_ASSISTANT_MAX_OUTPUT_TOKENS and APP_ASSISTANT_MAX_TOOL_CALLS. 0 disables a single limit. See docs/assistant-quota.md and .env.example.

Testing

  • mvn test: 502 tests, 0 failures.
  • New AssistantQuotaServiceIT and AssistantServiceQuotaIT cover daily limit and reset, rate window, concurrency (20 parallel threads against a limit of 5), global limits, per-user isolation, refund/charge policy, cancellation and usage.
  • Unit tests cover the controller's 429 response (including with Accept: text/event-stream), the usage endpoint, the token cap and the tool budget.
  • The two quota IT classes also pass against a real MariaDB 11 with migrations V1–V36 applied and ddl-auto=validate. The FK was dropped in that throwaway container only, because the tests use random user IDs.

Deployment notes

  • Tune APP_ASSISTANT_QUOTA_GLOBAL_* below the OpenRouter plan's limits. Allow for up to 1 + max-tool-calls provider requests per message.
  • V36 seeds the lock row. If the row is missing, reservations fail closed with 503.

Generated by Claude Code

Enforce Ask ApplyWell limits before any ChatModel call, independent of
the configured provider (OpenRouter, Gemini or future ones):

- daily quota per user with configurable reset timezone
- sliding-window rate limit and one in-flight generation per user
- global daily and per-window limits protecting the shared provider key
- portable max output tokens and a per-request tool-call budget

Check-and-reserve runs under a SELECT ... FOR UPDATE row lock in MariaDB,
so parallel tabs and multiple instances cannot overshoot. Rejections
return HTTP 429 with a stable code and Retry-After before the SSE stream
opens. Provider failures before any output are refunded; disconnects and
partial outputs stay charged. GET /api/v1/assistant/usage exposes the
caller's usage. Limits are configured via environment variables.

Closes #109

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GfjfbSZRwVyCUYMTGSLCAA
@github-actions github-actions Bot added documentation Improvements or additions to documentation backend tests database configuration labels Nov 22, 2026
@github-actions

Copy link
Copy Markdown

Qodana for JVM

5 new problems were found

Inspection name Severity Problems
Constant values 🔶 Warning 3
Non-atomic operation on 'volatile' field 🔶 Warning 2
View the detailed Qodana report

To be able to view the detailed Qodana report, you can either:

To get *.log files or any other Qodana artifacts, run the action with upload-result option set to true,
so that the action will upload the files as the job artifacts:

      - name: 'Qodana Scan'
        uses: JetBrains/qodana-action@v2025.3.2
        with:
          upload-result: true
Contact Qodana team

Contact us at qodana-support@jetbrains.com

@hugoalves-dev
hugoalves-dev merged commit 85bbfa4 into main Nov 23, 2026
6 checks passed
@hugoalves-dev
hugoalves-dev deleted the hugo/quirky-edison-i9ysz4 branch November 23, 2026 02:37
hugoalves-dev pushed a commit that referenced this pull request Nov 23, 2026
The PostgreSQL migration (#107) branched before the assistant quota (#110)
landed, so the Postgres schema lacked assistant_request_reservations and
assistant_quota_locks, and the entity still declared BINARY(16) columns.
With ddl-auto=validate the app would not start on PostgreSQL, and the data
migrator would refuse the cutover because the MariaDB source has the tables.

- add PostgreSQL V37 with both tables and the lock row seed
- map the reservation UUIDs with the native type
- migrator: expect Flyway V37 and replace the seeded lock row on import

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GfjfbSZRwVyCUYMTGSLCAA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend configuration database documentation Improvements or additions to documentation tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(ai): adicionar cota diária por usuário e proteção anti-flood no Ask ApplyWell

2 participants