Protect Your AI Feature From Abuse and Unexpected API Costs
Add usage limits and cost guardrails to an existing AI feature so one user or bot cannot repeatedly consume your AI API.
Roadmap & Resources
Inspect the AI Request
Confirm the AI Feature Works
Use the AI feature once, the way a normal user would.
The AI feature works right now
It returns a normal response
This is the feature you want to protect
If the feature is already broken, stop here. Fix it first as its own task — don't mix repairing the AI feature with abuse protection.
Fix a Bug in Your AI-Built Website or Web App With Claude Code
Use this first if the AI feature is not working.
/video/fix-a-bug-in-your-ai-built-website-or-web-app-with-claude-code
Inspect the AI Usage
Open Customize Prompt, fill in the three fields, then copy the prompt into the AI coding tool you use for this project.
Your API key can be hidden and your AI feature can still be abused: anyone who can use it can trigger it again and again, and every request can cost you. The safe order is request → check access → check the input and the usage limit → call AI. Never call AI first and decide afterward that it was too much.
Inspect the AI Usage
Tell AI which feature you want to protect, who should use it, and how much usage feels reasonable before changing anything.
I want to protect an existing AI feature from repeated or abusive usage. AI feature: {{AI_FEATURE}} Who should be allowed to use it: {{ACCESS_TYPE}} Usage rule: {{USAGE_LIMIT}} Do NOT modify the project yet. Never print secret values. Refer to credentials only by their variable name and location. 1. INSPECT THE CURRENT AI REQUEST PATH Find: - The UI action that triggers the AI request - The frontend request - The server route, API route, Edge Function or backend that receives it - The AI provider being called - The model being used - Where the provider credential is stored - Whether the provider credential is exposed to browser code - Whether authentication exists - Whether the server already knows the signed-in user - Whether any rate limit, quota or usage tracking already exists - Whether the project already has a database or cache suitable for usage tracking - The current input size - The current output or token limits, if configured - Whether the browser can control expensive provider settings such as the model, output size or other cost-sensitive parameters 2. CHECK THE SECRET FIRST If the private AI provider credential is exposed in browser or client code: STOP. Report: API CREDENTIAL EXPOSED Do not build abuse protection on top of an exposed private key. Point me to Profit Studio's existing API-key protection workflow first ("Protect API Keys Before Deploying an AI-Built Website or Web App") and do not duplicate that workflow here. If the key is already server-side, continue. 3. MAP THE REQUEST PATH Show the current path in a short form, for example: Button → /api/generate → Gemini API or: Chat UI → Supabase Edge Function → OpenAI API Then identify where the application's usage check should happen. The usage decision must occur BEFORE the paid AI provider request. 4. IDENTITY If the feature requires sign-in, prefer the authenticated user identity verified on the server. Do not trust a user_id sent by the browser as authority. If the feature is public, explain what identity or protection signal is realistically available in the current architecture, such as: - the server-observed IP address - an existing session - an anonymous server-issued identifier - existing bot protection Do not claim an IP address uniquely identifies a person. Do not add a complicated identity platform just for rate limiting. 5. COST DRIVERS Identify the biggest cost and abuse drivers for THIS feature, such as: - number of requests - maximum input length - maximum file size - maximum output tokens - expensive model choice - repeated retry loops - user-controlled model selection - multiple AI calls triggered by one click - concurrent requests Do not create a theoretical catalog. Only report real findings. 6. PROVIDER CONTROLS Identify which provider-level controls are currently available for this provider and project, such as: - rate limits or quotas - spend caps - budget or billing alerts - usage dashboards - project limits Provider limits do not replace application-level limits. Do not rely on them as the only protection. Do not invent provider dashboard labels. If exact dashboard instructions are needed later, tell me which provider or project page to open. 7. USAGE RULE If I gave a usage rule, check whether it fits normal use of this feature. If I did not give one, or I am not sure, recommend a conservative starter rule. It is a proposal for me to approve, not something to implement — there is no single correct limit for every app. Describe the rule in plain language: - Burst limit: how quickly repeated requests are allowed - Longer-period limit, where appropriate: how much one identity may use over a longer period - Input limit: maximum text length or file size, where relevant - Output limit: an explicit output or token ceiling, if the provider call supports it Return: 1. Current request path 2. Provider and model 3. Credential status 4. Current user and access model 5. Existing protection, if any 6. Main ways this feature could consume excessive AI usage 7. Recommended application-level protection 8. Usage rule to approve: mine checked against normal use, or your proposed starter rule if I did not provide one 9. Provider-level guardrails worth enabling 10. Files and data structures likely to change Do not implement anything yet.
Which AI feature do you want to protect?
AI chat, Generate button, document summary, image generator...
Who should be able to use it?
What usage limit do you want?
5 requests per minute and 50 per day, or "Not sure"
Review the proposed usage rule before continuing. The next step will turn it into an explicit limit.
Protect API Keys Before Deploying an AI-Built Website or Web App
Use this first if the report says API CREDENTIAL EXPOSED.
/video/protect-api-keys-before-deploying-ai-built-app
Set the Usage Rules
Approve the Limits
Find the usage rule in the inspection report. In plain language, it should cover:
Burst limit — how quickly one person can repeat requests, for example per minute
Longer-period limit — how much one person can use over a longer period, for example per day, where it makes sense
Input limit — the longest text or largest file the feature accepts
Output limit — the most the AI may generate for one request, if the provider supports a cap
Aim for limits a normal user never notices and obvious repeated abuse always hits. Don't pick huge numbers just to avoid blocking anyone, or tiny ones that break normal use. To change a number, tell AI in the same chat before you continue.
Normal usage still fits inside these limits
Repeated requests will be blocked
Input and output limits are reasonable
I approve these usage rules
Add the Protection
Add the Usage Limit
Let AI add the approved checks in front of the AI provider call.
Protect the AI Endpoint
Add the approved usage checks before the AI provider call and keep the existing AI feature working normally.
Implement the approved abuse protection for the existing AI feature. Use the request path and usage rules we already confirmed. Do not redesign the feature. Do not change unrelated AI functionality. Never print secret values. Do not commit, push or deploy. 1. CRITICAL ORDER The server-side flow must be: 1. Receive the request 2. Validate identity and access 3. Validate the request shape and input limits 4. Check the application usage limit 5. Reject the request if it is over the limit 6. Only if it is allowed, call the paid AI provider Do NOT call the provider first and rate-limit afterward. 2. IDENTITY — SIGNED-IN USERS If authentication exists and this feature is for signed-in users: - Use the authenticated user identity verified on the server. - Do not trust a user id sent by the browser. - Rate-limit the real authenticated account. - One user must not be able to consume another user's quota by changing an id in the request. 3. IDENTITY — PUBLIC VISITORS If the feature is public: - Use the smallest reasonable strategy that fits the current infrastructure, and explain its limitations. - Do not pretend anonymous rate limiting is perfect. - If you use an IP address, take it from the hosting platform's trusted source, not from a header the client can set. - If the current infrastructure already provides trustworthy request identity, bot protection or gateway controls, reuse them. - Do not add a new paid service unless it is genuinely necessary. 4. STORAGE AND COUNTER - Use an existing appropriate server-side store if one is available, such as the existing database, an existing Redis/KV store or another established server-side store. - Do not introduce Redis just because rate-limit tutorials commonly use it. - Choose the smallest reliable mechanism for THIS project. An in-memory counter is not reliable when the backend runs as serverless functions or on more than one instance. - The client must not be able to control or reset its own usage count. 5. SIMULTANEOUS REQUESTS Avoid an implementation where several simultaneous requests can bypass the limit because they all read the old counter before it updates. Use the atomic or transactional mechanism the chosen backend already provides, where appropriate. 6. INPUT PROTECTION Validate the request on the server. Where relevant: - trim input - reject empty input - cap text length - cap upload or file size - reject unsupported types - cap the number of items in a batch Do not rely only on HTML maxlength or other browser-side limits. 7. COST-SENSITIVE PROVIDER SETTINGS Do not let the browser freely choose expensive provider settings unless there is a real product reason. Server-side code should control values such as: - the allowed model - the maximum output or token limit - the number of generations - image count or resolution, where relevant - other major cost-sensitive options Preserve legitimate existing product choices. Do not make the feature worse just to minimize cost. 8. DUPLICATE AND CONCURRENT REQUESTS Check whether one click can currently trigger the same AI action more than once. Where appropriate, prevent accidental duplicate submissions — for example, disable the Generate button while its request is in progress, or stop the same form from being submitted twice at the same time. Do not rely on the UI as the security boundary. The server-side usage checks still apply. 9. BLOCKED RESPONSE - Return a clear application-level response, using a status such as 429 when that is consistent with the current backend. - Show a concise message in the UI, such as: "You've reached the usage limit. Try again later." - Do not reveal the provider secret, internal database data or infrastructure details. - Tell the user when they can try again only if the implementation reliably knows it. Do not invent retry times. 10. PROVIDER ERRORS Preserve the existing handling of real provider rate limits, quota exhaustion, outages and timeouts. The application usage limit and the provider's limits are separate. - Do not retry provider 429 responses aggressively. - Do not create an uncontrolled retry loop that increases usage. When finished, report: 1. Files changed 2. Identity used for limiting 3. Usage rule implemented 4. Store or counter used 5. Where the limit check happens relative to the provider call 6. Input limits added 7. Provider settings capped server-side 8. Duplicate and concurrent request protection 9. User-facing blocked state 10. Any infrastructure-level limitation this does not solve
This protects your AI provider usage. A request can still reach your hosting platform or server function before the limit check runs, and that invocation may still count there. Infrastructure-level DDoS and gateway protection is a separate setup.
Test a Blocked Request Without Spending Unnecessarily
Don't click Generate hundreds of times to test the limit. Let AI prove a blocked request never reaches the provider.
Test the Limit Without Paid AI Calls
Prove an over-limit request is blocked before the AI provider is called, without spending real API usage.
Test the usage limit we just added without spending unnecessary AI usage. Do NOT send large numbers of real paid AI requests to prove the limit works. Never print secret values. Do not commit, push or deploy. 1. CHOOSE THE SAFEST TEST METHOD Use the smallest existing test mechanism in this project that can prove this: once the application limit is exceeded, the request is blocked BEFORE the provider client or call runs. - If the project already has suitable tests or mocking, use them. - If it does not, use a temporary local or test-only method that proves the protected branch without repeatedly calling the real paid provider, such as a fake provider client in a local test run. - Do not add a full testing framework just for this. - Do not commit temporary test code, and never add a bypass, debug flag or lowered limit that could reach production. 2. PROVE - A normal request is allowed - An over-limit request is blocked - The blocked path does not call the provider - If authentication applies, another authenticated user still has their own independent allowance 3. REPORT For each check, report PASS or FAIL with brief evidence. Also report the test method used, how many real provider calls were made, and any temporary test code that must be removed before committing.
Add Cost Guardrails
Check Provider Controls
Open the dashboard for the AI provider and project named in the inspection report. Provider controls are a second layer — they never replace your app's own usage limit. Review the current:
Usage dashboard
API rate limits or quotas
Spend or cost controls, if available
Budget or billing alerts, if available
Alert vs. Cap
An alert tells you usage or spending went up — it does not stop requests. A spend cap or enforced limit tries to stop usage beyond a threshold you set. A cap may not act instantly, and once it is reached it blocks normal users too, so set it above your expected normal spend.
Using Gemini? Google AI Studio shows your usage and your project's rate limits, and lets you set a project spend cap. Google notes that billing data can lag by around 10 minutes, so usage can briefly go past a cap.
Confirm the Cost Boundaries
If your provider doesn't offer a control, mark it Not available instead of inventing a substitute.
AI usage dashboard checked
Current provider rate limits or quotas understood
Spend cap enabled if supported and appropriate — or marked Not available
Billing or usage alert enabled if supported — or marked Not available
Application-level usage limit still enabled
Test Normal and Abusive Use
Verify the AI Usage Protection
Verify AI Abuse Protection
Confirm normal users can still use the AI feature while repeated or oversized requests are stopped before the paid provider call.
Perform a focused verification of the AI usage protection we just added. Do not broaden this into a general security audit. Do not generate large amounts of paid AI usage during testing. If a check fails, report it — do not redesign the protection during this verification. Never print secret values. Do not commit, push or deploy. 1. NORMAL REQUEST Verify that a normal allowed request: - passes the application limit - reaches the provider - returns the expected AI result - does not change normal feature behavior Use the minimum number of real provider calls needed. 2. USAGE LIMIT Use the safe, focused test method we already established. Verify: - requests inside the approved allowance are accepted - an over-limit request is rejected - the provider call is NOT executed for the blocked request Do not test by spending large numbers of real provider calls. 3. IDENTITY ISOLATION If the feature uses authenticated accounts, verify: - User A reaching their limit does not consume User B's allowance - a user id sent by the browser cannot change whose quota is used If the feature is public, verify only what the chosen anonymous strategy can honestly guarantee. Do not claim perfect user identity. 4. INPUT LIMIT Send an oversized or invalid request using safe test data. Verify: - it is rejected before the provider call - the UI receives a usable error - no provider usage occurs 5. PROVIDER SETTINGS Verify that browser requests cannot override any expensive setting the server now controls, where relevant: - model - output or token limit - generation count 6. DUPLICATE REQUESTS If relevant to this feature, confirm the repeated click or submission protection behaves correctly. A disabled button alone is not security — the server-side checks must still apply. 7. SECRETS Confirm the provider's private credential remains server-side and these changes did not expose it. Do not perform a complete API-key security audit. 8. FINAL RESULT Return exactly one: AI USAGE PROTECTED or: NEEDS ATTENTION Use AI USAGE PROTECTED only if: - normal requests work - over-limit requests are blocked before the paid AI call - oversized requests are blocked before the provider call - identity-based limiting works as designed - private provider credentials remain server-side - no uncontrolled retry or duplicate request path remains If NEEDS ATTENTION, list only the remaining issues directly related to AI usage abuse or cost control. Also report any limitation that remains outside this guide, such as hosting, function-invocation or DDoS costs at the infrastructure level, and confirm that any temporary test-only code has been removed.
Use the AI feature once normally, then confirm the usage counter or limit reflects that request as expected.