diff --git a/.env.example b/.env.example
index 604d10e9..201a2503 100644
--- a/.env.example
+++ b/.env.example
@@ -47,6 +47,18 @@ OPENROUTER_API_KEY=
OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
# Choose an OpenRouter model that supports streaming and tool calling.
OPENROUTER_CHAT_MODEL=openai/gpt-4o-mini
+# Ask ApplyWell limits (all providers). 0 disables a single limit; see docs/assistant-quota.md.
+APP_ASSISTANT_MAX_OUTPUT_TOKENS=1024
+APP_ASSISTANT_MAX_TOOL_CALLS=8
+APP_ASSISTANT_QUOTA_ENABLED=true
+APP_ASSISTANT_QUOTA_DAILY_LIMIT=30
+APP_ASSISTANT_QUOTA_RESET_ZONE=America/Sao_Paulo
+APP_ASSISTANT_QUOTA_RATE_LIMIT=5
+APP_ASSISTANT_QUOTA_RATE_WINDOW=1m
+APP_ASSISTANT_QUOTA_MAX_CONCURRENT=1
+APP_ASSISTANT_QUOTA_GLOBAL_DAILY_LIMIT=500
+APP_ASSISTANT_QUOTA_GLOBAL_RATE_LIMIT=20
+APP_ASSISTANT_QUOTA_GLOBAL_RATE_WINDOW=1m
OPENAI_GPT_CLIENT_ID=
OPENAI_GPT_CLIENT_SECRET=
diff --git a/docs/ask-applywell-backend.md b/docs/ask-applywell-backend.md
index fdc0758e..086d38ef 100644
--- a/docs/ask-applywell-backend.md
+++ b/docs/ask-applywell-backend.md
@@ -10,6 +10,11 @@ Events:
- `complete`: `{"sources":["APPLICATION_STATS"]}`
- `error`: a sanitized provider failure
+Per-user daily quota, rate limit, single in-flight generation and global provider limits are
+enforced before the provider is called. Rejections return HTTP 429 before the stream opens.
+`GET /api/v1/assistant/usage` returns the caller's daily usage. See
+[assistant-quota.md](assistant-quota.md).
+
Enable with `APP_ASSISTANT_ENABLED=true`, set `OPENAI_API_KEY`, and optionally set
`OPENAI_CHAT_MODEL`. The feature is disabled by default. Every tool is read-only and binds
the user ID captured from the authenticated request; the model never receives a user ID.
diff --git a/docs/assistant-providers.md b/docs/assistant-providers.md
index 7a0cbd1d..f689c297 100644
--- a/docs/assistant-providers.md
+++ b/docs/assistant-providers.md
@@ -35,6 +35,9 @@ To disable the assistant, set `APP_ASSISTANT_ENABLED=false` and
`APP_ASSISTANT_PROVIDER=none`. API keys are server-side secrets: do not
commit real values or expose them to the frontend.
+Quotas, rate limits, output-token and tool-call caps apply to every provider the
+same way. See [assistant-quota.md](assistant-quota.md).
+
There is no automatic provider fallback: selecting a provider switches
the backend on restart. OpenRouter's own provider routing and retry
behavior are separate from this selection.
diff --git a/docs/assistant-quota.md b/docs/assistant-quota.md
new file mode 100644
index 00000000..418a66d1
--- /dev/null
+++ b/docs/assistant-quota.md
@@ -0,0 +1,115 @@
+# Ask ApplyWell: quotas and anti-flood
+
+Every `POST /api/v1/assistant/chat` request goes through `AssistantQuotaService` **before** a
+`ChatModel` is called. The checks live above Spring AI's `ChatModel` abstraction, so they apply
+to any configured provider (OpenRouter, Gemini or a future one) without provider-specific code.
+
+## Limits
+
+Configure them in the server `.env` (or deployment environment) and restart the backend.
+A value of `0` disables that single check.
+
+| Variable | Default | Meaning |
+| --- | --- | --- |
+| `APP_ASSISTANT_QUOTA_ENABLED` | `true` | Master switch for all checks below. |
+| `APP_ASSISTANT_QUOTA_DAILY_LIMIT` | `30` | Messages per user per day. |
+| `APP_ASSISTANT_QUOTA_RESET_ZONE` | `America/Sao_Paulo` | Daily reset happens at local midnight in this IANA zone. It is unrelated to the provider's own reset (Gemini resets at midnight Pacific time). |
+| `APP_ASSISTANT_QUOTA_RATE_LIMIT` | `5` | Messages per user in the short window. |
+| `APP_ASSISTANT_QUOTA_RATE_WINDOW` | `1m` | Short (sliding) window length. |
+| `APP_ASSISTANT_QUOTA_MAX_CONCURRENT` | `1` | Generations in progress per user, across all tabs, devices and instances. |
+| `APP_ASSISTANT_QUOTA_GLOBAL_DAILY_LIMIT` | `500` | Provider calls per day for all users together. |
+| `APP_ASSISTANT_QUOTA_GLOBAL_RATE_LIMIT` | `20` | Provider calls in the global window for all users together. |
+| `APP_ASSISTANT_QUOTA_GLOBAL_RATE_WINDOW` | `1m` | Global window length. |
+| `APP_ASSISTANT_QUOTA_RETENTION` | `7d` | How long request rows are kept (minimum 2 days). |
+| `APP_ASSISTANT_MAX_OUTPUT_TOKENS` | `1024` | Output cap per provider call, sent as Spring AI's portable `maxTokens`. `0` keeps the provider default. |
+| `APP_ASSISTANT_MAX_TOOL_CALLS` | `8` | Tool calls per message. After the budget, tools return an error and the model must answer with what it has. `0` means unlimited. |
+| `APP_ASSISTANT_MAX_MESSAGE_LENGTH` | `4000` | Prompt size cap (existing). Conversation memory is capped at 20 messages. |
+
+Set the global limits **below** your provider plan (OpenRouter key/model limits or Gemini
+project RPM/RPD). A single message can trigger several provider round-trips when the model
+uses tools, so the real provider request count can be up to `1 + APP_ASSISTANT_MAX_TOOL_CALLS`
+per message. Keep a margin.
+
+## How it stays correct
+
+- Each authorized request inserts a row in `assistant_request_reservations`. Checks and the
+ insert run in one transaction that first locks the `assistant_quota_locks` row
+ (`SELECT ... FOR UPDATE`, `READ COMMITTED`). Parallel requests, tabs and application instances
+ are serialized there, so limits cannot be overshot. No Redis is needed; the lock is held for a
+ few milliseconds and the expected traffic is low.
+- An `IN_PROGRESS` row only blocks new requests (concurrency check) for
+ `APP_ASSISTANT_STREAM_TIMEOUT + 30s`. If an instance crashes mid-stream, the user is unblocked
+ after that lease, but the message stays charged.
+- Timestamps are stored in UTC; the reset zone is only used to compute day boundaries.
+
+## Accounting policy
+
+| Outcome | Daily user quota | Short window / global limits |
+| --- | --- | --- |
+| Blocked by a local limit, validation error, assistant disabled | Not charged (no row) | Not counted |
+| Local failure after reserving but before the provider call | Not charged (`RELEASED`) | Not counted |
+| Completed | Charged (`COMPLETED`) | Counted |
+| Provider error before any token was streamed (e.g. provider 429) | Refunded (`REFUNDED`) | Counted, because the provider was called |
+| Provider error after tokens were streamed | Charged (`FAILED`) | Counted |
+| Client disconnect or SSE timeout | Charged (`CANCELLED`) | Counted |
+
+Refunded failures still count toward the short window, so retry loops are still throttled.
+
+## API contract
+
+Rejected requests get an HTTP `429` JSON response before the SSE stream opens. A generation
+that was already authorized is never interrupted by a later rejection.
+
+```json
+{
+ "status": 429,
+ "error": "Too Many Requests",
+ "code": "ASSISTANT_DAILY_QUOTA_EXCEEDED",
+ "message": "Daily assistant message limit reached",
+ "retryAfterSeconds": 43200,
+ "retryAt": "2026-11-23T03:00:00Z"
+}
+```
+
+The `Retry-After` header carries the same seconds when known. Codes:
+
+- `ASSISTANT_DAILY_QUOTA_EXCEEDED`: retry at the next local reset.
+- `ASSISTANT_RATE_LIMITED`: retry when the oldest request leaves the short window.
+- `ASSISTANT_REQUEST_IN_PROGRESS`: another generation from this user is still running (no `Retry-After`).
+- `ASSISTANT_GLOBAL_LIMIT_REACHED`: the shared capacity is exhausted.
+
+Provider rate limits keep the existing SSE `error` event with code `RATE_LIMITED`
+(see `AssistantProviderErrorMapper`), which separates local 429s from provider 429s.
+
+`GET /api/v1/assistant/usage` returns only the authenticated user's usage:
+
+```json
+{
+ "quotaEnabled": true,
+ "dailyLimit": 30,
+ "used": 4,
+ "remaining": 26,
+ "resetAt": "2026-11-23T03:00:00Z",
+ "resetTimezone": "America/Sao_Paulo"
+}
+```
+
+`dailyLimit` and `remaining` are `null` when the daily limit is disabled.
+
+## Observability
+
+Prompts are never logged. Metrics (Micrometer, exposed via Prometheus):
+
+- `assistant.quota.decisions{result=allowed|daily_quota|rate_limited|concurrent_request|global_limit}`
+- `assistant.requests.in_flight` (per instance gauge)
+- `assistant.requests.completed{result=success|failure|cancelled}`
+- `assistant.quota.reservations.finished{status=...}`
+- `assistant.provider.errors{code=RATE_LIMITED|PROVIDER_UNAVAILABLE}` (provider-side 429 vs other failures)
+- `assistant.tokens{type=prompt|completion}` and `assistant.tool.calls`
+
+Token usage comes from Spring AI's `ChatResponse` metadata. It is cumulative across tool-call
+rounds for OpenRouter (OpenAI adapter, `stream_options.include_usage` is on by default) and
+Gemini. It is also stored per request in `prompt_tokens` / `completion_tokens`. Providers that
+report no usage leave those columns `NULL`.
+
+The log event `ASSISTANT_QUOTA_REJECTED` records the reason, user ID and retry delay.
diff --git a/src/main/java/com/jobtracker/config/AssistantProperties.java b/src/main/java/com/jobtracker/config/AssistantProperties.java
index 1188833f..763d0a69 100644
--- a/src/main/java/com/jobtracker/config/AssistantProperties.java
+++ b/src/main/java/com/jobtracker/config/AssistantProperties.java
@@ -3,6 +3,7 @@
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.time.Duration;
+import java.time.ZoneId;
@Component
@ConfigurationProperties(prefix = "app.assistant")
@@ -13,6 +14,9 @@ public class AssistantProperties {
private int maxSearchResults = 20;
private int memoryMaxMessages = 20;
private Duration streamTimeout = Duration.ofSeconds(60);
+ private int maxOutputTokens = 1024;
+ private int maxToolCalls = 8;
+ private final Quota quota = new Quota();
public boolean isEnabled() { return enabled; }
public void setEnabled(boolean enabled) { this.enabled = enabled; }
@@ -26,9 +30,55 @@ public class AssistantProperties {
public void setMemoryMaxMessages(int value) { this.memoryMaxMessages = value; }
public Duration getStreamTimeout() { return streamTimeout; }
public void setStreamTimeout(Duration value) { this.streamTimeout = value; }
+ public int getMaxOutputTokens() { return maxOutputTokens; }
+ public void setMaxOutputTokens(int value) { this.maxOutputTokens = value; }
+ public int getMaxToolCalls() { return maxToolCalls; }
+ public void setMaxToolCalls(int value) { this.maxToolCalls = value; }
+ public Quota getQuota() { return quota; }
public int clampLimit(Integer requested) {
int value = requested == null ? defaultSearchResults : requested;
return Math.max(1, Math.min(value, maxSearchResults));
}
+
+ /**
+ * Provider-agnostic usage limits enforced before any ChatModel call.
+ * A limit of 0 disables that specific check.
+ */
+ public static class Quota {
+ private boolean enabled = true;
+ private int dailyLimit = 30;
+ private ZoneId resetZone = ZoneId.of("America/Sao_Paulo");
+ private int rateLimit = 5;
+ private Duration rateWindow = Duration.ofMinutes(1);
+ private int maxConcurrent = 1;
+ private int globalDailyLimit = 500;
+ private int globalRateLimit = 20;
+ private Duration globalRateWindow = Duration.ofMinutes(1);
+ private Duration inFlightLeaseMargin = Duration.ofSeconds(30);
+ private Duration retention = Duration.ofDays(7);
+
+ public boolean isEnabled() { return enabled; }
+ public void setEnabled(boolean enabled) { this.enabled = enabled; }
+ public int getDailyLimit() { return dailyLimit; }
+ public void setDailyLimit(int value) { this.dailyLimit = value; }
+ public ZoneId getResetZone() { return resetZone; }
+ public void setResetZone(ZoneId value) { this.resetZone = value; }
+ public int getRateLimit() { return rateLimit; }
+ public void setRateLimit(int value) { this.rateLimit = value; }
+ public Duration getRateWindow() { return rateWindow; }
+ public void setRateWindow(Duration value) { this.rateWindow = value; }
+ public int getMaxConcurrent() { return maxConcurrent; }
+ public void setMaxConcurrent(int value) { this.maxConcurrent = value; }
+ public int getGlobalDailyLimit() { return globalDailyLimit; }
+ public void setGlobalDailyLimit(int value) { this.globalDailyLimit = value; }
+ public int getGlobalRateLimit() { return globalRateLimit; }
+ public void setGlobalRateLimit(int value) { this.globalRateLimit = value; }
+ public Duration getGlobalRateWindow() { return globalRateWindow; }
+ public void setGlobalRateWindow(Duration value) { this.globalRateWindow = value; }
+ public Duration getInFlightLeaseMargin() { return inFlightLeaseMargin; }
+ public void setInFlightLeaseMargin(Duration value) { this.inFlightLeaseMargin = value; }
+ public Duration getRetention() { return retention; }
+ public void setRetention(Duration value) { this.retention = value; }
+ }
}
diff --git a/src/main/java/com/jobtracker/controller/AssistantController.java b/src/main/java/com/jobtracker/controller/AssistantController.java
index 56e36fe0..884301b3 100644
--- a/src/main/java/com/jobtracker/controller/AssistantController.java
+++ b/src/main/java/com/jobtracker/controller/AssistantController.java
@@ -2,6 +2,7 @@
import com.jobtracker.config.AssistantProperties;
import com.jobtracker.dto.assistant.AssistantChatRequest;
+import com.jobtracker.dto.assistant.AssistantUsageResponse;
import com.jobtracker.service.assistant.AssistantProviderErrorMapper;
import com.jobtracker.service.assistant.AssistantService;
import com.jobtracker.service.assistant.AssistantService.AssistantStream;
@@ -56,6 +57,12 @@ public SseEmitter chat(@Valid @RequestBody AssistantChatRequest request) {
return emitter;
}
+ @PreAuthorize("hasRole('USER') or hasAuthority('SCOPE_read:applications')")
+ @GetMapping(value = "/usage", produces = MediaType.APPLICATION_JSON_VALUE)
+ public AssistantUsageResponse usage() {
+ return assistant.usage();
+ }
+
private void send(SseEmitter emitter, String event, Object data) {
try {
emitter.send(SseEmitter.event().name(event).data(data));
diff --git a/src/main/java/com/jobtracker/dto/assistant/AssistantUsageResponse.java b/src/main/java/com/jobtracker/dto/assistant/AssistantUsageResponse.java
new file mode 100644
index 00000000..ec187e5d
--- /dev/null
+++ b/src/main/java/com/jobtracker/dto/assistant/AssistantUsageResponse.java
@@ -0,0 +1,13 @@
+package com.jobtracker.dto.assistant;
+
+import java.time.Instant;
+
+/** dailyLimit and remaining are null when the daily quota is disabled. */
+public record AssistantUsageResponse(
+ boolean quotaEnabled,
+ Integer dailyLimit,
+ long used,
+ Integer remaining,
+ Instant resetAt,
+ String resetTimezone
+) {}
diff --git a/src/main/java/com/jobtracker/entity/AssistantQuotaLock.java b/src/main/java/com/jobtracker/entity/AssistantQuotaLock.java
new file mode 100644
index 00000000..46cb7149
--- /dev/null
+++ b/src/main/java/com/jobtracker/entity/AssistantQuotaLock.java
@@ -0,0 +1,23 @@
+package com.jobtracker.entity;
+
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+
+/** Single-row mutex: reservations lock it FOR UPDATE so checks and inserts are atomic across instances. */
+@Entity
+@Table(name = "assistant_quota_locks")
+public class AssistantQuotaLock {
+ public static final String GLOBAL = "assistant-global";
+
+ @Id
+ @Column(name = "lock_name", length = 64, nullable = false)
+ private String name;
+
+ protected AssistantQuotaLock() {}
+
+ public AssistantQuotaLock(String name) { this.name = name; }
+
+ public String getName() { return name; }
+}
diff --git a/src/main/java/com/jobtracker/entity/AssistantRequestReservation.java b/src/main/java/com/jobtracker/entity/AssistantRequestReservation.java
new file mode 100644
index 00000000..dd4f7af4
--- /dev/null
+++ b/src/main/java/com/jobtracker/entity/AssistantRequestReservation.java
@@ -0,0 +1,57 @@
+package com.jobtracker.entity;
+
+import com.jobtracker.entity.enums.AssistantReservationStatus;
+import jakarta.persistence.*;
+import org.hibernate.annotations.UuidGenerator;
+
+import java.time.LocalDateTime;
+import java.util.UUID;
+
+/** Timestamps are stored as UTC wall-clock values, independent of the JVM time zone. */
+@Entity
+@Table(name = "assistant_request_reservations", indexes = {
+ @Index(name = "idx_assistant_reservations_user_created", columnList = "user_id, created_at"),
+ @Index(name = "idx_assistant_reservations_created", columnList = "created_at")
+})
+public class AssistantRequestReservation {
+
+ @Id
+ @UuidGenerator(style = UuidGenerator.Style.TIME)
+ @Column(name = "id", columnDefinition = "BINARY(16)", updatable = false, nullable = false)
+ private UUID id;
+
+ @Column(name = "user_id", columnDefinition = "BINARY(16)", nullable = false, updatable = false)
+ private UUID userId;
+
+ @Enumerated(EnumType.STRING)
+ @Column(name = "status", nullable = false, length = 20)
+ private AssistantReservationStatus status;
+
+ @Column(name = "created_at", nullable = false, updatable = false)
+ private LocalDateTime createdAt;
+
+ @Column(name = "finished_at")
+ private LocalDateTime finishedAt;
+
+ @Column(name = "prompt_tokens")
+ private Integer promptTokens;
+
+ @Column(name = "completion_tokens")
+ private Integer completionTokens;
+
+ protected AssistantRequestReservation() {}
+
+ public AssistantRequestReservation(UUID userId, LocalDateTime createdAtUtc) {
+ this.userId = userId;
+ this.createdAt = createdAtUtc;
+ this.status = AssistantReservationStatus.IN_PROGRESS;
+ }
+
+ public UUID getId() { return id; }
+ public UUID getUserId() { return userId; }
+ public AssistantReservationStatus getStatus() { return status; }
+ public LocalDateTime getCreatedAt() { return createdAt; }
+ public LocalDateTime getFinishedAt() { return finishedAt; }
+ public Integer getPromptTokens() { return promptTokens; }
+ public Integer getCompletionTokens() { return completionTokens; }
+}
diff --git a/src/main/java/com/jobtracker/entity/enums/AssistantReservationStatus.java b/src/main/java/com/jobtracker/entity/enums/AssistantReservationStatus.java
new file mode 100644
index 00000000..6d00af88
--- /dev/null
+++ b/src/main/java/com/jobtracker/entity/enums/AssistantReservationStatus.java
@@ -0,0 +1,28 @@
+package com.jobtracker.entity.enums;
+
+import java.util.EnumSet;
+import java.util.Set;
+
+/**
+ * Lifecycle of one Ask ApplyWell request slot.
+ *
+ * - IN_PROGRESS: authorized, generation running (counts as in flight while the lease is valid).
+ * - COMPLETED / CANCELLED / FAILED: the provider was reached and produced or may have produced output; charged.
+ * - REFUNDED: the provider failed before emitting any output; not charged to the user's daily quota,
+ * but still counts toward rate windows and global limits because the provider was called.
+ * - RELEASED: the request failed before the provider was called; counts nowhere.
+ *
+ */
+public enum AssistantReservationStatus {
+ IN_PROGRESS,
+ COMPLETED,
+ CANCELLED,
+ FAILED,
+ REFUNDED,
+ RELEASED;
+
+ public static final Set CHARGED =
+ EnumSet.of(IN_PROGRESS, COMPLETED, CANCELLED, FAILED);
+ public static final Set PROVIDER_REACHED =
+ EnumSet.of(IN_PROGRESS, COMPLETED, CANCELLED, FAILED, REFUNDED);
+}
diff --git a/src/main/java/com/jobtracker/exception/AssistantQuotaExceededException.java b/src/main/java/com/jobtracker/exception/AssistantQuotaExceededException.java
new file mode 100644
index 00000000..06b7a9ca
--- /dev/null
+++ b/src/main/java/com/jobtracker/exception/AssistantQuotaExceededException.java
@@ -0,0 +1,42 @@
+package com.jobtracker.exception;
+
+import java.time.Instant;
+
+/** Raised before any provider call when an Ask ApplyWell limit blocks the request (HTTP 429). */
+public class AssistantQuotaExceededException extends RuntimeException implements CodedException {
+
+ public enum Reason {
+ DAILY_QUOTA("ASSISTANT_DAILY_QUOTA_EXCEEDED", "Daily assistant message limit reached"),
+ RATE_LIMITED("ASSISTANT_RATE_LIMITED", "Too many assistant messages. Please wait a moment"),
+ CONCURRENT_REQUEST("ASSISTANT_REQUEST_IN_PROGRESS", "Another assistant response is still being generated"),
+ GLOBAL_LIMIT("ASSISTANT_GLOBAL_LIMIT_REACHED", "The assistant is temporarily at capacity");
+
+ private final String code;
+ private final String message;
+
+ Reason(String code, String message) {
+ this.code = code;
+ this.message = message;
+ }
+
+ public String code() { return code; }
+ public String message() { return message; }
+ }
+
+ private final Reason reason;
+ private final Long retryAfterSeconds;
+ private final Instant retryAt;
+
+ public AssistantQuotaExceededException(Reason reason, Long retryAfterSeconds, Instant retryAt) {
+ super(reason.message());
+ this.reason = reason;
+ this.retryAfterSeconds = retryAfterSeconds;
+ this.retryAt = retryAt;
+ }
+
+ @Override
+ public String getCode() { return reason.code(); }
+ public Reason getReason() { return reason; }
+ public Long getRetryAfterSeconds() { return retryAfterSeconds; }
+ public Instant getRetryAt() { return retryAt; }
+}
diff --git a/src/main/java/com/jobtracker/exception/GlobalExceptionHandler.java b/src/main/java/com/jobtracker/exception/GlobalExceptionHandler.java
index 74275440..0984f673 100644
--- a/src/main/java/com/jobtracker/exception/GlobalExceptionHandler.java
+++ b/src/main/java/com/jobtracker/exception/GlobalExceptionHandler.java
@@ -4,6 +4,7 @@
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.access.AccessDeniedException;
@@ -57,6 +58,25 @@ public ResponseEntity