Resource Consumption Protection
🎯 Introduction
Frequent requests and concurrent tasks can exhaust an AI application's connections and compute resources. Long waits for model responses also keep resources occupied. This article implements per-user rate limiting, user and application concurrency limits, and OpenAI SDK timeouts and cancellation.
🧱 Understand resource consumption risks
Even with concurrency limited to one, a user can still send many requests in succession. Limit both request rate and concurrency.
🛠 Limit request rates
Consider an AI text Q&A endpoint that allows each user up to 10 requests per minute. These Node.js 22 examples use limits chosen for teaching purposes.
Create guard.mjs:
const windows = new Map();
export function checkRate(userId) {
const now = Date.now();
let window = windows.get(userId);
if (!window || now - window.start >= 60000) {
window = { start: now, count: 0 };
windows.set(userId, window);
}
if (window.count >= 10) {
throw new Error('RATE_LIMIT');
}
window.count += 1;
}
Create test-rate.mjs and submit 11 consecutive requests:
import { checkRate } from './guard.mjs';
for (let i = 1; i <= 11; i++) {
try {
checkRate('user-1');
console.log(i, 'PASS');
} catch (error) {
console.log(i, error.message);
}
}
Run node test-rate.mjs. Output excerpt:
1 PASS
2 PASS
...
10 PASS
11 RATE_LIMIT
Rate limiting counts requests admitted to subsequent processing, rather than successfully generated answers. In a real endpoint, apply it after authentication and before tokenization. Fixed windows can allow bursts around window boundaries.
🛠 Limit concurrency
Per-user concurrency limits alone are insufficient: 100 users making simultaneous requests can still occupy 100 model connections.
Append the following to guard.mjs: allow one active task per user and two active tasks across the application.
const activeUsers = new Set();
let appActive = 0;
export async function withConcurrency(userId, task) {
if (activeUsers.has(userId)) {
throw new Error('USER_CONCURRENT_LIMIT');
}
if (appActive >= 2) {
throw new Error('APP_CONCURRENT_LIMIT');
}
// Check and reserve slots synchronously within one process
activeUsers.add(userId);
appActive += 1;
try {
return await task();
} finally {
activeUsers.delete(userId);
appActive -= 1;
}
}
Test per-user concurrency limits
Create test-concurrency.mjs, simulating model requests with tasks that take one second:
import { setTimeout as delay } from 'node:timers/promises';
import { withConcurrency } from './guard.mjs';
async function request(userId) {
try {
await withConcurrency(userId, async () => {
console.log(userId, 'Request started');
await delay(1000);
console.log(userId, 'Request completed');
});
} catch (error) {
console.log(userId, error.message);
}
}
request('user-1');
request('user-1');
Run node test-concurrency.mjs:
user-1 Request started
user-1 USER_CONCURRENT_LIMIT
user-1 Request completed
There is no await between the calls, so the second request reaches the concurrency check before the first finishes.
Test application concurrency limits
Replace the two requests at the end of test-concurrency.mjs with:
request('user-1');
request('user-2');
request('user-3');
Run again. Output:
user-1 Request started
user-2 Request started
user-3 APP_CONCURRENT_LIMIT
user-1 Request completed
user-2 Request completed
Test concurrency slot release
Replace the three requests at the end of the file with:
await request('user-1');
await request('user-1');
Run again. Output:
user-1 Request started
user-1 Request completed
user-1 Request started
user-1 Request completed
This time, await waits for the first request to finish. Its finally block releases the slot, allowing the second request to run. finally also runs when a task throws.
Map and Set only work within one process. In production, obtain user IDs from authentication results. Multiple instances need shared storage and atomic operations to enforce common limits, plus slot recovery after abnormal process termination.🛠 Request timeouts and cancellation
Use Node.js 22 and OpenAI SDK 5.12.2. Install the dependency and configure an API key and an available Chat Completions model that supports max_completion_tokens:
npm install openai@5.12.2
export OPENAI_API_KEY='your API key'
export OPENAI_MODEL='your model ID'
Request timeouts
When a model service responds slowly, use the SDK's timeout option to limit waiting time in milliseconds. Set maxRetries: 0 to disable automatic retries and avoid additional waiting and usage.
Create test-timeout.mjs:
import OpenAI from 'openai';
const openai = new OpenAI({
maxRetries: 0
});
try {
const response = await openai.chat.completions.create({
model: process.env.OPENAI_MODEL,
messages: [{ role: 'user', content: 'Introduce Vue in one sentence.' }],
max_completion_tokens: 200
}, {
timeout: 1
});
console.log(response.choices[0].message.content);
} catch (error) {
console.log(error.name);
}
Run node test-timeout.mjs. If the request times out, expect:
APIConnectionTimeoutError
The example deliberately uses one millisecond to make timeouts easy to observe. In practice, choose a reasonable value such as 10000 milliseconds based on task duration. A request-level timeout overrides the client default.
Cancel a request explicitly
When a user clicks Stop generating, use the built-in AbortController in browsers and Node.js to cancel the request without waiting for a timeout.
| Property or method | Purpose |
|---|---|
controller.signal | Cancellation signal created with the controller; pass it to an API that supports cancellation |
controller.abort() | Sends the cancellation signal, asking the receiving API to stop |
Create test-cancel.mjs and pass the signal in the OpenAI SDK's second argument:
import OpenAI from 'openai';
const openai = new OpenAI({
timeout: 10000,
maxRetries: 0
});
const controller = new AbortController();
// Simulate the user clicking Stop after one second
const timer = setTimeout(() => {
controller.abort();
}, 1000);
try {
const response = await openai.chat.completions.create({
model: process.env.OPENAI_MODEL,
messages: [{ role: 'user', content: 'Explain JavaScript in detail.' }],
max_completion_tokens: 200
}, {
signal: controller.signal
});
console.log(response.choices[0].message.content);
} catch (error) {
console.log(error.name);
} finally {
clearTimeout(timer);
}
Run node test-cancel.mjs. If the request is canceled before completion, expect:
APIUserAbortError
If the request finishes first, the answer prints normally. Create a new controller for every request; an aborted signal cannot be reset.
❓ Questions and answers
Q1: Why does the model provider still return 429 when the application already limits each user's request rate?
Multiple users may share a project's request and token limits. Their combined usage may reach provider limits even when each user follows application rules. Distinguish rate limiting from quota exhaustion when handling 429 responses, and avoid blind retries.
🧪 Exercise
Change the application concurrency limit in guard.mjs to three. Modify test-concurrency.mjs so four different users send requests simultaneously.
Acceptance criteria: The first three tasks start, the fourth outputs APP_CONCURRENT_LIMIT, and new requests work after the first three finish.
🎉 You have learned rate limiting, concurrency limits, and cancellation for AI requests.
Model Output Safety
Learn output moderation, schema and business validation, and safe Markdown rendering in Vue to keep untrusted model output out of unsafe rendering and execution paths.
Token and Cost Control
Limit model input and output tokens, track actual usage, estimate costs, and enforce cumulative quotas.
