Protecting Paid LLM API from Abuse
Summary
If a paid LLM API is integrated into a public service without protection, bots and scripts can drain the budget within hours. Here are four layers that make the integration secure: caching, quota, SSRF filter and key, and client-side invisible key.
Problem
APIs like DeepSeek/OpenAI are priced per token. When the service is free (e.g., 'check your site for free'), each request costs you money. Three threats:
- Repeats — the same request sent by a bot 1000 times.
- Quota abuse — bypassing the daily limit via VPN/IP changes.
- SSRF attack — forcing the server to access the internal network via a crafted URL.
Detailed analysis of all three is in the AI audit case.
Layer 1. URL Caching
A repeated request to the same URL should not trigger the neural network at all.
// Cache.php — result by hash URL in SQLite
$key = sha1($url);
$hit = $cache->get($key);
if ($hit) { return $hit; } // 0 tokens
$result = $llm->chat($prompt);
$cache->set($key, $result);
return $result;
This blocks the simplest draining scenario: one request — one LLM call, everything else from cache.
Layer 2. User Quota
Limit of 'N requests per day' for the client. The key point is how to identify the client so that a VPN cannot bypass the limit. Cascade:
user_id (if logged in) → cookie fingerprint → IP
A VPN changes IP but not cookies. Registration gives user_id, which a VPN cannot bypass at all. Upon exceeding — HTTP 429.
-- quota table
CREATE TABLE ai_quota (key TEXT, day TEXT, count INTEGER);
Layer 3. SSRF Filter
Before an outgoing request to an arbitrary URL — block internal addresses:
$blocked = [
'127.0.0.1', '0.0.0.0', '::1',
'169.254.169.254', // cloud metadata
'10.0.0.0/8', '192.168.0.0/16', '172.16.0.0/12',
];
Resolve DNS and compare the final IP with these ranges before the request.
Layer 4. Key, Invisible to Client
The sk-... key is stored as a constant on the server. The front-end never calls the provider directly — only through your PHP endpoint:
flowchart LR
A[Browser] -->|fetch to own PHP| B[Endpoint]
B -->|server-side key| C[DeepSeek API]
Stealing the key via DevTools is impossible: it simply isn't present in the browser's network requests.
Bonus: Token Limit in the Call Itself
Even with caching and quota, add a hard ceiling on the response:
'max_tokens' => 1200,
'temperature' => 0.4, // predictability, not creativity
This controls costs and response time, not aesthetics.
Summary
| Layer | What it covers |
|---|---|
| URL caching | repeats (0 tokens) |
| Quota + cascade | quota abuse via VPN |
| SSRF filter | internal network access |
| Server-side key | key theft |
| max_tokens | response cost ceiling |