Create a render concurrency safety net: max-inflight for bots, 5xx guardrails, and retry…
- User
Create a render concurrency safety net: max-inflight for bots, 5xx guardrails, and retry envelopes.
Assistant
Create a render concurrency safety net: max-inflight for bots, 5xx guardrails, and retry envelopes.
The user wants a "render concurrency safety net" with specific features: "max-inflight for bots", "5xx guardrails", and "retry envelopes".
This is likely a backend software engineering task, probably involving writing code (middleware, library, or service logic) to handle concurrent requests safely, specifically targeting web crawling/scraping scenarios or high-load API interactions where "bots" are involved.
Let's break down the requirements:
Render Concurrency Safety Net: This implies the context is rendering (headless browsers like Puppeteer/Playwright) or just generic HTTP fetching in a concurrent environment. "Render" usually suggests generating HTML/JS, so I should assume a context like a server rendering pages or a scraping service.
Max-inflight for bots:
5xx Guardrails:
Retry Envelopes:
Choice of Language: TypeScript/Node.js is the standard for "render" (Puppeteer/Playwright) and high-concurrency IO. I'll use TypeScript.
Architecture: I will create a class or a set of utilities that manages this "Safety Net".
ConcurrencyManager: Handles the "max-inflight" logic using Semaphores.CircuitBreaker: Handles the "5xx guardrails".RetryPolicy: Handles the "retry envelopes".I should wrap this in a clean API, perhaps a function called safeRender or safeFetch.
Drafting the Code Structure:
RequestOptions (url, botId, retries, etc.)RenderSafetyNet
acquireSlot(botId): Checks semaphore.execute(task): Wraps the task in retry and circuit breaker logic.releaseSlot(botId): Frees semaphore.Refining the components:
Max-Inflight:
Map<string, Semaphore> where key is botId.5xx Guardrails:
errors / total > threshold, trip the breaker.timeout before trying again.Retry Envelopes:
await sleep(2^attempt * base + jitter).Putting it together:
I will provide a TypeScript implementation. It's robust and fits the "render" ecosystem well.
npm install friction unless necessary.Corner Cases:
botId.Plan:
Semaphore (for max-inflight).CircuitBreaker (for 5xx).RetryManager (for envelopes).RenderSafetyNet class to orchestrate them.Let's write the code mentally first.
Semaphore: wait() adds to queue or decrements count. release() increments or pops queue.
CircuitBreaker: recordFailure(), recordSuccess(), isAllowed().
Retry: Loop 0..maxRetries. try { await fn() } catch { if (!retriable) throw; wait(backoff) }.
Refinement on "Render Concurrency":
The prompt specifically says "Render". This implies we might be managing Chrome instances or tabs. The logic is the same (concurrency control), but I should name the main entry point something like executeSafeRender.
Let's execute. I will write a clean, modular TypeScript solution.
I will package this as a cohesive class.
Self-Correction during drafting:
Should I use a library like async-semaphore or opossum? No, better to write vanilla TS for a complete, standalone answer that explains the mechanics. The user asked to "Create" it, not "Install" it.
Let's ensure the "Envelope" concept is clear. It usually means wrapping the request metadata (headers, timeout) along with the execution policy.
Final structure:
sleep function.BotRateLimiter (Semaphore wrapper).ServerErrorGuardrail (Circuit Breaker).RetryHandler (Backoff logic).RenderSafetyNet combining them.Let's generate. This solution implements a robust Render Safety Net in TypeScript. It is designed to manage concurrency for headless browsers (like Puppeteer/Playwright) or high-load scraping services.
It combines three specific patterns as requested:
Here is how you would integrate this into a service that spins up headless browsers.
// index.ts
async function main() {
const safetyNet = new RenderSafetyNet();
// 1. Configure limits
// Allow "PriceMonitorBot" to have max 3 concurrent renders
safetyNet.configureBot('PriceMonitorBot', 3);
// Allow "SeoCrawlerBot" to have max 10 concurrent renders
safetyNet.configureBot('SeoCrawlerBot', 10);
// Mock Render Function (Simulating Puppeteer/Playwright)
const mockRender = async (url: string): Promise<RenderResult> => {
console.log(` -> Rendering ${url}...`);
// Simulate random failure
if (Math.random() < 0.3) throw { status: 503, message: 'Service Unavailable' };
// Simulate work
await sleep(500);
return {
html: `<html><body>Content of ${url}</body></html>`,
status: 200,
timings: { total: 500, render: 400 }
};
};
// 2. Execute within the Safety Net
const taskContext = {
botId: 'PriceMonitorBot',
targetDomain: 'example.com'
};
try {
const result = await safetyNet.execute(taskContext, () => mockRender('https://example.com/product'));
console.log('✅ Render Success:', result.status);
} catch (error) {
console.error('❌ Render Failed after retries/guardrails:', error);
}
}
main();
RenderSafetyNet class composes the three layers. Requests flow from Guardrail (Is the target healthy?) -> Retry (Should we try again?) -> Semaphore (Do we have capacity?).PriceMonitorBot is at capacity (3), the 4th request sits in a promise queue until one of the previous 3 finishes.example.com returns three 500 errors in a row, the circuit trips. isAllowed returns false, immediately failing fast without wasting resources trying to render./**
* RENDER CONCURRENCY SAFETY NET
*
* Components:
* 1. BotSemaphore: Max-inflight request limits per Bot ID.
* 2. HttpGuardrail: Circuit breaker for 5xx server errors.
* 3. RetryEnvelope: Retries with backoff for transient failures.
*/
// --- Utilities ---
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
// Simple logger interface
interface Logger {
warn(message: string, ...args: any[]): void;
log(message: string, ...args: any[]): void;
error(message: string, ...args: any[]): void;
}
const consoleLogger: Logger = console;
// --- Component 1: Concurrency Limiting (Max-Inflight) ---
class BotSemaphore {
private locks: Map<string, { current: number; max: number; queue: (() => void)[] }> = new Map();
constructor(private defaultMax: number = 5) {}
// Configure limit for a specific bot
public registerBot(botId: string, maxInflight: number) {
if (!this.locks.has(botId)) {
this.locks.set(botId, { current: 0, max: maxInflight, queue: [] });
} else {
// Update max if bot already exists (dynamic config)
const lock = this.locks.get(botId)!;
lock.max = maxInflight;
// Process queue in case limit was increased
this.processQueue(botId);
}
}
private processQueue(botId: string) {
const lock = this.locks.get(botId);
if (!lock) return;
while (lock.current < lock.max && lock.queue.length > 0) {
const next = lock.queue.shift();
if (next) {
lock.current++;
next();
}
}
}
// Acquire a slot
public async acquire(botId: string): Promise<void> {
if (!this.locks.has(botId)) {
this.registerBot(botId, this.defaultMax);
}
const lock = this.locks.get(botId)!;
if (lock.current < lock.max) {
lock.current++;
return;
}
// Queue the request
return new Promise<void>((resolve) => {
lock.queue.push(() => resolve());
});
}
// Release a slot
public release(botId: string) {
const lock = this.locks.get(botId);
if (!lock) return;
lock.current = Math.max(0, lock.current - 1);
this.processQueue(botId);
}
}
// --- Component 2: 5xx Guardrails (Circuit Breaker) ---
type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
class HttpGuardrail {
private circuits: Map<string, {
state: CircuitState;
failureCount: number;
nextRetryTime: number
}> = new Map();
constructor(
private threshold: number = 3, // Failures before opening
private timeout: number = 30000, // Time (ms) circuit stays open
private logger: Logger = consoleLogger
) {}
private getState(key: string): { state: CircuitState; failureCount: number; nextRetryTime: number } {
if (!this.circuits.has(key)) {
this.circuits.set(key, { state: 'CLOSED', failureCount: 0, nextRetryTime: 0 });
}
return this.circuits.get(key)!;
}
// Check if request is allowed
public isAllowed(targetKey: string): boolean {
const circuit = this.getState(targetKey);
if (circuit.state === 'CLOSED') return true;
if (circuit.state === 'OPEN') {
if (Date.now() > circuit.nextRetryTime) {
this.logger.log(`[Guardrail] Entering HALF_OPEN state for ${targetKey}`);
circuit.state = 'HALF_OPEN';
return true; // Allow one test request
}
return false;
}
// HALF_OPEN allows one request through.
// If it fails, resultRecord will handle opening it again.
return true;
}
// Record result
public recordResult(targetKey: string, isSuccess: boolean, statusCode: number = 200) {
const circuit = this.getState(targetKey);
if (isSuccess) {
if (circuit.state === 'HALF_OPEN') {
this.logger.log(`[Guardrail] Circuit recovered for ${targetKey}`);
circuit.state = 'CLOSED';
circuit.failureCount = 0;
}
} else {
// Check if it's a 5xx error
const is5xx = statusCode >= 500 && statusCode < 600;
// We only trip on 5xx or network failures, not 404s
if (is5xx || statusCode === 0) {
circuit.failureCount++;
this.logger.warn(`[Guardrail] Failure ${circuit.failureCount} recorded for ${targetKey} (Status: ${statusCode})`);
if (circuit.failureCount >= this.threshold || circuit.state === 'HALF_OPEN') {
this.trip(targetKey);
}
}
}
}
private trip(targetKey: string) {
const circuit = this.getState(targetKey);
circuit.state = 'OPEN';
circuit.nextRetryTime = Date.now() + this.timeout;
this.logger.error(`[Guardrail] CIRCUIT OPEN for ${targetKey}. Retrying at ${new Date(circuit.nextRetryTime).toISOString()}`);
}
}
// --- Component 3: Retry Envelopes ---
class RetryEnvelope {
constructor(
private maxRetries: number = 3,
private baseDelay: number = 1000, // ms
private logger: Logger = consoleLogger
) {}
public async execute<T>(
task: () => Promise<T>,
isRetriable: (err: any) => boolean
): Promise<T> {
let attempt = 0;
while (attempt <= this.maxRetries) {
try {
const result = await task();
return result;
} catch (err: any) {
attempt++;
// Check status code for 4xx client errors (usually do not retry 404/403)
const status = err.status || err.statusCode || 0;
if (status >= 400 && status < 500 && status !== 429) {
throw err; // Non-retriable client error
}
if (attempt > this.maxRetries || !isRetriable(err)) {
this.logger.error(`[Retry] Max retries reached or non-retriable error.`);
throw err;
}
// Exponential Backoff with Jitter
const delay = Math.pow(2, attempt) * this.baseDelay + Math.random() * 100;
this.logger.warn(`[Retry] Attempt ${attempt}/${this.maxRetries} failed. Retrying in ${Math.round(delay)}ms...`);
await sleep(delay);
}
}
// Should be unreachable, but TS needs it
throw new Error('Retry logic failed unexpectedly');
}
}
// --- Aggregator: The Safety Net ---
export interface RenderTaskContext {
botId: string;
targetDomain: string; // Used for circuit breaking
}
export interface RenderResult {
html?: string;
status: number;
timings: {
total: number;
render: number;
};
}
export class RenderSafetyNet {
private semaphore = new BotSemaphore();
private guardrail = new HttpGuardrail();
private retryPolicy = new RetryEnvelope();
/**
* configureBot: Define max concurrent renders for a specific bot
*/
public configureBot(botId: string, maxInflight: number) {
this.semaphore.registerBot(botId, maxInflight);
}
/**
* safeRender: The main entry point
*/
public async execute(
ctx: RenderTaskContext,
renderFn: () => Promise<RenderResult>
): Promise<RenderResult> {
// 1. Guardrail Check
if (!this.guardrail.isAllowed(ctx.targetDomain)) {
throw new Error(`Circuit Breaker OPEN for domain: ${ctx.targetDomain}`);
}
// 2. Retry Envelope
return this.retryPolicy.execute(async () => {
// 3. Concurrency Limit (Acquire Lock)
await this.semaphore.acquire(ctx.botId);
const startTime = Date.now();
try {
// Execute Render
const result = await renderFn();
// Success
this.guardrail.recordResult(ctx.targetDomain, true, result.status);
return result;
} catch (err: any) {
// Failure handling
const status = err.status || 0; // 0 implies network error
this.guardrail.recordResult(ctx.targetDomain, false, status);
throw err; // Re-throw for RetryEnvelope to handle
} finally {
// Release Lock
this.semaphore.release(ctx.botId);
}
}, (err) => {
// Retriable logic:
// 1. Always retry network errors (status 0)
// 2. Retry 5xx (guardrail might trip eventually, but allow a few retries)
// 3. Retry 429 (Too Many Requests)
const status = err.status || 0;
return status === 0 || status === 429 || (status >= 500);
});
}
}